code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
def tail(log_file) cursor = File.size(log_file) last_checked = Time.now tail_thread = Thread.new do File.open(log_file, 'r') do |f| loop do f.seek cursor if f.mtime > last_checked last_checked = f.mtime contents = f.read cursor += contents.length print contents end sleep 1 end end end tail_thread end
bricooke/my-biz-expenses
vendor/rails/railties/lib/commands/servers/base.rb
Ruby
mit
404
module Timers VERSION = "4.0.1" end
eprislac/guard-yard
vendor/ruby/2.3.0/gems/timers-4.0.1/lib/timers/version.rb
Ruby
mit
38
<?php namespace Composer\Installers; use Composer\Composer; use Composer\Installer\BinaryInstaller; use Composer\Installer\LibraryInstaller; use Composer\IO\IOInterface; use Composer\Package\PackageInterface; use Composer\Repository\InstalledRepositoryInterface; use Composer\Util\Filesystem; class Installer extends LibraryInstaller { /** * Package types to installer class map * * @var array */ private $supportedTypes = array( 'aimeos' => 'AimeosInstaller', 'asgard' => 'AsgardInstaller', 'attogram' => 'AttogramInstaller', 'agl' => 'AglInstaller', 'annotatecms' => 'AnnotateCmsInstaller', 'bitrix' => 'BitrixInstaller', 'bonefish' => 'BonefishInstaller', 'cakephp' => 'CakePHPInstaller', 'chef' => 'ChefInstaller', 'civicrm' => 'CiviCrmInstaller', 'ccframework' => 'ClanCatsFrameworkInstaller', 'cockpit' => 'CockpitInstaller', 'codeigniter' => 'CodeIgniterInstaller', 'concrete5' => 'Concrete5Installer', 'craft' => 'CraftInstaller', 'croogo' => 'CroogoInstaller', 'dokuwiki' => 'DokuWikiInstaller', 'dolibarr' => 'DolibarrInstaller', 'decibel' => 'DecibelInstaller', 'drupal' => 'DrupalInstaller', 'elgg' => 'ElggInstaller', 'eliasis' => 'EliasisInstaller', 'ee3' => 'ExpressionEngineInstaller', 'ee2' => 'ExpressionEngineInstaller', 'ezplatform' => 'EzPlatformInstaller', 'fuel' => 'FuelInstaller', 'fuelphp' => 'FuelphpInstaller', 'grav' => 'GravInstaller', 'hurad' => 'HuradInstaller', 'imagecms' => 'ImageCMSInstaller', 'itop' => 'ItopInstaller', 'joomla' => 'JoomlaInstaller', 'kanboard' => 'KanboardInstaller', 'kirby' => 'KirbyInstaller', 'kodicms' => 'KodiCMSInstaller', 'kohana' => 'KohanaInstaller', 'lms' => 'LanManagementSystemInstaller', 'laravel' => 'LaravelInstaller', 'lavalite' => 'LavaLiteInstaller', 'lithium' => 'LithiumInstaller', 'magento' => 'MagentoInstaller', 'majima' => 'MajimaInstaller', 'mako' => 'MakoInstaller', 'maya' => 'MayaInstaller', 'mautic' => 'MauticInstaller', 'mediawiki' => 'MediaWikiInstaller', 'microweber' => 'MicroweberInstaller', 'modulework' => 'MODULEWorkInstaller', 'modx' => 'ModxInstaller', 'modxevo' => 'MODXEvoInstaller', 'moodle' => 'MoodleInstaller', 'october' => 'OctoberInstaller', 'ontowiki' => 'OntoWikiInstaller', 'oxid' => 'OxidInstaller', 'osclass' => 'OsclassInstaller', 'pxcms' => 'PxcmsInstaller', 'phpbb' => 'PhpBBInstaller', 'pimcore' => 'PimcoreInstaller', 'piwik' => 'PiwikInstaller', 'plentymarkets'=> 'PlentymarketsInstaller', 'ppi' => 'PPIInstaller', 'puppet' => 'PuppetInstaller', 'radphp' => 'RadPHPInstaller', 'phifty' => 'PhiftyInstaller', 'porto' => 'PortoInstaller', 'redaxo' => 'RedaxoInstaller', 'reindex' => 'ReIndexInstaller', 'roundcube' => 'RoundcubeInstaller', 'shopware' => 'ShopwareInstaller', 'sitedirect' => 'SiteDirectInstaller', 'silverstripe' => 'SilverStripeInstaller', 'smf' => 'SMFInstaller', 'sydes' => 'SyDESInstaller', 'symfony1' => 'Symfony1Installer', 'thelia' => 'TheliaInstaller', 'tusk' => 'TuskInstaller', 'typo3-cms' => 'TYPO3CmsInstaller', 'typo3-flow' => 'TYPO3FlowInstaller', 'userfrosting' => 'UserFrostingInstaller', 'vanilla' => 'VanillaInstaller', 'whmcs' => 'WHMCSInstaller', 'wolfcms' => 'WolfCMSInstaller', 'wordpress' => 'WordPressInstaller', 'yawik' => 'YawikInstaller', 'zend' => 'ZendInstaller', 'zikula' => 'ZikulaInstaller', 'prestashop' => 'PrestashopInstaller' ); /** * Installer constructor. * * Disables installers specified in main composer extra installer-disable * list * * @param IOInterface $io * @param Composer $composer * @param string $type * @param Filesystem|null $filesystem * @param BinaryInstaller|null $binaryInstaller */ public function __construct( IOInterface $io, Composer $composer, $type = 'library', Filesystem $filesystem = null, BinaryInstaller $binaryInstaller = null ) { parent::__construct($io, $composer, $type, $filesystem, $binaryInstaller); $this->removeDisabledInstallers(); } /** * {@inheritDoc} */ public function getInstallPath(PackageInterface $package) { $type = $package->getType(); $frameworkType = $this->findFrameworkType($type); if ($frameworkType === false) { throw new \InvalidArgumentException( 'Sorry the package type of this package is not yet supported.' ); } $class = 'Composer\\Installers\\' . $this->supportedTypes[$frameworkType]; $installer = new $class($package, $this->composer, $this->getIO()); return $installer->getInstallPath($package, $frameworkType); } public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package) { parent::uninstall($repo, $package); $installPath = $this->getPackageBasePath($package); $this->io->write(sprintf('Deleting %s - %s', $installPath, !file_exists($installPath) ? '<comment>deleted</comment>' : '<error>not deleted</error>')); } /** * {@inheritDoc} */ public function supports($packageType) { $frameworkType = $this->findFrameworkType($packageType); if ($frameworkType === false) { return false; } $locationPattern = $this->getLocationPattern($frameworkType); return preg_match('#' . $frameworkType . '-' . $locationPattern . '#', $packageType, $matches) === 1; } /** * Finds a supported framework type if it exists and returns it * * @param string $type * @return string */ protected function findFrameworkType($type) { $frameworkType = false; krsort($this->supportedTypes); foreach ($this->supportedTypes as $key => $val) { if ($key === substr($type, 0, strlen($key))) { $frameworkType = substr($type, 0, strlen($key)); break; } } return $frameworkType; } /** * Get the second part of the regular expression to check for support of a * package type * * @param string $frameworkType * @return string */ protected function getLocationPattern($frameworkType) { $pattern = false; if (!empty($this->supportedTypes[$frameworkType])) { $frameworkClass = 'Composer\\Installers\\' . $this->supportedTypes[$frameworkType]; /** @var BaseInstaller $framework */ $framework = new $frameworkClass(null, $this->composer, $this->getIO()); $locations = array_keys($framework->getLocations()); $pattern = $locations ? '(' . implode('|', $locations) . ')' : false; } return $pattern ? : '(\w+)'; } /** * Get I/O object * * @return IOInterface */ private function getIO() { return $this->io; } /** * Look for installers set to be disabled in composer's extra config and * remove them from the list of supported installers. * * Globals: * - true, "all", and "*" - disable all installers. * - false - enable all installers (useful with * wikimedia/composer-merge-plugin or similar) * * @return void */ protected function removeDisabledInstallers() { $extra = $this->composer->getPackage()->getExtra(); if (!isset($extra['installer-disable']) || $extra['installer-disable'] === false) { // No installers are disabled return; } // Get installers to disable $disable = $extra['installer-disable']; // Ensure $disabled is an array if (!is_array($disable)) { $disable = array($disable); } // Check which installers should be disabled $all = array(true, "all", "*"); $intersect = array_intersect($all, $disable); if (!empty($intersect)) { // Disable all installers $this->supportedTypes = array(); } else { // Disable specified installers foreach ($disable as $key => $installer) { if (is_string($installer) && key_exists($installer, $this->supportedTypes)) { unset($this->supportedTypes[$installer]); } } } } }
rsathishkumar/drupal8
vendor/composer/installers/src/Composer/Installers/Installer.php
PHP
gpl-2.0
9,519
/** * @copyright (C) 2016 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ !(function(document, $) { "use strict"; function initMinicolorsField (event) { $(event.target).find('.minicolors').each(function() { $(this).minicolors({ control: $(this).attr('data-control') || 'hue', format: $(this).attr('data-validate') === 'color' ? 'hex' : ($(this).attr('data-format') === 'rgba' ? 'rgb' : $(this).attr('data-format')) || 'hex', keywords: $(this).attr('data-keywords') || '', opacity: $(this).attr('data-format') === 'rgba', position: $(this).attr('data-position') || 'default', swatches: $(this).attr('data-colors') ? $(this).attr('data-colors').split(",") : [], theme: 'bootstrap' }); }); } /** * Initialize at an initial page load */ document.addEventListener("DOMContentLoaded", initMinicolorsField); /** * Initialize when a part of the page was updated */ document.addEventListener("joomla:updated", initMinicolorsField); })(document, jQuery);
Fedik/joomla-cms
build/media_source/system/js/fields/color-field-adv-init.es5.js
JavaScript
gpl-2.0
1,118
<?php /** * Shows a shipping line * * @var object $item The item being displayed * @var int $item_id The id of the item being displayed */ if ( ! defined( 'ABSPATH' ) ) { exit; } ?> <tr class="shipping <?php echo ( ! empty( $class ) ) ? esc_attr( $class ) : ''; ?>" data-order_item_id="<?php echo esc_attr( $item_id ); ?>"> <td class="thumb"><div></div></td> <td class="name"> <div class="view"> <?php echo esc_html( $item->get_name() ? $item->get_name() : __( 'Shipping', 'woocommerce' ) ); ?> </div> <div class="edit" style="display: none;"> <input type="hidden" name="shipping_method_id[]" value="<?php echo esc_attr( $item_id ); ?>" /> <input type="text" class="shipping_method_name" placeholder="<?php esc_attr_e( 'Shipping name', 'woocommerce' ); ?>" name="shipping_method_title[<?php echo esc_attr( $item_id ); ?>]" value="<?php echo esc_attr( $item->get_name() ); ?>" /> <select class="shipping_method" name="shipping_method[<?php echo esc_attr( $item_id ); ?>]"> <optgroup label="<?php esc_attr_e( 'Shipping method', 'woocommerce' ); ?>"> <option value=""><?php esc_html_e( 'N/A', 'woocommerce' ); ?></option> <?php $found_method = false; foreach ( $shipping_methods as $method ) { $current_method = ( 0 === strpos( $item->get_method_id(), $method->id ) ) ? $item->get_method_id() : $method->id; echo '<option value="' . esc_attr( $current_method ) . '" ' . selected( $item->get_method_id() === $current_method, true, false ) . '>' . esc_html( $method->get_method_title() ) . '</option>'; if ( $item->get_method_id() === $current_method ) { $found_method = true; } } if ( ! $found_method && $item->get_method_id() ) { echo '<option value="' . esc_attr( $item->get_method_id() ) . '" selected="selected">' . esc_html__( 'Other', 'woocommerce' ) . '</option>'; } else { echo '<option value="other">' . esc_html__( 'Other', 'woocommerce' ) . '</option>'; } ?> </optgroup> </select> </div> <?php do_action( 'woocommerce_before_order_itemmeta', $item_id, $item, null ); ?> <?php require 'html-order-item-meta.php'; ?> <?php do_action( 'woocommerce_after_order_itemmeta', $item_id, $item, null ); ?> </td> <?php do_action( 'woocommerce_admin_order_item_values', null, $item, absint( $item_id ) ); ?> <td class="item_cost" width="1%">&nbsp;</td> <td class="quantity" width="1%">&nbsp;</td> <td class="line_cost" width="1%"> <div class="view"> <?php echo wc_price( $item->get_total(), array( 'currency' => $order->get_currency() ) ); $refunded = $order->get_total_refunded_for_item( $item_id, 'shipping' ); if ( $refunded ) { echo '<small class="refunded">-' . wc_price( $refunded, array( 'currency' => $order->get_currency() ) ) . '</small>'; } ?> </div> <div class="edit" style="display: none;"> <input type="text" name="shipping_cost[<?php echo esc_attr( $item_id ); ?>]" placeholder="<?php echo esc_attr( wc_format_localized_price( 0 ) ); ?>" value="<?php echo esc_attr( wc_format_localized_price( $item->get_total() ) ); ?>" class="line_total wc_input_price" /> </div> <div class="refund" style="display: none;"> <input type="text" name="refund_line_total[<?php echo absint( $item_id ); ?>]" placeholder="<?php echo esc_attr( wc_format_localized_price( 0 ) ); ?>" class="refund_line_total wc_input_price" /> </div> </td> <?php if ( ( $tax_data = $item->get_taxes() ) && wc_tax_enabled() ) { foreach ( $order_taxes as $tax_item ) { $tax_item_id = $tax_item->get_rate_id(); $tax_item_total = isset( $tax_data['total'][ $tax_item_id ] ) ? $tax_data['total'][ $tax_item_id ] : ''; ?> <td class="line_tax" width="1%"> <div class="view"> <?php echo ( '' !== $tax_item_total ) ? wc_price( wc_round_tax_total( $tax_item_total ), array( 'currency' => $order->get_currency() ) ) : '&ndash;'; $refunded = $order->get_tax_refunded_for_item( $item_id, $tax_item_id, 'shipping' ); if ( $refunded ) { echo '<small class="refunded">-' . wc_price( $refunded, array( 'currency' => $order->get_currency() ) ) . '</small>'; } ?> </div> <div class="edit" style="display: none;"> <input type="text" name="shipping_taxes[<?php echo absint( $item_id ); ?>][<?php echo esc_attr( $tax_item_id ); ?>]" placeholder="<?php echo esc_attr( wc_format_localized_price( 0 ) ); ?>" value="<?php echo ( isset( $tax_item_total ) ) ? esc_attr( wc_format_localized_price( $tax_item_total ) ) : ''; ?>" class="line_tax wc_input_price" /> </div> <div class="refund" style="display: none;"> <input type="text" name="refund_line_tax[<?php echo absint( $item_id ); ?>][<?php echo esc_attr( $tax_item_id ); ?>]" placeholder="<?php echo esc_attr( wc_format_localized_price( 0 ) ); ?>" class="refund_line_tax wc_input_price" data-tax_id="<?php echo esc_attr( $tax_item_id ); ?>" /> </div> </td> <?php } } ?> <td class="wc-order-edit-line-item"> <?php if ( $order->is_editable() ) : ?> <div class="wc-order-edit-line-item-actions"> <a class="edit-order-item" href="#"></a><a class="delete-order-item" href="#"></a> </div> <?php endif; ?> </td> </tr>
pcutler/stoneopen
wp-content/plugins/woocommerce/includes/admin/meta-boxes/views/html-order-shipping.php
PHP
gpl-2.0
5,212
/* ***************************************************************************** * A.L.E (Arcade Learning Environment) * Copyright (c) 2009-2013 by Yavar Naddaf, Joel Veness, Marc G. Bellemare and * the Reinforcement Learning and Artificial Intelligence Laboratory * Released under the GNU General Public License; see License.txt for details. * * Based on: Stella -- "An Atari 2600 VCS Emulator" * Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team * * ***************************************************************************** */ #ifndef __ASTEROIDS_HPP__ #define __ASTEROIDS_HPP__ #include "../RomSettings.hpp" /* RL wrapper for Asteroids */ class AsteroidsSettings : public RomSettings { public: AsteroidsSettings(); // reset void reset(); // is end of game bool isTerminal() const; // get the most recently observed reward reward_t getReward() const; // the rom-name const char* rom() const { return "asteroids"; } // create a new instance of the rom RomSettings* clone() const; // is an action part of the minimal set? bool isMinimal(const Action& a) const; // process the latest information from ALE void step(const System& system); // saves the state of the rom settings void saveState(Serializer & ser); // loads the state of the rom settings void loadState(Deserializer & ser); private: bool m_terminal; reward_t m_reward; reward_t m_score; }; #endif // __ASTEROIDS_HPP__
soumith/Arcade-Learning-Environment
src/games/supported/Asteroids.hpp
C++
gpl-2.0
1,679
<?php /** * @package Joomla.Administrator * @subpackage com_languages * * @copyright (C) 2018 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; use Joomla\CMS\Dispatcher\ComponentDispatcherFactoryInterface; use Joomla\CMS\Extension\ComponentInterface; use Joomla\CMS\Extension\Service\Provider\ComponentDispatcherFactory; use Joomla\CMS\Extension\Service\Provider\MVCFactory; use Joomla\CMS\HTML\Registry; use Joomla\CMS\MVC\Factory\MVCFactoryInterface; use Joomla\Component\Languages\Administrator\Extension\LanguagesComponent; use Joomla\DI\Container; use Joomla\DI\ServiceProviderInterface; /** * The language service provider. * * @since 4.0.0 */ return new class implements ServiceProviderInterface { /** * Registers the service provider with a DI container. * * @param Container $container The DI container. * * @return void * * @since 4.0.0 */ public function register(Container $container) { $container->registerServiceProvider(new MVCFactory('\\Joomla\\Component\\Languages')); $container->registerServiceProvider(new ComponentDispatcherFactory('\\Joomla\\Component\\Languages')); $container->set( ComponentInterface::class, function (Container $container) { $component = new LanguagesComponent($container->get(ComponentDispatcherFactoryInterface::class)); $component->setMVCFactory($container->get(MVCFactoryInterface::class)); $component->setRegistry($container->get(Registry::class)); return $component; } ); } };
Hackwar/joomla-cms
administrator/components/com_languages/services/provider.php
PHP
gpl-2.0
1,620
/** * Plugin that highlights matched word partials in a given element. * TODO: Add a function for restoring the previous text. * TODO: Accept mappings for converting shortcuts like WP: to Wikipedia:. */ ( function ( $ ) { $.highlightText = { // Split our pattern string at spaces and run our highlight function on the results splitAndHighlight: function ( node, pat ) { var i, patArray = pat.split( ' ' ); for ( i = 0; i < patArray.length; i++ ) { if ( patArray[i].length === 0 ) { continue; } $.highlightText.innerHighlight( node, patArray[i] ); } return node; }, // scans a node looking for the pattern and wraps a span around each match innerHighlight: function ( node, pat ) { var i, match, pos, spannode, middlebit, middleclone; // if this is a text node if ( node.nodeType === 3 ) { // TODO - need to be smarter about the character matching here. // non latin characters can make regex think a new word has begun: do not use \b // http://stackoverflow.com/questions/3787072/regex-wordwrap-with-utf8-characters-in-js // look for an occurrence of our pattern and store the starting position match = node.data.match( new RegExp( "(^|\\s)" + $.escapeRE( pat ), "i" ) ); if ( match ) { pos = match.index + match[1].length; // include length of any matched spaces // create the span wrapper for the matched text spannode = document.createElement( 'span' ); spannode.className = 'highlight'; // shave off the characters preceding the matched text middlebit = node.splitText( pos ); // shave off any unmatched text off the end middlebit.splitText( pat.length ); // clone for appending to our span middleclone = middlebit.cloneNode( true ); // append the matched text node to the span spannode.appendChild( middleclone ); // replace the matched node, with our span-wrapped clone of the matched node middlebit.parentNode.replaceChild( spannode, middlebit ); } // if this is an element with childnodes, and not a script, style or an element we created } else if ( node.nodeType === 1 && node.childNodes && !/(script|style)/i.test( node.tagName ) && !( node.tagName.toLowerCase() === 'span' && node.className.match( /\bhighlight/ ) ) ) { for ( i = 0; i < node.childNodes.length; ++i ) { // call the highlight function for each child node $.highlightText.innerHighlight( node.childNodes[i], pat ); } } } }; $.fn.highlightText = function ( matchString ) { return this.each( function () { var $el = $( this ); $el.data( 'highlightText', { originalText: $el.text() } ); $.highlightText.splitAndHighlight( this, matchString ); } ); }; }( jQuery ) );
IEEEBerkeley/anabolic_window
resources/jquery/jquery.highlightText.js
JavaScript
gpl-2.0
2,750
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Automatically generated strings for Moodle installer * * Do not edit this file manually! It contains just a subset of strings * needed during the very first steps of installation. This file was * generated automatically by export-installer.php (which is part of AMOS * {@link http://docs.moodle.org/dev/Languages/AMOS}) using the * list of strings defined in /install/stringnames.txt. * * @package installer * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['parentlanguage'] = 'el'; $string['thisdirection'] = 'ltr'; $string['thislanguage'] = 'Ελληνικά για Χώρους Εργασίας';
marcusboon/moodle
install/lang/el_wp/langconfig.php
PHP
gpl-3.0
1,381
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ $subpanel_layout = array( 'top_buttons' => array( array('widget_class' => 'SubPanelTopCreateButton'), array('widget_class' => 'SubPanelTopSelectButton', 'popup_module' => 'People'), ), 'where' => '', 'list_fields' => array( 'first_name'=>array( 'name'=>'first_name', 'usage' => 'query_only', ), 'last_name'=>array( 'name'=>'last_name', 'usage' => 'query_only', ), 'salutation'=>array( 'name'=>'salutation', 'usage' => 'query_only', ), 'name'=>array( 'name'=>'name', 'vname' => 'LBL_LIST_NAME', 'sort_by' => 'last_name', 'sort_order' => 'asc', 'widget_class' => 'SubPanelDetailViewLink', 'module' => 'Contacts', 'width' => '40%', ), 'email1'=>array( 'name'=>'email1', 'vname' => 'LBL_LIST_EMAIL', 'widget_class' => 'SubPanelEmailLink', 'width' => '35%', ), 'phone_work'=>array ( 'name'=>'phone_work', 'vname' => 'LBL_LIST_PHONE', 'width' => '15%', ), 'edit_button'=>array( 'widget_class' => 'SubPanelEditButton', 'module' => 'Contacts', 'width' => '5%', ), 'remove_button'=>array( 'widget_class' => 'SubPanelRemoveButton', 'module' => 'Contacts', 'width' => '5%', ), ), ); ?>
yonkon/nedvig
modules/sphr_Intermediary/metadata/subpanels/default.php
PHP
agpl-3.0
3,311
odoo.define('web.domain_tests', function (require) { "use strict"; var Domain = require('web.Domain'); QUnit.module('core', {}, function () { QUnit.module('domain'); QUnit.test("basic", function (assert) { assert.expect(3); var fields = { a: 3, group_method: 'line', select1: 'day', rrule_type: 'monthly', }; assert.ok(new Domain([['a', '=', 3]]).compute(fields)); assert.ok(new Domain([['group_method','!=','count']]).compute(fields)); assert.ok(new Domain([['select1','=','day'], ['rrule_type','=','monthly']]).compute(fields)); }); QUnit.test("or", function (assert) { assert.expect(3); var web = { section_id: null, user_id: null, member_ids: null, }; var currentDomain = [ '|', ['section_id', '=', 42], '|', ['user_id', '=', 3], ['member_ids', 'in', [3]] ]; assert.ok(new Domain(currentDomain).compute(_.extend({}, web, {section_id: 42}))); assert.ok(new Domain(currentDomain).compute(_.extend({}, web, {user_id: 3}))); assert.ok(new Domain(currentDomain).compute(_.extend({}, web, {member_ids: 3}))); }); QUnit.test("not", function (assert) { assert.expect(2); var fields = { a: 5, group_method: 'line', }; assert.ok(new Domain(['!', ['a', '=', 3]]).compute(fields)); assert.ok(new Domain(['!', ['group_method','=','count']]).compute(fields)); }); QUnit.test("domains initialized with a number", function (assert) { assert.expect(2); assert.ok(new Domain(1).compute({})); assert.notOk(new Domain(0).compute({})); }); }); });
maxive/erp
addons/web/static/tests/core/domain_tests.js
JavaScript
agpl-3.0
1,846
<?php /* * $Id$ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.doctrine-project.org>. */ /** * Doctrine_Migration_Diff_TestCase * * @package Doctrine * @author Konsta Vesterinen <kvesteri@cc.hut.fi> * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @category Object Relational Mapping * @link www.doctrine-project.org * @since 1.0 * @version $Revision$ */ class Doctrine_Migration_Diff_TestCase extends Doctrine_UnitTestCase { public function testTest() { $from = dirname(__FILE__) . '/Diff/schema/from.yml'; $to = dirname(__FILE__) . '/Diff/schema/to.yml'; $migrationsPath = dirname(__FILE__) . '/Diff/migrations'; Doctrine_Lib::makeDirectories($migrationsPath); $diff = new Doctrine_Migration_Diff($from, $to, $migrationsPath); $changes = $diff->generateChanges(); $this->assertEqual($changes['dropped_tables']['homepage']['tableName'], 'homepage'); $this->assertEqual($changes['created_tables']['blog_post']['tableName'], 'blog_post'); $this->assertEqual($changes['created_columns']['profile']['user_id'], array('type' => 'integer', 'length' => 8)); $this->assertEqual($changes['dropped_columns']['user']['homepage_id'], array('type' => 'integer', 'length' => 8)); $this->assertEqual($changes['dropped_columns']['user']['profile_id'], array('type' => 'integer', 'length' => 8)); $this->assertEqual($changes['changed_columns']['user']['username'], array('type' => 'string', 'length' => 255, 'unique' => true, 'notnull' => true)); $this->assertEqual($changes['created_foreign_keys']['profile']['profile_user_id_user_id']['local'], 'user_id'); $this->assertEqual($changes['created_foreign_keys']['blog_post']['blog_post_user_id_user_id']['local'], 'user_id'); $this->assertEqual($changes['dropped_foreign_keys']['user']['user_profile_id_profile_id']['local'], 'profile_id'); $this->assertEqual($changes['dropped_foreign_keys']['user']['user_homepage_id_homepage_id']['local'], 'homepage_id'); $this->assertEqual($changes['created_indexes']['blog_post']['blog_post_user_id'], array('fields' => array('user_id'))); $this->assertEqual($changes['created_indexes']['profile']['profile_user_id'], array('fields' => array('user_id'))); $this->assertEqual($changes['dropped_indexes']['user']['is_active'], array('fields' => array('is_active'))); $diff->generateMigrationClasses(); $files = glob($migrationsPath . '/*.php'); $this->assertEqual(count($files), 2); $this->assertTrue(strpos($files[0], '_version1.php')); $this->assertTrue(strpos($files[1], '_version2.php')); $code1 = file_get_contents($files[0]); $this->assertTrue(strpos($code1, 'this->dropTable')); $this->assertTrue(strpos($code1, 'this->createTable')); $this->assertTrue(strpos($code1, 'this->removeColumn')); $this->assertTrue(strpos($code1, 'this->addColumn')); $this->assertTrue(strpos($code1, 'this->changeColumn')); $code2 = file_get_contents($files[1]); $this->assertTrue(strpos($code2, 'this->dropForeignKey')); $this->assertTrue(strpos($code2, 'this->removeIndex')); $this->assertTrue(strpos($code2, 'this->addIndex')); $this->assertTrue(strpos($code2, 'this->createForeignKey')); Doctrine_Lib::removeDirectories($migrationsPath); } }
aripringle/doctrine1
tests/Migration/DiffTestCase.php
PHP
lgpl-2.1
4,384
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.undertow.server; /** * Connector level statistics * * * @author Stuart Douglas */ public interface ConnectorStatistics { /** * * @return The number of requests processed by this connector */ long getRequestCount(); /** * * @return The number of bytes sent on this connector */ long getBytesSent(); /** * * @return The number of bytes that have been received by this connector */ long getBytesReceived(); /** * * @return The number of requests that triggered an error (i.e. 500) response. */ long getErrorCount(); /** * * @return The total amount of time spent processing all requests on this connector * (nanoseconds) */ long getProcessingTime(); /** * * @return The time taken by the slowest request * (nanoseconds) */ long getMaxProcessingTime(); /** * Resets all values to zero */ void reset(); /** * * @return The current number of active connections */ long getActiveConnections(); /** * * @return The maximum number of active connections that have every been active on this connector */ long getMaxActiveConnections(); /** * * @return The current number of active requests */ long getActiveRequests(); /** * * @return The maximum number of active requests */ long getMaxActiveRequests(); }
rhusar/undertow
core/src/main/java/io/undertow/server/ConnectorStatistics.java
Java
apache-2.0
2,212
// "Simplify boolean expression" "true" class A { public static void m(boolean fullSearch, boolean partialSearch) { if (!partialSearch) { return; } // comment String str = fullSearch ? "str1" : "str2 " + "str3"; } }
goodwinnk/intellij-community
java/java-tests/testData/inspection/dataFlow/fixture/KeepComments_after.java
Java
apache-2.0
273
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'elementspath', 'ca', { eleLabel: 'Ruta dels elements', eleTitle: '%1 element' } );
Jasig/resource-server
resource-server-content/src/main/webapp/rs/ckeditor/4.3.2/_source/plugins/elementspath/lang/ca.js
JavaScript
apache-2.0
258
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CompoundAssignmentForDelegate : EmitMetadataTestBase { // The method to removal or concatenation with ‘optional’ parameter [Fact] public void OptionalParaInCompAssignOperator() { var text = @" delegate void MyDelegate1(int x, float y); class C { public void DelegatedMethod(int x, float y = 3.0f) { System.Console.WriteLine(y); } static void Main(string[] args) { C mc = new C(); MyDelegate1 md1 = null; md1 += mc.DelegatedMethod; md1(1, 5); md1 -= mc.DelegatedMethod; } } "; string expectedIL = @"{ // Code size 65 (0x41) .maxstack 4 .locals init (C V_0) //mc IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldnull IL_0007: ldloc.0 IL_0008: ldftn ""void C.DelegatedMethod(int, float)"" IL_000e: newobj ""MyDelegate1..ctor(object, System.IntPtr)"" IL_0013: call ""System.Delegate System.Delegate.Combine(System.Delegate, System.Delegate)"" IL_0018: castclass ""MyDelegate1"" IL_001d: dup IL_001e: ldc.i4.1 IL_001f: ldc.r4 5 IL_0024: callvirt ""void MyDelegate1.Invoke(int, float)"" IL_0029: ldloc.0 IL_002a: ldftn ""void C.DelegatedMethod(int, float)"" IL_0030: newobj ""MyDelegate1..ctor(object, System.IntPtr)"" IL_0035: call ""System.Delegate System.Delegate.Remove(System.Delegate, System.Delegate)"" IL_003a: castclass ""MyDelegate1"" IL_003f: pop IL_0040: ret } "; //var tree = SyntaxTree.ParseCompilationUnit(text); //var type = from item in ((CompilationUnitSyntax)tree.Root).Members where item as TypeDeclarationSyntax != null select item as TypeDeclarationSyntax; //var cla = type.First() as TypeDeclarationSyntax; //var method = from item in cla.Members where (MethodDeclarationSyntax)item != null select item as MethodDeclarationSyntax ; //var block = method.Last().Body; //var statement = block.Statements; CompileAndVerify(text, expectedOutput: "5").VerifyIL("C.Main", expectedIL); } // The object to removal or concatenation could be create a new instance of a method or an method name [Fact] public void ObjectOfCompAssignOperator() { var text = @" delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } } class C { static void Main(string[] args) { abc p = new abc(); boo foo = null; foo += p.bar; foo += new boo(p.bar); foo(); foo -= p.bar; foo -= new boo(p.bar); } } "; var expectedOutput = @"bar bar"; CompileAndVerify(text, expectedOutput: expectedOutput); } // The object to removal or concatenation could be null [Fact] public void ObjectOfCompAssignOperatorIsNull() { var text = @" delegate void boo(); class C { static void Main(string[] args) { boo foo = null; foo += (boo)null; foo -= (boo)null; foo += null; foo -= null; } } "; var expectedIL = @"{ // Code size 47 (0x2f) .maxstack 2 IL_0000: ldnull IL_0001: ldnull IL_0002: call ""System.Delegate System.Delegate.Combine(System.Delegate, System.Delegate)"" IL_0007: castclass ""boo"" IL_000c: ldnull IL_000d: call ""System.Delegate System.Delegate.Remove(System.Delegate, System.Delegate)"" IL_0012: castclass ""boo"" IL_0017: ldnull IL_0018: call ""System.Delegate System.Delegate.Combine(System.Delegate, System.Delegate)"" IL_001d: castclass ""boo"" IL_0022: ldnull IL_0023: call ""System.Delegate System.Delegate.Remove(System.Delegate, System.Delegate)"" IL_0028: castclass ""boo"" IL_002d: pop IL_002e: ret }"; CompileAndVerify(text).VerifyIL("C.Main", expectedIL); } // The object to removal or concatenation could be an object of delegate [Fact] public void ObjectOfCompAssignOperatorIsObjectOfDelegate() { var text = @" using System; delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } static public void far() { System.Console.WriteLine(""far""); } } class C { static void Main(string[] args) { abc p = new abc(); boo foo = null; boo foo1 = new boo(abc.far); foo += foo1; // Same type foo(); foo -= foo1; // Same type boo[] arrfoo = { p.bar, abc.far }; foo += (boo)Delegate.Combine(arrfoo); // OK foo += (boo)Delegate.Combine(foo, foo1); // OK foo(); } } "; var expectedOutput = @" far bar far bar far far"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void AnonymousMethodToRemovalOrConcatenation() { var text = @" using System; delegate void boo(int x); class C { static void Main() { boo foo = null; foo += delegate (int x) { System.Console.WriteLine(x); }; foo(10); Delegate[] del = foo.GetInvocationList(); foo -= (boo)del[0]; } } "; CompileAndVerify(text, expectedOutput: "10").VerifyIL("C.Main", @" { // Code size 77 (0x4d) .maxstack 3 .locals init (System.Delegate[] V_0) //del IL_0000: ldnull IL_0001: ldsfld ""boo C.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""C.<>c C.<>c.<>9"" IL_000f: ldftn ""void C.<>c.<Main>b__0_0(int)"" IL_0015: newobj ""boo..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""boo C.<>c.<>9__0_0"" IL_0020: call ""System.Delegate System.Delegate.Combine(System.Delegate, System.Delegate)"" IL_0025: castclass ""boo"" IL_002a: dup IL_002b: ldc.i4.s 10 IL_002d: callvirt ""void boo.Invoke(int)"" IL_0032: dup IL_0033: callvirt ""System.Delegate[] System.Delegate.GetInvocationList()"" IL_0038: stloc.0 IL_0039: ldloc.0 IL_003a: ldc.i4.0 IL_003b: ldelem.ref IL_003c: castclass ""boo"" IL_0041: call ""System.Delegate System.Delegate.Remove(System.Delegate, System.Delegate)"" IL_0046: castclass ""boo"" IL_004b: pop IL_004c: ret } "); } [Fact] public void LambdaMethodToRemovalOrConcatenation() { var text = @" using System; delegate void boo(string x); class C { static void Main() { boo foo = null; foo += (x) => { System.Console.WriteLine(x); }; foo(""Hello""); Delegate[] del = foo.GetInvocationList(); foo -= (boo)del[0]; } } "; CompileAndVerify(text, expectedOutput: "Hello").VerifyIL("C.Main()", @" { // Code size 80 (0x50) .maxstack 3 .locals init (System.Delegate[] V_0) //del IL_0000: ldnull IL_0001: ldsfld ""boo C.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""C.<>c C.<>c.<>9"" IL_000f: ldftn ""void C.<>c.<Main>b__0_0(string)"" IL_0015: newobj ""boo..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""boo C.<>c.<>9__0_0"" IL_0020: call ""System.Delegate System.Delegate.Combine(System.Delegate, System.Delegate)"" IL_0025: castclass ""boo"" IL_002a: dup IL_002b: ldstr ""Hello"" IL_0030: callvirt ""void boo.Invoke(string)"" IL_0035: dup IL_0036: callvirt ""System.Delegate[] System.Delegate.GetInvocationList()"" IL_003b: stloc.0 IL_003c: ldloc.0 IL_003d: ldc.i4.0 IL_003e: ldelem.ref IL_003f: castclass ""boo"" IL_0044: call ""System.Delegate System.Delegate.Remove(System.Delegate, System.Delegate)"" IL_0049: castclass ""boo"" IL_004e: pop IL_004f: ret } "); } // Mixed named method and Lambda expression to removal or concatenation [Fact] public void MixedNamedMethodAndLambdaToRemovalOrConcatenation() { var text = @" using System; delegate void boo(int x); class C { static public void far(int x) { Console.WriteLine(""far:{0}"", x); } static void Main(string[] args) { boo foo = far; foo += (x) => System.Console.WriteLine(""lambda:{0}"", x); foo(10); Delegate[] del = foo.GetInvocationList(); foo -= (boo)del[0]; foo(20); } } "; var expectedOutPut = @"far:10 lambda:10 lambda:20"; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Mixed named method and Anonymous method to removal or concatenation [Fact] public void MixedNamedMethodAndAnonymousToRemovalOrConcatenation() { var text = @" using System; delegate void boo(int x); class C { static public void far(int x) { Console.WriteLine(""far:{0}"", x); } static void Main(string[] args) { boo foo = far; foo += delegate(int x) { System.Console.WriteLine(""Anonymous:{0}"", x); }; foo(10); Delegate[] del = foo.GetInvocationList(); foo -= (boo)del[0]; foo(20); } } "; var expectedOutPut = @"far:10 Anonymous:10 Anonymous:20"; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Mixed Lambda expression and Anonymous method to removal or concatenation [Fact] public void MixedAnonymousAndLambdaToRemovalOrConcatenation() { var text = @" using System; delegate void boo(int x); class C { static public void far(int x) { Console.WriteLine(""far:{0}"", x); } static void Main(string[] args) { boo foo = far; foo += x => { System.Console.WriteLine(""Lambda:{0}"", x); }; foo += delegate(int x) { System.Console.WriteLine(""Anonymous:{0}"", x); }; foo(10); Delegate[] del = foo.GetInvocationList(); foo -= (boo)del[0]; foo(20); } } "; var expectedOutPut = @"far:10 Lambda:10 Anonymous:10 Lambda:20 Anonymous:20"; CompileAndVerify(text, expectedOutput: expectedOutPut); } // To removal or concatenation same method multi- times [Fact] public void RemoveSameMethodMultiTime() { var text = @" using System; delegate void D(ref int x); class C { public static void M1(ref int i) { Console.WriteLine(""M1: "" + i); i = 1; } public static void M2(ref int i) { Console.WriteLine(""M2: "" + i); i = 2; } static void Main(string[] args) { int i = 0; D cd1 = new D(M1); // M1 D cd2 = cd1; cd1 += M2; // M1,M2 cd1 += M1; // M1,M2,M1 cd1(ref i); cd1 -= cd2;// remove last M1 cd1(ref i); cd1 -= M1; // remove first M1 cd1(ref i); } } "; var expectedOutPut = @"M1: 0 M2: 1 M1: 2 M1: 1 M2: 1 M2: 2 "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Remove Non existed method [Fact] public void RemoveNotExistMethod() { var text = @" using System; delegate void D(ref int x); class C { public static void M1(ref int i) { Console.WriteLine(""M1: "" + i); i = 1; } public static void M2(ref int i) { Console.WriteLine(""M2: "" + i); i = 2; } static void Main(string[] args) { int i = 0; D cd1 = new D(M1); // M1 cd1 -= M2; // M1 cd1 -= M2; // M1 cd1(ref i); } } "; var expectedOutPut = @"M1: 0"; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Removal and concatenation woks on both static and instance methods [Fact] public void RemovebothStaticAndInstanceMethod() { var text = @" delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } static public void far() { System.Console.WriteLine(""far""); } } class C { static void Main(string[] args) { abc p = new abc(); boo foo = new boo(p.bar); foo(); foo -= p.bar; foo = new boo(abc.far); foo(); foo -= abc.far; foo += p.bar; foo += abc.far; foo(); } } "; var expectedOutPut = @"bar far bar far"; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Removal or concatenation for the delegate that is member of classes [Fact] public void RemoveDelegateIsMemberOfClass() { var text = @" public delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } static public void far() { System.Console.WriteLine(""far""); } public boo foo = null; } class C { static void Main(string[] args) { abc p = new abc(); p.foo = null; p.foo += abc.far; p.foo += p.bar; p.foo(); p.foo -= abc.far; p.foo -= p.bar; } } "; var expectedOutPut = @"far bar "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Removal or concatenation for the delegate works on ternary operator [Fact] public void CompAssignWorksOnTernaryOperator() { var text = @" delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } static public void far() { System.Console.WriteLine(""far""); } } class C { static void Main(string[] args) { abc p = new abc(); boo foo = null; foo += loo() ? new boo(p.bar) : new boo(abc.far); foo(); foo -= loo() ? new boo(p.bar) : new boo(abc.far); boo left = null; boo right = null; foo = !loo() ? left += new boo(abc.far) : right += new boo(p.bar); foo(); foo = !loo() ? left -= new boo(abc.far) : right -= new boo(p.bar); } private static bool loo() { return true; } } "; var expectedOutPut = @"bar bar "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Removal or concatenation for the delegate that with 9 args [Fact] public void DelegateWithNineArgs() { var text = @" delegate void boo(out int i, double d, ref float f, string s, char c, decimal dc, C client, byte b, short sh); class C { public static void Hello(out int i, double d, ref float f, string s, char c, decimal dc, C client, byte b, short sh) { i = 1; System.Console.WriteLine(""Hello""); } static void Main(string[] args) { boo foo = null; foo += new boo(C.Hello); int i = 1; float ff = 0; foo(out i, 5.5, ref ff, ""a string"", 'C', 0.555m, new C(), 3, 16); } } "; var expectedOutPut = @"Hello "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Removal or concatenation for the delegate that is virtual struct methods [WorkItem(539908, "DevDiv")] [Fact] public void DelegateWithStructMethods() { var text = @" delegate int boo(); interface I { int bar(); } public struct abc : I { public int bar() { System.Console.WriteLine(""bar""); return 0x01; } } class C { static void Main(string[] args) { abc p = new abc(); boo foo = null; foo += new boo(p.bar); foo(); } } "; var expectedOutPut = @"bar "; var expectedIL = @" { // Code size 44 (0x2c) .maxstack 3 .locals init (abc V_0) //p IL_0000: ldloca.s V_0 IL_0002: initobj ""abc"" IL_0008: ldnull IL_0009: ldloc.0 IL_000a: box ""abc"" IL_000f: dup IL_0010: ldvirtftn ""int abc.bar()"" IL_0016: newobj ""boo..ctor(object, System.IntPtr)"" IL_001b: call ""System.Delegate System.Delegate.Combine(System.Delegate, System.Delegate)"" IL_0020: castclass ""boo"" IL_0025: callvirt ""int boo.Invoke()"" IL_002a: pop IL_002b: ret } "; CompileAndVerify(text, expectedOutput: expectedOutPut).VerifyIL("C.Main", expectedIL); } // Removal or concatenation for the delegate that the method is in base class [Fact] public void AddMethodThatInBaseClass() { var text = @" delegate double MyDelegate(int integerPortion, float fraction); public class BaseClass { public delegate void MyDelegate(); public void DelegatedMethod() { System.Console.WriteLine(""Base""); } } public class DerivedClass : BaseClass { new public delegate void MyDelegate(); public new void DelegatedMethod() { System.Console.WriteLine(""Derived""); } static void Main(string[] args) { DerivedClass derived = new DerivedClass(); BaseClass baseCls = new BaseClass(); MyDelegate derivedDel = new MyDelegate(derived.DelegatedMethod); derivedDel += baseCls.DelegatedMethod; derivedDel(); BaseClass.MyDelegate BaseDel = new BaseClass.MyDelegate(((BaseClass)derived).DelegatedMethod); BaseDel += derived.DelegatedMethod; BaseDel(); } } "; var expectedOutPut = @"Derived Base Base Derived "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // delegate-in-a-generic-class (C<t>.foo(…)) += methodgroup-in-a-generic-class (C<T>.bar(…)) [Fact] public void CompAssignOperatorForGenericClass() { var text = @" delegate void boo(short x); class C<T> { public void bar(short x) { System.Console.WriteLine(""bar""); } public static void far(T x) { System.Console.WriteLine(""far""); } public static void par<U>(U x) { System.Console.WriteLine(""par""); } public static boo foo = null; } class D { static void Main(string[] args) { C<long> p = new C<long>(); C<long>.foo += p.bar; C<short>.foo += C<short>.far; C<long>.foo += C<long>.par<short>; C<long>.foo(short.MaxValue); C<short>.foo(short.MaxValue); } } "; var expectedOutPut = @"bar par far "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Compound assignment for the method with derived return type [Fact] public void CompAssignOperatorForInherit01() { var text = @" delegate BaseClass MyBaseDelegate(BaseClass x); delegate DerivedClass MyDerivedDelegate(DerivedClass x); public class BaseClass { public static BaseClass DelegatedMethod(BaseClass x) { System.Console.WriteLine(""Base""); return x; } } public class DerivedClass : BaseClass { public static DerivedClass DelegatedMethod(DerivedClass x) { System.Console.WriteLine(""Derived""); return x; } static void Main(string[] args) { MyBaseDelegate foo = null; foo += BaseClass.DelegatedMethod; foo += DerivedClass.DelegatedMethod; foo(new BaseClass()); foo(new DerivedClass()); MyDerivedDelegate foo1 = null; //foo1 += BaseClass.DelegatedMethod; foo1 += DerivedClass.DelegatedMethod; foo1(new DerivedClass()); } } "; var expectedOutPut = @"Base Base Base Base Derived "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Compound assignment for the method with derived return type [Fact] public void CompAssignOperatorForInherit02() { var text = @" delegate T MyDelegate<T>(T x); public class BaseClass { public static BaseClass DelegatedMethod(BaseClass x) { System.Console.WriteLine(""Base1""); return x; } public static DerivedClass DelegatedMethod(DerivedClass x) { System.Console.WriteLine(""Base2""); return x; } } public class DerivedClass : BaseClass { public static new DerivedClass DelegatedMethod(DerivedClass x) { System.Console.WriteLine(""Derived1""); return x; } public static new BaseClass DelegatedMethod(BaseClass x) { System.Console.WriteLine(""Derived2""); return x; } static void Main(string[] args) { MyDelegate<BaseClass> foo = null; foo += BaseClass.DelegatedMethod; foo += DerivedClass.DelegatedMethod; foo(new BaseClass()); foo(new DerivedClass()); MyDelegate<DerivedClass> foo1 = null; foo1 += BaseClass.DelegatedMethod; foo1 += DerivedClass.DelegatedMethod; //foo1(new BaseClass()); foo1(new DerivedClass()); } } "; var expectedOutPut = @"Base1 Derived2 Base1 Derived2 Base2 Derived1 "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Compound assignment for the method with derived return type [WorkItem(539927, "DevDiv")] [Fact] public void CompAssignOperatorForInherit03() { var text = @" delegate T MyDelegate<T>(T x); public class BaseClass { public static T DelegatedMethod<T>(T x) { System.Console.WriteLine(""Base""); return x; } public static double DelegatedMethod(double x) { System.Console.WriteLine(""double""); return x; } } public class DerivedClass : BaseClass { public static new T DelegatedMethod<T>(T x) { System.Console.WriteLine(""Derived""); return x; } static void Main(string[] args) { MyDelegate<BaseClass> foo = null; foo += BaseClass.DelegatedMethod; foo += DerivedClass.DelegatedMethod; foo(new BaseClass()); foo(new DerivedClass()); MyDelegate<DerivedClass> foo1 = null; foo1 += BaseClass.DelegatedMethod; foo1 += DerivedClass.DelegatedMethod; //foo1(new BaseClass()); foo1(new DerivedClass()); MyDelegate<double> foo2 = null; foo2 += BaseClass.DelegatedMethod<double>; foo2 += BaseClass.DelegatedMethod; foo2 += DerivedClass.DelegatedMethod; foo2(2); } } "; var expectedOutPut = @"Base Derived Base Derived Base Derived Base double Derived "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Compound assignment for the method with derived return type [WorkItem(539927, "DevDiv")] [Fact] public void CompAssignOperatorForInherit04() { var text = @" delegate double MyDelegate(double x); public class BaseClass { public static T DelegatedMethod<T>(T x) { System.Console.WriteLine(""Base""); return x; } public static double DelegatedMethod(double x) { System.Console.WriteLine(""double""); return x; } } public class DerivedClass : BaseClass { public static new T DelegatedMethod<T>(T x) { System.Console.WriteLine(""Derived""); return x; } static void Main(string[] args) { MyDelegate foo = null; foo += BaseClass.DelegatedMethod<double>; foo += BaseClass.DelegatedMethod; foo += DerivedClass.DelegatedMethod; MyDelegate foo1 = null; foo1 += foo; foo += foo1; foo(1); foo1(1); } } "; var expectedOutPut = @"Base double Derived Base double Derived Base double Derived "; CompileAndVerify(text, expectedOutput: expectedOutPut); } } }
paladique/roslyn
src/Compilers/CSharp/Test/Emit/CodeGen/CompoundAssignmentForDelegate.cs
C#
apache-2.0
24,519
var colors = require('../safe'); console.log(colors.yellow('First some yellow text')); console.log(colors.yellow.underline('Underline that text')); console.log(colors.red.bold('Make it bold and red')); console.log(colors.rainbow('Double Raindows All Day Long')); console.log(colors.trap('Drop the bass')); console.log(colors.rainbow(colors.trap('DROP THE RAINBOW BASS'))); // styles not widely supported console.log(colors.bold.italic.underline.red('Chains are also cool.')); // styles not widely supported console.log(colors.green('So ') + colors.underline('are') + ' ' + colors.inverse('inverse') + colors.yellow.bold(' styles! ')); console.log(colors.zebra('Zebras are so fun!')); console.log('This is ' + colors.strikethrough('not') + ' fun.'); console.log(colors.black.bgWhite('Background color attack!')); console.log(colors.random('Use random styles on everything!')); console.log(colors.america('America, Heck Yeah!')); console.log(colors.brightCyan('Blindingly ') + colors.brightRed('bright? ') + colors.brightYellow('Why ') + colors.brightGreen('not?!')); console.log('Setting themes is useful'); // // Custom themes // // console.log('Generic logging theme as JSON'.green.bold.underline); // Load theme with JSON literal colors.setTheme({ silly: 'rainbow', input: 'blue', verbose: 'cyan', prompt: 'grey', info: 'green', data: 'grey', help: 'cyan', warn: 'yellow', debug: 'blue', error: 'red', }); // outputs red text console.log(colors.error('this is an error')); // outputs yellow text console.log(colors.warn('this is a warning')); // outputs blue text console.log(colors.input('this is an input')); // console.log('Generic logging theme as file'.green.bold.underline); // Load a theme from file colors.setTheme(require(__dirname + '/../themes/generic-logging.js')); // outputs red text console.log(colors.error('this is an error')); // outputs yellow text console.log(colors.warn('this is a warning')); // outputs grey text console.log(colors.input('this is an input')); // console.log(colors.zalgo("Don't summon him"))
BigBoss424/portfolio
v8/development/node_modules/colors/examples/safe-string.js
JavaScript
apache-2.0
2,083
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.impl.protocol.icq; import java.util.*; import net.java.sip.communicator.service.protocol.*; import org.osgi.framework.*; /** * The ICQ implementation of the ProtocolProviderFactory. * @author Emil Ivov */ public class ProtocolProviderFactoryIcqImpl extends ProtocolProviderFactory { /** * Is this factory is created for aim or icq accounts */ private boolean isAimFactory = false; /** * Creates an instance of the ProtocolProviderFactoryIcqImpl. * @param isAimFactory whether its an aim factory */ protected ProtocolProviderFactoryIcqImpl(boolean isAimFactory) { super(IcqActivator.getBundleContext(), isAimFactory ? ProtocolNames.AIM : ProtocolNames.ICQ); this.isAimFactory = isAimFactory; } /** * Initializes and creates an account corresponding to the specified * accountProperties and registers the resulting ProtocolProvider in the * <tt>context</tt> BundleContext parameter. This method has a persistent * effect. Once created the resulting account will remain installed until * removed through the uninstall account method. * * @param userIDStr the user identifier for the new account * @param accountProperties a set of protocol (or implementation) * specific properties defining the new account. * @return the AccountID of the newly created account */ @Override public AccountID installAccount( String userIDStr, Map<String, String> accountProperties) { BundleContext context = IcqActivator.getBundleContext(); if (context == null) throw new NullPointerException("The specified BundleContext was null"); if (userIDStr == null) throw new NullPointerException("The specified AccountID was null"); if (accountProperties == null) throw new NullPointerException("The specified property map was null"); accountProperties.put(USER_ID, userIDStr); // we are installing new aim account from the wizzard, so mark it as aim if(isAimFactory) accountProperties.put(IcqAccountID.IS_AIM, "true"); AccountID accountID = new IcqAccountID(userIDStr, accountProperties); //make sure we haven't seen this account id before. if( registeredAccounts.containsKey(accountID) ) throw new IllegalStateException( "An account for id " + userIDStr + " was already installed!"); //first store the account and only then load it as the load generates //an osgi event, the osgi event triggers (through the UI) a call to //the register() method and it needs to access the configuration service //and check for a password. this.storeAccount(accountID, false); accountID = loadAccount(accountProperties); return accountID; } /** * Initializes and creates an account corresponding to the specified * accountProperties and registers the resulting ProtocolProvider in the * <tt>context</tt> BundleContext parameter. * * @param accountProperties a set of protocol (or implementation) specific * properties defining the new account. * @return the AccountID of the newly created account */ @Override public AccountID loadAccount(Map<String, String> accountProperties) { // there are two factories - one for icq accounts and one for aim ones. // if we are trying to load an icq account in aim factory - skip it // and the same for aim accounts in icq factory boolean accountPropertiesIsAIM = IcqAccountID.isAIM(accountProperties); if ((accountPropertiesIsAIM && !isAimFactory) || (!accountPropertiesIsAIM && isAimFactory)) { return null; } return super.loadAccount(accountProperties); } /** * Creates a protocol provider for the given <tt>accountID</tt> and * registers it in the bundle context. This method has a persistent * effect. Once created the resulting account will remain installed until * removed through the uninstallAccount method. * * @param accountID the account identifier * @return <tt>true</tt> if the account with the given <tt>accountID</tt> is * successfully loaded, otherwise returns <tt>false</tt> */ @Override public boolean loadAccount(AccountID accountID) { // there are two factories - one for icq accounts and one for aim ones. // if we are trying to load an icq account in aim factory - skip it // and the same for aim accounts in icq factory boolean accountPropertiesIsAIM = IcqAccountID.isAIM(accountID.getAccountProperties()); if ((accountPropertiesIsAIM && !isAimFactory) || (!accountPropertiesIsAIM && isAimFactory)) { return false; } return super.loadAccount(accountID); } /** * Initializes and creates an account corresponding to the specified * accountProperties. * * @param accountProperties a set of protocol (or implementation) specific * properties defining the new account. * @return the AccountID of the newly created account */ @Override public AccountID createAccount(Map<String, String> accountProperties) { // there are two factories - one for icq accounts and one for aim ones. // if we are trying to load an icq account in aim factory - skip it // and the same for aim accounts in icq factory boolean accountPropertiesIsAIM = IcqAccountID.isAIM(accountProperties); if ((accountPropertiesIsAIM && !isAimFactory) || (!accountPropertiesIsAIM && isAimFactory)) { return null; } return super.createAccount(accountProperties); } @Override protected AccountID createAccountID(String userID, Map<String, String> accountProperties) { return new IcqAccountID(userID, accountProperties); } @Override protected ProtocolProviderService createService(String userID, AccountID accountID) { ProtocolProviderServiceIcqImpl service = new ProtocolProviderServiceIcqImpl(); service.initialize(userID, accountID); return service; } @Override public void modifyAccount( ProtocolProviderService protocolProvider, Map<String, String> accountProperties) throws NullPointerException { // Make sure the specified arguments are valid. if (protocolProvider == null) throw new NullPointerException( "The specified Protocol Provider was null"); if (accountProperties == null) throw new NullPointerException( "The specified property map was null"); BundleContext context = IcqActivator.getBundleContext(); if (context == null) throw new NullPointerException( "The specified BundleContext was null"); IcqAccountID accountID = (IcqAccountID) protocolProvider.getAccountID(); // If the given accountID doesn't correspond to an existing account // we return. if(!registeredAccounts.containsKey(accountID)) return; ServiceRegistration registration = registeredAccounts.get(accountID); // kill the service if (registration != null) registration.unregister(); accountProperties.put(USER_ID, accountID.getUserID()); if (!accountProperties.containsKey(PROTOCOL)) accountProperties.put(PROTOCOL, ProtocolNames.ICQ); accountID.setAccountProperties(accountProperties); // First store the account and only then load it as the load generates // an osgi event, the osgi event triggers (trhgough the UI) a call to // the register() method and it needs to acces the configuration service // and check for a password. this.storeAccount(accountID); Hashtable<String, String> properties = new Hashtable<String, String>(); properties.put(PROTOCOL, ProtocolNames.ICQ); properties.put(USER_ID, accountID.getUserID()); ((ProtocolProviderServiceIcqImpl) protocolProvider) .initialize(accountID.getUserID(), accountID); // We store again the account in order to store all properties added // during the protocol provider initialization. this.storeAccount(accountID); registration = context.registerService( ProtocolProviderService.class.getName(), protocolProvider, properties); registeredAccounts.put(accountID, registration); } }
gpolitis/jitsi
src/net/java/sip/communicator/impl/protocol/icq/ProtocolProviderFactoryIcqImpl.java
Java
apache-2.0
9,612
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.aggregations.bucket.histogram; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.SortedNumericDocValues; import org.apache.lucene.util.CollectionUtil; import org.elasticsearch.common.inject.internal.Nullable; import org.elasticsearch.common.lease.Releasables; import org.elasticsearch.common.rounding.Rounding; import org.elasticsearch.common.util.LongHash; import org.elasticsearch.search.aggregations.Aggregator; import org.elasticsearch.search.aggregations.AggregatorFactories; import org.elasticsearch.search.aggregations.InternalAggregation; import org.elasticsearch.search.aggregations.LeafBucketCollector; import org.elasticsearch.search.aggregations.LeafBucketCollectorBase; import org.elasticsearch.search.aggregations.bucket.BucketsAggregator; import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator; import org.elasticsearch.search.aggregations.support.AggregationContext; import org.elasticsearch.search.aggregations.support.ValuesSource; import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory; import org.elasticsearch.search.aggregations.support.ValuesSourceConfig; import org.elasticsearch.search.aggregations.support.format.ValueFormatter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class HistogramAggregator extends BucketsAggregator { private final ValuesSource.Numeric valuesSource; private final ValueFormatter formatter; private final Rounding rounding; private final InternalOrder order; private final boolean keyed; private final long minDocCount; private final ExtendedBounds extendedBounds; private final InternalHistogram.Factory histogramFactory; private final LongHash bucketOrds; public HistogramAggregator(String name, AggregatorFactories factories, Rounding rounding, InternalOrder order, boolean keyed, long minDocCount, @Nullable ExtendedBounds extendedBounds, @Nullable ValuesSource.Numeric valuesSource, ValueFormatter formatter, InternalHistogram.Factory<?> histogramFactory, AggregationContext aggregationContext, Aggregator parent, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) throws IOException { super(name, factories, aggregationContext, parent, pipelineAggregators, metaData); this.rounding = rounding; this.order = order; this.keyed = keyed; this.minDocCount = minDocCount; this.extendedBounds = extendedBounds; this.valuesSource = valuesSource; this.formatter = formatter; this.histogramFactory = histogramFactory; bucketOrds = new LongHash(1, aggregationContext.bigArrays()); } @Override public boolean needsScores() { return (valuesSource != null && valuesSource.needsScores()) || super.needsScores(); } @Override public LeafBucketCollector getLeafCollector(LeafReaderContext ctx, final LeafBucketCollector sub) throws IOException { if (valuesSource == null) { return LeafBucketCollector.NO_OP_COLLECTOR; } final SortedNumericDocValues values = valuesSource.longValues(ctx); return new LeafBucketCollectorBase(sub, values) { @Override public void collect(int doc, long bucket) throws IOException { assert bucket == 0; values.setDocument(doc); final int valuesCount = values.count(); long previousKey = Long.MIN_VALUE; for (int i = 0; i < valuesCount; ++i) { long value = values.valueAt(i); long key = rounding.roundKey(value); assert key >= previousKey; if (key == previousKey) { continue; } long bucketOrd = bucketOrds.add(key); if (bucketOrd < 0) { // already seen bucketOrd = -1 - bucketOrd; collectExistingBucket(sub, doc, bucketOrd); } else { collectBucket(sub, doc, bucketOrd); } previousKey = key; } } }; } @Override public InternalAggregation buildAggregation(long owningBucketOrdinal) throws IOException { assert owningBucketOrdinal == 0; List<InternalHistogram.Bucket> buckets = new ArrayList<>((int) bucketOrds.size()); for (long i = 0; i < bucketOrds.size(); i++) { buckets.add(histogramFactory.createBucket(rounding.valueForKey(bucketOrds.get(i)), bucketDocCount(i), bucketAggregations(i), keyed, formatter)); } // the contract of the histogram aggregation is that shards must return buckets ordered by key in ascending order CollectionUtil.introSort(buckets, InternalOrder.KEY_ASC.comparator()); // value source will be null for unmapped fields InternalHistogram.EmptyBucketInfo emptyBucketInfo = minDocCount == 0 ? new InternalHistogram.EmptyBucketInfo(rounding, buildEmptySubAggregations(), extendedBounds) : null; return histogramFactory.create(name, buckets, order, minDocCount, emptyBucketInfo, formatter, keyed, pipelineAggregators(), metaData()); } @Override public InternalAggregation buildEmptyAggregation() { InternalHistogram.EmptyBucketInfo emptyBucketInfo = minDocCount == 0 ? new InternalHistogram.EmptyBucketInfo(rounding, buildEmptySubAggregations(), extendedBounds) : null; return histogramFactory.create(name, Collections.emptyList(), order, minDocCount, emptyBucketInfo, formatter, keyed, pipelineAggregators(), metaData()); } @Override public void doClose() { Releasables.close(bucketOrds); } public static class Factory extends ValuesSourceAggregatorFactory<ValuesSource.Numeric> { private final Rounding rounding; private final InternalOrder order; private final boolean keyed; private final long minDocCount; private final ExtendedBounds extendedBounds; private final InternalHistogram.Factory<?> histogramFactory; public Factory(String name, ValuesSourceConfig<ValuesSource.Numeric> config, Rounding rounding, InternalOrder order, boolean keyed, long minDocCount, ExtendedBounds extendedBounds, InternalHistogram.Factory<?> histogramFactory) { super(name, histogramFactory.type(), config); this.rounding = rounding; this.order = order; this.keyed = keyed; this.minDocCount = minDocCount; this.extendedBounds = extendedBounds; this.histogramFactory = histogramFactory; } public long minDocCount() { return minDocCount; } @Override protected Aggregator createUnmapped(AggregationContext aggregationContext, Aggregator parent, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) throws IOException { return new HistogramAggregator(name, factories, rounding, order, keyed, minDocCount, extendedBounds, null, config.formatter(), histogramFactory, aggregationContext, parent, pipelineAggregators, metaData); } @Override protected Aggregator doCreateInternal(ValuesSource.Numeric valuesSource, AggregationContext aggregationContext, Aggregator parent, boolean collectsFromSingleBucket, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) throws IOException { if (collectsFromSingleBucket == false) { return asMultiBucketAggregator(this, aggregationContext, parent); } // we need to round the bounds given by the user and we have to do it for every aggregator we crate // as the rounding is not necessarily an idempotent operation. // todo we need to think of a better structure to the factory/agtor code so we won't need to do that ExtendedBounds roundedBounds = null; if (extendedBounds != null) { // we need to process & validate here using the parser extendedBounds.processAndValidate(name, aggregationContext.searchContext(), config.parser()); roundedBounds = extendedBounds.round(rounding); } return new HistogramAggregator(name, factories, rounding, order, keyed, minDocCount, roundedBounds, valuesSource, config.formatter(), histogramFactory, aggregationContext, parent, pipelineAggregators, metaData); } } }
martinstuga/elasticsearch
core/src/main/java/org/elasticsearch/search/aggregations/bucket/histogram/HistogramAggregator.java
Java
apache-2.0
9,668
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.jstorm.container.cgroup; import java.util.HashMap; import java.util.Map; import java.util.Set; import com.alibaba.jstorm.container.SubSystemType; import com.alibaba.jstorm.container.cgroup.core.BlkioCore; import com.alibaba.jstorm.container.cgroup.core.CgroupCore; import com.alibaba.jstorm.container.cgroup.core.CpuCore; import com.alibaba.jstorm.container.cgroup.core.CpuacctCore; import com.alibaba.jstorm.container.cgroup.core.CpusetCore; import com.alibaba.jstorm.container.cgroup.core.DevicesCore; import com.alibaba.jstorm.container.cgroup.core.FreezerCore; import com.alibaba.jstorm.container.cgroup.core.MemoryCore; import com.alibaba.jstorm.container.cgroup.core.NetClsCore; import com.alibaba.jstorm.container.cgroup.core.NetPrioCore; public class CgroupCoreFactory { public static Map<SubSystemType, CgroupCore> getInstance( Set<SubSystemType> types, String dir) { Map<SubSystemType, CgroupCore> result = new HashMap<SubSystemType, CgroupCore>(); for (SubSystemType type : types) { switch (type) { case blkio: result.put(SubSystemType.blkio, new BlkioCore(dir)); break; case cpuacct: result.put(SubSystemType.cpuacct, new CpuacctCore(dir)); break; case cpuset: result.put(SubSystemType.cpuset, new CpusetCore(dir)); break; case cpu: result.put(SubSystemType.cpu, new CpuCore(dir)); break; case devices: result.put(SubSystemType.devices, new DevicesCore(dir)); break; case freezer: result.put(SubSystemType.freezer, new FreezerCore(dir)); break; case memory: result.put(SubSystemType.memory, new MemoryCore(dir)); break; case net_cls: result.put(SubSystemType.net_cls, new NetClsCore(dir)); break; case net_prio: result.put(SubSystemType.net_prio, new NetPrioCore(dir)); break; default: break; } } return result; } }
yangcwGIT/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/container/cgroup/CgroupCoreFactory.java
Java
apache-2.0
3,072
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.rest; import org.camunda.bpm.engine.rest.dto.CountResultDto; import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationCheckResultDto; import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationCreateDto; import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationDto; import org.camunda.bpm.engine.rest.sub.authorization.AuthorizationResource; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import java.util.List; /** * @author Daniel Meyer * */ @Produces(MediaType.APPLICATION_JSON) public interface AuthorizationRestService { public static final String PATH = "/authorization"; @GET @Path("/check") @Produces(MediaType.APPLICATION_JSON) AuthorizationCheckResultDto isUserAuthorized( @QueryParam("permissionName") String permissionName, @QueryParam("resourceName") String resourceName, @QueryParam("resourceType") Integer resourceType, @QueryParam("resourceId") String resourceId); @Path("/{id}") AuthorizationResource getAuthorization(@PathParam("id") String id); @GET @Produces(MediaType.APPLICATION_JSON) List<AuthorizationDto> queryAuthorizations(@Context UriInfo uriInfo, @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) CountResultDto getAuthorizationCount(@Context UriInfo uriInfo); @POST @Path("/create") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) AuthorizationDto createAuthorization(@Context UriInfo context, AuthorizationCreateDto dto); @OPTIONS @Produces(MediaType.APPLICATION_JSON) ResourceOptionsDto availableOperations(@Context UriInfo context); }
rainerh/camunda-bpm-platform
engine-rest/src/main/java/org/camunda/bpm/engine/rest/AuthorizationRestService.java
Java
apache-2.0
2,439
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.qpid.proton.codec.messaging; import java.util.AbstractList; import java.util.Date; import java.util.List; import org.apache.qpid.proton.amqp.Binary; import org.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.UnsignedInteger; import org.apache.qpid.proton.amqp.UnsignedLong; import org.apache.qpid.proton.amqp.messaging.Properties; import org.apache.qpid.proton.codec.AbstractDescribedType; import org.apache.qpid.proton.codec.Decoder; import org.apache.qpid.proton.codec.DescribedTypeConstructor; import org.apache.qpid.proton.codec.EncoderImpl; public class PropertiesType extends AbstractDescribedType<Properties,List> implements DescribedTypeConstructor<Properties> { private static final Object[] DESCRIPTORS = { UnsignedLong.valueOf(0x0000000000000073L), Symbol.valueOf("amqp:properties:list"), }; private static final UnsignedLong DESCRIPTOR = UnsignedLong.valueOf(0x0000000000000073L); private PropertiesType(EncoderImpl encoder) { super(encoder); } public UnsignedLong getDescriptor() { return DESCRIPTOR; } @Override protected List wrap(Properties val) { return new PropertiesWrapper(val); } private static final class PropertiesWrapper extends AbstractList { private Properties _impl; public PropertiesWrapper(Properties propertiesType) { _impl = propertiesType; } public Object get(final int index) { switch(index) { case 0: return _impl.getMessageId(); case 1: return _impl.getUserId(); case 2: return _impl.getTo(); case 3: return _impl.getSubject(); case 4: return _impl.getReplyTo(); case 5: return _impl.getCorrelationId(); case 6: return _impl.getContentType(); case 7: return _impl.getContentEncoding(); case 8: return _impl.getAbsoluteExpiryTime(); case 9: return _impl.getCreationTime(); case 10: return _impl.getGroupId(); case 11: return _impl.getGroupSequence(); case 12: return _impl.getReplyToGroupId(); } throw new IllegalStateException("Unknown index " + index); } public int size() { return _impl.getReplyToGroupId() != null ? 13 : _impl.getGroupSequence() != null ? 12 : _impl.getGroupId() != null ? 11 : _impl.getCreationTime() != null ? 10 : _impl.getAbsoluteExpiryTime() != null ? 9 : _impl.getContentEncoding() != null ? 8 : _impl.getContentType() != null ? 7 : _impl.getCorrelationId() != null ? 6 : _impl.getReplyTo() != null ? 5 : _impl.getSubject() != null ? 4 : _impl.getTo() != null ? 3 : _impl.getUserId() != null ? 2 : _impl.getMessageId() != null ? 1 : 0; } } public Properties newInstance(Object described) { List l = (List) described; Properties o = new Properties(); switch(13 - l.size()) { case 0: o.setReplyToGroupId( (String) l.get( 12 ) ); case 1: o.setGroupSequence( (UnsignedInteger) l.get( 11 ) ); case 2: o.setGroupId( (String) l.get( 10 ) ); case 3: o.setCreationTime( (Date) l.get( 9 ) ); case 4: o.setAbsoluteExpiryTime( (Date) l.get( 8 ) ); case 5: o.setContentEncoding( (Symbol) l.get( 7 ) ); case 6: o.setContentType( (Symbol) l.get( 6 ) ); case 7: o.setCorrelationId( (Object) l.get( 5 ) ); case 8: o.setReplyTo( (String) l.get( 4 ) ); case 9: o.setSubject( (String) l.get( 3 ) ); case 10: o.setTo( (String) l.get( 2 ) ); case 11: o.setUserId( (Binary) l.get( 1 ) ); case 12: o.setMessageId( (Object) l.get( 0 ) ); } return o; } public Class<Properties> getTypeClass() { return Properties.class; } public static void register(Decoder decoder, EncoderImpl encoder) { PropertiesType type = new PropertiesType(encoder); for(Object descriptor : DESCRIPTORS) { decoder.register(descriptor, type); } encoder.register(type); } }
mbroadst/debian-qpid-cpp-old
proton-j/src/main/java/org/apache/qpid/proton/codec/messaging/PropertiesType.java
Java
apache-2.0
6,304
package automation // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "net/http" ) // ConnectionClient is the automation Client type ConnectionClient struct { BaseClient } // NewConnectionClient creates an instance of the ConnectionClient client. func NewConnectionClient(subscriptionID string, resourceGroupName string, clientRequestID string, automationAccountName string) ConnectionClient { return NewConnectionClientWithBaseURI(DefaultBaseURI, subscriptionID, resourceGroupName, clientRequestID, automationAccountName) } // NewConnectionClientWithBaseURI creates an instance of the ConnectionClient client. func NewConnectionClientWithBaseURI(baseURI string, subscriptionID string, resourceGroupName string, clientRequestID string, automationAccountName string) ConnectionClient { return ConnectionClient{NewWithBaseURI(baseURI, subscriptionID, resourceGroupName, clientRequestID, automationAccountName)} } // CreateOrUpdate create or update a connection. // // automationAccountName is the automation account name. connectionName is the parameters supplied to the create or // update connection operation. parameters is the parameters supplied to the create or update connection operation. func (client ConnectionClient) CreateOrUpdate(ctx context.Context, automationAccountName string, connectionName string, parameters ConnectionCreateOrUpdateParameters) (result Connection, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: client.ResourceGroupName, Constraints: []validation.Constraint{{Target: "client.ResourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.Name", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.ConnectionCreateOrUpdateProperties", Name: validation.Null, Rule: true, Chain: []validation.Constraint{{Target: "parameters.ConnectionCreateOrUpdateProperties.ConnectionType", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { return result, validation.NewError("automation.ConnectionClient", "CreateOrUpdate", err.Error()) } req, err := client.CreateOrUpdatePreparer(ctx, automationAccountName, connectionName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "CreateOrUpdate", nil, "Failure preparing request") return } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "CreateOrUpdate", resp, "Failure sending request") return } result, err = client.CreateOrUpdateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client ConnectionClient) CreateOrUpdatePreparer(ctx context.Context, automationAccountName string, connectionName string, parameters ConnectionCreateOrUpdateParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "automationAccountName": autorest.Encode("path", automationAccountName), "connectionName": autorest.Encode("path", connectionName), "resourceGroupName": autorest.Encode("path", client.ResourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-10-31" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connections/{connectionName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client ConnectionClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client ConnectionClient) CreateOrUpdateResponder(resp *http.Response) (result Connection, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete delete the connection. // // automationAccountName is the automation account name. connectionName is the name of connection. func (client ConnectionClient) Delete(ctx context.Context, automationAccountName string, connectionName string) (result Connection, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: client.ResourceGroupName, Constraints: []validation.Constraint{{Target: "client.ResourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("automation.ConnectionClient", "Delete", err.Error()) } req, err := client.DeletePreparer(ctx, automationAccountName, connectionName) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Delete", nil, "Failure preparing request") return } resp, err := client.DeleteSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Delete", resp, "Failure sending request") return } result, err = client.DeleteResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. func (client ConnectionClient) DeletePreparer(ctx context.Context, automationAccountName string, connectionName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "automationAccountName": autorest.Encode("path", automationAccountName), "connectionName": autorest.Encode("path", connectionName), "resourceGroupName": autorest.Encode("path", client.ResourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-10-31" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connections/{connectionName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client ConnectionClient) DeleteSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client ConnectionClient) DeleteResponder(resp *http.Response) (result Connection, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Get retrieve the connection identified by connection name. // // automationAccountName is the automation account name. connectionName is the name of connection. func (client ConnectionClient) Get(ctx context.Context, automationAccountName string, connectionName string) (result Connection, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: client.ResourceGroupName, Constraints: []validation.Constraint{{Target: "client.ResourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("automation.ConnectionClient", "Get", err.Error()) } req, err := client.GetPreparer(ctx, automationAccountName, connectionName) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client ConnectionClient) GetPreparer(ctx context.Context, automationAccountName string, connectionName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "automationAccountName": autorest.Encode("path", automationAccountName), "connectionName": autorest.Encode("path", connectionName), "resourceGroupName": autorest.Encode("path", client.ResourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-10-31" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connections/{connectionName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ConnectionClient) GetSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client ConnectionClient) GetResponder(resp *http.Response) (result Connection, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ListByAutomationAccount retrieve a list of connections. // // automationAccountName is the automation account name. func (client ConnectionClient) ListByAutomationAccount(ctx context.Context, automationAccountName string) (result ConnectionListResultPage, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: client.ResourceGroupName, Constraints: []validation.Constraint{{Target: "client.ResourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("automation.ConnectionClient", "ListByAutomationAccount", err.Error()) } result.fn = client.listByAutomationAccountNextResults req, err := client.ListByAutomationAccountPreparer(ctx, automationAccountName) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "ListByAutomationAccount", nil, "Failure preparing request") return } resp, err := client.ListByAutomationAccountSender(req) if err != nil { result.clr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "ListByAutomationAccount", resp, "Failure sending request") return } result.clr, err = client.ListByAutomationAccountResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "ListByAutomationAccount", resp, "Failure responding to request") } return } // ListByAutomationAccountPreparer prepares the ListByAutomationAccount request. func (client ConnectionClient) ListByAutomationAccountPreparer(ctx context.Context, automationAccountName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "automationAccountName": autorest.Encode("path", automationAccountName), "resourceGroupName": autorest.Encode("path", client.ResourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-10-31" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connections", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListByAutomationAccountSender sends the ListByAutomationAccount request. The method will close the // http.Response Body if it receives an error. func (client ConnectionClient) ListByAutomationAccountSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // ListByAutomationAccountResponder handles the response to the ListByAutomationAccount request. The method always // closes the http.Response Body. func (client ConnectionClient) ListByAutomationAccountResponder(resp *http.Response) (result ConnectionListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listByAutomationAccountNextResults retrieves the next set of results, if any. func (client ConnectionClient) listByAutomationAccountNextResults(lastResults ConnectionListResult) (result ConnectionListResult, err error) { req, err := lastResults.connectionListResultPreparer() if err != nil { return result, autorest.NewErrorWithError(err, "automation.ConnectionClient", "listByAutomationAccountNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListByAutomationAccountSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "automation.ConnectionClient", "listByAutomationAccountNextResults", resp, "Failure sending next results request") } result, err = client.ListByAutomationAccountResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "listByAutomationAccountNextResults", resp, "Failure responding to next results request") } return } // ListByAutomationAccountComplete enumerates all values, automatically crossing page boundaries as required. func (client ConnectionClient) ListByAutomationAccountComplete(ctx context.Context, automationAccountName string) (result ConnectionListResultIterator, err error) { result.page, err = client.ListByAutomationAccount(ctx, automationAccountName) return } // Update update a connection. // // automationAccountName is the automation account name. connectionName is the parameters supplied to the update a // connection operation. parameters is the parameters supplied to the update a connection operation. func (client ConnectionClient) Update(ctx context.Context, automationAccountName string, connectionName string, parameters ConnectionUpdateParameters) (result Connection, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: client.ResourceGroupName, Constraints: []validation.Constraint{{Target: "client.ResourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("automation.ConnectionClient", "Update", err.Error()) } req, err := client.UpdatePreparer(ctx, automationAccountName, connectionName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Update", nil, "Failure preparing request") return } resp, err := client.UpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Update", resp, "Failure sending request") return } result, err = client.UpdateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Update", resp, "Failure responding to request") } return } // UpdatePreparer prepares the Update request. func (client ConnectionClient) UpdatePreparer(ctx context.Context, automationAccountName string, connectionName string, parameters ConnectionUpdateParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "automationAccountName": autorest.Encode("path", automationAccountName), "connectionName": autorest.Encode("path", connectionName), "resourceGroupName": autorest.Encode("path", client.ResourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-10-31" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsJSON(), autorest.AsPatch(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connections/{connectionName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client ConnectionClient) UpdateSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // UpdateResponder handles the response to the Update request. The method always // closes the http.Response Body. func (client ConnectionClient) UpdateResponder(resp *http.Response) (result Connection, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
childsb/origin
vendor/github.com/Azure/azure-sdk-for-go/services/automation/mgmt/2017-05-15-preview/connection.go
GO
apache-2.0
20,113
package org.newdawn.slick.geom; import org.newdawn.slick.Image; import org.newdawn.slick.ShapeFill; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureImpl; import org.newdawn.slick.opengl.renderer.LineStripRenderer; import org.newdawn.slick.opengl.renderer.Renderer; import org.newdawn.slick.opengl.renderer.SGL; /** * @author Mark Bernard * * Use this class to render shpaes directly to OpenGL. Allows you to bypass the Graphics class. */ public final class ShapeRenderer { /** The renderer to use for all GL operations */ private static SGL GL = Renderer.get(); /** The renderer to use line strips */ private static LineStripRenderer LSR = Renderer.getLineStripRenderer(); /** * Draw the outline of the given shape. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to draw. */ public static final void draw(Shape shape) { Texture t = TextureImpl.getLastBind(); TextureImpl.bindNone(); float points[] = shape.getPoints(); LSR.start(); for(int i=0;i<points.length;i+=2) { LSR.vertex(points[i], points[i + 1]); } if (shape.closed()) { LSR.vertex(points[0], points[1]); } LSR.end(); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Draw the outline of the given shape. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to draw. * @param fill The fill to apply */ public static final void draw(Shape shape, ShapeFill fill) { float points[] = shape.getPoints(); Texture t = TextureImpl.getLastBind(); TextureImpl.bindNone(); float center[] = shape.getCenter(); GL.glBegin(SGL.GL_LINE_STRIP); for(int i=0;i<points.length;i+=2) { fill.colorAt(shape, points[i], points[i + 1]).bind(); Vector2f offset = fill.getOffsetAt(shape, points[i], points[i + 1]); GL.glVertex2f(points[i] + offset.x, points[i + 1] + offset.y); } if (shape.closed()) { fill.colorAt(shape, points[0], points[1]).bind(); Vector2f offset = fill.getOffsetAt(shape, points[0], points[1]); GL.glVertex2f(points[0] + offset.x, points[1] + offset.y); } GL.glEnd(); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Check there are enough points to fill * * @param shape THe shape we're drawing * @return True if the fill is valid */ public static boolean validFill(Shape shape) { if (shape.getTriangles() == null) { return false; } return shape.getTriangles().getTriangleCount() != 0; } /** * Draw the the given shape filled in. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to fill. */ public static final void fill(Shape shape) { if (!validFill(shape)) { return; } Texture t = TextureImpl.getLastBind(); TextureImpl.bindNone(); fill(shape, new PointCallback() { public float[] preRenderPoint(Shape shape, float x, float y) { // do nothing, we're just filling the shape this time return null; } }); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Draw the the given shape filled in. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to fill. * @param callback The callback that will be invoked for each shape point */ private static final void fill(Shape shape, PointCallback callback) { Triangulator tris = shape.getTriangles(); GL.glBegin(SGL.GL_TRIANGLES); for (int i=0;i<tris.getTriangleCount();i++) { for (int p=0;p<3;p++) { float[] pt = tris.getTrianglePoint(i, p); float[] np = callback.preRenderPoint(shape, pt[0],pt[1]); if (np == null) { GL.glVertex2f(pt[0],pt[1]); } else { GL.glVertex2f(np[0],np[1]); } } } GL.glEnd(); } /** * Draw the the given shape filled in with a texture. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to texture. * @param image The image to tile across the shape */ public static final void texture(Shape shape, Image image) { texture(shape, image, 0.01f, 0.01f); } /** * Draw the the given shape filled in with a texture. Only the vertices are set. * The colour has to be set independently of this method. This method is required to * fit the texture once across the shape. * * @param shape The shape to texture. * @param image The image to tile across the shape */ public static final void textureFit(Shape shape, Image image) { textureFit(shape, image,1f,1f); } /** * Draw the the given shape filled in with a texture. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to texture. * @param image The image to tile across the shape * @param scaleX The scale to apply on the x axis for texturing * @param scaleY The scale to apply on the y axis for texturing */ public static final void texture(Shape shape, final Image image, final float scaleX, final float scaleY) { if (!validFill(shape)) { return; } final Texture t = TextureImpl.getLastBind(); image.getTexture().bind(); fill(shape, new PointCallback() { public float[] preRenderPoint(Shape shape, float x, float y) { float tx = x * scaleX; float ty = y * scaleY; tx = image.getTextureOffsetX() + (image.getTextureWidth() * tx); ty = image.getTextureOffsetY() + (image.getTextureHeight() * ty); GL.glTexCoord2f(tx, ty); return null; } }); float points[] = shape.getPoints(); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Draw the the given shape filled in with a texture. Only the vertices are set. * The colour has to be set independently of this method. This method is required to * fit the texture scaleX times across the shape and scaleY times down the shape. * * @param shape The shape to texture. * @param image The image to tile across the shape * @param scaleX The scale to apply on the x axis for texturing * @param scaleY The scale to apply on the y axis for texturing */ public static final void textureFit(Shape shape, final Image image, final float scaleX, final float scaleY) { if (!validFill(shape)) { return; } float points[] = shape.getPoints(); Texture t = TextureImpl.getLastBind(); image.getTexture().bind(); final float minX = shape.getX(); final float minY = shape.getY(); final float maxX = shape.getMaxX() - minX; final float maxY = shape.getMaxY() - minY; fill(shape, new PointCallback() { public float[] preRenderPoint(Shape shape, float x, float y) { x -= shape.getMinX(); y -= shape.getMinY(); x /= (shape.getMaxX() - shape.getMinX()); y /= (shape.getMaxY() - shape.getMinY()); float tx = x * scaleX; float ty = y * scaleY; tx = image.getTextureOffsetX() + (image.getTextureWidth() * tx); ty = image.getTextureOffsetY() + (image.getTextureHeight() * ty); GL.glTexCoord2f(tx, ty); return null; } }); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Draw the the given shape filled in. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to fill. * @param fill The fill to apply */ public static final void fill(final Shape shape, final ShapeFill fill) { if (!validFill(shape)) { return; } Texture t = TextureImpl.getLastBind(); TextureImpl.bindNone(); final float center[] = shape.getCenter(); fill(shape, new PointCallback() { public float[] preRenderPoint(Shape shape, float x, float y) { fill.colorAt(shape, x, y).bind(); Vector2f offset = fill.getOffsetAt(shape, x, y); return new float[] {offset.x + x,offset.y + y}; } }); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Draw the the given shape filled in with a texture. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to texture. * @param image The image to tile across the shape * @param scaleX The scale to apply on the x axis for texturing * @param scaleY The scale to apply on the y axis for texturing * @param fill The fill to apply */ public static final void texture(final Shape shape, final Image image, final float scaleX, final float scaleY, final ShapeFill fill) { if (!validFill(shape)) { return; } Texture t = TextureImpl.getLastBind(); image.getTexture().bind(); final float center[] = shape.getCenter(); fill(shape, new PointCallback() { public float[] preRenderPoint(Shape shape, float x, float y) { fill.colorAt(shape, x - center[0], y - center[1]).bind(); Vector2f offset = fill.getOffsetAt(shape, x, y); x += offset.x; y += offset.y; float tx = x * scaleX; float ty = y * scaleY; tx = image.getTextureOffsetX() + (image.getTextureWidth() * tx); ty = image.getTextureOffsetY() + (image.getTextureHeight() * ty); GL.glTexCoord2f(tx, ty); return new float[] {offset.x + x,offset.y + y}; } }); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Draw the the given shape filled in with a texture. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to texture. * @param image The image to tile across the shape * @param gen The texture coordinate generator to create coordiantes for the shape */ public static final void texture(final Shape shape, Image image, final TexCoordGenerator gen) { Texture t = TextureImpl.getLastBind(); image.getTexture().bind(); final float center[] = shape.getCenter(); fill(shape, new PointCallback() { public float[] preRenderPoint(Shape shape, float x, float y) { Vector2f tex = gen.getCoordFor(x, y); GL.glTexCoord2f(tex.x, tex.y); return new float[] {x,y}; } }); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Description of some feature that will be applied to each point render * * @author kevin */ private static interface PointCallback { /** * Apply feature before the call to glVertex * * @param shape The shape the point belongs to * @param x The x poisiton the vertex will be at * @param y The y position the vertex will be at * @return The new coordinates of null */ float[] preRenderPoint(Shape shape, float x, float y); } }
TomyLobo/Slick
src/main/java/org/newdawn/slick/geom/ShapeRenderer.java
Java
bsd-3-clause
12,251
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <mutex> // template <class Mutex> class unique_lock; // explicit unique_lock(mutex_type& m); #include <mutex> #include <thread> #include <cstdlib> #include <cassert> std::mutex m; typedef std::chrono::system_clock Clock; typedef Clock::time_point time_point; typedef Clock::duration duration; typedef std::chrono::milliseconds ms; typedef std::chrono::nanoseconds ns; void f() { time_point t0 = Clock::now(); time_point t1; { std::unique_lock<std::mutex> ul(m); t1 = Clock::now(); } ns d = t1 - t0 - ms(250); assert(d < ms(50)); // within 50ms } int main() { m.lock(); std::thread t(f); std::this_thread::sleep_for(ms(250)); m.unlock(); t.join(); }
mxOBS/deb-pkg_trusty_chromium-browser
third_party/libc++/trunk/test/thread/thread.mutex/thread.lock/thread.lock.unique/thread.lock.unique.cons/mutex.pass.cpp
C++
bsd-3-clause
1,069
// Copyright 2009 the Sputnik authors. All rights reserved. /** * Operator x ? y : z uses GetValue * * @path ch11/11.12/S11.12_A2.1_T3.js * @description If ToBoolean(x) is true and GetBase(y) is null, throw ReferenceError */ //CHECK#1 try { true ? y : false; $ERROR('#1.1: true ? y : false throw ReferenceError. Actual: ' + (true ? y : false)); } catch (e) { if ((e instanceof ReferenceError) !== true) { $ERROR('#1.2: true ? y : false throw ReferenceError. Actual: ' + (e)); } }
Oceanswave/NiL.JS
Tests/tests/sputnik/ch11/11.12/S11.12_A2.1_T3.js
JavaScript
bsd-3-clause
504
/** * sp-pnp-js v2.0.6-beta.1 - A JavaScript library for SharePoint development. * MIT (https://github.com/SharePoint/PnP-JS-Core/blob/master/LICENSE) * Copyright (c) 2017 Microsoft * docs: http://officedev.github.io/PnP-JS-Core * source: https://github.com/SharePoint/PnP-JS-Core * bugs: https://github.com/SharePoint/PnP-JS-Core/issues */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["$pnp"] = factory(); else root["$pnp"] = factory(); })(this, function() { return /******/ (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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/assets/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 41); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { Object.defineProperty(exports, "__esModule", { value: true }); var pnplibconfig_1 = __webpack_require__(4); var Util = (function () { function Util() { } /** * Gets a callback function which will maintain context across async calls. * Allows for the calling pattern getCtxCallback(thisobj, method, methodarg1, methodarg2, ...) * * @param context The object that will be the 'this' value in the callback * @param method The method to which we will apply the context and parameters * @param params Optional, additional arguments to supply to the wrapped method when it is invoked */ Util.getCtxCallback = function (context, method) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } return function () { method.apply(context, params); }; }; /** * Tests if a url param exists * * @param name The name of the url paramter to check */ Util.urlParamExists = function (name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); return regex.test(location.search); }; /** * Gets a url param value by name * * @param name The name of the paramter for which we want the value */ Util.getUrlParamByName = function (name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); var results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); }; /** * Gets a url param by name and attempts to parse a bool value * * @param name The name of the paramter for which we want the boolean value */ Util.getUrlParamBoolByName = function (name) { var p = this.getUrlParamByName(name); var isFalse = (p === "" || /false|0/i.test(p)); return !isFalse; }; /** * Inserts the string s into the string target as the index specified by index * * @param target The string into which we will insert s * @param index The location in target to insert s (zero based) * @param s The string to insert into target at position index */ Util.stringInsert = function (target, index, s) { if (index > 0) { return target.substring(0, index) + s + target.substring(index, target.length); } return s + target; }; /** * Adds a value to a date * * @param date The date to which we will add units, done in local time * @param interval The name of the interval to add, one of: ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'] * @param units The amount to add to date of the given interval * * http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object */ Util.dateAdd = function (date, interval, units) { var ret = new Date(date.toLocaleString()); // don't change original date switch (interval.toLowerCase()) { case "year": ret.setFullYear(ret.getFullYear() + units); break; case "quarter": ret.setMonth(ret.getMonth() + 3 * units); break; case "month": ret.setMonth(ret.getMonth() + units); break; case "week": ret.setDate(ret.getDate() + 7 * units); break; case "day": ret.setDate(ret.getDate() + units); break; case "hour": ret.setTime(ret.getTime() + units * 3600000); break; case "minute": ret.setTime(ret.getTime() + units * 60000); break; case "second": ret.setTime(ret.getTime() + units * 1000); break; default: ret = undefined; break; } return ret; }; /** * Loads a stylesheet into the current page * * @param path The url to the stylesheet * @param avoidCache If true a value will be appended as a query string to avoid browser caching issues */ Util.loadStylesheet = function (path, avoidCache) { if (avoidCache) { path += "?" + encodeURIComponent((new Date()).getTime().toString()); } var head = document.getElementsByTagName("head"); if (head.length > 0) { var e = document.createElement("link"); head[0].appendChild(e); e.setAttribute("type", "text/css"); e.setAttribute("rel", "stylesheet"); e.setAttribute("href", path); } }; /** * Combines an arbitrary set of paths ensuring that the slashes are normalized * * @param paths 0 to n path parts to combine */ Util.combinePaths = function () { var paths = []; for (var _i = 0; _i < arguments.length; _i++) { paths[_i] = arguments[_i]; } return paths .filter(function (path) { return !Util.stringIsNullOrEmpty(path); }) .map(function (path) { return path.replace(/^[\\|\/]/, "").replace(/[\\|\/]$/, ""); }) .join("/") .replace(/\\/g, "/"); }; /** * Gets a random string of chars length * * @param chars The length of the random string to generate */ Util.getRandomString = function (chars) { var text = new Array(chars); var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < chars; i++) { text[i] = possible.charAt(Math.floor(Math.random() * possible.length)); } return text.join(""); }; /** * Gets a random GUID value * * http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript */ /* tslint:disable no-bitwise */ Util.getGUID = function () { var d = new Date().getTime(); var guid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16); }); return guid; }; /* tslint:enable */ /** * Determines if a given value is a function * * @param candidateFunction The thing to test for being a function */ Util.isFunction = function (candidateFunction) { return typeof candidateFunction === "function"; }; /** * @returns whether the provided parameter is a JavaScript Array or not. */ Util.isArray = function (array) { if (Array.isArray) { return Array.isArray(array); } return array && typeof array.length === "number" && array.constructor === Array; }; /** * Determines if a string is null or empty or undefined * * @param s The string to test */ Util.stringIsNullOrEmpty = function (s) { return typeof s === "undefined" || s === null || s.length < 1; }; /** * Provides functionality to extend the given object by doing a shallow copy * * @param target The object to which properties will be copied * @param source The source object from which properties will be copied * @param noOverwrite If true existing properties on the target are not overwritten from the source * */ Util.extend = function (target, source, noOverwrite) { if (noOverwrite === void 0) { noOverwrite = false; } if (source === null || typeof source === "undefined") { return target; } // ensure we don't overwrite things we don't want overwritten var check = noOverwrite ? function (o, i) { return !(i in o); } : function () { return true; }; return Object.getOwnPropertyNames(source) .filter(function (v) { return check(target, v); }) .reduce(function (t, v) { t[v] = source[v]; return t; }, target); }; /** * Determines if a given url is absolute * * @param url The url to check to see if it is absolute */ Util.isUrlAbsolute = function (url) { return /^https?:\/\/|^\/\//i.test(url); }; /** * Ensures that a given url is absolute for the current web based on context * * @param candidateUrl The url to make absolute * */ Util.toAbsoluteUrl = function (candidateUrl) { return new Promise(function (resolve) { if (Util.isUrlAbsolute(candidateUrl)) { // if we are already absolute, then just return the url return resolve(candidateUrl); } if (pnplibconfig_1.RuntimeConfig.baseUrl !== null) { // base url specified either with baseUrl of spfxContext config property return resolve(Util.combinePaths(pnplibconfig_1.RuntimeConfig.baseUrl, candidateUrl)); } if (typeof global._spPageContextInfo !== "undefined") { // operating in classic pages if (global._spPageContextInfo.hasOwnProperty("webAbsoluteUrl")) { return resolve(Util.combinePaths(global._spPageContextInfo.webAbsoluteUrl, candidateUrl)); } else if (global._spPageContextInfo.hasOwnProperty("webServerRelativeUrl")) { return resolve(Util.combinePaths(global._spPageContextInfo.webServerRelativeUrl, candidateUrl)); } } // does window.location exist and have _layouts in it? if (typeof global.location !== "undefined") { var index = global.location.toString().toLowerCase().indexOf("/_layouts/"); if (index > 0) { // we are likely in the workbench in /_layouts/ return resolve(Util.combinePaths(global.location.toString().substr(0, index), candidateUrl)); } } return resolve(candidateUrl); }); }; return Util; }()); exports.Util = Util; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32))) /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var collections_1 = __webpack_require__(6); var odata_1 = __webpack_require__(2); var pnplibconfig_1 = __webpack_require__(4); var exceptions_1 = __webpack_require__(3); var logging_1 = __webpack_require__(5); var pipeline_1 = __webpack_require__(45); /** * Queryable Base Class * */ var Queryable = (function () { /** * Creates a new instance of the Queryable class * * @constructor * @param baseUrl A string or Queryable that should form the base part of the url * */ function Queryable(baseUrl, path) { this._query = new collections_1.Dictionary(); this._batch = null; if (typeof baseUrl === "string") { // we need to do some extra parsing to get the parent url correct if we are // being created from just a string. var urlStr = baseUrl; if (util_1.Util.isUrlAbsolute(urlStr) || urlStr.lastIndexOf("/") < 0) { this._parentUrl = urlStr; this._url = util_1.Util.combinePaths(urlStr, path); } else if (urlStr.lastIndexOf("/") > urlStr.lastIndexOf("(")) { // .../items(19)/fields var index = urlStr.lastIndexOf("/"); this._parentUrl = urlStr.slice(0, index); path = util_1.Util.combinePaths(urlStr.slice(index), path); this._url = util_1.Util.combinePaths(this._parentUrl, path); } else { // .../items(19) var index = urlStr.lastIndexOf("("); this._parentUrl = urlStr.slice(0, index); this._url = util_1.Util.combinePaths(urlStr, path); } } else { var q = baseUrl; this._parentUrl = q._url; var target = q._query.get("@target"); if (target !== null) { this._query.add("@target", target); } this._url = util_1.Util.combinePaths(this._parentUrl, path); } } /** * Directly concatonates the supplied string to the current url, not normalizing "/" chars * * @param pathPart The string to concatonate to the url */ Queryable.prototype.concat = function (pathPart) { this._url += pathPart; return this; }; /** * Appends the given string and normalizes "/" chars * * @param pathPart The string to append */ Queryable.prototype.append = function (pathPart) { this._url = util_1.Util.combinePaths(this._url, pathPart); }; /** * Blocks a batch call from occuring, MUST be cleared by calling the returned function */ Queryable.prototype.addBatchDependency = function () { if (this.hasBatch) { return this._batch.addDependency(); } return function () { return null; }; }; Object.defineProperty(Queryable.prototype, "hasBatch", { /** * Indicates if the current query has a batch associated * */ get: function () { return this._batch !== null; }, enumerable: true, configurable: true }); Object.defineProperty(Queryable.prototype, "batch", { /** * The batch currently associated with this query or null * */ get: function () { return this.hasBatch ? this._batch : null; }, enumerable: true, configurable: true }); Object.defineProperty(Queryable.prototype, "parentUrl", { /** * Gets the parent url used when creating this instance * */ get: function () { return this._parentUrl; }, enumerable: true, configurable: true }); Object.defineProperty(Queryable.prototype, "query", { /** * Provides access to the query builder for this url * */ get: function () { return this._query; }, enumerable: true, configurable: true }); /** * Creates a new instance of the supplied factory and extends this into that new instance * * @param factory constructor for the new queryable */ Queryable.prototype.as = function (factory) { var o = new factory(this._url, null); return util_1.Util.extend(o, this, true); }; /** * Adds this query to the supplied batch * * @example * ``` * * let b = pnp.sp.createBatch(); * pnp.sp.web.inBatch(b).get().then(...); * b.execute().then(...) * ``` */ Queryable.prototype.inBatch = function (batch) { if (this._batch !== null) { throw new exceptions_1.AlreadyInBatchException(); } this._batch = batch; return this; }; /** * Enables caching for this request * * @param options Defines the options used when caching this request */ Queryable.prototype.usingCaching = function (options) { if (!pnplibconfig_1.RuntimeConfig.globalCacheDisable) { this._useCaching = true; this._cachingOptions = options; } return this; }; /** * Gets the currentl url, made absolute based on the availability of the _spPageContextInfo object * */ Queryable.prototype.toUrl = function () { return this._url; }; /** * Gets the full url with query information * */ Queryable.prototype.toUrlAndQuery = function () { var aliasedParams = new collections_1.Dictionary(); var url = this.toUrl().replace(/'!(@.*?)::(.*?)'/ig, function (match, labelName, value) { logging_1.Logger.write("Rewriting aliased parameter from match " + match + " to label: " + labelName + " value: " + value, logging_1.LogLevel.Verbose); aliasedParams.add(labelName, "'" + value + "'"); return labelName; }); // inlude our explicitly set query string params aliasedParams.merge(this._query); if (aliasedParams.count() > 0) { url += "?" + aliasedParams.getKeys().map(function (key) { return key + "=" + aliasedParams.get(key); }).join("&"); } return url; }; /** * Gets a parent for this instance as specified * * @param factory The contructor for the class to create */ Queryable.prototype.getParent = function (factory, baseUrl, path, batch) { if (baseUrl === void 0) { baseUrl = this.parentUrl; } var parent = new factory(baseUrl, path); var target = this.query.get("@target"); if (target !== null) { parent.query.add("@target", target); } if (typeof batch !== "undefined") { parent = parent.inBatch(batch); } return parent; }; /** * Clones this queryable into a new queryable instance of T * @param factory Constructor used to create the new instance * @param additionalPath Any additional path to include in the clone * @param includeBatch If true this instance's batch will be added to the cloned instance */ Queryable.prototype.clone = function (factory, additionalPath, includeBatch) { if (includeBatch === void 0) { includeBatch = false; } var clone = new factory(this, additionalPath); var target = this.query.get("@target"); if (target !== null) { clone.query.add("@target", target); } if (includeBatch && this.hasBatch) { clone = clone.inBatch(this.batch); } return clone; }; /** * Executes the currently built request * * @param parser Allows you to specify a parser to handle the result * @param getOptions The options used for this request */ Queryable.prototype.get = function (parser, getOptions) { if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } if (getOptions === void 0) { getOptions = {}; } return this.toRequestContext("GET", getOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.getAs = function (parser, getOptions) { if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } if (getOptions === void 0) { getOptions = {}; } return this.toRequestContext("GET", getOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.post = function (postOptions, parser) { if (postOptions === void 0) { postOptions = {}; } if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } return this.toRequestContext("POST", postOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.postAs = function (postOptions, parser) { if (postOptions === void 0) { postOptions = {}; } if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } return this.toRequestContext("POST", postOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.patch = function (patchOptions, parser) { if (patchOptions === void 0) { patchOptions = {}; } if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } return this.toRequestContext("PATCH", patchOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.delete = function (deleteOptions, parser) { if (deleteOptions === void 0) { deleteOptions = {}; } if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } return this.toRequestContext("DELETE", deleteOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; /** * Converts the current instance to a request context * * @param verb The request verb * @param options The set of supplied request options * @param parser The supplied ODataParser instance * @param pipeline Optional request processing pipeline */ Queryable.prototype.toRequestContext = function (verb, options, parser, pipeline) { var _this = this; if (options === void 0) { options = {}; } if (pipeline === void 0) { pipeline = pipeline_1.PipelineMethods.default; } var dependencyDispose = this.hasBatch ? this.addBatchDependency() : function () { return; }; return util_1.Util.toAbsoluteUrl(this.toUrlAndQuery()).then(function (url) { // build our request context var context = { batch: _this._batch, batchDependency: dependencyDispose, cachingOptions: _this._cachingOptions, isBatched: _this.hasBatch, isCached: _this._useCaching, options: options, parser: parser, pipeline: pipeline, requestAbsoluteUrl: url, requestId: util_1.Util.getGUID(), verb: verb, }; return context; }); }; return Queryable; }()); exports.Queryable = Queryable; /** * Represents a REST collection which can be filtered, paged, and selected * */ var QueryableCollection = (function (_super) { __extends(QueryableCollection, _super); function QueryableCollection() { return _super !== null && _super.apply(this, arguments) || this; } /** * Filters the returned collection (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#bk_supported) * * @param filter The string representing the filter query */ QueryableCollection.prototype.filter = function (filter) { this._query.add("$filter", filter); return this; }; /** * Choose which fields to return * * @param selects One or more fields to return */ QueryableCollection.prototype.select = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } if (selects.length > 0) { this._query.add("$select", selects.join(",")); } return this; }; /** * Expands fields such as lookups to get additional data * * @param expands The Fields for which to expand the values */ QueryableCollection.prototype.expand = function () { var expands = []; for (var _i = 0; _i < arguments.length; _i++) { expands[_i] = arguments[_i]; } if (expands.length > 0) { this._query.add("$expand", expands.join(",")); } return this; }; /** * Orders based on the supplied fields ascending * * @param orderby The name of the field to sort on * @param ascending If false DESC is appended, otherwise ASC (default) */ QueryableCollection.prototype.orderBy = function (orderBy, ascending) { if (ascending === void 0) { ascending = true; } var keys = this._query.getKeys(); var query = []; var asc = ascending ? " asc" : " desc"; for (var i = 0; i < keys.length; i++) { if (keys[i] === "$orderby") { query.push(this._query.get("$orderby")); break; } } query.push("" + orderBy + asc); this._query.add("$orderby", query.join(",")); return this; }; /** * Skips the specified number of items * * @param skip The number of items to skip */ QueryableCollection.prototype.skip = function (skip) { this._query.add("$skip", skip.toString()); return this; }; /** * Limits the query to only return the specified number of items * * @param top The query row limit */ QueryableCollection.prototype.top = function (top) { this._query.add("$top", top.toString()); return this; }; return QueryableCollection; }(Queryable)); exports.QueryableCollection = QueryableCollection; /** * Represents an instance that can be selected * */ var QueryableInstance = (function (_super) { __extends(QueryableInstance, _super); function QueryableInstance() { return _super !== null && _super.apply(this, arguments) || this; } /** * Choose which fields to return * * @param selects One or more fields to return */ QueryableInstance.prototype.select = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } if (selects.length > 0) { this._query.add("$select", selects.join(",")); } return this; }; /** * Expands fields such as lookups to get additional data * * @param expands The Fields for which to expand the values */ QueryableInstance.prototype.expand = function () { var expands = []; for (var _i = 0; _i < arguments.length; _i++) { expands[_i] = arguments[_i]; } if (expands.length > 0) { this._query.add("$expand", expands.join(",")); } return this; }; return QueryableInstance; }(Queryable)); exports.QueryableInstance = QueryableInstance; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var logging_1 = __webpack_require__(5); var httpclient_1 = __webpack_require__(15); var pnplibconfig_1 = __webpack_require__(4); var exceptions_1 = __webpack_require__(3); var exceptions_2 = __webpack_require__(3); function extractOdataId(candidate) { if (candidate.hasOwnProperty("odata.id")) { return candidate["odata.id"]; } else if (candidate.hasOwnProperty("__metadata") && candidate.__metadata.hasOwnProperty("id")) { return candidate.__metadata.id; } else { throw new exceptions_1.ODataIdException(candidate); } } exports.extractOdataId = extractOdataId; var ODataParserBase = (function () { function ODataParserBase() { } ODataParserBase.prototype.parse = function (r) { var _this = this; return new Promise(function (resolve, reject) { if (_this.handleError(r, reject)) { if ((r.headers.has("Content-Length") && parseFloat(r.headers.get("Content-Length")) === 0) || r.status === 204) { resolve({}); } else { r.json().then(function (json) { return resolve(_this.parseODataJSON(json)); }).catch(function (e) { return reject(e); }); } } }); }; ODataParserBase.prototype.handleError = function (r, reject) { if (!r.ok) { r.json().then(function (json) { // include the headers as they contain diagnostic information var data = { responseBody: json, responseHeaders: r.headers, }; reject(new exceptions_2.ProcessHttpClientResponseException(r.status, r.statusText, data)); }).catch(function (e) { // we failed to read the body - possibly it is empty. Let's report the original status that caused // the request to fail and log the error with parsing the body if anyone needs it for debugging logging_1.Logger.log({ data: e, level: logging_1.LogLevel.Warning, message: "There was an error parsing the error response body. See data for details.", }); // include the headers as they contain diagnostic information var data = { responseBody: "[[body not available]]", responseHeaders: r.headers, }; reject(new exceptions_2.ProcessHttpClientResponseException(r.status, r.statusText, data)); }); } return r.ok; }; ODataParserBase.prototype.parseODataJSON = function (json) { var result = json; if (json.hasOwnProperty("d")) { if (json.d.hasOwnProperty("results")) { result = json.d.results; } else { result = json.d; } } else if (json.hasOwnProperty("value")) { result = json.value; } return result; }; return ODataParserBase; }()); exports.ODataParserBase = ODataParserBase; var ODataDefaultParser = (function (_super) { __extends(ODataDefaultParser, _super); function ODataDefaultParser() { return _super !== null && _super.apply(this, arguments) || this; } return ODataDefaultParser; }(ODataParserBase)); exports.ODataDefaultParser = ODataDefaultParser; var ODataRawParserImpl = (function () { function ODataRawParserImpl() { } ODataRawParserImpl.prototype.parse = function (r) { return r.json(); }; return ODataRawParserImpl; }()); exports.ODataRawParserImpl = ODataRawParserImpl; var ODataValueParserImpl = (function (_super) { __extends(ODataValueParserImpl, _super); function ODataValueParserImpl() { return _super !== null && _super.apply(this, arguments) || this; } ODataValueParserImpl.prototype.parse = function (r) { return _super.prototype.parse.call(this, r).then(function (d) { return d; }); }; return ODataValueParserImpl; }(ODataParserBase)); var ODataEntityParserImpl = (function (_super) { __extends(ODataEntityParserImpl, _super); function ODataEntityParserImpl(factory) { var _this = _super.call(this) || this; _this.factory = factory; return _this; } ODataEntityParserImpl.prototype.parse = function (r) { var _this = this; return _super.prototype.parse.call(this, r).then(function (d) { var o = new _this.factory(getEntityUrl(d), null); return util_1.Util.extend(o, d); }); }; return ODataEntityParserImpl; }(ODataParserBase)); var ODataEntityArrayParserImpl = (function (_super) { __extends(ODataEntityArrayParserImpl, _super); function ODataEntityArrayParserImpl(factory) { var _this = _super.call(this) || this; _this.factory = factory; return _this; } ODataEntityArrayParserImpl.prototype.parse = function (r) { var _this = this; return _super.prototype.parse.call(this, r).then(function (d) { return d.map(function (v) { var o = new _this.factory(getEntityUrl(v), null); return util_1.Util.extend(o, v); }); }); }; return ODataEntityArrayParserImpl; }(ODataParserBase)); function getEntityUrl(entity) { if (entity.hasOwnProperty("odata.editLink")) { // we are dealign with minimal metadata (default) return util_1.Util.combinePaths("_api", entity["odata.editLink"]); } else if (entity.hasOwnProperty("__metadata")) { // we are dealing with verbose, which has an absolute uri return entity.__metadata.uri; } else { // we are likely dealing with nometadata, so don't error but we won't be able to // chain off these objects logging_1.Logger.write("No uri information found in ODataEntity parsing, chaining will fail for this object.", logging_1.LogLevel.Warning); return ""; } } exports.getEntityUrl = getEntityUrl; exports.ODataRaw = new ODataRawParserImpl(); function ODataValue() { return new ODataValueParserImpl(); } exports.ODataValue = ODataValue; function ODataEntity(factory) { return new ODataEntityParserImpl(factory); } exports.ODataEntity = ODataEntity; function ODataEntityArray(factory) { return new ODataEntityArrayParserImpl(factory); } exports.ODataEntityArray = ODataEntityArray; /** * Manages a batch of OData operations */ var ODataBatch = (function () { function ODataBatch(baseUrl, _batchId) { if (_batchId === void 0) { _batchId = util_1.Util.getGUID(); } this.baseUrl = baseUrl; this._batchId = _batchId; this._requests = []; this._dependencies = []; } Object.defineProperty(ODataBatch.prototype, "batchId", { get: function () { return this._batchId; }, enumerable: true, configurable: true }); /** * Adds a request to a batch (not designed for public use) * * @param url The full url of the request * @param method The http method GET, POST, etc * @param options Any options to include in the request * @param parser The parser that will hadle the results of the request */ ODataBatch.prototype.add = function (url, method, options, parser) { var info = { method: method.toUpperCase(), options: options, parser: parser, reject: null, resolve: null, url: url, }; var p = new Promise(function (resolve, reject) { info.resolve = resolve; info.reject = reject; }); this._requests.push(info); return p; }; /** * Adds a dependency insuring that some set of actions will occur before a batch is processed. * MUST be cleared using the returned resolve delegate to allow batches to run */ ODataBatch.prototype.addDependency = function () { var resolver; var promise = new Promise(function (resolve) { resolver = resolve; }); this._dependencies.push(promise); return resolver; }; /** * Execute the current batch and resolve the associated promises * * @returns A promise which will be resolved once all of the batch's child promises have resolved */ ODataBatch.prototype.execute = function () { var _this = this; // we need to check the dependencies twice due to how different engines handle things. // We can get a second set of promises added after the first set resolve return Promise.all(this._dependencies).then(function () { return Promise.all(_this._dependencies); }).then(function () { return _this.executeImpl(); }); }; ODataBatch.prototype.executeImpl = function () { var _this = this; logging_1.Logger.write("[" + this.batchId + "] (" + (new Date()).getTime() + ") Executing batch with " + this._requests.length + " requests.", logging_1.LogLevel.Info); // if we don't have any requests, don't bother sending anything // this could be due to caching further upstream, or just an empty batch if (this._requests.length < 1) { logging_1.Logger.write("Resolving empty batch.", logging_1.LogLevel.Info); return Promise.resolve(); } // creating the client here allows the url to be populated for nodejs client as well as potentially // any other hacks needed for other types of clients. Essentially allows the absoluteRequestUrl // below to be correct var client = new httpclient_1.HttpClient(); // due to timing we need to get the absolute url here so we can use it for all the individual requests // and for sending the entire batch return util_1.Util.toAbsoluteUrl(this.baseUrl).then(function (absoluteRequestUrl) { // build all the requests, send them, pipe results in order to parsers var batchBody = []; var currentChangeSetId = ""; for (var i = 0; i < _this._requests.length; i++) { var reqInfo = _this._requests[i]; if (reqInfo.method === "GET") { if (currentChangeSetId.length > 0) { // end an existing change set batchBody.push("--changeset_" + currentChangeSetId + "--\n\n"); currentChangeSetId = ""; } batchBody.push("--batch_" + _this._batchId + "\n"); } else { if (currentChangeSetId.length < 1) { // start new change set currentChangeSetId = util_1.Util.getGUID(); batchBody.push("--batch_" + _this._batchId + "\n"); batchBody.push("Content-Type: multipart/mixed; boundary=\"changeset_" + currentChangeSetId + "\"\n\n"); } batchBody.push("--changeset_" + currentChangeSetId + "\n"); } // common batch part prefix batchBody.push("Content-Type: application/http\n"); batchBody.push("Content-Transfer-Encoding: binary\n\n"); var headers = { "Accept": "application/json;", }; // this is the url of the individual request within the batch var url = util_1.Util.isUrlAbsolute(reqInfo.url) ? reqInfo.url : util_1.Util.combinePaths(absoluteRequestUrl, reqInfo.url); logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Adding request " + reqInfo.method + " " + url + " to batch.", logging_1.LogLevel.Verbose); if (reqInfo.method !== "GET") { var method = reqInfo.method; if (reqInfo.hasOwnProperty("options") && reqInfo.options.hasOwnProperty("headers") && typeof reqInfo.options.headers["X-HTTP-Method"] !== "undefined") { method = reqInfo.options.headers["X-HTTP-Method"]; delete reqInfo.options.headers["X-HTTP-Method"]; } batchBody.push(method + " " + url + " HTTP/1.1\n"); headers = util_1.Util.extend(headers, { "Content-Type": "application/json;odata=verbose;charset=utf-8" }); } else { batchBody.push(reqInfo.method + " " + url + " HTTP/1.1\n"); } if (typeof pnplibconfig_1.RuntimeConfig.headers !== "undefined") { headers = util_1.Util.extend(headers, pnplibconfig_1.RuntimeConfig.headers); } if (reqInfo.options && reqInfo.options.headers) { headers = util_1.Util.extend(headers, reqInfo.options.headers); } for (var name_1 in headers) { if (headers.hasOwnProperty(name_1)) { batchBody.push(name_1 + ": " + headers[name_1] + "\n"); } } batchBody.push("\n"); if (reqInfo.options.body) { batchBody.push(reqInfo.options.body + "\n\n"); } } if (currentChangeSetId.length > 0) { // Close the changeset batchBody.push("--changeset_" + currentChangeSetId + "--\n\n"); currentChangeSetId = ""; } batchBody.push("--batch_" + _this._batchId + "--\n"); var batchHeaders = { "Content-Type": "multipart/mixed; boundary=batch_" + _this._batchId, }; var batchOptions = { "body": batchBody.join(""), "headers": batchHeaders, }; logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Sending batch request.", logging_1.LogLevel.Info); return client.post(util_1.Util.combinePaths(absoluteRequestUrl, "/_api/$batch"), batchOptions) .then(function (r) { return r.text(); }) .then(_this._parseResponse) .then(function (responses) { if (responses.length !== _this._requests.length) { throw new exceptions_1.BatchParseException("Could not properly parse responses to match requests in batch."); } logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched requests.", logging_1.LogLevel.Info); return responses.reduce(function (chain, response, index) { var request = _this._requests[index]; logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched request " + request.method + " " + request.url + ".", logging_1.LogLevel.Verbose); return chain.then(function (_) { return request.parser.parse(response).then(request.resolve).catch(request.reject); }); }, Promise.resolve()); }); }); }; /** * Parses the response from a batch request into an array of Response instances * * @param body Text body of the response from the batch request */ ODataBatch.prototype._parseResponse = function (body) { return new Promise(function (resolve, reject) { var responses = []; var header = "--batchresponse_"; // Ex. "HTTP/1.1 500 Internal Server Error" var statusRegExp = new RegExp("^HTTP/[0-9.]+ +([0-9]+) +(.*)", "i"); var lines = body.split("\n"); var state = "batch"; var status; var statusText; for (var i = 0; i < lines.length; ++i) { var line = lines[i]; switch (state) { case "batch": if (line.substr(0, header.length) === header) { state = "batchHeaders"; } else { if (line.trim() !== "") { throw new exceptions_1.BatchParseException("Invalid response, line " + i); } } break; case "batchHeaders": if (line.trim() === "") { state = "status"; } break; case "status": var parts = statusRegExp.exec(line); if (parts.length !== 3) { throw new exceptions_1.BatchParseException("Invalid status, line " + i); } status = parseInt(parts[1], 10); statusText = parts[2]; state = "statusHeaders"; break; case "statusHeaders": if (line.trim() === "") { state = "body"; } break; case "body": responses.push((status === 204) ? new Response() : new Response(line, { status: status, statusText: statusText })); state = "batch"; break; } } if (state !== "status") { reject(new exceptions_1.BatchParseException("Unexpected end of input")); } resolve(responses); }); }; return ODataBatch; }()); exports.ODataBatch = ODataBatch; var TextFileParser = (function () { function TextFileParser() { } TextFileParser.prototype.parse = function (r) { return r.text(); }; return TextFileParser; }()); exports.TextFileParser = TextFileParser; var BlobFileParser = (function () { function BlobFileParser() { } BlobFileParser.prototype.parse = function (r) { return r.blob(); }; return BlobFileParser; }()); exports.BlobFileParser = BlobFileParser; var JSONFileParser = (function () { function JSONFileParser() { } JSONFileParser.prototype.parse = function (r) { return r.json(); }; return JSONFileParser; }()); exports.JSONFileParser = JSONFileParser; var BufferFileParser = (function () { function BufferFileParser() { } BufferFileParser.prototype.parse = function (r) { if (util_1.Util.isFunction(r.arrayBuffer)) { return r.arrayBuffer(); } return r.buffer(); }; return BufferFileParser; }()); exports.BufferFileParser = BufferFileParser; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var logging_1 = __webpack_require__(5); function defaultLog(error) { logging_1.Logger.log({ data: {}, level: logging_1.LogLevel.Error, message: "[" + error.name + "]::" + error.message }); } /** * Represents an exception with an HttpClient request * */ var ProcessHttpClientResponseException = (function (_super) { __extends(ProcessHttpClientResponseException, _super); function ProcessHttpClientResponseException(status, statusText, data) { var _this = _super.call(this, "Error making HttpClient request in queryable: [" + status + "] " + statusText) || this; _this.status = status; _this.statusText = statusText; _this.data = data; _this.name = "ProcessHttpClientResponseException"; logging_1.Logger.log({ data: _this.data, level: logging_1.LogLevel.Error, message: _this.message }); return _this; } return ProcessHttpClientResponseException; }(Error)); exports.ProcessHttpClientResponseException = ProcessHttpClientResponseException; var NoCacheAvailableException = (function (_super) { __extends(NoCacheAvailableException, _super); function NoCacheAvailableException(msg) { if (msg === void 0) { msg = "Cannot create a caching configuration provider since cache is not available."; } var _this = _super.call(this, msg) || this; _this.name = "NoCacheAvailableException"; defaultLog(_this); return _this; } return NoCacheAvailableException; }(Error)); exports.NoCacheAvailableException = NoCacheAvailableException; var APIUrlException = (function (_super) { __extends(APIUrlException, _super); function APIUrlException(msg) { if (msg === void 0) { msg = "Unable to determine API url."; } var _this = _super.call(this, msg) || this; _this.name = "APIUrlException"; defaultLog(_this); return _this; } return APIUrlException; }(Error)); exports.APIUrlException = APIUrlException; var AuthUrlException = (function (_super) { __extends(AuthUrlException, _super); function AuthUrlException(data, msg) { if (msg === void 0) { msg = "Auth URL Endpoint could not be determined from data. Data logged."; } var _this = _super.call(this, msg) || this; _this.name = "APIUrlException"; logging_1.Logger.log({ data: data, level: logging_1.LogLevel.Error, message: _this.message }); return _this; } return AuthUrlException; }(Error)); exports.AuthUrlException = AuthUrlException; var NodeFetchClientUnsupportedException = (function (_super) { __extends(NodeFetchClientUnsupportedException, _super); function NodeFetchClientUnsupportedException(msg) { if (msg === void 0) { msg = "Using NodeFetchClient in the browser is not supported."; } var _this = _super.call(this, msg) || this; _this.name = "NodeFetchClientUnsupportedException"; defaultLog(_this); return _this; } return NodeFetchClientUnsupportedException; }(Error)); exports.NodeFetchClientUnsupportedException = NodeFetchClientUnsupportedException; var SPRequestExecutorUndefinedException = (function (_super) { __extends(SPRequestExecutorUndefinedException, _super); function SPRequestExecutorUndefinedException() { var _this = this; var msg = [ "SP.RequestExecutor is undefined. ", "Load the SP.RequestExecutor.js library (/_layouts/15/SP.RequestExecutor.js) before loading the PnP JS Core library.", ].join(" "); _this = _super.call(this, msg) || this; _this.name = "SPRequestExecutorUndefinedException"; defaultLog(_this); return _this; } return SPRequestExecutorUndefinedException; }(Error)); exports.SPRequestExecutorUndefinedException = SPRequestExecutorUndefinedException; var MaxCommentLengthException = (function (_super) { __extends(MaxCommentLengthException, _super); function MaxCommentLengthException(msg) { if (msg === void 0) { msg = "The maximum comment length is 1023 characters."; } var _this = _super.call(this, msg) || this; _this.name = "MaxCommentLengthException"; defaultLog(_this); return _this; } return MaxCommentLengthException; }(Error)); exports.MaxCommentLengthException = MaxCommentLengthException; var NotSupportedInBatchException = (function (_super) { __extends(NotSupportedInBatchException, _super); function NotSupportedInBatchException(operation) { if (operation === void 0) { operation = "This operation"; } var _this = _super.call(this, operation + " is not supported as part of a batch.") || this; _this.name = "NotSupportedInBatchException"; defaultLog(_this); return _this; } return NotSupportedInBatchException; }(Error)); exports.NotSupportedInBatchException = NotSupportedInBatchException; var ODataIdException = (function (_super) { __extends(ODataIdException, _super); function ODataIdException(data, msg) { if (msg === void 0) { msg = "Could not extract odata id in object, you may be using nometadata. Object data logged to logger."; } var _this = _super.call(this, msg) || this; _this.name = "ODataIdException"; logging_1.Logger.log({ data: data, level: logging_1.LogLevel.Error, message: _this.message }); return _this; } return ODataIdException; }(Error)); exports.ODataIdException = ODataIdException; var BatchParseException = (function (_super) { __extends(BatchParseException, _super); function BatchParseException(msg) { var _this = _super.call(this, msg) || this; _this.name = "BatchParseException"; defaultLog(_this); return _this; } return BatchParseException; }(Error)); exports.BatchParseException = BatchParseException; var AlreadyInBatchException = (function (_super) { __extends(AlreadyInBatchException, _super); function AlreadyInBatchException(msg) { if (msg === void 0) { msg = "This query is already part of a batch."; } var _this = _super.call(this, msg) || this; _this.name = "AlreadyInBatchException"; defaultLog(_this); return _this; } return AlreadyInBatchException; }(Error)); exports.AlreadyInBatchException = AlreadyInBatchException; var FunctionExpectedException = (function (_super) { __extends(FunctionExpectedException, _super); function FunctionExpectedException(msg) { if (msg === void 0) { msg = "This query is already part of a batch."; } var _this = _super.call(this, msg) || this; _this.name = "FunctionExpectedException"; defaultLog(_this); return _this; } return FunctionExpectedException; }(Error)); exports.FunctionExpectedException = FunctionExpectedException; var UrlException = (function (_super) { __extends(UrlException, _super); function UrlException(msg) { var _this = _super.call(this, msg) || this; _this.name = "UrlException"; defaultLog(_this); return _this; } return UrlException; }(Error)); exports.UrlException = UrlException; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var fetchclient_1 = __webpack_require__(21); var RuntimeConfigImpl = (function () { function RuntimeConfigImpl() { // these are our default values for the library this._headers = null; this._defaultCachingStore = "session"; this._defaultCachingTimeoutSeconds = 60; this._globalCacheDisable = false; this._fetchClientFactory = function () { return new fetchclient_1.FetchClient(); }; this._baseUrl = null; this._spfxContext = null; } RuntimeConfigImpl.prototype.set = function (config) { if (config.hasOwnProperty("headers")) { this._headers = config.headers; } if (config.hasOwnProperty("globalCacheDisable")) { this._globalCacheDisable = config.globalCacheDisable; } if (config.hasOwnProperty("defaultCachingStore")) { this._defaultCachingStore = config.defaultCachingStore; } if (config.hasOwnProperty("defaultCachingTimeoutSeconds")) { this._defaultCachingTimeoutSeconds = config.defaultCachingTimeoutSeconds; } if (config.hasOwnProperty("fetchClientFactory")) { this._fetchClientFactory = config.fetchClientFactory; } if (config.hasOwnProperty("baseUrl")) { this._baseUrl = config.baseUrl; } if (config.hasOwnProperty("spfxContext")) { this._spfxContext = config.spfxContext; } }; Object.defineProperty(RuntimeConfigImpl.prototype, "headers", { get: function () { return this._headers; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingStore", { get: function () { return this._defaultCachingStore; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingTimeoutSeconds", { get: function () { return this._defaultCachingTimeoutSeconds; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "globalCacheDisable", { get: function () { return this._globalCacheDisable; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "fetchClientFactory", { get: function () { return this._fetchClientFactory; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "baseUrl", { get: function () { if (this._baseUrl !== null) { return this._baseUrl; } else if (this._spfxContext !== null) { return this._spfxContext.pageContext.web.absoluteUrl; } return null; }, enumerable: true, configurable: true }); return RuntimeConfigImpl; }()); exports.RuntimeConfigImpl = RuntimeConfigImpl; var _runtimeConfig = new RuntimeConfigImpl(); exports.RuntimeConfig = _runtimeConfig; function setRuntimeConfig(config) { _runtimeConfig.set(config); } exports.setRuntimeConfig = setRuntimeConfig; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * A set of logging levels * */ var LogLevel; (function (LogLevel) { LogLevel[LogLevel["Verbose"] = 0] = "Verbose"; LogLevel[LogLevel["Info"] = 1] = "Info"; LogLevel[LogLevel["Warning"] = 2] = "Warning"; LogLevel[LogLevel["Error"] = 3] = "Error"; LogLevel[LogLevel["Off"] = 99] = "Off"; })(LogLevel = exports.LogLevel || (exports.LogLevel = {})); /** * Class used to subscribe ILogListener and log messages throughout an application * */ var Logger = (function () { function Logger() { } Object.defineProperty(Logger, "activeLogLevel", { get: function () { return Logger.instance.activeLogLevel; }, set: function (value) { Logger.instance.activeLogLevel = value; }, enumerable: true, configurable: true }); Object.defineProperty(Logger, "instance", { get: function () { if (typeof Logger._instance === "undefined" || Logger._instance === null) { Logger._instance = new LoggerImpl(); } return Logger._instance; }, enumerable: true, configurable: true }); /** * Adds ILogListener instances to the set of subscribed listeners * * @param listeners One or more listeners to subscribe to this log */ Logger.subscribe = function () { var listeners = []; for (var _i = 0; _i < arguments.length; _i++) { listeners[_i] = arguments[_i]; } listeners.map(function (listener) { return Logger.instance.subscribe(listener); }); }; /** * Clears the subscribers collection, returning the collection before modifiction */ Logger.clearSubscribers = function () { return Logger.instance.clearSubscribers(); }; Object.defineProperty(Logger, "count", { /** * Gets the current subscriber count */ get: function () { return Logger.instance.count; }, enumerable: true, configurable: true }); /** * Writes the supplied string to the subscribed listeners * * @param message The message to write * @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose) */ Logger.write = function (message, level) { if (level === void 0) { level = LogLevel.Verbose; } Logger.instance.log({ level: level, message: message }); }; /** * Writes the supplied string to the subscribed listeners * * @param json The json object to stringify and write * @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose) */ Logger.writeJSON = function (json, level) { if (level === void 0) { level = LogLevel.Verbose; } Logger.instance.log({ level: level, message: JSON.stringify(json) }); }; /** * Logs the supplied entry to the subscribed listeners * * @param entry The message to log */ Logger.log = function (entry) { Logger.instance.log(entry); }; /** * Logs performance tracking data for the the execution duration of the supplied function using console.profile * * @param name The name of this profile boundary * @param f The function to execute and track within this performance boundary */ Logger.measure = function (name, f) { return Logger.instance.measure(name, f); }; return Logger; }()); exports.Logger = Logger; var LoggerImpl = (function () { function LoggerImpl(activeLogLevel, subscribers) { if (activeLogLevel === void 0) { activeLogLevel = LogLevel.Warning; } if (subscribers === void 0) { subscribers = []; } this.activeLogLevel = activeLogLevel; this.subscribers = subscribers; } LoggerImpl.prototype.subscribe = function (listener) { this.subscribers.push(listener); }; LoggerImpl.prototype.clearSubscribers = function () { var s = this.subscribers.slice(0); this.subscribers.length = 0; return s; }; Object.defineProperty(LoggerImpl.prototype, "count", { get: function () { return this.subscribers.length; }, enumerable: true, configurable: true }); LoggerImpl.prototype.write = function (message, level) { if (level === void 0) { level = LogLevel.Verbose; } this.log({ level: level, message: message }); }; LoggerImpl.prototype.log = function (entry) { if (typeof entry === "undefined" || entry.level < this.activeLogLevel) { return; } this.subscribers.map(function (subscriber) { return subscriber.log(entry); }); }; LoggerImpl.prototype.measure = function (name, f) { console.profile(name); try { return f(); } finally { console.profileEnd(); } }; return LoggerImpl; }()); /** * Implementation of ILogListener which logs to the browser console * */ var ConsoleListener = (function () { function ConsoleListener() { } /** * Any associated data that a given logging listener may choose to log or ignore * * @param entry The information to be logged */ ConsoleListener.prototype.log = function (entry) { var msg = this.format(entry); switch (entry.level) { case LogLevel.Verbose: case LogLevel.Info: console.log(msg); break; case LogLevel.Warning: console.warn(msg); break; case LogLevel.Error: console.error(msg); break; } }; /** * Formats the message * * @param entry The information to format into a string */ ConsoleListener.prototype.format = function (entry) { return "Message: " + entry.message + " Data: " + JSON.stringify(entry.data); }; return ConsoleListener; }()); exports.ConsoleListener = ConsoleListener; /** * Implementation of ILogListener which logs to the supplied function * */ var FunctionListener = (function () { /** * Creates a new instance of the FunctionListener class * * @constructor * @param method The method to which any logging data will be passed */ function FunctionListener(method) { this.method = method; } /** * Any associated data that a given logging listener may choose to log or ignore * * @param entry The information to be logged */ FunctionListener.prototype.log = function (entry) { this.method(entry); }; return FunctionListener; }()); exports.FunctionListener = FunctionListener; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Generic dictionary */ var Dictionary = (function () { /** * Creates a new instance of the Dictionary<T> class * * @constructor */ function Dictionary(keys, values) { if (keys === void 0) { keys = []; } if (values === void 0) { values = []; } this.keys = keys; this.values = values; } /** * Gets a value from the collection using the specified key * * @param key The key whose value we want to return, returns null if the key does not exist */ Dictionary.prototype.get = function (key) { var index = this.keys.indexOf(key); if (index < 0) { return null; } return this.values[index]; }; /** * Adds the supplied key and value to the dictionary * * @param key The key to add * @param o The value to add */ Dictionary.prototype.add = function (key, o) { var index = this.keys.indexOf(key); if (index > -1) { this.values[index] = o; } else { this.keys.push(key); this.values.push(o); } }; /** * Merges the supplied typed hash into this dictionary instance. Existing values are updated and new ones are created as appropriate. */ Dictionary.prototype.merge = function (source) { var _this = this; if ("getKeys" in source) { var sourceAsDictionary_1 = source; sourceAsDictionary_1.getKeys().map(function (key) { _this.add(key, sourceAsDictionary_1.get(key)); }); } else { var sourceAsHash = source; for (var key in sourceAsHash) { if (sourceAsHash.hasOwnProperty(key)) { this.add(key, sourceAsHash[key]); } } } }; /** * Removes a value from the dictionary * * @param key The key of the key/value pair to remove. Returns null if the key was not found. */ Dictionary.prototype.remove = function (key) { var index = this.keys.indexOf(key); if (index < 0) { return null; } var val = this.values[index]; this.keys.splice(index, 1); this.values.splice(index, 1); return val; }; /** * Returns all the keys currently in the dictionary as an array */ Dictionary.prototype.getKeys = function () { return this.keys; }; /** * Returns all the values currently in the dictionary as an array */ Dictionary.prototype.getValues = function () { return this.values; }; /** * Clears the current dictionary */ Dictionary.prototype.clear = function () { this.keys = []; this.values = []; }; /** * Gets a count of the items currently in the dictionary */ Dictionary.prototype.count = function () { return this.keys.length; }; return Dictionary; }()); exports.Dictionary = Dictionary; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var odata_1 = __webpack_require__(2); var util_1 = __webpack_require__(0); var exceptions_1 = __webpack_require__(3); var webparts_1 = __webpack_require__(50); var items_1 = __webpack_require__(10); var queryableshareable_1 = __webpack_require__(12); var odata_2 = __webpack_require__(2); /** * Describes a collection of File objects * */ var Files = (function (_super) { __extends(Files, _super); /** * Creates a new instance of the Files class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Files(baseUrl, path) { if (path === void 0) { path = "files"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a File by filename * * @param name The name of the file, including extension. */ Files.prototype.getByName = function (name) { var f = new File(this); f.concat("('" + name + "')"); return f; }; /** * Uploads a file. Not supported for batching * * @param url The folder-relative url of the file. * @param content The file contents blob. * @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true) * @returns The new File and the raw response. */ Files.prototype.add = function (url, content, shouldOverWrite) { var _this = this; if (shouldOverWrite === void 0) { shouldOverWrite = true; } return new Files(this, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')") .post({ body: content, }).then(function (response) { return { data: response, file: _this.getByName(url), }; }); }; /** * Uploads a file. Not supported for batching * * @param url The folder-relative url of the file. * @param content The Blob file content to add * @param progress A callback function which can be used to track the progress of the upload * @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true) * @param chunkSize The size of each file slice, in bytes (default: 10485760) * @returns The new File and the raw response. */ Files.prototype.addChunked = function (url, content, progress, shouldOverWrite, chunkSize) { var _this = this; if (shouldOverWrite === void 0) { shouldOverWrite = true; } if (chunkSize === void 0) { chunkSize = 10485760; } var adder = this.clone(Files, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')"); return adder.post().then(function () { return _this.getByName(url); }).then(function (file) { return file.setContentChunked(content, progress, chunkSize); }).then(function (response) { return { data: response, file: _this.getByName(url), }; }); }; /** * Adds a ghosted file to an existing list or document library. Not supported for batching. * * @param fileUrl The server-relative url where you want to save the file. * @param templateFileType The type of use to create the file. * @returns The template file that was added and the raw response. */ Files.prototype.addTemplateFile = function (fileUrl, templateFileType) { var _this = this; return this.clone(Files, "addTemplateFile(urloffile='" + fileUrl + "',templatefiletype=" + templateFileType + ")") .post().then(function (response) { return { data: response, file: _this.getByName(fileUrl), }; }); }; return Files; }(queryable_1.QueryableCollection)); exports.Files = Files; /** * Describes a single File instance * */ var File = (function (_super) { __extends(File, _super); function File() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(File.prototype, "listItemAllFields", { /** * Gets a value that specifies the list item field values for the list item corresponding to the file. * */ get: function () { return new queryable_1.QueryableCollection(this, "listItemAllFields"); }, enumerable: true, configurable: true }); Object.defineProperty(File.prototype, "versions", { /** * Gets a collection of versions * */ get: function () { return new Versions(this); }, enumerable: true, configurable: true }); /** * Approves the file submitted for content approval with the specified comment. * Only documents in lists that are enabled for content approval can be approved. * * @param comment The comment for the approval. */ File.prototype.approve = function (comment) { if (comment === void 0) { comment = ""; } return this.clone(File, "approve(comment='" + comment + "')", true).post(); }; /** * Stops the chunk upload session without saving the uploaded data. Does not support batching. * If the file doesn’t already exist in the library, the partially uploaded file will be deleted. * Use this in response to user action (as in a request to cancel an upload) or an error or exception. * Use the uploadId value that was passed to the StartUpload method that started the upload session. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. */ File.prototype.cancelUpload = function (uploadId) { return this.clone(File, "cancelUpload(uploadId=guid'" + uploadId + "')", false).post(); }; /** * Checks the file in to a document library based on the check-in type. * * @param comment A comment for the check-in. Its length must be <= 1023. * @param checkinType The check-in type for the file. */ File.prototype.checkin = function (comment, checkinType) { if (comment === void 0) { comment = ""; } if (checkinType === void 0) { checkinType = CheckinType.Major; } if (comment.length > 1023) { throw new exceptions_1.MaxCommentLengthException(); } return this.clone(File, "checkin(comment='" + comment + "',checkintype=" + checkinType + ")", true).post(); }; /** * Checks out the file from a document library. */ File.prototype.checkout = function () { return this.clone(File, "checkout", true).post(); }; /** * Copies the file to the destination url. * * @param url The absolute url or server relative url of the destination file path to copy to. * @param shouldOverWrite Should a file with the same name in the same location be overwritten? */ File.prototype.copyTo = function (url, shouldOverWrite) { if (shouldOverWrite === void 0) { shouldOverWrite = true; } return this.clone(File, "copyTo(strnewurl='" + url + "',boverwrite=" + shouldOverWrite + ")", true).post(); }; /** * Delete this file. * * @param eTag Value used in the IF-Match header, by default "*" */ File.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.clone(File, null, true).post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; /** * Denies approval for a file that was submitted for content approval. * Only documents in lists that are enabled for content approval can be denied. * * @param comment The comment for the denial. */ File.prototype.deny = function (comment) { if (comment === void 0) { comment = ""; } if (comment.length > 1023) { throw new exceptions_1.MaxCommentLengthException(); } return this.clone(File, "deny(comment='" + comment + "')", true).post(); }; /** * Specifies the control set used to access, modify, or add Web Parts associated with this Web Part Page and view. * An exception is thrown if the file is not an ASPX page. * * @param scope The WebPartsPersonalizationScope view on the Web Parts page. */ File.prototype.getLimitedWebPartManager = function (scope) { if (scope === void 0) { scope = WebPartsPersonalizationScope.Shared; } return new webparts_1.LimitedWebPartManager(this, "getLimitedWebPartManager(scope=" + scope + ")"); }; /** * Moves the file to the specified destination url. * * @param url The absolute url or server relative url of the destination file path to move to. * @param moveOperations The bitwise MoveOperations value for how to move the file. */ File.prototype.moveTo = function (url, moveOperations) { if (moveOperations === void 0) { moveOperations = MoveOperations.Overwrite; } return this.clone(File, "moveTo(newurl='" + url + "',flags=" + moveOperations + ")", true).post(); }; /** * Submits the file for content approval with the specified comment. * * @param comment The comment for the published file. Its length must be <= 1023. */ File.prototype.publish = function (comment) { if (comment === void 0) { comment = ""; } if (comment.length > 1023) { throw new exceptions_1.MaxCommentLengthException(); } return this.clone(File, "publish(comment='" + comment + "')", true).post(); }; /** * Moves the file to the Recycle Bin and returns the identifier of the new Recycle Bin item. * * @returns The GUID of the recycled file. */ File.prototype.recycle = function () { return this.clone(File, "recycle", true).post(); }; /** * Reverts an existing checkout for the file. * */ File.prototype.undoCheckout = function () { return this.clone(File, "undoCheckout", true).post(); }; /** * Removes the file from content approval or unpublish a major version. * * @param comment The comment for the unpublish operation. Its length must be <= 1023. */ File.prototype.unpublish = function (comment) { if (comment === void 0) { comment = ""; } if (comment.length > 1023) { throw new exceptions_1.MaxCommentLengthException(); } return this.clone(File, "unpublish(comment='" + comment + "')", true).post(); }; /** * Gets the contents of the file as text. Not supported in batching. * */ File.prototype.getText = function () { return this.clone(File, "$value").get(new odata_1.TextFileParser(), { headers: { "binaryStringResponseBody": "true" } }); }; /** * Gets the contents of the file as a blob, does not work in Node.js. Not supported in batching. * */ File.prototype.getBlob = function () { return this.clone(File, "$value").get(new odata_1.BlobFileParser(), { headers: { "binaryStringResponseBody": "true" } }); }; /** * Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching. */ File.prototype.getBuffer = function () { return this.clone(File, "$value").get(new odata_1.BufferFileParser(), { headers: { "binaryStringResponseBody": "true" } }); }; /** * Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching. */ File.prototype.getJSON = function () { return this.clone(File, "$value").get(new odata_1.JSONFileParser(), { headers: { "binaryStringResponseBody": "true" } }); }; /** * Sets the content of a file, for large files use setContentChunked. Not supported in batching. * * @param content The file content * */ File.prototype.setContent = function (content) { var _this = this; return this.clone(File, "$value").post({ body: content, headers: { "X-HTTP-Method": "PUT", }, }).then(function (_) { return new File(_this); }); }; /** * Gets the associated list item for this folder, loading the default properties */ File.prototype.getItem = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } var q = this.listItemAllFields; return q.select.apply(q, selects).get().then(function (d) { return util_1.Util.extend(new items_1.Item(odata_2.getEntityUrl(d)), d); }); }; /** * Sets the contents of a file using a chunked upload approach. Not supported in batching. * * @param file The file to upload * @param progress A callback function which can be used to track the progress of the upload * @param chunkSize The size of each file slice, in bytes (default: 10485760) */ File.prototype.setContentChunked = function (file, progress, chunkSize) { if (chunkSize === void 0) { chunkSize = 10485760; } if (typeof progress === "undefined") { progress = function () { return null; }; } var self = this; var fileSize = file.size; var blockCount = parseInt((file.size / chunkSize).toString(), 10) + ((file.size % chunkSize === 0) ? 1 : 0); var uploadId = util_1.Util.getGUID(); // start the chain with the first fragment progress({ blockNumber: 1, chunkSize: chunkSize, currentPointer: 0, fileSize: fileSize, stage: "starting", totalBlocks: blockCount }); var chain = self.startUpload(uploadId, file.slice(0, chunkSize)); var _loop_1 = function (i) { chain = chain.then(function (pointer) { progress({ blockNumber: i, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "continue", totalBlocks: blockCount }); return self.continueUpload(uploadId, pointer, file.slice(pointer, pointer + chunkSize)); }); }; // skip the first and last blocks for (var i = 2; i < blockCount; i++) { _loop_1(i); } return chain.then(function (pointer) { progress({ blockNumber: blockCount, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "finishing", totalBlocks: blockCount }); return self.finishUpload(uploadId, pointer, file.slice(pointer)); }).then(function (_) { return self; }); }; /** * Starts a new chunk upload session and uploads the first fragment. * The current file content is not changed when this method completes. * The method is idempotent (and therefore does not change the result) as long as you use the same values for uploadId and stream. * The upload session ends either when you use the CancelUpload method or when you successfully * complete the upload session by passing the rest of the file contents through the ContinueUpload and FinishUpload methods. * The StartUpload and ContinueUpload methods return the size of the running total of uploaded data in bytes, * so you can pass those return values to subsequent uses of ContinueUpload and FinishUpload. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. * @param fragment The file contents. * @returns The size of the total uploaded data in bytes. */ File.prototype.startUpload = function (uploadId, fragment) { return this.clone(File, "startUpload(uploadId=guid'" + uploadId + "')").postAs({ body: fragment }).then(function (n) { return parseFloat(n); }); }; /** * Continues the chunk upload session with an additional fragment. * The current file content is not changed. * Use the uploadId value that was passed to the StartUpload method that started the upload session. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. * @param fileOffset The size of the offset into the file where the fragment starts. * @param fragment The file contents. * @returns The size of the total uploaded data in bytes. */ File.prototype.continueUpload = function (uploadId, fileOffset, fragment) { return this.clone(File, "continueUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")").postAs({ body: fragment }).then(function (n) { return parseFloat(n); }); }; /** * Uploads the last file fragment and commits the file. The current file content is changed when this method completes. * Use the uploadId value that was passed to the StartUpload method that started the upload session. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. * @param fileOffset The size of the offset into the file where the fragment starts. * @param fragment The file contents. * @returns The newly uploaded file. */ File.prototype.finishUpload = function (uploadId, fileOffset, fragment) { return this.clone(File, "finishUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")") .postAs({ body: fragment }).then(function (response) { return { data: response, file: new File(response.ServerRelativeUrl), }; }); }; return File; }(queryableshareable_1.QueryableShareableFile)); exports.File = File; /** * Describes a collection of Version objects * */ var Versions = (function (_super) { __extends(Versions, _super); /** * Creates a new instance of the File class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Versions(baseUrl, path) { if (path === void 0) { path = "versions"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a version by id * * @param versionId The id of the version to retrieve */ Versions.prototype.getById = function (versionId) { var v = new Version(this); v.concat("(" + versionId + ")"); return v; }; /** * Deletes all the file version objects in the collection. * */ Versions.prototype.deleteAll = function () { return new Versions(this, "deleteAll").post(); }; /** * Deletes the specified version of the file. * * @param versionId The ID of the file version to delete. */ Versions.prototype.deleteById = function (versionId) { return this.clone(Versions, "deleteById(vid=" + versionId + ")", true).post(); }; /** * Deletes the file version object with the specified version label. * * @param label The version label of the file version to delete, for example: 1.2 */ Versions.prototype.deleteByLabel = function (label) { return this.clone(Versions, "deleteByLabel(versionlabel='" + label + "')", true).post(); }; /** * Creates a new file version from the file specified by the version label. * * @param label The version label of the file version to restore, for example: 1.2 */ Versions.prototype.restoreByLabel = function (label) { return this.clone(Versions, "restoreByLabel(versionlabel='" + label + "')", true).post(); }; return Versions; }(queryable_1.QueryableCollection)); exports.Versions = Versions; /** * Describes a single Version instance * */ var Version = (function (_super) { __extends(Version, _super); function Version() { return _super !== null && _super.apply(this, arguments) || this; } /** * Delete a specific version of a file. * * @param eTag Value used in the IF-Match header, by default "*" */ Version.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; return Version; }(queryable_1.QueryableInstance)); exports.Version = Version; var CheckinType; (function (CheckinType) { CheckinType[CheckinType["Minor"] = 0] = "Minor"; CheckinType[CheckinType["Major"] = 1] = "Major"; CheckinType[CheckinType["Overwrite"] = 2] = "Overwrite"; })(CheckinType = exports.CheckinType || (exports.CheckinType = {})); var WebPartsPersonalizationScope; (function (WebPartsPersonalizationScope) { WebPartsPersonalizationScope[WebPartsPersonalizationScope["User"] = 0] = "User"; WebPartsPersonalizationScope[WebPartsPersonalizationScope["Shared"] = 1] = "Shared"; })(WebPartsPersonalizationScope = exports.WebPartsPersonalizationScope || (exports.WebPartsPersonalizationScope = {})); var MoveOperations; (function (MoveOperations) { MoveOperations[MoveOperations["Overwrite"] = 1] = "Overwrite"; MoveOperations[MoveOperations["AllowBrokenThickets"] = 8] = "AllowBrokenThickets"; })(MoveOperations = exports.MoveOperations || (exports.MoveOperations = {})); var TemplateFileType; (function (TemplateFileType) { TemplateFileType[TemplateFileType["StandardPage"] = 0] = "StandardPage"; TemplateFileType[TemplateFileType["WikiPage"] = 1] = "WikiPage"; TemplateFileType[TemplateFileType["FormPage"] = 2] = "FormPage"; })(TemplateFileType = exports.TemplateFileType || (exports.TemplateFileType = {})); /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var lists_1 = __webpack_require__(11); var fields_1 = __webpack_require__(24); var navigation_1 = __webpack_require__(25); var sitegroups_1 = __webpack_require__(18); var contenttypes_1 = __webpack_require__(16); var folders_1 = __webpack_require__(9); var roles_1 = __webpack_require__(17); var files_1 = __webpack_require__(7); var util_1 = __webpack_require__(0); var lists_2 = __webpack_require__(11); var siteusers_1 = __webpack_require__(30); var usercustomactions_1 = __webpack_require__(19); var odata_1 = __webpack_require__(2); var features_1 = __webpack_require__(23); var decorators_1 = __webpack_require__(51); var queryableshareable_1 = __webpack_require__(12); var relateditems_1 = __webpack_require__(46); var Webs = (function (_super) { __extends(Webs, _super); function Webs(baseUrl, webPath) { if (webPath === void 0) { webPath = "webs"; } return _super.call(this, baseUrl, webPath) || this; } /** * Adds a new web to the collection * * @param title The new web's title * @param url The new web's relative url * @param description The web web's description * @param template The web's template * @param language The language code to use for this web * @param inheritPermissions If true permissions will be inherited from the partent web * @param additionalSettings Will be passed as part of the web creation body */ Webs.prototype.add = function (title, url, description, template, language, inheritPermissions, additionalSettings) { if (description === void 0) { description = ""; } if (template === void 0) { template = "STS"; } if (language === void 0) { language = 1033; } if (inheritPermissions === void 0) { inheritPermissions = true; } if (additionalSettings === void 0) { additionalSettings = {}; } var props = util_1.Util.extend({ Description: description, Language: language, Title: title, Url: url, UseSamePermissionsAsParentSite: inheritPermissions, WebTemplate: template, }, additionalSettings); var postBody = JSON.stringify({ "parameters": util_1.Util.extend({ "__metadata": { "type": "SP.WebCreationInformation" }, }, props), }); return this.clone(Webs, "add", true).post({ body: postBody }).then(function (data) { return { data: data, web: new Web(odata_1.extractOdataId(data).replace(/_api\/web\/?/i, "")), }; }); }; return Webs; }(queryable_1.QueryableCollection)); exports.Webs = Webs; var WebInfos = (function (_super) { __extends(WebInfos, _super); function WebInfos(baseUrl, webPath) { if (webPath === void 0) { webPath = "webinfos"; } return _super.call(this, baseUrl, webPath) || this; } return WebInfos; }(queryable_1.QueryableCollection)); exports.WebInfos = WebInfos; /** * Describes a web * */ var Web = (function (_super) { __extends(Web, _super); function Web(baseUrl, path) { if (path === void 0) { path = "_api/web"; } return _super.call(this, baseUrl, path) || this; } /** * Creates a new web instance from the given url by indexing the location of the /_api/ * segment. If this is not found the method creates a new web with the entire string as * supplied. * * @param url */ Web.fromUrl = function (url, path) { if (url === null) { return new Web(""); } var index = url.indexOf("_api/"); if (index > -1) { return new Web(url.substr(0, index), path); } return new Web(url, path); }; Object.defineProperty(Web.prototype, "webs", { get: function () { return new Webs(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "webinfos", { get: function () { return new WebInfos(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "contentTypes", { /** * Get the content types available in this web * */ get: function () { return new contenttypes_1.ContentTypes(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "lists", { /** * Get the lists in this web * */ get: function () { return new lists_1.Lists(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "fields", { /** * Gets the fields in this web * */ get: function () { return new fields_1.Fields(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "features", { /** * Gets the active features for this web * */ get: function () { return new features_1.Features(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "availablefields", { /** * Gets the available fields in this web * */ get: function () { return new fields_1.Fields(this, "availablefields"); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "navigation", { /** * Get the navigation options in this web * */ get: function () { return new navigation_1.Navigation(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "siteUsers", { /** * Gets the site users * */ get: function () { return new siteusers_1.SiteUsers(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "siteGroups", { /** * Gets the site groups * */ get: function () { return new sitegroups_1.SiteGroups(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "currentUser", { /** * Gets the current user */ get: function () { return new siteusers_1.CurrentUser(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "folders", { /** * Get the folders in this web * */ get: function () { return new folders_1.Folders(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "userCustomActions", { /** * Get all custom actions on a site * */ get: function () { return new usercustomactions_1.UserCustomActions(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "roleDefinitions", { /** * Gets the collection of RoleDefinition resources. * */ get: function () { return new roles_1.RoleDefinitions(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "relatedItems", { /** * Provides an interface to manage related items * */ get: function () { return relateditems_1.RelatedItemManagerImpl.FromUrl(this.toUrl()); }, enumerable: true, configurable: true }); /** * Creates a new batch for requests within the context of context this web * */ Web.prototype.createBatch = function () { return new odata_1.ODataBatch(this.parentUrl); }; Object.defineProperty(Web.prototype, "rootFolder", { /** * The root folder of the web */ get: function () { return new folders_1.Folder(this, "rootFolder"); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "associatedOwnerGroup", { get: function () { return new sitegroups_1.SiteGroup(this, "associatedownergroup"); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "associatedMemberGroup", { get: function () { return new sitegroups_1.SiteGroup(this, "associatedmembergroup"); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "associatedVisitorGroup", { get: function () { return new sitegroups_1.SiteGroup(this, "associatedvisitorgroup"); }, enumerable: true, configurable: true }); /** * Get a folder by server relative url * * @param folderRelativeUrl the server relative path to the folder (including /sites/ if applicable) */ Web.prototype.getFolderByServerRelativeUrl = function (folderRelativeUrl) { return new folders_1.Folder(this, "getFolderByServerRelativeUrl('" + folderRelativeUrl + "')"); }; /** * Get a file by server relative url * * @param fileRelativeUrl the server relative path to the file (including /sites/ if applicable) */ Web.prototype.getFileByServerRelativeUrl = function (fileRelativeUrl) { return new files_1.File(this, "getFileByServerRelativeUrl('" + fileRelativeUrl + "')"); }; /** * Get a list by server relative url (list's root folder) * * @param listRelativeUrl the server relative path to the list's root folder (including /sites/ if applicable) */ Web.prototype.getList = function (listRelativeUrl) { return new lists_2.List(this, "getList('" + listRelativeUrl + "')"); }; /** * Updates this web intance with the supplied properties * * @param properties A plain object hash of values to update for the web */ Web.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.Web" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, web: _this, }; }); }; /** * Delete this web * */ Web.prototype.delete = function () { return _super.prototype.delete.call(this); }; /** * Applies the theme specified by the contents of each of the files specified in the arguments to the site. * * @param colorPaletteUrl Server-relative URL of the color palette file. * @param fontSchemeUrl Server-relative URL of the font scheme. * @param backgroundImageUrl Server-relative URL of the background image. * @param shareGenerated true to store the generated theme files in the root site, or false to store them in this site. */ Web.prototype.applyTheme = function (colorPaletteUrl, fontSchemeUrl, backgroundImageUrl, shareGenerated) { var postBody = JSON.stringify({ backgroundImageUrl: backgroundImageUrl, colorPaletteUrl: colorPaletteUrl, fontSchemeUrl: fontSchemeUrl, shareGenerated: shareGenerated, }); return this.clone(Web, "applytheme", true).post({ body: postBody }); }; /** * Applies the specified site definition or site template to the Web site that has no template applied to it. * * @param template Name of the site definition or the name of the site template */ Web.prototype.applyWebTemplate = function (template) { var q = this.clone(Web, "applywebtemplate", true); q.concat("(@t)"); q.query.add("@t", template); return q.post(); }; /** * Returns whether the current user has the given set of permissions. * * @param perms The high and low permission range. */ Web.prototype.doesUserHavePermissions = function (perms) { var q = this.clone(Web, "doesuserhavepermissions", true); q.concat("(@p)"); q.query.add("@p", JSON.stringify(perms)); return q.get(); }; /** * Checks whether the specified login name belongs to a valid user in the site. If the user doesn't exist, adds the user to the site. * * @param loginName The login name of the user (ex: i:0#.f|membership|user@domain.onmicrosoft.com) */ Web.prototype.ensureUser = function (loginName) { var postBody = JSON.stringify({ logonName: loginName, }); return this.clone(Web, "ensureuser", true).post({ body: postBody }).then(function (data) { return { data: data, user: new siteusers_1.SiteUser(odata_1.extractOdataId(data)), }; }); }; /** * Returns a collection of site templates available for the site. * * @param language The LCID of the site templates to get. * @param true to include language-neutral site templates; otherwise false */ Web.prototype.availableWebTemplates = function (language, includeCrossLanugage) { if (language === void 0) { language = 1033; } if (includeCrossLanugage === void 0) { includeCrossLanugage = true; } return new queryable_1.QueryableCollection(this, "getavailablewebtemplates(lcid=" + language + ", doincludecrosslanguage=" + includeCrossLanugage + ")"); }; /** * Returns the list gallery on the site. * * @param type The gallery type - WebTemplateCatalog = 111, WebPartCatalog = 113 ListTemplateCatalog = 114, * MasterPageCatalog = 116, SolutionCatalog = 121, ThemeCatalog = 123, DesignCatalog = 124, AppDataCatalog = 125 */ Web.prototype.getCatalog = function (type) { return this.clone(Web, "getcatalog(" + type + ")", true).select("Id").get().then(function (data) { return new lists_2.List(odata_1.extractOdataId(data)); }); }; /** * Returns the collection of changes from the change log that have occurred within the list, based on the specified query. */ Web.prototype.getChanges = function (query) { var postBody = JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) }); return this.clone(Web, "getchanges", true).post({ body: postBody }); }; Object.defineProperty(Web.prototype, "customListTemplate", { /** * Gets the custom list templates for the site. * */ get: function () { return new queryable_1.QueryableCollection(this, "getcustomlisttemplates"); }, enumerable: true, configurable: true }); /** * Returns the user corresponding to the specified member identifier for the current site. * * @param id The ID of the user. */ Web.prototype.getUserById = function (id) { return new siteusers_1.SiteUser(this, "getUserById(" + id + ")"); }; /** * Returns the name of the image file for the icon that is used to represent the specified file. * * @param filename The file name. If this parameter is empty, the server returns an empty string. * @param size The size of the icon: 16x16 pixels = 0, 32x32 pixels = 1. * @param progId The ProgID of the application that was used to create the file, in the form OLEServerName.ObjectName */ Web.prototype.mapToIcon = function (filename, size, progId) { if (size === void 0) { size = 0; } if (progId === void 0) { progId = ""; } return this.clone(Web, "maptoicon(filename='" + filename + "', progid='" + progId + "', size=" + size + ")", true).get(); }; return Web; }(queryableshareable_1.QueryableShareableWeb)); __decorate([ decorators_1.deprecated("This method will be removed in future releases. Please use the methods found in queryable securable.") ], Web.prototype, "doesUserHavePermissions", null); exports.Web = Web; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var queryableshareable_1 = __webpack_require__(12); var files_1 = __webpack_require__(7); var util_1 = __webpack_require__(0); var odata_1 = __webpack_require__(2); var items_1 = __webpack_require__(10); /** * Describes a collection of Folder objects * */ var Folders = (function (_super) { __extends(Folders, _super); /** * Creates a new instance of the Folders class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Folders(baseUrl, path) { if (path === void 0) { path = "folders"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a folder by folder name * */ Folders.prototype.getByName = function (name) { var f = new Folder(this); f.concat("('" + name + "')"); return f; }; /** * Adds a new folder to the current folder (relative) or any folder (absolute) * * @param url The relative or absolute url where the new folder will be created. Urls starting with a forward slash are absolute. * @returns The new Folder and the raw response. */ Folders.prototype.add = function (url) { var _this = this; return this.clone(Folders, "add('" + url + "')", true).post().then(function (response) { return { data: response, folder: _this.getByName(url), }; }); }; return Folders; }(queryable_1.QueryableCollection)); exports.Folders = Folders; /** * Describes a single Folder instance * */ var Folder = (function (_super) { __extends(Folder, _super); function Folder() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Folder.prototype, "contentTypeOrder", { /** * Specifies the sequence in which content types are displayed. * */ get: function () { return new queryable_1.QueryableCollection(this, "contentTypeOrder"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "files", { /** * Gets this folder's files * */ get: function () { return new files_1.Files(this); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "folders", { /** * Gets this folder's sub folders * */ get: function () { return new Folders(this); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "listItemAllFields", { /** * Gets this folder's list item field values * */ get: function () { return new queryable_1.QueryableCollection(this, "listItemAllFields"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "parentFolder", { /** * Gets the parent folder, if available * */ get: function () { return new Folder(this, "parentFolder"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "properties", { /** * Gets this folder's properties * */ get: function () { return new queryable_1.QueryableInstance(this, "properties"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "serverRelativeUrl", { /** * Gets this folder's server relative url * */ get: function () { return new queryable_1.Queryable(this, "serverRelativeUrl"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "uniqueContentTypeOrder", { /** * Gets a value that specifies the content type order. * */ get: function () { return new queryable_1.QueryableCollection(this, "uniqueContentTypeOrder"); }, enumerable: true, configurable: true }); Folder.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.Folder" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, folder: _this, }; }); }; /** * Delete this folder * * @param eTag Value used in the IF-Match header, by default "*" */ Folder.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.clone(Folder, null, true).post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; /** * Moves the folder to the Recycle Bin and returns the identifier of the new Recycle Bin item. */ Folder.prototype.recycle = function () { return this.clone(Folder, "recycle", true).post(); }; /** * Gets the associated list item for this folder, loading the default properties */ Folder.prototype.getItem = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } var q = this.listItemAllFields; return q.select.apply(q, selects).get().then(function (d) { return util_1.Util.extend(new items_1.Item(odata_1.getEntityUrl(d)), d); }); }; return Folder; }(queryableshareable_1.QueryableShareableFolder)); exports.Folder = Folder; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var queryableshareable_1 = __webpack_require__(12); var folders_1 = __webpack_require__(9); var files_1 = __webpack_require__(7); var contenttypes_1 = __webpack_require__(16); var util_1 = __webpack_require__(0); var odata_1 = __webpack_require__(2); var attachmentfiles_1 = __webpack_require__(42); var lists_1 = __webpack_require__(11); /** * Describes a collection of Item objects * */ var Items = (function (_super) { __extends(Items, _super); /** * Creates a new instance of the Items class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Items(baseUrl, path) { if (path === void 0) { path = "items"; } return _super.call(this, baseUrl, path) || this; } /** * Gets an Item by id * * @param id The integer id of the item to retrieve */ Items.prototype.getById = function (id) { var i = new Item(this); i.concat("(" + id + ")"); return i; }; /** * Skips the specified number of items (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#sectionSection6) * * @param skip The starting id where the page should start, use with top to specify pages */ Items.prototype.skip = function (skip) { this._query.add("$skiptoken", encodeURIComponent("Paged=TRUE&p_ID=" + skip)); return this; }; /** * Gets a collection designed to aid in paging through data * */ Items.prototype.getPaged = function () { return this.getAs(new PagedItemCollectionParser()); }; // /** * Adds a new item to the collection * * @param properties The new items's properties */ Items.prototype.add = function (properties, listItemEntityTypeFullName) { var _this = this; if (properties === void 0) { properties = {}; } if (listItemEntityTypeFullName === void 0) { listItemEntityTypeFullName = null; } var removeDependency = this.addBatchDependency(); return this.ensureListItemEntityTypeName(listItemEntityTypeFullName).then(function (listItemEntityType) { var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": listItemEntityType }, }, properties)); var promise = _this.clone(Items, null, true).postAs({ body: postBody }).then(function (data) { return { data: data, item: _this.getById(data.Id), }; }); removeDependency(); return promise; }); }; /** * Ensures we have the proper list item entity type name, either from the value provided or from the list * * @param candidatelistItemEntityTypeFullName The potential type name */ Items.prototype.ensureListItemEntityTypeName = function (candidatelistItemEntityTypeFullName) { return candidatelistItemEntityTypeFullName ? Promise.resolve(candidatelistItemEntityTypeFullName) : this.getParent(lists_1.List).getListItemEntityTypeFullName(); }; return Items; }(queryable_1.QueryableCollection)); exports.Items = Items; /** * Descrines a single Item instance * */ var Item = (function (_super) { __extends(Item, _super); function Item() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Item.prototype, "attachmentFiles", { /** * Gets the set of attachments for this item * */ get: function () { return new attachmentfiles_1.AttachmentFiles(this); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "contentType", { /** * Gets the content type for this item * */ get: function () { return new contenttypes_1.ContentType(this, "ContentType"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "effectiveBasePermissions", { /** * Gets the effective base permissions for the item * */ get: function () { return new queryable_1.Queryable(this, "EffectiveBasePermissions"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "effectiveBasePermissionsForUI", { /** * Gets the effective base permissions for the item in a UI context * */ get: function () { return new queryable_1.Queryable(this, "EffectiveBasePermissionsForUI"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "fieldValuesAsHTML", { /** * Gets the field values for this list item in their HTML representation * */ get: function () { return new queryable_1.QueryableInstance(this, "FieldValuesAsHTML"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "fieldValuesAsText", { /** * Gets the field values for this list item in their text representation * */ get: function () { return new queryable_1.QueryableInstance(this, "FieldValuesAsText"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "fieldValuesForEdit", { /** * Gets the field values for this list item for use in editing controls * */ get: function () { return new queryable_1.QueryableInstance(this, "FieldValuesForEdit"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "folder", { /** * Gets the folder associated with this list item (if this item represents a folder) * */ get: function () { return new folders_1.Folder(this, "folder"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "file", { /** * Gets the folder associated with this list item (if this item represents a folder) * */ get: function () { return new files_1.File(this, "file"); }, enumerable: true, configurable: true }); /** * Updates this list intance with the supplied properties * * @param properties A plain object hash of values to update for the list * @param eTag Value used in the IF-Match header, by default "*" */ Item.prototype.update = function (properties, eTag) { var _this = this; if (eTag === void 0) { eTag = "*"; } return new Promise(function (resolve, reject) { var removeDependency = _this.addBatchDependency(); var parentList = _this.getParent(queryable_1.QueryableInstance, _this.parentUrl.substr(0, _this.parentUrl.lastIndexOf("/"))); parentList.select("ListItemEntityTypeFullName").getAs().then(function (d) { var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": d.ListItemEntityTypeFullName }, }, properties)); removeDependency(); return _this.post({ body: postBody, headers: { "IF-Match": eTag, "X-HTTP-Method": "MERGE", }, }, new ItemUpdatedParser()).then(function (data) { resolve({ data: data, item: _this, }); }); }).catch(function (e) { return reject(e); }); }); }; /** * Delete this item * * @param eTag Value used in the IF-Match header, by default "*" */ Item.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; /** * Moves the list item to the Recycle Bin and returns the identifier of the new Recycle Bin item. */ Item.prototype.recycle = function () { return this.clone(Item, "recycle", true).post(); }; /** * Gets a string representation of the full URL to the WOPI frame. * If there is no associated WOPI application, or no associated action, an empty string is returned. * * @param action Display mode: 0: view, 1: edit, 2: mobileView, 3: interactivePreview */ Item.prototype.getWopiFrameUrl = function (action) { if (action === void 0) { action = 0; } var i = this.clone(Item, "getWOPIFrameUrl(@action)", true); i._query.add("@action", action); return i.post().then(function (data) { return data.GetWOPIFrameUrl; }); }; /** * Validates and sets the values of the specified collection of fields for the list item. * * @param formValues The fields to change and their new values. * @param newDocumentUpdate true if the list item is a document being updated after upload; otherwise false. */ Item.prototype.validateUpdateListItem = function (formValues, newDocumentUpdate) { if (newDocumentUpdate === void 0) { newDocumentUpdate = false; } return this.clone(Item, "validateupdatelistitem", true).post({ body: JSON.stringify({ "formValues": formValues, bNewDocumentUpdate: newDocumentUpdate }), }); }; return Item; }(queryableshareable_1.QueryableShareableItem)); exports.Item = Item; /** * Provides paging functionality for list items */ var PagedItemCollection = (function () { function PagedItemCollection(nextUrl, results) { this.nextUrl = nextUrl; this.results = results; } Object.defineProperty(PagedItemCollection.prototype, "hasNext", { /** * If true there are more results available in the set, otherwise there are not */ get: function () { return typeof this.nextUrl === "string" && this.nextUrl.length > 0; }, enumerable: true, configurable: true }); /** * Gets the next set of results, or resolves to null if no results are available */ PagedItemCollection.prototype.getNext = function () { if (this.hasNext) { var items = new Items(this.nextUrl, null); return items.getPaged(); } return new Promise(function (r) { return r(null); }); }; return PagedItemCollection; }()); exports.PagedItemCollection = PagedItemCollection; var PagedItemCollectionParser = (function (_super) { __extends(PagedItemCollectionParser, _super); function PagedItemCollectionParser() { return _super !== null && _super.apply(this, arguments) || this; } PagedItemCollectionParser.prototype.parse = function (r) { var _this = this; return new Promise(function (resolve, reject) { if (_this.handleError(r, reject)) { r.json().then(function (json) { var nextUrl = json.hasOwnProperty("d") && json.d.hasOwnProperty("__next") ? json.d.__next : json["odata.nextLink"]; resolve(new PagedItemCollection(nextUrl, _this.parseODataJSON(json))); }); } }); }; return PagedItemCollectionParser; }(odata_1.ODataParserBase)); var ItemUpdatedParser = (function (_super) { __extends(ItemUpdatedParser, _super); function ItemUpdatedParser() { return _super !== null && _super.apply(this, arguments) || this; } ItemUpdatedParser.prototype.parse = function (r) { var _this = this; return new Promise(function (resolve, reject) { if (_this.handleError(r, reject)) { resolve({ "odata.etag": r.headers.get("etag"), }); } }); }; return ItemUpdatedParser; }(odata_1.ODataParserBase)); /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var items_1 = __webpack_require__(10); var views_1 = __webpack_require__(49); var contenttypes_1 = __webpack_require__(16); var fields_1 = __webpack_require__(24); var forms_1 = __webpack_require__(43); var subscriptions_1 = __webpack_require__(47); var queryable_1 = __webpack_require__(1); var queryablesecurable_1 = __webpack_require__(26); var util_1 = __webpack_require__(0); var usercustomactions_1 = __webpack_require__(19); var odata_1 = __webpack_require__(2); var exceptions_1 = __webpack_require__(3); var folders_1 = __webpack_require__(9); /** * Describes a collection of List objects * */ var Lists = (function (_super) { __extends(Lists, _super); /** * Creates a new instance of the Lists class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Lists(baseUrl, path) { if (path === void 0) { path = "lists"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a list from the collection by title * * @param title The title of the list */ Lists.prototype.getByTitle = function (title) { return new List(this, "getByTitle('" + title + "')"); }; /** * Gets a list from the collection by guid id * * @param id The Id of the list (GUID) */ Lists.prototype.getById = function (id) { var list = new List(this); list.concat("('" + id + "')"); return list; }; /** * Adds a new list to the collection * * @param title The new list's title * @param description The new list's description * @param template The list template value * @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled * @param additionalSettings Will be passed as part of the list creation body */ Lists.prototype.add = function (title, description, template, enableContentTypes, additionalSettings) { var _this = this; if (description === void 0) { description = ""; } if (template === void 0) { template = 100; } if (enableContentTypes === void 0) { enableContentTypes = false; } if (additionalSettings === void 0) { additionalSettings = {}; } var addSettings = util_1.Util.extend({ "AllowContentTypes": enableContentTypes, "BaseTemplate": template, "ContentTypesEnabled": enableContentTypes, "Description": description, "Title": title, "__metadata": { "type": "SP.List" }, }, additionalSettings); return this.post({ body: JSON.stringify(addSettings) }).then(function (data) { return { data: data, list: _this.getByTitle(addSettings.Title) }; }); }; /** * Ensures that the specified list exists in the collection (note: this method not supported for batching) * * @param title The new list's title * @param description The new list's description * @param template The list template value * @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled * @param additionalSettings Will be passed as part of the list creation body or used to update an existing list */ Lists.prototype.ensure = function (title, description, template, enableContentTypes, additionalSettings) { var _this = this; if (description === void 0) { description = ""; } if (template === void 0) { template = 100; } if (enableContentTypes === void 0) { enableContentTypes = false; } if (additionalSettings === void 0) { additionalSettings = {}; } if (this.hasBatch) { throw new exceptions_1.NotSupportedInBatchException("The ensure list method"); } return new Promise(function (resolve, reject) { var addOrUpdateSettings = util_1.Util.extend(additionalSettings, { Title: title, Description: description, ContentTypesEnabled: enableContentTypes }, true); var list = _this.getByTitle(addOrUpdateSettings.Title); list.get().then(function (_) { list.update(addOrUpdateSettings).then(function (d) { resolve({ created: false, data: d, list: _this.getByTitle(addOrUpdateSettings.Title) }); }).catch(function (e) { return reject(e); }); }).catch(function (_) { _this.add(title, description, template, enableContentTypes, addOrUpdateSettings).then(function (r) { resolve({ created: true, data: r.data, list: _this.getByTitle(addOrUpdateSettings.Title) }); }).catch(function (e) { return reject(e); }); }); }); }; /** * Gets a list that is the default asset location for images or other files, which the users upload to their wiki pages. */ Lists.prototype.ensureSiteAssetsLibrary = function () { return this.clone(Lists, "ensuresiteassetslibrary", true).post().then(function (json) { return new List(odata_1.extractOdataId(json)); }); }; /** * Gets a list that is the default location for wiki pages. */ Lists.prototype.ensureSitePagesLibrary = function () { return this.clone(Lists, "ensuresitepageslibrary", true).post().then(function (json) { return new List(odata_1.extractOdataId(json)); }); }; return Lists; }(queryable_1.QueryableCollection)); exports.Lists = Lists; /** * Describes a single List instance * */ var List = (function (_super) { __extends(List, _super); function List() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(List.prototype, "contentTypes", { /** * Gets the content types in this list * */ get: function () { return new contenttypes_1.ContentTypes(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "items", { /** * Gets the items in this list * */ get: function () { return new items_1.Items(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "views", { /** * Gets the views in this list * */ get: function () { return new views_1.Views(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "fields", { /** * Gets the fields in this list * */ get: function () { return new fields_1.Fields(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "forms", { /** * Gets the forms in this list * */ get: function () { return new forms_1.Forms(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "defaultView", { /** * Gets the default view of this list * */ get: function () { return new queryable_1.QueryableInstance(this, "DefaultView"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "userCustomActions", { /** * Get all custom actions on a site collection * */ get: function () { return new usercustomactions_1.UserCustomActions(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "effectiveBasePermissions", { /** * Gets the effective base permissions of this list * */ get: function () { return new queryable_1.Queryable(this, "EffectiveBasePermissions"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "eventReceivers", { /** * Gets the event receivers attached to this list * */ get: function () { return new queryable_1.QueryableCollection(this, "EventReceivers"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "relatedFields", { /** * Gets the related fields of this list * */ get: function () { return new queryable_1.Queryable(this, "getRelatedFields"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "informationRightsManagementSettings", { /** * Gets the IRM settings for this list * */ get: function () { return new queryable_1.Queryable(this, "InformationRightsManagementSettings"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "subscriptions", { /** * Gets the webhook subscriptions of this list * */ get: function () { return new subscriptions_1.Subscriptions(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "rootFolder", { /** * The root folder of the list */ get: function () { return new folders_1.Folder(this, "rootFolder"); }, enumerable: true, configurable: true }); /** * Gets a view by view guid id * */ List.prototype.getView = function (viewId) { return new views_1.View(this, "getView('" + viewId + "')"); }; /** * Updates this list intance with the supplied properties * * @param properties A plain object hash of values to update for the list * @param eTag Value used in the IF-Match header, by default "*" */ /* tslint:disable no-string-literal */ List.prototype.update = function (properties, eTag) { var _this = this; if (eTag === void 0) { eTag = "*"; } var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.List" }, }, properties)); return this.post({ body: postBody, headers: { "IF-Match": eTag, "X-HTTP-Method": "MERGE", }, }).then(function (data) { var retList = _this; if (properties.hasOwnProperty("Title")) { retList = _this.getParent(List, _this.parentUrl, "getByTitle('" + properties["Title"] + "')"); } return { data: data, list: retList, }; }); }; /* tslint:enable */ /** * Delete this list * * @param eTag Value used in the IF-Match header, by default "*" */ List.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; /** * Returns the collection of changes from the change log that have occurred within the list, based on the specified query. */ List.prototype.getChanges = function (query) { return this.clone(List, "getchanges", true).post({ body: JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) }), }); }; /** * Returns a collection of items from the list based on the specified query. * * @param CamlQuery The Query schema of Collaborative Application Markup * Language (CAML) is used in various ways within the context of Microsoft SharePoint Foundation * to define queries against list data. * see: * * https://msdn.microsoft.com/en-us/library/office/ms467521.aspx * * @param expands A URI with a $expand System Query Option indicates that Entries associated with * the Entry or Collection of Entries identified by the Resource Path * section of the URI must be represented inline (i.e. eagerly loaded). * see: * * https://msdn.microsoft.com/en-us/library/office/fp142385.aspx * * http://www.odata.org/documentation/odata-version-2-0/uri-conventions/#ExpandSystemQueryOption */ List.prototype.getItemsByCAMLQuery = function (query) { var expands = []; for (var _i = 1; _i < arguments.length; _i++) { expands[_i - 1] = arguments[_i]; } var q = this.clone(List, "getitems", true); return q.expand.apply(q, expands).post({ body: JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.CamlQuery" } }, query) }), }); }; /** * See: https://msdn.microsoft.com/en-us/library/office/dn292554.aspx */ List.prototype.getListItemChangesSinceToken = function (query) { return this.clone(List, "getlistitemchangessincetoken", true).post({ body: JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.ChangeLogItemQuery" } }, query) }), }, { parse: function (r) { return r.text(); } }); }; /** * Moves the list to the Recycle Bin and returns the identifier of the new Recycle Bin item. */ List.prototype.recycle = function () { return this.clone(List, "recycle", true).post().then(function (data) { if (data.hasOwnProperty("Recycle")) { return data.Recycle; } else { return data; } }); }; /** * Renders list data based on the view xml provided */ List.prototype.renderListData = function (viewXml) { var q = this.clone(List, "renderlistdata(@viewXml)"); q.query.add("@viewXml", "'" + viewXml + "'"); return q.post().then(function (data) { // data will be a string, so we parse it again data = JSON.parse(data); if (data.hasOwnProperty("RenderListData")) { return data.RenderListData; } else { return data; } }); }; /** * Gets the field values and field schema attributes for a list item. */ List.prototype.renderListFormData = function (itemId, formId, mode) { return this.clone(List, "renderlistformdata(itemid=" + itemId + ", formid='" + formId + "', mode='" + mode + "')", true).post().then(function (data) { // data will be a string, so we parse it again data = JSON.parse(data); if (data.hasOwnProperty("ListData")) { return data.ListData; } else { return data; } }); }; /** * Reserves a list item ID for idempotent list item creation. */ List.prototype.reserveListItemId = function () { return this.clone(List, "reservelistitemid", true).post().then(function (data) { if (data.hasOwnProperty("ReserveListItemId")) { return data.ReserveListItemId; } else { return data; } }); }; /** * Returns the ListItemEntityTypeFullName for this list, used when adding/updating list items. Does not support batching. * */ List.prototype.getListItemEntityTypeFullName = function () { return this.clone(List, null).select("ListItemEntityTypeFullName").getAs().then(function (o) { return o.ListItemEntityTypeFullName; }); }; return List; }(queryablesecurable_1.QueryableSecurable)); exports.List = List; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var webs_1 = __webpack_require__(8); var odata_1 = __webpack_require__(2); var queryable_1 = __webpack_require__(1); var queryablesecurable_1 = __webpack_require__(26); var types_1 = __webpack_require__(13); /** * Internal helper class used to augment classes to include sharing functionality */ var QueryableShareable = (function (_super) { __extends(QueryableShareable, _super); function QueryableShareable() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a sharing link for the supplied * * @param kind The kind of link to share * @param expiration The optional expiration for this link */ QueryableShareable.prototype.getShareLink = function (kind, expiration) { if (expiration === void 0) { expiration = null; } // date needs to be an ISO string or null var expString = expiration !== null ? expiration.toISOString() : null; // clone using the factory and send the request return this.clone(QueryableShareable, "shareLink", true).postAs({ body: JSON.stringify({ request: { createLink: true, emailData: null, settings: { expiration: expString, linkKind: kind, }, }, }), }); }; /** * Shares this instance with the supplied users * * @param loginNames Resolved login names to share * @param role The role * @param requireSignin True to require the user is authenticated, otherwise false * @param propagateAcl True to apply this share to all children * @param emailData If supplied an email will be sent with the indicated properties */ QueryableShareable.prototype.shareWith = function (loginNames, role, requireSignin, propagateAcl, emailData) { var _this = this; if (requireSignin === void 0) { requireSignin = true; } if (propagateAcl === void 0) { propagateAcl = false; } // handle the multiple input types if (!Array.isArray(loginNames)) { loginNames = [loginNames]; } var userStr = JSON.stringify(loginNames.map(function (login) { return { Key: login }; })); var roleFilter = role === types_1.SharingRole.Edit ? types_1.RoleType.Contributor : types_1.RoleType.Reader; // start by looking up the role definition id we need to set the roleValue return webs_1.Web.fromUrl(this.toUrl()).roleDefinitions.select("Id").filter("RoleTypeKind eq " + roleFilter).get().then(function (def) { if (!Array.isArray(def) || def.length < 1) { throw new Error("Could not locate a role defintion with RoleTypeKind " + roleFilter); } var postBody = { includeAnonymousLinkInEmail: requireSignin, peoplePickerInput: userStr, propagateAcl: propagateAcl, roleValue: "role:" + def[0].Id, useSimplifiedRoles: true, }; if (typeof emailData !== "undefined") { postBody = util_1.Util.extend(postBody, { emailBody: emailData.body, emailSubject: typeof emailData.subject !== "undefined" ? emailData.subject : "", sendEmail: true, }); } return _this.clone(QueryableShareable, "shareObject", true).postAs({ body: JSON.stringify(postBody), }); }); }; /** * Shares an object based on the supplied options * * @param options The set of options to send to the ShareObject method * @param bypass If true any processing is skipped and the options are sent directly to the ShareObject method */ QueryableShareable.prototype.shareObject = function (options, bypass) { var _this = this; if (bypass === void 0) { bypass = false; } if (bypass) { // if the bypass flag is set send the supplied parameters directly to the service return this.sendShareObjectRequest(options); } // extend our options with some defaults options = util_1.Util.extend(options, { group: null, includeAnonymousLinkInEmail: false, propagateAcl: false, useSimplifiedRoles: true, }, true); return this.getRoleValue(options.role, options.group).then(function (roleValue) { // handle the multiple input types if (!Array.isArray(options.loginNames)) { options.loginNames = [options.loginNames]; } var userStr = JSON.stringify(options.loginNames.map(function (login) { return { Key: login }; })); var postBody = { peoplePickerInput: userStr, roleValue: roleValue, url: options.url, }; if (typeof options.emailData !== "undefined" && options.emailData !== null) { postBody = util_1.Util.extend(postBody, { emailBody: options.emailData.body, emailSubject: typeof options.emailData.subject !== "undefined" ? options.emailData.subject : "Shared with you.", sendEmail: true, }); } return _this.sendShareObjectRequest(postBody); }); }; /** * Calls the web's UnshareObject method * * @param url The url of the object to unshare */ QueryableShareable.prototype.unshareObjectWeb = function (url) { return this.clone(QueryableShareable, "unshareObject", true).postAs({ body: JSON.stringify({ url: url, }), }); }; /** * Checks Permissions on the list of Users and returns back role the users have on the Item. * * @param recipients The array of Entities for which Permissions need to be checked. */ QueryableShareable.prototype.checkPermissions = function (recipients) { return this.clone(QueryableShareable, "checkPermissions", true).postAs({ body: JSON.stringify({ recipients: recipients, }), }); }; /** * Get Sharing Information. * * @param request The SharingInformationRequest Object. */ QueryableShareable.prototype.getSharingInformation = function (request) { if (request === void 0) { request = null; } return this.clone(QueryableShareable, "getSharingInformation", true).postAs({ body: JSON.stringify({ request: request, }), }); }; /** * Gets the sharing settings of an item. * * @param useSimplifiedRoles Determines whether to use simplified roles. */ QueryableShareable.prototype.getObjectSharingSettings = function (useSimplifiedRoles) { if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; } return this.clone(QueryableShareable, "getObjectSharingSettings", true).postAs({ body: JSON.stringify({ useSimplifiedRoles: useSimplifiedRoles, }), }); }; /** * Unshares this object */ QueryableShareable.prototype.unshareObject = function () { return this.clone(QueryableShareable, "unshareObject", true).postAs(); }; /** * Deletes a link by type * * @param kind Deletes a sharing link by the kind of link */ QueryableShareable.prototype.deleteLinkByKind = function (kind) { return this.clone(QueryableShareable, "deleteLinkByKind", true).post({ body: JSON.stringify({ linkKind: kind }), }); }; /** * Removes the specified link to the item. * * @param kind The kind of link to be deleted. * @param shareId */ QueryableShareable.prototype.unshareLink = function (kind, shareId) { if (shareId === void 0) { shareId = "00000000-0000-0000-0000-000000000000"; } return this.clone(QueryableShareable, "unshareLink", true).post({ body: JSON.stringify({ linkKind: kind, shareId: shareId }), }); }; /** * Calculates the roleValue string used in the sharing query * * @param role The Sharing Role * @param group The Group type */ QueryableShareable.prototype.getRoleValue = function (role, group) { // we will give group precedence, because we had to make a choice if (typeof group !== "undefined" && group !== null) { switch (group) { case types_1.RoleType.Contributor: return webs_1.Web.fromUrl(this.toUrl()).associatedMemberGroup.select("Id").getAs().then(function (g) { return "group: " + g.Id; }); case types_1.RoleType.Reader: case types_1.RoleType.Guest: return webs_1.Web.fromUrl(this.toUrl()).associatedVisitorGroup.select("Id").getAs().then(function (g) { return "group: " + g.Id; }); default: throw new Error("Could not determine role value for supplied value. Contributor, Reader, and Guest are supported"); } } else { var roleFilter = role === types_1.SharingRole.Edit ? types_1.RoleType.Contributor : types_1.RoleType.Reader; return webs_1.Web.fromUrl(this.toUrl()).roleDefinitions.select("Id").top(1).filter("RoleTypeKind eq " + roleFilter).getAs().then(function (def) { if (def.length < 1) { throw new Error("Could not locate associated role definition for supplied role. Edit and View are supported"); } return "role: " + def[0].Id; }); } }; QueryableShareable.prototype.getShareObjectWeb = function (candidate) { return Promise.resolve(webs_1.Web.fromUrl(candidate, "/_api/SP.Web.ShareObject")); }; QueryableShareable.prototype.sendShareObjectRequest = function (options) { return this.getShareObjectWeb(this.toUrl()).then(function (web) { return web.expand("UsersWithAccessRequests", "GroupsSharedWith").as(QueryableShareable).post({ body: JSON.stringify(options), }); }); }; return QueryableShareable; }(queryable_1.Queryable)); exports.QueryableShareable = QueryableShareable; var QueryableShareableWeb = (function (_super) { __extends(QueryableShareableWeb, _super); function QueryableShareableWeb() { return _super !== null && _super.apply(this, arguments) || this; } /** * Shares this web with the supplied users * @param loginNames The resolved login names to share * @param role The role to share this web * @param emailData Optional email data */ QueryableShareableWeb.prototype.shareWith = function (loginNames, role, emailData) { var _this = this; if (role === void 0) { role = types_1.SharingRole.View; } var dependency = this.addBatchDependency(); return webs_1.Web.fromUrl(this.toUrl(), "/_api/web/url").get().then(function (url) { dependency(); return _this.shareObject(util_1.Util.combinePaths(url, "/_layouts/15/aclinv.aspx?forSharing=1&mbypass=1"), loginNames, role, emailData); }); }; /** * Provides direct access to the static web.ShareObject method * * @param url The url to share * @param loginNames Resolved loginnames string[] of a single login name string * @param roleValue Role value * @param emailData Optional email data * @param groupId Optional group id * @param propagateAcl * @param includeAnonymousLinkInEmail * @param useSimplifiedRoles */ QueryableShareableWeb.prototype.shareObject = function (url, loginNames, role, emailData, group, propagateAcl, includeAnonymousLinkInEmail, useSimplifiedRoles) { if (propagateAcl === void 0) { propagateAcl = false; } if (includeAnonymousLinkInEmail === void 0) { includeAnonymousLinkInEmail = false; } if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; } return this.clone(QueryableShareable, null, true).shareObject({ emailData: emailData, group: group, includeAnonymousLinkInEmail: includeAnonymousLinkInEmail, loginNames: loginNames, propagateAcl: propagateAcl, role: role, url: url, useSimplifiedRoles: useSimplifiedRoles, }); }; /** * Supplies a method to pass any set of arguments to ShareObject * * @param options The set of options to send to ShareObject */ QueryableShareableWeb.prototype.shareObjectRaw = function (options) { return this.clone(QueryableShareable, null, true).shareObject(options, true); }; /** * Unshares the object * * @param url The url of the object to stop sharing */ QueryableShareableWeb.prototype.unshareObject = function (url) { return this.clone(QueryableShareable, null, true).unshareObjectWeb(url); }; return QueryableShareableWeb; }(queryablesecurable_1.QueryableSecurable)); exports.QueryableShareableWeb = QueryableShareableWeb; var QueryableShareableItem = (function (_super) { __extends(QueryableShareableItem, _super); function QueryableShareableItem() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a link suitable for sharing for this item * * @param kind The type of link to share * @param expiration The optional expiration date */ QueryableShareableItem.prototype.getShareLink = function (kind, expiration) { if (kind === void 0) { kind = types_1.SharingLinkKind.OrganizationView; } if (expiration === void 0) { expiration = null; } return this.clone(QueryableShareable, null, true).getShareLink(kind, expiration); }; /** * Shares this item with one or more users * * @param loginNames string or string[] of resolved login names to which this item will be shared * @param role The role (View | Edit) applied to the share * @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect. */ QueryableShareableItem.prototype.shareWith = function (loginNames, role, requireSignin, emailData) { if (role === void 0) { role = types_1.SharingRole.View; } if (requireSignin === void 0) { requireSignin = true; } return this.clone(QueryableShareable, null, true).shareWith(loginNames, role, requireSignin, false, emailData); }; /** * Checks Permissions on the list of Users and returns back role the users have on the Item. * * @param recipients The array of Entities for which Permissions need to be checked. */ QueryableShareableItem.prototype.checkSharingPermissions = function (recipients) { return this.clone(QueryableShareable, null, true).checkPermissions(recipients); }; /** * Get Sharing Information. * * @param request The SharingInformationRequest Object. */ QueryableShareableItem.prototype.getSharingInformation = function (request) { if (request === void 0) { request = null; } return this.clone(QueryableShareable, null, true).getSharingInformation(request); }; /** * Gets the sharing settings of an item. * * @param useSimplifiedRoles Determines whether to use simplified roles. */ QueryableShareableItem.prototype.getObjectSharingSettings = function (useSimplifiedRoles) { if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; } return this.clone(QueryableShareable, null, true).getObjectSharingSettings(useSimplifiedRoles); }; /** * Unshare this item */ QueryableShareableItem.prototype.unshare = function () { return this.clone(QueryableShareable, null, true).unshareObject(); }; /** * Deletes a sharing link by kind * * @param kind Deletes a sharing link by the kind of link */ QueryableShareableItem.prototype.deleteSharingLinkByKind = function (kind) { return this.clone(QueryableShareable, null, true).deleteLinkByKind(kind); }; /** * Removes the specified link to the item. * * @param kind The kind of link to be deleted. * @param shareId */ QueryableShareableItem.prototype.unshareLink = function (kind, shareId) { return this.clone(QueryableShareable, null, true).unshareLink(kind, shareId); }; return QueryableShareableItem; }(queryablesecurable_1.QueryableSecurable)); exports.QueryableShareableItem = QueryableShareableItem; var FileFolderShared = (function (_super) { __extends(FileFolderShared, _super); function FileFolderShared() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a link suitable for sharing * * @param kind The kind of link to get * @param expiration Optional, an expiration for this link */ FileFolderShared.prototype.getShareLink = function (kind, expiration) { if (kind === void 0) { kind = types_1.SharingLinkKind.OrganizationView; } if (expiration === void 0) { expiration = null; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.getShareLink(kind, expiration); }); }; /** * Checks Permissions on the list of Users and returns back role the users have on the Item. * * @param recipients The array of Entities for which Permissions need to be checked. */ FileFolderShared.prototype.checkSharingPermissions = function (recipients) { var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.checkPermissions(recipients); }); }; /** * Get Sharing Information. * * @param request The SharingInformationRequest Object. */ FileFolderShared.prototype.getSharingInformation = function (request) { if (request === void 0) { request = null; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.getSharingInformation(request); }); }; /** * Gets the sharing settings of an item. * * @param useSimplifiedRoles Determines whether to use simplified roles. */ FileFolderShared.prototype.getObjectSharingSettings = function (useSimplifiedRoles) { if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.getObjectSharingSettings(useSimplifiedRoles); }); }; /** * Unshare this item */ FileFolderShared.prototype.unshare = function () { var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.unshareObject(); }); }; /** * Deletes a sharing link by the kind of link * * @param kind The kind of link to be deleted. */ FileFolderShared.prototype.deleteSharingLinkByKind = function (kind) { var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.deleteLinkByKind(kind); }); }; /** * Removes the specified link to the item. * * @param kind The kind of link to be deleted. * @param shareId The share id to delete */ FileFolderShared.prototype.unshareLink = function (kind, shareId) { var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.unshareLink(kind, shareId); }); }; /** * For files and folders we need to use the associated item end point */ FileFolderShared.prototype.getShareable = function () { var _this = this; // sharing only works on the item end point, not the file one - so we create a folder instance with the item url internally return this.clone(QueryableShareableFile, "listItemAllFields", false).select("odata.editlink").get().then(function (d) { var shareable = new QueryableShareable(odata_1.getEntityUrl(d)); // we need to handle batching if (_this.hasBatch) { shareable = shareable.inBatch(_this.batch); } return shareable; }); }; return FileFolderShared; }(queryable_1.QueryableInstance)); exports.FileFolderShared = FileFolderShared; var QueryableShareableFile = (function (_super) { __extends(QueryableShareableFile, _super); function QueryableShareableFile() { return _super !== null && _super.apply(this, arguments) || this; } /** * Shares this item with one or more users * * @param loginNames string or string[] of resolved login names to which this item will be shared * @param role The role (View | Edit) applied to the share * @param shareEverything Share everything in this folder, even items with unique permissions. * @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource * @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect. */ QueryableShareableFile.prototype.shareWith = function (loginNames, role, requireSignin, emailData) { if (role === void 0) { role = types_1.SharingRole.View; } if (requireSignin === void 0) { requireSignin = true; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.shareWith(loginNames, role, requireSignin, false, emailData); }); }; return QueryableShareableFile; }(FileFolderShared)); exports.QueryableShareableFile = QueryableShareableFile; var QueryableShareableFolder = (function (_super) { __extends(QueryableShareableFolder, _super); function QueryableShareableFolder() { return _super !== null && _super.apply(this, arguments) || this; } /** * Shares this item with one or more users * * @param loginNames string or string[] of resolved login names to which this item will be shared * @param role The role (View | Edit) applied to the share * @param shareEverything Share everything in this folder, even items with unique permissions. * @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource * @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect. */ QueryableShareableFolder.prototype.shareWith = function (loginNames, role, requireSignin, shareEverything, emailData) { if (role === void 0) { role = types_1.SharingRole.View; } if (requireSignin === void 0) { requireSignin = true; } if (shareEverything === void 0) { shareEverything = false; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.shareWith(loginNames, role, requireSignin, shareEverything, emailData); }); }; return QueryableShareableFolder; }(FileFolderShared)); exports.QueryableShareableFolder = QueryableShareableFolder; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // reference: https://msdn.microsoft.com/en-us/library/office/dn600183.aspx Object.defineProperty(exports, "__esModule", { value: true }); /** * Determines the display mode of the given control or view */ var ControlMode; (function (ControlMode) { ControlMode[ControlMode["Display"] = 1] = "Display"; ControlMode[ControlMode["Edit"] = 2] = "Edit"; ControlMode[ControlMode["New"] = 3] = "New"; })(ControlMode = exports.ControlMode || (exports.ControlMode = {})); /** * Specifies the type of the field. */ var FieldTypes; (function (FieldTypes) { FieldTypes[FieldTypes["Invalid"] = 0] = "Invalid"; FieldTypes[FieldTypes["Integer"] = 1] = "Integer"; FieldTypes[FieldTypes["Text"] = 2] = "Text"; FieldTypes[FieldTypes["Note"] = 3] = "Note"; FieldTypes[FieldTypes["DateTime"] = 4] = "DateTime"; FieldTypes[FieldTypes["Counter"] = 5] = "Counter"; FieldTypes[FieldTypes["Choice"] = 6] = "Choice"; FieldTypes[FieldTypes["Lookup"] = 7] = "Lookup"; FieldTypes[FieldTypes["Boolean"] = 8] = "Boolean"; FieldTypes[FieldTypes["Number"] = 9] = "Number"; FieldTypes[FieldTypes["Currency"] = 10] = "Currency"; FieldTypes[FieldTypes["URL"] = 11] = "URL"; FieldTypes[FieldTypes["Computed"] = 12] = "Computed"; FieldTypes[FieldTypes["Threading"] = 13] = "Threading"; FieldTypes[FieldTypes["Guid"] = 14] = "Guid"; FieldTypes[FieldTypes["MultiChoice"] = 15] = "MultiChoice"; FieldTypes[FieldTypes["GridChoice"] = 16] = "GridChoice"; FieldTypes[FieldTypes["Calculated"] = 17] = "Calculated"; FieldTypes[FieldTypes["File"] = 18] = "File"; FieldTypes[FieldTypes["Attachments"] = 19] = "Attachments"; FieldTypes[FieldTypes["User"] = 20] = "User"; FieldTypes[FieldTypes["Recurrence"] = 21] = "Recurrence"; FieldTypes[FieldTypes["CrossProjectLink"] = 22] = "CrossProjectLink"; FieldTypes[FieldTypes["ModStat"] = 23] = "ModStat"; FieldTypes[FieldTypes["Error"] = 24] = "Error"; FieldTypes[FieldTypes["ContentTypeId"] = 25] = "ContentTypeId"; FieldTypes[FieldTypes["PageSeparator"] = 26] = "PageSeparator"; FieldTypes[FieldTypes["ThreadIndex"] = 27] = "ThreadIndex"; FieldTypes[FieldTypes["WorkflowStatus"] = 28] = "WorkflowStatus"; FieldTypes[FieldTypes["AllDayEvent"] = 29] = "AllDayEvent"; FieldTypes[FieldTypes["WorkflowEventType"] = 30] = "WorkflowEventType"; })(FieldTypes = exports.FieldTypes || (exports.FieldTypes = {})); var DateTimeFieldFormatType; (function (DateTimeFieldFormatType) { DateTimeFieldFormatType[DateTimeFieldFormatType["DateOnly"] = 0] = "DateOnly"; DateTimeFieldFormatType[DateTimeFieldFormatType["DateTime"] = 1] = "DateTime"; })(DateTimeFieldFormatType = exports.DateTimeFieldFormatType || (exports.DateTimeFieldFormatType = {})); /** * Specifies the control settings while adding a field. */ var AddFieldOptions; (function (AddFieldOptions) { /** * Specify that a new field added to the list must also be added to the default content type in the site collection */ AddFieldOptions[AddFieldOptions["DefaultValue"] = 0] = "DefaultValue"; /** * Specify that a new field added to the list must also be added to the default content type in the site collection. */ AddFieldOptions[AddFieldOptions["AddToDefaultContentType"] = 1] = "AddToDefaultContentType"; /** * Specify that a new field must not be added to any other content type */ AddFieldOptions[AddFieldOptions["AddToNoContentType"] = 2] = "AddToNoContentType"; /** * Specify that a new field that is added to the specified list must also be added to all content types in the site collection */ AddFieldOptions[AddFieldOptions["AddToAllContentTypes"] = 4] = "AddToAllContentTypes"; /** * Specify adding an internal field name hint for the purpose of avoiding possible database locking or field renaming operations */ AddFieldOptions[AddFieldOptions["AddFieldInternalNameHint"] = 8] = "AddFieldInternalNameHint"; /** * Specify that a new field that is added to the specified list must also be added to the default list view */ AddFieldOptions[AddFieldOptions["AddFieldToDefaultView"] = 16] = "AddFieldToDefaultView"; /** * Specify to confirm that no other field has the same display name */ AddFieldOptions[AddFieldOptions["AddFieldCheckDisplayName"] = 32] = "AddFieldCheckDisplayName"; })(AddFieldOptions = exports.AddFieldOptions || (exports.AddFieldOptions = {})); var CalendarType; (function (CalendarType) { CalendarType[CalendarType["Gregorian"] = 1] = "Gregorian"; CalendarType[CalendarType["Japan"] = 3] = "Japan"; CalendarType[CalendarType["Taiwan"] = 4] = "Taiwan"; CalendarType[CalendarType["Korea"] = 5] = "Korea"; CalendarType[CalendarType["Hijri"] = 6] = "Hijri"; CalendarType[CalendarType["Thai"] = 7] = "Thai"; CalendarType[CalendarType["Hebrew"] = 8] = "Hebrew"; CalendarType[CalendarType["GregorianMEFrench"] = 9] = "GregorianMEFrench"; CalendarType[CalendarType["GregorianArabic"] = 10] = "GregorianArabic"; CalendarType[CalendarType["GregorianXLITEnglish"] = 11] = "GregorianXLITEnglish"; CalendarType[CalendarType["GregorianXLITFrench"] = 12] = "GregorianXLITFrench"; CalendarType[CalendarType["KoreaJapanLunar"] = 14] = "KoreaJapanLunar"; CalendarType[CalendarType["ChineseLunar"] = 15] = "ChineseLunar"; CalendarType[CalendarType["SakaEra"] = 16] = "SakaEra"; CalendarType[CalendarType["UmAlQura"] = 23] = "UmAlQura"; })(CalendarType = exports.CalendarType || (exports.CalendarType = {})); var UrlFieldFormatType; (function (UrlFieldFormatType) { UrlFieldFormatType[UrlFieldFormatType["Hyperlink"] = 0] = "Hyperlink"; UrlFieldFormatType[UrlFieldFormatType["Image"] = 1] = "Image"; })(UrlFieldFormatType = exports.UrlFieldFormatType || (exports.UrlFieldFormatType = {})); var PermissionKind; (function (PermissionKind) { /** * Has no permissions on the Site. Not available through the user interface. */ PermissionKind[PermissionKind["EmptyMask"] = 0] = "EmptyMask"; /** * View items in lists, documents in document libraries, and Web discussion comments. */ PermissionKind[PermissionKind["ViewListItems"] = 1] = "ViewListItems"; /** * Add items to lists, documents to document libraries, and Web discussion comments. */ PermissionKind[PermissionKind["AddListItems"] = 2] = "AddListItems"; /** * Edit items in lists, edit documents in document libraries, edit Web discussion comments * in documents, and customize Web Part Pages in document libraries. */ PermissionKind[PermissionKind["EditListItems"] = 3] = "EditListItems"; /** * Delete items from a list, documents from a document library, and Web discussion * comments in documents. */ PermissionKind[PermissionKind["DeleteListItems"] = 4] = "DeleteListItems"; /** * Approve a minor version of a list item or document. */ PermissionKind[PermissionKind["ApproveItems"] = 5] = "ApproveItems"; /** * View the source of documents with server-side file handlers. */ PermissionKind[PermissionKind["OpenItems"] = 6] = "OpenItems"; /** * View past versions of a list item or document. */ PermissionKind[PermissionKind["ViewVersions"] = 7] = "ViewVersions"; /** * Delete past versions of a list item or document. */ PermissionKind[PermissionKind["DeleteVersions"] = 8] = "DeleteVersions"; /** * Discard or check in a document which is checked out to another user. */ PermissionKind[PermissionKind["CancelCheckout"] = 9] = "CancelCheckout"; /** * Create, change, and delete personal views of lists. */ PermissionKind[PermissionKind["ManagePersonalViews"] = 10] = "ManagePersonalViews"; /** * Create and delete lists, add or remove columns in a list, and add or remove public views of a list. */ PermissionKind[PermissionKind["ManageLists"] = 12] = "ManageLists"; /** * View forms, views, and application pages, and enumerate lists. */ PermissionKind[PermissionKind["ViewFormPages"] = 13] = "ViewFormPages"; /** * Make content of a list or document library retrieveable for anonymous users through SharePoint search. * The list permissions in the site do not change. */ PermissionKind[PermissionKind["AnonymousSearchAccessList"] = 14] = "AnonymousSearchAccessList"; /** * Allow users to open a Site, list, or folder to access items inside that container. */ PermissionKind[PermissionKind["Open"] = 17] = "Open"; /** * View pages in a Site. */ PermissionKind[PermissionKind["ViewPages"] = 18] = "ViewPages"; /** * Add, change, or delete HTML pages or Web Part Pages, and edit the Site using * a Windows SharePoint Services compatible editor. */ PermissionKind[PermissionKind["AddAndCustomizePages"] = 19] = "AddAndCustomizePages"; /** * Apply a theme or borders to the entire Site. */ PermissionKind[PermissionKind["ApplyThemeAndBorder"] = 20] = "ApplyThemeAndBorder"; /** * Apply a style sheet (.css file) to the Site. */ PermissionKind[PermissionKind["ApplyStyleSheets"] = 21] = "ApplyStyleSheets"; /** * View reports on Site usage. */ PermissionKind[PermissionKind["ViewUsageData"] = 22] = "ViewUsageData"; /** * Create a Site using Self-Service Site Creation. */ PermissionKind[PermissionKind["CreateSSCSite"] = 23] = "CreateSSCSite"; /** * Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites. */ PermissionKind[PermissionKind["ManageSubwebs"] = 24] = "ManageSubwebs"; /** * Create a group of users that can be used anywhere within the site collection. */ PermissionKind[PermissionKind["CreateGroups"] = 25] = "CreateGroups"; /** * Create and change permission levels on the Site and assign permissions to users * and groups. */ PermissionKind[PermissionKind["ManagePermissions"] = 26] = "ManagePermissions"; /** * Enumerate files and folders in a Site using Microsoft Office SharePoint Designer * and WebDAV interfaces. */ PermissionKind[PermissionKind["BrowseDirectories"] = 27] = "BrowseDirectories"; /** * View information about users of the Site. */ PermissionKind[PermissionKind["BrowseUserInfo"] = 28] = "BrowseUserInfo"; /** * Add or remove personal Web Parts on a Web Part Page. */ PermissionKind[PermissionKind["AddDelPrivateWebParts"] = 29] = "AddDelPrivateWebParts"; /** * Update Web Parts to display personalized information. */ PermissionKind[PermissionKind["UpdatePersonalWebParts"] = 30] = "UpdatePersonalWebParts"; /** * Grant the ability to perform all administration tasks for the Site as well as * manage content, activate, deactivate, or edit properties of Site scoped Features * through the object model or through the user interface (UI). When granted on the * root Site of a Site Collection, activate, deactivate, or edit properties of * site collection scoped Features through the object model. To browse to the Site * Collection Features page and activate or deactivate Site Collection scoped Features * through the UI, you must be a Site Collection administrator. */ PermissionKind[PermissionKind["ManageWeb"] = 31] = "ManageWeb"; /** * Content of lists and document libraries in the Web site will be retrieveable for anonymous users through * SharePoint search if the list or document library has AnonymousSearchAccessList set. */ PermissionKind[PermissionKind["AnonymousSearchAccessWebLists"] = 32] = "AnonymousSearchAccessWebLists"; /** * Use features that launch client applications. Otherwise, users must work on documents * locally and upload changes. */ PermissionKind[PermissionKind["UseClientIntegration"] = 37] = "UseClientIntegration"; /** * Use SOAP, WebDAV, or Microsoft Office SharePoint Designer interfaces to access the Site. */ PermissionKind[PermissionKind["UseRemoteAPIs"] = 38] = "UseRemoteAPIs"; /** * Manage alerts for all users of the Site. */ PermissionKind[PermissionKind["ManageAlerts"] = 39] = "ManageAlerts"; /** * Create e-mail alerts. */ PermissionKind[PermissionKind["CreateAlerts"] = 40] = "CreateAlerts"; /** * Allows a user to change his or her user information, such as adding a picture. */ PermissionKind[PermissionKind["EditMyUserInfo"] = 41] = "EditMyUserInfo"; /** * Enumerate permissions on Site, list, folder, document, or list item. */ PermissionKind[PermissionKind["EnumeratePermissions"] = 63] = "EnumeratePermissions"; /** * Has all permissions on the Site. Not available through the user interface. */ PermissionKind[PermissionKind["FullMask"] = 65] = "FullMask"; })(PermissionKind = exports.PermissionKind || (exports.PermissionKind = {})); var PrincipalType; (function (PrincipalType) { PrincipalType[PrincipalType["None"] = 0] = "None"; PrincipalType[PrincipalType["User"] = 1] = "User"; PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList"; PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup"; PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup"; PrincipalType[PrincipalType["All"] = 15] = "All"; })(PrincipalType = exports.PrincipalType || (exports.PrincipalType = {})); var PrincipalSource; (function (PrincipalSource) { PrincipalSource[PrincipalSource["None"] = 0] = "None"; PrincipalSource[PrincipalSource["UserInfoList"] = 1] = "UserInfoList"; PrincipalSource[PrincipalSource["Windows"] = 2] = "Windows"; PrincipalSource[PrincipalSource["MembershipProvider"] = 4] = "MembershipProvider"; PrincipalSource[PrincipalSource["RoleProvider"] = 8] = "RoleProvider"; PrincipalSource[PrincipalSource["All"] = 15] = "All"; })(PrincipalSource = exports.PrincipalSource || (exports.PrincipalSource = {})); var RoleType; (function (RoleType) { RoleType[RoleType["None"] = 0] = "None"; RoleType[RoleType["Guest"] = 1] = "Guest"; RoleType[RoleType["Reader"] = 2] = "Reader"; RoleType[RoleType["Contributor"] = 3] = "Contributor"; RoleType[RoleType["WebDesigner"] = 4] = "WebDesigner"; RoleType[RoleType["Administrator"] = 5] = "Administrator"; })(RoleType = exports.RoleType || (exports.RoleType = {})); var PageType; (function (PageType) { PageType[PageType["Invalid"] = -1] = "Invalid"; PageType[PageType["DefaultView"] = 0] = "DefaultView"; PageType[PageType["NormalView"] = 1] = "NormalView"; PageType[PageType["DialogView"] = 2] = "DialogView"; PageType[PageType["View"] = 3] = "View"; PageType[PageType["DisplayForm"] = 4] = "DisplayForm"; PageType[PageType["DisplayFormDialog"] = 5] = "DisplayFormDialog"; PageType[PageType["EditForm"] = 6] = "EditForm"; PageType[PageType["EditFormDialog"] = 7] = "EditFormDialog"; PageType[PageType["NewForm"] = 8] = "NewForm"; PageType[PageType["NewFormDialog"] = 9] = "NewFormDialog"; PageType[PageType["SolutionForm"] = 10] = "SolutionForm"; PageType[PageType["PAGE_MAXITEMS"] = 11] = "PAGE_MAXITEMS"; })(PageType = exports.PageType || (exports.PageType = {})); var SharingLinkKind; (function (SharingLinkKind) { /** * Uninitialized link */ SharingLinkKind[SharingLinkKind["Uninitialized"] = 0] = "Uninitialized"; /** * Direct link to the object being shared */ SharingLinkKind[SharingLinkKind["Direct"] = 1] = "Direct"; /** * Organization-shareable link to the object being shared with view permissions */ SharingLinkKind[SharingLinkKind["OrganizationView"] = 2] = "OrganizationView"; /** * Organization-shareable link to the object being shared with edit permissions */ SharingLinkKind[SharingLinkKind["OrganizationEdit"] = 3] = "OrganizationEdit"; /** * View only anonymous link */ SharingLinkKind[SharingLinkKind["AnonymousView"] = 4] = "AnonymousView"; /** * Read/Write anonymous link */ SharingLinkKind[SharingLinkKind["AnonymousEdit"] = 5] = "AnonymousEdit"; /** * Flexible sharing Link where properties can change without affecting link URL */ SharingLinkKind[SharingLinkKind["Flexible"] = 6] = "Flexible"; })(SharingLinkKind = exports.SharingLinkKind || (exports.SharingLinkKind = {})); ; /** * Indicates the role of the sharing link */ var SharingRole; (function (SharingRole) { SharingRole[SharingRole["None"] = 0] = "None"; SharingRole[SharingRole["View"] = 1] = "View"; SharingRole[SharingRole["Edit"] = 2] = "Edit"; SharingRole[SharingRole["Owner"] = 3] = "Owner"; })(SharingRole = exports.SharingRole || (exports.SharingRole = {})); var SharingOperationStatusCode; (function (SharingOperationStatusCode) { /** * The share operation completed without errors. */ SharingOperationStatusCode[SharingOperationStatusCode["CompletedSuccessfully"] = 0] = "CompletedSuccessfully"; /** * The share operation completed and generated requests for access. */ SharingOperationStatusCode[SharingOperationStatusCode["AccessRequestsQueued"] = 1] = "AccessRequestsQueued"; /** * The share operation failed as there were no resolved users. */ SharingOperationStatusCode[SharingOperationStatusCode["NoResolvedUsers"] = -1] = "NoResolvedUsers"; /** * The share operation failed due to insufficient permissions. */ SharingOperationStatusCode[SharingOperationStatusCode["AccessDenied"] = -2] = "AccessDenied"; /** * The share operation failed when attempting a cross site share, which is not supported. */ SharingOperationStatusCode[SharingOperationStatusCode["CrossSiteRequestNotSupported"] = -3] = "CrossSiteRequestNotSupported"; /** * The sharing operation failed due to an unknown error. */ SharingOperationStatusCode[SharingOperationStatusCode["UnknowError"] = -4] = "UnknowError"; /** * The text you typed is too long. Please shorten it. */ SharingOperationStatusCode[SharingOperationStatusCode["EmailBodyTooLong"] = -5] = "EmailBodyTooLong"; /** * The maximum number of unique scopes in the list has been exceeded. */ SharingOperationStatusCode[SharingOperationStatusCode["ListUniqueScopesExceeded"] = -6] = "ListUniqueScopesExceeded"; /** * The share operation failed because a sharing capability is disabled in the site. */ SharingOperationStatusCode[SharingOperationStatusCode["CapabilityDisabled"] = -7] = "CapabilityDisabled"; /** * The specified object for the share operation is not supported. */ SharingOperationStatusCode[SharingOperationStatusCode["ObjectNotSupported"] = -8] = "ObjectNotSupported"; /** * A SharePoint group cannot contain another SharePoint group. */ SharingOperationStatusCode[SharingOperationStatusCode["NestedGroupsNotSupported"] = -9] = "NestedGroupsNotSupported"; })(SharingOperationStatusCode = exports.SharingOperationStatusCode || (exports.SharingOperationStatusCode = {})); var SPSharedObjectType; (function (SPSharedObjectType) { SPSharedObjectType[SPSharedObjectType["Unknown"] = 0] = "Unknown"; SPSharedObjectType[SPSharedObjectType["File"] = 1] = "File"; SPSharedObjectType[SPSharedObjectType["Folder"] = 2] = "Folder"; SPSharedObjectType[SPSharedObjectType["Item"] = 3] = "Item"; SPSharedObjectType[SPSharedObjectType["List"] = 4] = "List"; SPSharedObjectType[SPSharedObjectType["Web"] = 5] = "Web"; SPSharedObjectType[SPSharedObjectType["Max"] = 6] = "Max"; })(SPSharedObjectType = exports.SPSharedObjectType || (exports.SPSharedObjectType = {})); var SharingDomainRestrictionMode; (function (SharingDomainRestrictionMode) { SharingDomainRestrictionMode[SharingDomainRestrictionMode["None"] = 0] = "None"; SharingDomainRestrictionMode[SharingDomainRestrictionMode["AllowList"] = 1] = "AllowList"; SharingDomainRestrictionMode[SharingDomainRestrictionMode["BlockList"] = 2] = "BlockList"; })(SharingDomainRestrictionMode = exports.SharingDomainRestrictionMode || (exports.SharingDomainRestrictionMode = {})); ; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var collections_1 = __webpack_require__(6); var pnplibconfig_1 = __webpack_require__(4); /** * A wrapper class to provide a consistent interface to browser based storage * */ var PnPClientStorageWrapper = (function () { /** * Creates a new instance of the PnPClientStorageWrapper class * * @constructor */ function PnPClientStorageWrapper(store, defaultTimeoutMinutes) { this.store = store; this.defaultTimeoutMinutes = defaultTimeoutMinutes; this.defaultTimeoutMinutes = (defaultTimeoutMinutes === void 0) ? -1 : defaultTimeoutMinutes; this.enabled = this.test(); } /** * Get a value from storage, or null if that value does not exist * * @param key The key whose value we want to retrieve */ PnPClientStorageWrapper.prototype.get = function (key) { if (!this.enabled) { return null; } var o = this.store.getItem(key); if (o == null) { return null; } var persistable = JSON.parse(o); if (new Date(persistable.expiration) <= new Date()) { this.delete(key); return null; } else { return persistable.value; } }; /** * Adds a value to the underlying storage * * @param key The key to use when storing the provided value * @param o The value to store * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.put = function (key, o, expire) { if (this.enabled) { this.store.setItem(key, this.createPersistable(o, expire)); } }; /** * Deletes a value from the underlying storage * * @param key The key of the pair we want to remove from storage */ PnPClientStorageWrapper.prototype.delete = function (key) { if (this.enabled) { this.store.removeItem(key); } }; /** * Gets an item from the underlying storage, or adds it if it does not exist using the supplied getter function * * @param key The key to use when storing the provided value * @param getter A function which will upon execution provide the desired value * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.getOrPut = function (key, getter, expire) { var _this = this; if (!this.enabled) { return getter(); } return new Promise(function (resolve) { var o = _this.get(key); if (o == null) { getter().then(function (d) { _this.put(key, d, expire); resolve(d); }); } else { resolve(o); } }); }; /** * Used to determine if the wrapped storage is available currently */ PnPClientStorageWrapper.prototype.test = function () { var str = "test"; try { this.store.setItem(str, str); this.store.removeItem(str); return true; } catch (e) { return false; } }; /** * Creates the persistable to store */ PnPClientStorageWrapper.prototype.createPersistable = function (o, expire) { if (typeof expire === "undefined") { // ensure we are by default inline with the global library setting var defaultTimeout = pnplibconfig_1.RuntimeConfig.defaultCachingTimeoutSeconds; if (this.defaultTimeoutMinutes > 0) { defaultTimeout = this.defaultTimeoutMinutes * 60; } expire = util_1.Util.dateAdd(new Date(), "second", defaultTimeout); } return JSON.stringify({ expiration: expire, value: o }); }; return PnPClientStorageWrapper; }()); exports.PnPClientStorageWrapper = PnPClientStorageWrapper; /** * A thin implementation of in-memory storage for use in nodejs */ var MemoryStorage = (function () { function MemoryStorage(_store) { if (_store === void 0) { _store = new collections_1.Dictionary(); } this._store = _store; } Object.defineProperty(MemoryStorage.prototype, "length", { get: function () { return this._store.count(); }, enumerable: true, configurable: true }); MemoryStorage.prototype.clear = function () { this._store.clear(); }; MemoryStorage.prototype.getItem = function (key) { return this._store.get(key); }; MemoryStorage.prototype.key = function (index) { return this._store.getKeys()[index]; }; MemoryStorage.prototype.removeItem = function (key) { this._store.remove(key); }; MemoryStorage.prototype.setItem = function (key, data) { this._store.add(key, data); }; return MemoryStorage; }()); /** * A class that will establish wrappers for both local and session storage */ var PnPClientStorage = (function () { /** * Creates a new instance of the PnPClientStorage class * * @constructor */ function PnPClientStorage() { this.local = typeof localStorage !== "undefined" ? new PnPClientStorageWrapper(localStorage) : new PnPClientStorageWrapper(new MemoryStorage()); this.session = typeof sessionStorage !== "undefined" ? new PnPClientStorageWrapper(sessionStorage) : new PnPClientStorageWrapper(new MemoryStorage()); } return PnPClientStorage; }()); exports.PnPClientStorage = PnPClientStorage; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var digestcache_1 = __webpack_require__(38); var util_1 = __webpack_require__(0); var pnplibconfig_1 = __webpack_require__(4); var exceptions_1 = __webpack_require__(3); var HttpClient = (function () { function HttpClient() { this._impl = pnplibconfig_1.RuntimeConfig.fetchClientFactory(); this._digestCache = new digestcache_1.DigestCache(this); } HttpClient.prototype.fetch = function (url, options) { var _this = this; if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { cache: "no-cache", credentials: "same-origin" }, true); var headers = new Headers(); // first we add the global headers so they can be overwritten by any passed in locally to this call this.mergeHeaders(headers, pnplibconfig_1.RuntimeConfig.headers); // second we add the local options so we can overwrite the globals this.mergeHeaders(headers, options.headers); // lastly we apply any default headers we need that may not exist if (!headers.has("Accept")) { headers.append("Accept", "application/json"); } if (!headers.has("Content-Type")) { headers.append("Content-Type", "application/json;odata=verbose;charset=utf-8"); } if (!headers.has("X-ClientService-ClientTag")) { headers.append("X-ClientService-ClientTag", "PnPCoreJS:2.0.6-beta.1"); } opts = util_1.Util.extend(opts, { headers: headers }); if (opts.method && opts.method.toUpperCase() !== "GET") { if (!headers.has("X-RequestDigest")) { var index = url.indexOf("_api/"); if (index < 0) { throw new exceptions_1.APIUrlException(); } var webUrl = url.substr(0, index); return this._digestCache.getDigest(webUrl) .then(function (digest) { headers.append("X-RequestDigest", digest); return _this.fetchRaw(url, opts); }); } } return this.fetchRaw(url, opts); }; HttpClient.prototype.fetchRaw = function (url, options) { var _this = this; if (options === void 0) { options = {}; } // here we need to normalize the headers var rawHeaders = new Headers(); this.mergeHeaders(rawHeaders, options.headers); options = util_1.Util.extend(options, { headers: rawHeaders }); var retry = function (ctx) { _this._impl.fetch(url, options).then(function (response) { return ctx.resolve(response); }).catch(function (response) { // grab our current delay var delay = ctx.delay; // Check if request was throttled - http status code 429 // Check is request failed due to server unavailable - http status code 503 if (response.status !== 429 && response.status !== 503) { ctx.reject(response); } // Increment our counters. ctx.delay *= 2; ctx.attempts++; // If we have exceeded the retry count, reject. if (ctx.retryCount <= ctx.attempts) { ctx.reject(response); } // Set our retry timeout for {delay} milliseconds. setTimeout(util_1.Util.getCtxCallback(_this, retry, ctx), delay); }); }; return new Promise(function (resolve, reject) { var retryContext = { attempts: 0, delay: 100, reject: reject, resolve: resolve, retryCount: 7, }; retry.call(_this, retryContext); }); }; HttpClient.prototype.get = function (url, options) { if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { method: "GET" }); return this.fetch(url, opts); }; HttpClient.prototype.post = function (url, options) { if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { method: "POST" }); return this.fetch(url, opts); }; HttpClient.prototype.patch = function (url, options) { if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { method: "PATCH" }); return this.fetch(url, opts); }; HttpClient.prototype.delete = function (url, options) { if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { method: "DELETE" }); return this.fetch(url, opts); }; HttpClient.prototype.mergeHeaders = function (target, source) { if (typeof source !== "undefined" && source !== null) { var temp = new Request("", { headers: source }); temp.headers.forEach(function (value, name) { target.append(name, value); }); } }; return HttpClient; }()); exports.HttpClient = HttpClient; ; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var queryable_1 = __webpack_require__(1); /** * Describes a collection of content types * */ var ContentTypes = (function (_super) { __extends(ContentTypes, _super); /** * Creates a new instance of the ContentTypes class * * @param baseUrl The url or Queryable which forms the parent of this content types collection */ function ContentTypes(baseUrl, path) { if (path === void 0) { path = "contenttypes"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a ContentType by content type id */ ContentTypes.prototype.getById = function (id) { var ct = new ContentType(this); ct.concat("('" + id + "')"); return ct; }; /** * Adds an existing contenttype to a content type collection * * @param contentTypeId in the following format, for example: 0x010102 */ ContentTypes.prototype.addAvailableContentType = function (contentTypeId) { var _this = this; var postBody = JSON.stringify({ "contentTypeId": contentTypeId, }); return this.clone(ContentTypes, "addAvailableContentType", true).postAs({ body: postBody }).then(function (data) { return { contentType: _this.getById(data.id), data: data, }; }); }; /** * Adds a new content type to the collection * * @param id The desired content type id for the new content type (also determines the parent content type) * @param name The name of the content type * @param description The description of the content type * @param group The group in which to add the content type * @param additionalSettings Any additional settings to provide when creating the content type * */ ContentTypes.prototype.add = function (id, name, description, group, additionalSettings) { var _this = this; if (description === void 0) { description = ""; } if (group === void 0) { group = "Custom Content Types"; } if (additionalSettings === void 0) { additionalSettings = {}; } var postBody = JSON.stringify(util_1.Util.extend({ "Description": description, "Group": group, "Id": { "StringValue": id }, "Name": name, "__metadata": { "type": "SP.ContentType" }, }, additionalSettings)); return this.post({ body: postBody }).then(function (data) { return { contentType: _this.getById(data.id), data: data }; }); }; return ContentTypes; }(queryable_1.QueryableCollection)); exports.ContentTypes = ContentTypes; /** * Describes a single ContentType instance * */ var ContentType = (function (_super) { __extends(ContentType, _super); function ContentType() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ContentType.prototype, "fieldLinks", { /** * Gets the column (also known as field) references in the content type. */ get: function () { return new FieldLinks(this); }, enumerable: true, configurable: true }); Object.defineProperty(ContentType.prototype, "fields", { /** * Gets a value that specifies the collection of fields for the content type. */ get: function () { return new queryable_1.QueryableCollection(this, "fields"); }, enumerable: true, configurable: true }); Object.defineProperty(ContentType.prototype, "parent", { /** * Gets the parent content type of the content type. */ get: function () { return new ContentType(this, "parent"); }, enumerable: true, configurable: true }); Object.defineProperty(ContentType.prototype, "workflowAssociations", { /** * Gets a value that specifies the collection of workflow associations for the content type. */ get: function () { return new queryable_1.QueryableCollection(this, "workflowAssociations"); }, enumerable: true, configurable: true }); /** * Delete this content type */ ContentType.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; return ContentType; }(queryable_1.QueryableInstance)); exports.ContentType = ContentType; /** * Represents a collection of field link instances */ var FieldLinks = (function (_super) { __extends(FieldLinks, _super); /** * Creates a new instance of the ContentType class * * @param baseUrl The url or Queryable which forms the parent of this content type instance */ function FieldLinks(baseUrl, path) { if (path === void 0) { path = "fieldlinks"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a FieldLink by GUID id * * @param id The GUID id of the field link */ FieldLinks.prototype.getById = function (id) { var fl = new FieldLink(this); fl.concat("(guid'" + id + "')"); return fl; }; return FieldLinks; }(queryable_1.QueryableCollection)); exports.FieldLinks = FieldLinks; /** * Represents a field link instance */ var FieldLink = (function (_super) { __extends(FieldLink, _super); function FieldLink() { return _super !== null && _super.apply(this, arguments) || this; } return FieldLink; }(queryable_1.QueryableInstance)); exports.FieldLink = FieldLink; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var sitegroups_1 = __webpack_require__(18); var util_1 = __webpack_require__(0); /** * Describes a set of role assignments for the current scope * */ var RoleAssignments = (function (_super) { __extends(RoleAssignments, _super); /** * Creates a new instance of the RoleAssignments class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function RoleAssignments(baseUrl, path) { if (path === void 0) { path = "roleassignments"; } return _super.call(this, baseUrl, path) || this; } /** * Adds a new role assignment with the specified principal and role definitions to the collection. * * @param principalId The ID of the user or group to assign permissions to * @param roleDefId The ID of the role definition that defines the permissions to assign * */ RoleAssignments.prototype.add = function (principalId, roleDefId) { return this.clone(RoleAssignments, "addroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")", true).post(); }; /** * Removes the role assignment with the specified principal and role definition from the collection * * @param principalId The ID of the user or group in the role assignment. * @param roleDefId The ID of the role definition in the role assignment * */ RoleAssignments.prototype.remove = function (principalId, roleDefId) { return this.clone(RoleAssignments, "removeroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")", true).post(); }; /** * Gets the role assignment associated with the specified principal ID from the collection. * * @param id The id of the role assignment */ RoleAssignments.prototype.getById = function (id) { var ra = new RoleAssignment(this); ra.concat("(" + id + ")"); return ra; }; return RoleAssignments; }(queryable_1.QueryableCollection)); exports.RoleAssignments = RoleAssignments; var RoleAssignment = (function (_super) { __extends(RoleAssignment, _super); function RoleAssignment() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(RoleAssignment.prototype, "groups", { get: function () { return new sitegroups_1.SiteGroups(this, "groups"); }, enumerable: true, configurable: true }); Object.defineProperty(RoleAssignment.prototype, "bindings", { /** * Get the role definition bindings for this role assignment * */ get: function () { return new RoleDefinitionBindings(this); }, enumerable: true, configurable: true }); /** * Delete this role assignment * */ RoleAssignment.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; return RoleAssignment; }(queryable_1.QueryableInstance)); exports.RoleAssignment = RoleAssignment; var RoleDefinitions = (function (_super) { __extends(RoleDefinitions, _super); /** * Creates a new instance of the RoleDefinitions class * * @param baseUrl The url or Queryable which forms the parent of this fields collection * @param path * */ function RoleDefinitions(baseUrl, path) { if (path === void 0) { path = "roledefinitions"; } return _super.call(this, baseUrl, path) || this; } /** * Gets the role definition with the specified ID from the collection. * * @param id The ID of the role definition. * */ RoleDefinitions.prototype.getById = function (id) { return new RoleDefinition(this, "getById(" + id + ")"); }; /** * Gets the role definition with the specified name. * * @param name The name of the role definition. * */ RoleDefinitions.prototype.getByName = function (name) { return new RoleDefinition(this, "getbyname('" + name + "')"); }; /** * Gets the role definition with the specified type. * * @param name The name of the role definition. * */ RoleDefinitions.prototype.getByType = function (roleTypeKind) { return new RoleDefinition(this, "getbytype(" + roleTypeKind + ")"); }; /** * Create a role definition * * @param name The new role definition's name * @param description The new role definition's description * @param order The order in which the role definition appears * @param basePermissions The permissions mask for this role definition * */ RoleDefinitions.prototype.add = function (name, description, order, basePermissions) { var _this = this; var postBody = JSON.stringify({ BasePermissions: util_1.Util.extend({ __metadata: { type: "SP.BasePermissions" } }, basePermissions), Description: description, Name: name, Order: order, __metadata: { "type": "SP.RoleDefinition" }, }); return this.post({ body: postBody }).then(function (data) { return { data: data, definition: _this.getById(data.Id), }; }); }; return RoleDefinitions; }(queryable_1.QueryableCollection)); exports.RoleDefinitions = RoleDefinitions; var RoleDefinition = (function (_super) { __extends(RoleDefinition, _super); function RoleDefinition() { return _super !== null && _super.apply(this, arguments) || this; } /** * Updates this web intance with the supplied properties * * @param properties A plain object hash of values to update for the web */ /* tslint:disable no-string-literal */ RoleDefinition.prototype.update = function (properties) { var _this = this; if (typeof properties.hasOwnProperty("BasePermissions") !== "undefined") { properties["BasePermissions"] = util_1.Util.extend({ __metadata: { type: "SP.BasePermissions" } }, properties["BasePermissions"]); } var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.RoleDefinition" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { var retDef = _this; if (properties.hasOwnProperty("Name")) { var parent_1 = _this.getParent(RoleDefinitions, _this.parentUrl, ""); retDef = parent_1.getByName(properties["Name"]); } return { data: data, definition: retDef, }; }); }; /* tslint:enable */ /** * Delete this role definition * */ RoleDefinition.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; return RoleDefinition; }(queryable_1.QueryableInstance)); exports.RoleDefinition = RoleDefinition; var RoleDefinitionBindings = (function (_super) { __extends(RoleDefinitionBindings, _super); function RoleDefinitionBindings(baseUrl, path) { if (path === void 0) { path = "roledefinitionbindings"; } return _super.call(this, baseUrl, path) || this; } return RoleDefinitionBindings; }(queryable_1.QueryableCollection)); exports.RoleDefinitionBindings = RoleDefinitionBindings; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var siteusers_1 = __webpack_require__(30); var util_1 = __webpack_require__(0); /** * Principal Type enum * */ var PrincipalType; (function (PrincipalType) { PrincipalType[PrincipalType["None"] = 0] = "None"; PrincipalType[PrincipalType["User"] = 1] = "User"; PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList"; PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup"; PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup"; PrincipalType[PrincipalType["All"] = 15] = "All"; })(PrincipalType = exports.PrincipalType || (exports.PrincipalType = {})); /** * Describes a collection of site groups * */ var SiteGroups = (function (_super) { __extends(SiteGroups, _super); /** * Creates a new instance of the SiteGroups class * * @param baseUrl The url or Queryable which forms the parent of this group collection */ function SiteGroups(baseUrl, path) { if (path === void 0) { path = "sitegroups"; } return _super.call(this, baseUrl, path) || this; } /** * Adds a new group to the site collection * * @param props The group properties object of property names and values to be set for the group */ SiteGroups.prototype.add = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.Group" } }, properties)); return this.post({ body: postBody }).then(function (data) { return { data: data, group: _this.getById(data.Id), }; }); }; /** * Gets a group from the collection by name * * @param groupName The name of the group to retrieve */ SiteGroups.prototype.getByName = function (groupName) { return new SiteGroup(this, "getByName('" + groupName + "')"); }; /** * Gets a group from the collection by id * * @param id The id of the group to retrieve */ SiteGroups.prototype.getById = function (id) { var sg = new SiteGroup(this); sg.concat("(" + id + ")"); return sg; }; /** * Removes the group with the specified member id from the collection * * @param id The id of the group to remove */ SiteGroups.prototype.removeById = function (id) { return this.clone(SiteGroups, "removeById('" + id + "')", true).post(); }; /** * Removes the cross-site group with the specified name from the collection * * @param loginName The name of the group to remove */ SiteGroups.prototype.removeByLoginName = function (loginName) { return this.clone(SiteGroups, "removeByLoginName('" + loginName + "')", true).post(); }; return SiteGroups; }(queryable_1.QueryableCollection)); exports.SiteGroups = SiteGroups; /** * Describes a single group * */ var SiteGroup = (function (_super) { __extends(SiteGroup, _super); function SiteGroup() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(SiteGroup.prototype, "users", { /** * Gets the users for this group * */ get: function () { return new siteusers_1.SiteUsers(this, "users"); }, enumerable: true, configurable: true }); /** * Updates this group instance with the supplied properties * * @param properties A GroupWriteableProperties object of property names and values to update for the group */ /* tslint:disable no-string-literal */ SiteGroup.prototype.update = function (properties) { var _this = this; var postBody = util_1.Util.extend({ "__metadata": { "type": "SP.Group" } }, properties); return this.post({ body: JSON.stringify(postBody), headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { var retGroup = _this; if (properties.hasOwnProperty("Title")) { retGroup = _this.getParent(SiteGroup, _this.parentUrl, "getByName('" + properties["Title"] + "')"); } return { data: data, group: retGroup, }; }); }; return SiteGroup; }(queryable_1.QueryableInstance)); exports.SiteGroup = SiteGroup; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); /** * Describes a collection of user custom actions * */ var UserCustomActions = (function (_super) { __extends(UserCustomActions, _super); /** * Creates a new instance of the UserCustomActions class * * @param baseUrl The url or Queryable which forms the parent of this user custom actions collection */ function UserCustomActions(baseUrl, path) { if (path === void 0) { path = "usercustomactions"; } return _super.call(this, baseUrl, path) || this; } /** * Returns the user custom action with the specified id * * @param id The GUID id of the user custom action to retrieve */ UserCustomActions.prototype.getById = function (id) { var uca = new UserCustomAction(this); uca.concat("('" + id + "')"); return uca; }; /** * Creates a user custom action * * @param properties The information object of property names and values which define the new user custom action * */ UserCustomActions.prototype.add = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ __metadata: { "type": "SP.UserCustomAction" } }, properties)); return this.post({ body: postBody }).then(function (data) { return { action: _this.getById(data.Id), data: data, }; }); }; /** * Deletes all user custom actions in the collection * */ UserCustomActions.prototype.clear = function () { return this.clone(UserCustomActions, "clear", true).post(); }; return UserCustomActions; }(queryable_1.QueryableCollection)); exports.UserCustomActions = UserCustomActions; /** * Describes a single user custom action * */ var UserCustomAction = (function (_super) { __extends(UserCustomAction, _super); function UserCustomAction() { return _super !== null && _super.apply(this, arguments) || this; } /** * Updates this user custom action with the supplied properties * * @param properties An information object of property names and values to update for this user custom action */ UserCustomAction.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.UserCustomAction" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { action: _this, data: data, }; }); }; /** * Removes this user custom action * */ UserCustomAction.prototype.delete = function () { return _super.prototype.delete.call(this); }; return UserCustomAction; }(queryable_1.QueryableInstance)); exports.UserCustomAction = UserCustomAction; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var storage = __webpack_require__(14); var exceptions_1 = __webpack_require__(3); /** * A caching provider which can wrap other non-caching providers * */ var CachingConfigurationProvider = (function () { /** * Creates a new caching configuration provider * @constructor * @param {IConfigurationProvider} wrappedProvider Provider which will be used to fetch the configuration * @param {string} cacheKey Key that will be used to store cached items to the cache * @param {IPnPClientStore} cacheStore OPTIONAL storage, which will be used to store cached settings. */ function CachingConfigurationProvider(wrappedProvider, cacheKey, cacheStore) { this.wrappedProvider = wrappedProvider; this.store = (cacheStore) ? cacheStore : this.selectPnPCache(); this.cacheKey = "_configcache_" + cacheKey; } /** * Gets the wrapped configuration providers * * @return {IConfigurationProvider} Wrapped configuration provider */ CachingConfigurationProvider.prototype.getWrappedProvider = function () { return this.wrappedProvider; }; /** * Loads the configuration values either from the cache or from the wrapped provider * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ CachingConfigurationProvider.prototype.getConfiguration = function () { var _this = this; // Cache not available, pass control to the wrapped provider if ((!this.store) || (!this.store.enabled)) { return this.wrappedProvider.getConfiguration(); } // Value is found in cache, return it directly var cachedConfig = this.store.get(this.cacheKey); if (cachedConfig) { return new Promise(function (resolve) { resolve(cachedConfig); }); } // Get and cache value from the wrapped provider var providerPromise = this.wrappedProvider.getConfiguration(); providerPromise.then(function (providedConfig) { _this.store.put(_this.cacheKey, providedConfig); }); return providerPromise; }; CachingConfigurationProvider.prototype.selectPnPCache = function () { var pnpCache = new storage.PnPClientStorage(); if ((pnpCache.local) && (pnpCache.local.enabled)) { return pnpCache.local; } if ((pnpCache.session) && (pnpCache.session.enabled)) { return pnpCache.session; } throw new exceptions_1.NoCacheAvailableException(); }; return CachingConfigurationProvider; }()); exports.default = CachingConfigurationProvider; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { Object.defineProperty(exports, "__esModule", { value: true }); /** * Makes requests using the fetch API */ var FetchClient = (function () { function FetchClient() { } FetchClient.prototype.fetch = function (url, options) { return global.fetch(url, options); }; return FetchClient; }()); exports.FetchClient = FetchClient; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32))) /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var storage_1 = __webpack_require__(14); var util_1 = __webpack_require__(0); var pnplibconfig_1 = __webpack_require__(4); var CachingOptions = (function () { function CachingOptions(key) { this.key = key; this.expiration = util_1.Util.dateAdd(new Date(), "second", pnplibconfig_1.RuntimeConfig.defaultCachingTimeoutSeconds); this.storeName = pnplibconfig_1.RuntimeConfig.defaultCachingStore; } Object.defineProperty(CachingOptions.prototype, "store", { get: function () { if (this.storeName === "local") { return CachingOptions.storage.local; } else { return CachingOptions.storage.session; } }, enumerable: true, configurable: true }); return CachingOptions; }()); CachingOptions.storage = new storage_1.PnPClientStorage(); exports.CachingOptions = CachingOptions; var CachingParserWrapper = (function () { function CachingParserWrapper(_parser, _cacheOptions) { this._parser = _parser; this._cacheOptions = _cacheOptions; } CachingParserWrapper.prototype.parse = function (response) { var _this = this; // add this to the cache based on the options return this._parser.parse(response).then(function (data) { if (_this._cacheOptions.store !== null) { _this._cacheOptions.store.put(_this._cacheOptions.key, data, _this._cacheOptions.expiration); } return data; }); }; return CachingParserWrapper; }()); exports.CachingParserWrapper = CachingParserWrapper; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); /** * Describes a collection of List objects * */ var Features = (function (_super) { __extends(Features, _super); /** * Creates a new instance of the Lists class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Features(baseUrl, path) { if (path === void 0) { path = "features"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a list from the collection by guid id * * @param id The Id of the feature (GUID) */ Features.prototype.getById = function (id) { var feature = new Feature(this); feature.concat("('" + id + "')"); return feature; }; /** * Adds a new list to the collection * * @param id The Id of the feature (GUID) * @param force If true the feature activation will be forced */ Features.prototype.add = function (id, force) { var _this = this; if (force === void 0) { force = false; } return this.clone(Features, "add", true).post({ body: JSON.stringify({ featdefScope: 0, featureId: id, force: force, }), }).then(function (data) { return { data: data, feature: _this.getById(id), }; }); }; /** * Removes (deactivates) a feature from the collection * * @param id The Id of the feature (GUID) * @param force If true the feature deactivation will be forced */ Features.prototype.remove = function (id, force) { if (force === void 0) { force = false; } return this.clone(Features, "remove", true).post({ body: JSON.stringify({ featureId: id, force: force, }), }); }; return Features; }(queryable_1.QueryableCollection)); exports.Features = Features; var Feature = (function (_super) { __extends(Feature, _super); function Feature() { return _super !== null && _super.apply(this, arguments) || this; } /** * Removes (deactivates) a feature from the collection * * @param force If true the feature deactivation will be forced */ Feature.prototype.deactivate = function (force) { var _this = this; if (force === void 0) { force = false; } var removeDependency = this.addBatchDependency(); var idGet = new Feature(this).select("DefinitionId"); return idGet.getAs().then(function (feature) { var promise = _this.getParent(Features, _this.parentUrl, "", _this.batch).remove(feature.DefinitionId, force); removeDependency(); return promise; }); }; return Feature; }(queryable_1.QueryableInstance)); exports.Feature = Feature; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); var types_1 = __webpack_require__(13); /** * Describes a collection of Field objects * */ var Fields = (function (_super) { __extends(Fields, _super); /** * Creates a new instance of the Fields class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Fields(baseUrl, path) { if (path === void 0) { path = "fields"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a field from the collection by title * * @param title The case-sensitive title of the field */ Fields.prototype.getByTitle = function (title) { return new Field(this, "getByTitle('" + title + "')"); }; /** * Gets a field from the collection by using internal name or title * * @param name The case-sensitive internal name or title of the field */ Fields.prototype.getByInternalNameOrTitle = function (name) { return new Field(this, "getByInternalNameOrTitle('" + name + "')"); }; /** * Gets a list from the collection by guid id * * @param title The Id of the list */ Fields.prototype.getById = function (id) { var f = new Field(this); f.concat("('" + id + "')"); return f; }; /** * Creates a field based on the specified schema */ Fields.prototype.createFieldAsXml = function (xml) { var _this = this; var info; if (typeof xml === "string") { info = { SchemaXml: xml }; } else { info = xml; } var postBody = JSON.stringify({ "parameters": util_1.Util.extend({ "__metadata": { "type": "SP.XmlSchemaFieldCreationInformation", }, }, info), }); return this.clone(Fields, "createfieldasxml", true).postAs({ body: postBody }).then(function (data) { return { data: data, field: _this.getById(data.Id), }; }); }; /** * Adds a new list to the collection * * @param title The new field's title * @param fieldType The new field's type (ex: SP.FieldText) * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.add = function (title, fieldType, properties) { var _this = this; if (properties === void 0) { properties = {}; } var postBody = JSON.stringify(util_1.Util.extend({ "Title": title, "__metadata": { "type": fieldType }, }, properties)); return this.clone(Fields, null, true).postAs({ body: postBody }).then(function (data) { return { data: data, field: _this.getById(data.Id), }; }); }; /** * Adds a new SP.FieldText to the collection * * @param title The field title * @param maxLength The maximum number of characters allowed in the value of the field. * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addText = function (title, maxLength, properties) { if (maxLength === void 0) { maxLength = 255; } var props = { FieldTypeKind: 2, MaxLength: maxLength, }; return this.add(title, "SP.FieldText", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldCalculated to the collection * * @param title The field title. * @param formula The formula for the field. * @param dateFormat The date and time format that is displayed in the field. * @param outputType Specifies the output format for the field. Represents a FieldType value. * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addCalculated = function (title, formula, dateFormat, outputType, properties) { if (outputType === void 0) { outputType = types_1.FieldTypes.Text; } var props = { DateFormat: dateFormat, FieldTypeKind: 17, Formula: formula, OutputType: outputType, }; return this.add(title, "SP.FieldCalculated", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldDateTime to the collection * * @param title The field title * @param displayFormat The format of the date and time that is displayed in the field. * @param calendarType Specifies the calendar type of the field. * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addDateTime = function (title, displayFormat, calendarType, friendlyDisplayFormat, properties) { if (displayFormat === void 0) { displayFormat = types_1.DateTimeFieldFormatType.DateOnly; } if (calendarType === void 0) { calendarType = types_1.CalendarType.Gregorian; } if (friendlyDisplayFormat === void 0) { friendlyDisplayFormat = 0; } var props = { DateTimeCalendarType: calendarType, DisplayFormat: displayFormat, FieldTypeKind: 4, FriendlyDisplayFormat: friendlyDisplayFormat, }; return this.add(title, "SP.FieldDateTime", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldNumber to the collection * * @param title The field title * @param minValue The field's minimum value * @param maxValue The field's maximum value * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addNumber = function (title, minValue, maxValue, properties) { var props = { FieldTypeKind: 9 }; if (typeof minValue !== "undefined") { props = util_1.Util.extend({ MinimumValue: minValue }, props); } if (typeof maxValue !== "undefined") { props = util_1.Util.extend({ MaximumValue: maxValue }, props); } return this.add(title, "SP.FieldNumber", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldCurrency to the collection * * @param title The field title * @param minValue The field's minimum value * @param maxValue The field's maximum value * @param currencyLocalId Specifies the language code identifier (LCID) used to format the value of the field * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addCurrency = function (title, minValue, maxValue, currencyLocalId, properties) { if (currencyLocalId === void 0) { currencyLocalId = 1033; } var props = { CurrencyLocaleId: currencyLocalId, FieldTypeKind: 10, }; if (typeof minValue !== "undefined") { props = util_1.Util.extend({ MinimumValue: minValue }, props); } if (typeof maxValue !== "undefined") { props = util_1.Util.extend({ MaximumValue: maxValue }, props); } return this.add(title, "SP.FieldCurrency", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldMultiLineText to the collection * * @param title The field title * @param numberOfLines Specifies the number of lines of text to display for the field. * @param richText Specifies whether the field supports rich formatting. * @param restrictedMode Specifies whether the field supports a subset of rich formatting. * @param appendOnly Specifies whether all changes to the value of the field are displayed in list forms. * @param allowHyperlink Specifies whether a hyperlink is allowed as a value of the field. * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) * */ Fields.prototype.addMultilineText = function (title, numberOfLines, richText, restrictedMode, appendOnly, allowHyperlink, properties) { if (numberOfLines === void 0) { numberOfLines = 6; } if (richText === void 0) { richText = true; } if (restrictedMode === void 0) { restrictedMode = false; } if (appendOnly === void 0) { appendOnly = false; } if (allowHyperlink === void 0) { allowHyperlink = true; } var props = { AllowHyperlink: allowHyperlink, AppendOnly: appendOnly, FieldTypeKind: 3, NumberOfLines: numberOfLines, RestrictedMode: restrictedMode, RichText: richText, }; return this.add(title, "SP.FieldMultiLineText", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldUrl to the collection * * @param title The field title */ Fields.prototype.addUrl = function (title, displayFormat, properties) { if (displayFormat === void 0) { displayFormat = types_1.UrlFieldFormatType.Hyperlink; } var props = { DisplayFormat: displayFormat, FieldTypeKind: 11, }; return this.add(title, "SP.FieldUrl", util_1.Util.extend(props, properties)); }; return Fields; }(queryable_1.QueryableCollection)); exports.Fields = Fields; /** * Describes a single of Field instance * */ var Field = (function (_super) { __extends(Field, _super); function Field() { return _super !== null && _super.apply(this, arguments) || this; } /** * Updates this field intance with the supplied properties * * @param properties A plain object hash of values to update for the list * @param fieldType The type value, required to update child field type properties */ Field.prototype.update = function (properties, fieldType) { var _this = this; if (fieldType === void 0) { fieldType = "SP.Field"; } var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": fieldType }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, field: _this, }; }); }; /** * Delete this fields * */ Field.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; /** * Sets the value of the ShowInDisplayForm property for this field. */ Field.prototype.setShowInDisplayForm = function (show) { return this.clone(Field, "setshowindisplayform(" + show + ")", true).post(); }; /** * Sets the value of the ShowInEditForm property for this field. */ Field.prototype.setShowInEditForm = function (show) { return this.clone(Field, "setshowineditform(" + show + ")", true).post(); }; /** * Sets the value of the ShowInNewForm property for this field. */ Field.prototype.setShowInNewForm = function (show) { return this.clone(Field, "setshowinnewform(" + show + ")", true).post(); }; return Field; }(queryable_1.QueryableInstance)); exports.Field = Field; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var queryable_1 = __webpack_require__(1); /** * Represents a collection of navigation nodes * */ var NavigationNodes = (function (_super) { __extends(NavigationNodes, _super); function NavigationNodes() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a navigation node by id * * @param id The id of the node */ NavigationNodes.prototype.getById = function (id) { var node = new NavigationNode(this); node.concat("(" + id + ")"); return node; }; /** * Adds a new node to the collection * * @param title Display name of the node * @param url The url of the node * @param visible If true the node is visible, otherwise it is hidden (default: true) */ NavigationNodes.prototype.add = function (title, url, visible) { var _this = this; if (visible === void 0) { visible = true; } var postBody = JSON.stringify({ IsVisible: visible, Title: title, Url: url, "__metadata": { "type": "SP.NavigationNode" }, }); return this.clone(NavigationNodes, null, true).post({ body: postBody }).then(function (data) { return { data: data, node: _this.getById(data.Id), }; }); }; /** * Moves a node to be after another node in the navigation * * @param nodeId Id of the node to move * @param previousNodeId Id of the node after which we move the node specified by nodeId */ NavigationNodes.prototype.moveAfter = function (nodeId, previousNodeId) { var postBody = JSON.stringify({ nodeId: nodeId, previousNodeId: previousNodeId, }); return this.clone(NavigationNodes, "MoveAfter", true).post({ body: postBody }); }; return NavigationNodes; }(queryable_1.QueryableCollection)); exports.NavigationNodes = NavigationNodes; var NavigationNode = (function (_super) { __extends(NavigationNode, _super); function NavigationNode() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(NavigationNode.prototype, "children", { /** * Represents the child nodes of this node */ get: function () { return new NavigationNodes(this, "Children"); }, enumerable: true, configurable: true }); /** * Updates this node based on the supplied properties * * @param properties The hash of key/value pairs to update */ NavigationNode.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.NavigationNode" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, node: _this, }; }); }; /** * Deletes this node and any child nodes */ NavigationNode.prototype.delete = function () { return _super.prototype.delete.call(this); }; return NavigationNode; }(queryable_1.QueryableInstance)); exports.NavigationNode = NavigationNode; /** * Exposes the navigation components * */ var Navigation = (function (_super) { __extends(Navigation, _super); /** * Creates a new instance of the Lists class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Navigation(baseUrl, path) { if (path === void 0) { path = "navigation"; } return _super.call(this, baseUrl, path) || this; } Object.defineProperty(Navigation.prototype, "quicklaunch", { /** * Gets the quicklaunch navigation for the current context * */ get: function () { return new NavigationNodes(this, "quicklaunch"); }, enumerable: true, configurable: true }); Object.defineProperty(Navigation.prototype, "topNavigationBar", { /** * Gets the top bar navigation navigation for the current context * */ get: function () { return new NavigationNodes(this, "topnavigationbar"); }, enumerable: true, configurable: true }); return Navigation; }(queryable_1.Queryable)); exports.Navigation = Navigation; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var webs_1 = __webpack_require__(8); var roles_1 = __webpack_require__(17); var types_1 = __webpack_require__(13); var queryable_1 = __webpack_require__(1); var QueryableSecurable = (function (_super) { __extends(QueryableSecurable, _super); function QueryableSecurable() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(QueryableSecurable.prototype, "roleAssignments", { /** * Gets the set of role assignments for this item * */ get: function () { return new roles_1.RoleAssignments(this); }, enumerable: true, configurable: true }); Object.defineProperty(QueryableSecurable.prototype, "firstUniqueAncestorSecurableObject", { /** * Gets the closest securable up the security hierarchy whose permissions are applied to this list item * */ get: function () { return new queryable_1.QueryableInstance(this, "FirstUniqueAncestorSecurableObject"); }, enumerable: true, configurable: true }); /** * Gets the effective permissions for the user supplied * * @param loginName The claims username for the user (ex: i:0#.f|membership|user@domain.com) */ QueryableSecurable.prototype.getUserEffectivePermissions = function (loginName) { var q = this.clone(queryable_1.Queryable, "getUserEffectivePermissions(@user)", true); q.query.add("@user", "'" + encodeURIComponent(loginName) + "'"); return q.getAs(); }; /** * Gets the effective permissions for the current user */ QueryableSecurable.prototype.getCurrentUserEffectivePermissions = function () { var _this = this; var w = webs_1.Web.fromUrl(this.toUrl()); return w.currentUser.select("LoginName").getAs().then(function (user) { return _this.getUserEffectivePermissions(user.LoginName); }); }; /** * Breaks the security inheritance at this level optinally copying permissions and clearing subscopes * * @param copyRoleAssignments If true the permissions are copied from the current parent scope * @param clearSubscopes Optional. true to make all child securable objects inherit role assignments from the current object */ QueryableSecurable.prototype.breakRoleInheritance = function (copyRoleAssignments, clearSubscopes) { if (copyRoleAssignments === void 0) { copyRoleAssignments = false; } if (clearSubscopes === void 0) { clearSubscopes = false; } return this.clone(QueryableSecurable, "breakroleinheritance(copyroleassignments=" + copyRoleAssignments + ", clearsubscopes=" + clearSubscopes + ")", true).post(); }; /** * Removes the local role assignments so that it re-inherit role assignments from the parent object. * */ QueryableSecurable.prototype.resetRoleInheritance = function () { return this.clone(QueryableSecurable, "resetroleinheritance", true).post(); }; /** * Determines if a given user has the appropriate permissions * * @param loginName The user to check * @param permission The permission being checked */ QueryableSecurable.prototype.userHasPermissions = function (loginName, permission) { var _this = this; return this.getUserEffectivePermissions(loginName).then(function (perms) { return _this.hasPermissions(perms, permission); }); }; /** * Determines if the current user has the requested permissions * * @param permission The permission we wish to check */ QueryableSecurable.prototype.currentUserHasPermissions = function (permission) { var _this = this; return this.getCurrentUserEffectivePermissions().then(function (perms) { return _this.hasPermissions(perms, permission); }); }; /** * Taken from sp.js, checks the supplied permissions against the mask * * @param value The security principal's permissions on the given object * @param perm The permission checked against the value */ /* tslint:disable:no-bitwise */ QueryableSecurable.prototype.hasPermissions = function (value, perm) { if (!perm) { return true; } if (perm === types_1.PermissionKind.FullMask) { return (value.High & 32767) === 32767 && value.Low === 65535; } perm = perm - 1; var num = 1; if (perm >= 0 && perm < 32) { num = num << perm; return 0 !== (value.Low & num); } else if (perm >= 32 && perm < 64) { num = num << perm - 32; return 0 !== (value.High & num); } return false; }; return QueryableSecurable; }(queryable_1.QueryableInstance)); exports.QueryableSecurable = QueryableSecurable; /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); /** * Allows for the fluent construction of search queries */ var SearchQueryBuilder = (function () { function SearchQueryBuilder(queryText, _query) { if (queryText === void 0) { queryText = ""; } if (_query === void 0) { _query = {}; } this._query = _query; if (typeof queryText === "string" && queryText.length > 0) { this.extendQuery({ Querytext: queryText }); } } SearchQueryBuilder.create = function (queryText, queryTemplate) { if (queryText === void 0) { queryText = ""; } if (queryTemplate === void 0) { queryTemplate = {}; } return new SearchQueryBuilder(queryText, queryTemplate); }; SearchQueryBuilder.prototype.text = function (queryText) { return this.extendQuery({ Querytext: queryText }); }; SearchQueryBuilder.prototype.template = function (template) { return this.extendQuery({ QueryTemplate: template }); }; SearchQueryBuilder.prototype.sourceId = function (id) { return this.extendQuery({ SourceId: id }); }; Object.defineProperty(SearchQueryBuilder.prototype, "enableInterleaving", { get: function () { return this.extendQuery({ EnableInterleaving: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableStemming", { get: function () { return this.extendQuery({ EnableStemming: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "trimDuplicates", { get: function () { return this.extendQuery({ TrimDuplicates: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableNicknames", { get: function () { return this.extendQuery({ EnableNicknames: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableFql", { get: function () { return this.extendQuery({ EnableFql: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enablePhonetic", { get: function () { return this.extendQuery({ EnablePhonetic: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "bypassResultTypes", { get: function () { return this.extendQuery({ BypassResultTypes: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "processBestBets", { get: function () { return this.extendQuery({ ProcessBestBets: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableQueryRules", { get: function () { return this.extendQuery({ EnableQueryRules: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableSorting", { get: function () { return this.extendQuery({ EnableSorting: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "generateBlockRankLog", { get: function () { return this.extendQuery({ GenerateBlockRankLog: true }); }, enumerable: true, configurable: true }); SearchQueryBuilder.prototype.rankingModelId = function (id) { return this.extendQuery({ RankingModelId: id }); }; SearchQueryBuilder.prototype.startRow = function (id) { return this.extendQuery({ StartRow: id }); }; SearchQueryBuilder.prototype.rowLimit = function (id) { return this.extendQuery({ RowLimit: id }); }; SearchQueryBuilder.prototype.rowsPerPage = function (id) { return this.extendQuery({ RowsPerPage: id }); }; SearchQueryBuilder.prototype.selectProperties = function () { var properties = []; for (var _i = 0; _i < arguments.length; _i++) { properties[_i] = arguments[_i]; } return this.extendQuery({ SelectProperties: properties }); }; SearchQueryBuilder.prototype.culture = function (culture) { return this.extendQuery({ Culture: culture }); }; SearchQueryBuilder.prototype.refinementFilters = function () { var filters = []; for (var _i = 0; _i < arguments.length; _i++) { filters[_i] = arguments[_i]; } return this.extendQuery({ RefinementFilters: filters }); }; SearchQueryBuilder.prototype.refiners = function (refiners) { return this.extendQuery({ Refiners: refiners }); }; SearchQueryBuilder.prototype.hiddenConstraints = function (constraints) { return this.extendQuery({ HiddenConstraints: constraints }); }; SearchQueryBuilder.prototype.sortList = function () { var sorts = []; for (var _i = 0; _i < arguments.length; _i++) { sorts[_i] = arguments[_i]; } return this.extendQuery({ SortList: sorts }); }; SearchQueryBuilder.prototype.timeout = function (milliseconds) { return this.extendQuery({ Timeout: milliseconds }); }; SearchQueryBuilder.prototype.hithighlightedProperties = function () { var properties = []; for (var _i = 0; _i < arguments.length; _i++) { properties[_i] = arguments[_i]; } return this.extendQuery({ HithighlightedProperties: properties }); }; SearchQueryBuilder.prototype.clientType = function (clientType) { return this.extendQuery({ ClientType: clientType }); }; SearchQueryBuilder.prototype.personalizationData = function (data) { return this.extendQuery({ PersonalizationData: data }); }; SearchQueryBuilder.prototype.resultsURL = function (url) { return this.extendQuery({ ResultsURL: url }); }; SearchQueryBuilder.prototype.queryTag = function () { var tags = []; for (var _i = 0; _i < arguments.length; _i++) { tags[_i] = arguments[_i]; } return this.extendQuery({ QueryTag: tags }); }; SearchQueryBuilder.prototype.properties = function () { var properties = []; for (var _i = 0; _i < arguments.length; _i++) { properties[_i] = arguments[_i]; } return this.extendQuery({ Properties: properties }); }; Object.defineProperty(SearchQueryBuilder.prototype, "processPersonalFavorites", { get: function () { return this.extendQuery({ ProcessPersonalFavorites: true }); }, enumerable: true, configurable: true }); SearchQueryBuilder.prototype.queryTemplatePropertiesUrl = function (url) { return this.extendQuery({ QueryTemplatePropertiesUrl: url }); }; SearchQueryBuilder.prototype.reorderingRules = function () { var rules = []; for (var _i = 0; _i < arguments.length; _i++) { rules[_i] = arguments[_i]; } return this.extendQuery({ ReorderingRules: rules }); }; SearchQueryBuilder.prototype.hitHighlightedMultivaluePropertyLimit = function (limit) { return this.extendQuery({ HitHighlightedMultivaluePropertyLimit: limit }); }; Object.defineProperty(SearchQueryBuilder.prototype, "enableOrderingHitHighlightedProperty", { get: function () { return this.extendQuery({ EnableOrderingHitHighlightedProperty: true }); }, enumerable: true, configurable: true }); SearchQueryBuilder.prototype.collapseSpecification = function (spec) { return this.extendQuery({ CollapseSpecification: spec }); }; SearchQueryBuilder.prototype.uiLanguage = function (lang) { return this.extendQuery({ UIlanguage: lang }); }; SearchQueryBuilder.prototype.desiredSnippetLength = function (len) { return this.extendQuery({ DesiredSnippetLength: len }); }; SearchQueryBuilder.prototype.maxSnippetLength = function (len) { return this.extendQuery({ MaxSnippetLength: len }); }; SearchQueryBuilder.prototype.summaryLength = function (len) { return this.extendQuery({ SummaryLength: len }); }; SearchQueryBuilder.prototype.toSearchQuery = function () { return this._query; }; SearchQueryBuilder.prototype.extendQuery = function (part) { this._query = util_1.Util.extend(this._query, part); return this; }; return SearchQueryBuilder; }()); exports.SearchQueryBuilder = SearchQueryBuilder; /** * Describes the search API * */ var Search = (function (_super) { __extends(Search, _super); /** * Creates a new instance of the Search class * * @param baseUrl The url for the search context * @param query The SearchQuery object to execute */ function Search(baseUrl, path) { if (path === void 0) { path = "_api/search/postquery"; } return _super.call(this, baseUrl, path) || this; } /** * ....... * @returns Promise */ Search.prototype.execute = function (query) { var _this = this; var formattedBody; formattedBody = query; if (formattedBody.SelectProperties) { formattedBody.SelectProperties = { results: query.SelectProperties }; } if (formattedBody.RefinementFilters) { formattedBody.RefinementFilters = { results: query.RefinementFilters }; } if (formattedBody.SortList) { formattedBody.SortList = { results: query.SortList }; } if (formattedBody.HithighlightedProperties) { formattedBody.HithighlightedProperties = { results: query.HithighlightedProperties }; } if (formattedBody.ReorderingRules) { formattedBody.ReorderingRules = { results: query.ReorderingRules }; } if (formattedBody.Properties) { formattedBody.Properties = { results: query.Properties }; } var postBody = JSON.stringify({ request: util_1.Util.extend({ "__metadata": { "type": "Microsoft.Office.Server.Search.REST.SearchRequest" }, }, formattedBody), }); return this.post({ body: postBody }).then(function (data) { return new SearchResults(data, _this.toUrl(), query); }); }; return Search; }(queryable_1.QueryableInstance)); exports.Search = Search; /** * Describes the SearchResults class, which returns the formatted and raw version of the query response */ var SearchResults = (function () { /** * Creates a new instance of the SearchResult class * */ function SearchResults(rawResponse, _url, _query, _raw, _primary) { if (_raw === void 0) { _raw = null; } if (_primary === void 0) { _primary = null; } this._url = _url; this._query = _query; this._raw = _raw; this._primary = _primary; this._raw = rawResponse.postquery ? rawResponse.postquery : rawResponse; } Object.defineProperty(SearchResults.prototype, "ElapsedTime", { get: function () { return this.RawSearchResults.ElapsedTime; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "RowCount", { get: function () { return this.RawSearchResults.PrimaryQueryResult.RelevantResults.RowCount; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "TotalRows", { get: function () { return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRows; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "TotalRowsIncludingDuplicates", { get: function () { return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRowsIncludingDuplicates; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "RawSearchResults", { get: function () { return this._raw; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "PrimarySearchResults", { get: function () { if (this._primary === null) { this._primary = this.formatSearchResults(this._raw.PrimaryQueryResult.RelevantResults.Table.Rows); } return this._primary; }, enumerable: true, configurable: true }); /** * Gets a page of results * * @param pageNumber Index of the page to return. Used to determine StartRow * @param pageSize Optional, items per page (default = 10) */ SearchResults.prototype.getPage = function (pageNumber, pageSize) { // if we got all the available rows we don't have another page if (this.TotalRows < this.RowCount) { return Promise.resolve(null); } // if pageSize is supplied, then we use that regardless of any previous values // otherwise get the previous RowLimit or default to 10 var rows = typeof pageSize !== "undefined" ? pageSize : this._query.hasOwnProperty("RowLimit") ? this._query.RowLimit : 10; var query = util_1.Util.extend(this._query, { RowLimit: rows, StartRow: rows * (pageNumber - 1) + 1, }); // we have reached the end if (query.StartRow > this.TotalRows) { return Promise.resolve(null); } var search = new Search(this._url, null); return search.execute(query); }; /** * Formats a search results array * * @param rawResults The array to process */ SearchResults.prototype.formatSearchResults = function (rawResults) { var results = new Array(); var tempResults = rawResults.results ? rawResults.results : rawResults; for (var _i = 0, tempResults_1 = tempResults; _i < tempResults_1.length; _i++) { var tempResult = tempResults_1[_i]; var cells = tempResult.Cells.results ? tempResult.Cells.results : tempResult.Cells; results.push(cells.reduce(function (res, cell) { Object.defineProperty(res, cell.Key, { configurable: false, enumerable: false, value: cell.Value, writable: false, }); return res; }, {})); } return results; }; return SearchResults; }()); exports.SearchResults = SearchResults; /** * defines the SortDirection enum */ var SortDirection; (function (SortDirection) { SortDirection[SortDirection["Ascending"] = 0] = "Ascending"; SortDirection[SortDirection["Descending"] = 1] = "Descending"; SortDirection[SortDirection["FQLFormula"] = 2] = "FQLFormula"; })(SortDirection = exports.SortDirection || (exports.SortDirection = {})); /** * defines the ReorderingRuleMatchType enum */ var ReorderingRuleMatchType; (function (ReorderingRuleMatchType) { ReorderingRuleMatchType[ReorderingRuleMatchType["ResultContainsKeyword"] = 0] = "ResultContainsKeyword"; ReorderingRuleMatchType[ReorderingRuleMatchType["TitleContainsKeyword"] = 1] = "TitleContainsKeyword"; ReorderingRuleMatchType[ReorderingRuleMatchType["TitleMatchesKeyword"] = 2] = "TitleMatchesKeyword"; ReorderingRuleMatchType[ReorderingRuleMatchType["UrlStartsWith"] = 3] = "UrlStartsWith"; ReorderingRuleMatchType[ReorderingRuleMatchType["UrlExactlyMatches"] = 4] = "UrlExactlyMatches"; ReorderingRuleMatchType[ReorderingRuleMatchType["ContentTypeIs"] = 5] = "ContentTypeIs"; ReorderingRuleMatchType[ReorderingRuleMatchType["FileExtensionMatches"] = 6] = "FileExtensionMatches"; ReorderingRuleMatchType[ReorderingRuleMatchType["ResultHasTag"] = 7] = "ResultHasTag"; ReorderingRuleMatchType[ReorderingRuleMatchType["ManualCondition"] = 8] = "ManualCondition"; })(ReorderingRuleMatchType = exports.ReorderingRuleMatchType || (exports.ReorderingRuleMatchType = {})); /** * Specifies the type value for the property */ var QueryPropertyValueType; (function (QueryPropertyValueType) { QueryPropertyValueType[QueryPropertyValueType["None"] = 0] = "None"; QueryPropertyValueType[QueryPropertyValueType["StringType"] = 1] = "StringType"; QueryPropertyValueType[QueryPropertyValueType["Int32TYpe"] = 2] = "Int32TYpe"; QueryPropertyValueType[QueryPropertyValueType["BooleanType"] = 3] = "BooleanType"; QueryPropertyValueType[QueryPropertyValueType["StringArrayType"] = 4] = "StringArrayType"; QueryPropertyValueType[QueryPropertyValueType["UnSupportedType"] = 5] = "UnSupportedType"; })(QueryPropertyValueType = exports.QueryPropertyValueType || (exports.QueryPropertyValueType = {})); var SearchBuiltInSourceId = (function () { function SearchBuiltInSourceId() { } return SearchBuiltInSourceId; }()); SearchBuiltInSourceId.Documents = "e7ec8cee-ded8-43c9-beb5-436b54b31e84"; SearchBuiltInSourceId.ItemsMatchingContentType = "5dc9f503-801e-4ced-8a2c-5d1237132419"; SearchBuiltInSourceId.ItemsMatchingTag = "e1327b9c-2b8c-4b23-99c9-3730cb29c3f7"; SearchBuiltInSourceId.ItemsRelatedToCurrentUser = "48fec42e-4a92-48ce-8363-c2703a40e67d"; SearchBuiltInSourceId.ItemsWithSameKeywordAsThisItem = "5c069288-1d17-454a-8ac6-9c642a065f48"; SearchBuiltInSourceId.LocalPeopleResults = "b09a7990-05ea-4af9-81ef-edfab16c4e31"; SearchBuiltInSourceId.LocalReportsAndDataResults = "203fba36-2763-4060-9931-911ac8c0583b"; SearchBuiltInSourceId.LocalSharePointResults = "8413cd39-2156-4e00-b54d-11efd9abdb89"; SearchBuiltInSourceId.LocalVideoResults = "78b793ce-7956-4669-aa3b-451fc5defebf"; SearchBuiltInSourceId.Pages = "5e34578e-4d08-4edc-8bf3-002acf3cdbcc"; SearchBuiltInSourceId.Pictures = "38403c8c-3975-41a8-826e-717f2d41568a"; SearchBuiltInSourceId.Popular = "97c71db1-58ce-4891-8b64-585bc2326c12"; SearchBuiltInSourceId.RecentlyChangedItems = "ba63bbae-fa9c-42c0-b027-9a878f16557c"; SearchBuiltInSourceId.RecommendedItems = "ec675252-14fa-4fbe-84dd-8d098ed74181"; SearchBuiltInSourceId.Wiki = "9479bf85-e257-4318-b5a8-81a180f5faa1"; exports.SearchBuiltInSourceId = SearchBuiltInSourceId; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var SearchSuggest = (function (_super) { __extends(SearchSuggest, _super); function SearchSuggest(baseUrl, path) { if (path === void 0) { path = "_api/search/suggest"; } return _super.call(this, baseUrl, path) || this; } SearchSuggest.prototype.execute = function (query) { this.mapQueryToQueryString(query); return this.get().then(function (response) { return new SearchSuggestResult(response); }); }; SearchSuggest.prototype.mapQueryToQueryString = function (query) { this.query.add("querytext", "'" + query.querytext + "'"); if (query.hasOwnProperty("count")) { this.query.add("inumberofquerysuggestions", query.count.toString()); } if (query.hasOwnProperty("personalCount")) { this.query.add("inumberofresultsuggestions", query.personalCount.toString()); } if (query.hasOwnProperty("preQuery")) { this.query.add("fprequerysuggestions", query.preQuery.toString()); } if (query.hasOwnProperty("hitHighlighting")) { this.query.add("fhithighlighting", query.hitHighlighting.toString()); } if (query.hasOwnProperty("capitalize")) { this.query.add("fcapitalizefirstletters", query.capitalize.toString()); } if (query.hasOwnProperty("culture")) { this.query.add("culture", query.culture.toString()); } if (query.hasOwnProperty("stemming")) { this.query.add("enablestemming", query.stemming.toString()); } if (query.hasOwnProperty("includePeople")) { this.query.add("showpeoplenamesuggestions", query.includePeople.toString()); } if (query.hasOwnProperty("queryRules")) { this.query.add("enablequeryrules", query.queryRules.toString()); } if (query.hasOwnProperty("prefixMatch")) { this.query.add("fprefixmatchallterms", query.prefixMatch.toString()); } }; return SearchSuggest; }(queryable_1.QueryableInstance)); exports.SearchSuggest = SearchSuggest; var SearchSuggestResult = (function () { function SearchSuggestResult(json) { if (json.hasOwnProperty("suggest")) { // verbose this.PeopleNames = json.suggest.PeopleNames.results; this.PersonalResults = json.suggest.PersonalResults.results; this.Queries = json.suggest.Queries.results; } else { this.PeopleNames = json.PeopleNames; this.PersonalResults = json.PersonalResults; this.Queries = json.Queries; } } return SearchSuggestResult; }()); exports.SearchSuggestResult = SearchSuggestResult; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var webs_1 = __webpack_require__(8); var usercustomactions_1 = __webpack_require__(19); var odata_1 = __webpack_require__(2); var features_1 = __webpack_require__(23); /** * Describes a site collection * */ var Site = (function (_super) { __extends(Site, _super); /** * Creates a new instance of the Site class * * @param baseUrl The url or Queryable which forms the parent of this site collection */ function Site(baseUrl, path) { if (path === void 0) { path = "_api/site"; } return _super.call(this, baseUrl, path) || this; } Object.defineProperty(Site.prototype, "rootWeb", { /** * Gets the root web of the site collection * */ get: function () { return new webs_1.Web(this, "rootweb"); }, enumerable: true, configurable: true }); Object.defineProperty(Site.prototype, "features", { /** * Gets the active features for this site collection * */ get: function () { return new features_1.Features(this); }, enumerable: true, configurable: true }); Object.defineProperty(Site.prototype, "userCustomActions", { /** * Gets all custom actions for this site collection * */ get: function () { return new usercustomactions_1.UserCustomActions(this); }, enumerable: true, configurable: true }); /** * Gets the context information for this site collection */ Site.prototype.getContextInfo = function () { var q = new Site(this.parentUrl, "_api/contextinfo"); return q.post().then(function (data) { if (data.hasOwnProperty("GetContextWebInformation")) { var info = data.GetContextWebInformation; info.SupportedSchemaVersions = info.SupportedSchemaVersions.results; return info; } else { return data; } }); }; /** * Gets the document libraries on a site. Static method. (SharePoint Online only) * * @param absoluteWebUrl The absolute url of the web whose document libraries should be returned */ Site.prototype.getDocumentLibraries = function (absoluteWebUrl) { var q = new queryable_1.Queryable("", "_api/sp.web.getdocumentlibraries(@v)"); q.query.add("@v", "'" + absoluteWebUrl + "'"); return q.get().then(function (data) { if (data.hasOwnProperty("GetDocumentLibraries")) { return data.GetDocumentLibraries; } else { return data; } }); }; /** * Gets the site url from a page url * * @param absolutePageUrl The absolute url of the page */ Site.prototype.getWebUrlFromPageUrl = function (absolutePageUrl) { var q = new queryable_1.Queryable("", "_api/sp.web.getweburlfrompageurl(@v)"); q.query.add("@v", "'" + absolutePageUrl + "'"); return q.get().then(function (data) { if (data.hasOwnProperty("GetWebUrlFromPageUrl")) { return data.GetWebUrlFromPageUrl; } else { return data; } }); }; /** * Creates a new batch for requests within the context of this site collection * */ Site.prototype.createBatch = function () { return new odata_1.ODataBatch(this.parentUrl); }; /** * Opens a web by id (using POST) * * @param webId The GUID id of the web to open */ Site.prototype.openWebById = function (webId) { return this.clone(Site, "openWebById('" + webId + "')", true).post().then(function (d) { return { data: d, web: webs_1.Web.fromUrl(odata_1.extractOdataId(d)), }; }); }; return Site; }(queryable_1.QueryableInstance)); exports.Site = Site; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var sitegroups_1 = __webpack_require__(18); var util_1 = __webpack_require__(0); /** * Describes a collection of all site collection users * */ var SiteUsers = (function (_super) { __extends(SiteUsers, _super); /** * Creates a new instance of the SiteUsers class * * @param baseUrl The url or Queryable which forms the parent of this user collection */ function SiteUsers(baseUrl, path) { if (path === void 0) { path = "siteusers"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a user from the collection by email * * @param email The email address of the user to retrieve */ SiteUsers.prototype.getByEmail = function (email) { return new SiteUser(this, "getByEmail('" + email + "')"); }; /** * Gets a user from the collection by id * * @param id The id of the user to retrieve */ SiteUsers.prototype.getById = function (id) { return new SiteUser(this, "getById(" + id + ")"); }; /** * Gets a user from the collection by login name * * @param loginName The login name of the user to retrieve */ SiteUsers.prototype.getByLoginName = function (loginName) { var su = new SiteUser(this); su.concat("(@v)"); su.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return su; }; /** * Removes a user from the collection by id * * @param id The id of the user to remove */ SiteUsers.prototype.removeById = function (id) { return this.clone(SiteUsers, "removeById(" + id + ")", true).post(); }; /** * Removes a user from the collection by login name * * @param loginName The login name of the user to remove */ SiteUsers.prototype.removeByLoginName = function (loginName) { var o = this.clone(SiteUsers, "removeByLoginName(@v)", true); o.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return o.post(); }; /** * Adds a user to a group * * @param loginName The login name of the user to add to the group * */ SiteUsers.prototype.add = function (loginName) { var _this = this; return this.clone(SiteUsers, null, true).post({ body: JSON.stringify({ "__metadata": { "type": "SP.User" }, LoginName: loginName }), }).then(function () { return _this.getByLoginName(loginName); }); }; return SiteUsers; }(queryable_1.QueryableCollection)); exports.SiteUsers = SiteUsers; /** * Describes a single user * */ var SiteUser = (function (_super) { __extends(SiteUser, _super); function SiteUser() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(SiteUser.prototype, "groups", { /** * Gets the groups for this user * */ get: function () { return new sitegroups_1.SiteGroups(this, "groups"); }, enumerable: true, configurable: true }); /** * Updates this user instance with the supplied properties * * @param properties A plain object of property names and values to update for the user */ SiteUser.prototype.update = function (properties) { var _this = this; var postBody = util_1.Util.extend({ "__metadata": { "type": "SP.User" } }, properties); return this.post({ body: JSON.stringify(postBody), headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, user: _this, }; }); }; /** * Delete this user * */ SiteUser.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; return SiteUser; }(queryable_1.QueryableInstance)); exports.SiteUser = SiteUser; /** * Represents the current user */ var CurrentUser = (function (_super) { __extends(CurrentUser, _super); function CurrentUser(baseUrl, path) { if (path === void 0) { path = "currentuser"; } return _super.call(this, baseUrl, path) || this; } return CurrentUser; }(queryable_1.QueryableInstance)); exports.CurrentUser = CurrentUser; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); var files_1 = __webpack_require__(7); var odata_1 = __webpack_require__(2); /** * Allows for calling of the static SP.Utilities.Utility methods by supplying the method name */ var UtilityMethod = (function (_super) { __extends(UtilityMethod, _super); /** * Creates a new instance of the Utility method class * * @param baseUrl The parent url provider * @param methodName The static method name to call on the utility class */ function UtilityMethod(baseUrl, methodName) { return _super.call(this, UtilityMethod.getBaseUrl(baseUrl), "_api/SP.Utilities.Utility." + methodName) || this; } UtilityMethod.getBaseUrl = function (candidate) { if (typeof candidate === "string") { return candidate; } var c = candidate; var url = c.toUrl(); var index = url.indexOf("_api/"); if (index < 0) { return url; } return url.substr(0, index); }; UtilityMethod.prototype.excute = function (props) { return this.postAs({ body: JSON.stringify(props), }); }; /** * Clones this queryable into a new queryable instance of T * @param factory Constructor used to create the new instance * @param additionalPath Any additional path to include in the clone * @param includeBatch If true this instance's batch will be added to the cloned instance */ UtilityMethod.prototype.create = function (methodName, includeBatch) { var clone = new UtilityMethod(this.parentUrl, methodName); var target = this.query.get("@target"); if (target !== null) { clone.query.add("@target", target); } if (includeBatch && this.hasBatch) { clone = clone.inBatch(this.batch); } return clone; }; /** * Sends an email based on the supplied properties * * @param props The properties of the email to send */ UtilityMethod.prototype.sendEmail = function (props) { var params = { properties: { Body: props.Body, From: props.From, Subject: props.Subject, "__metadata": { "type": "SP.Utilities.EmailProperties" }, }, }; if (props.To && props.To.length > 0) { params.properties = util_1.Util.extend(params.properties, { To: { results: props.To }, }); } if (props.CC && props.CC.length > 0) { params.properties = util_1.Util.extend(params.properties, { CC: { results: props.CC }, }); } if (props.BCC && props.BCC.length > 0) { params.properties = util_1.Util.extend(params.properties, { BCC: { results: props.BCC }, }); } if (props.AdditionalHeaders) { params.properties = util_1.Util.extend(params.properties, { AdditionalHeaders: props.AdditionalHeaders, }); } return this.create("SendEmail", true).excute(params); }; UtilityMethod.prototype.getCurrentUserEmailAddresses = function () { return this.create("GetCurrentUserEmailAddresses", true).excute({}); }; UtilityMethod.prototype.resolvePrincipal = function (input, scopes, sources, inputIsEmailOnly, addToUserInfoList, matchUserInfoList) { if (matchUserInfoList === void 0) { matchUserInfoList = false; } var params = { addToUserInfoList: addToUserInfoList, input: input, inputIsEmailOnly: inputIsEmailOnly, matchUserInfoList: matchUserInfoList, scopes: scopes, sources: sources, }; return this.create("ResolvePrincipalInCurrentContext", true).excute(params); }; UtilityMethod.prototype.searchPrincipals = function (input, scopes, sources, groupName, maxCount) { var params = { groupName: groupName, input: input, maxCount: maxCount, scopes: scopes, sources: sources, }; return this.create("SearchPrincipalsUsingContextWeb", true).excute(params); }; UtilityMethod.prototype.createEmailBodyForInvitation = function (pageAddress) { var params = { pageAddress: pageAddress, }; return this.create("CreateEmailBodyForInvitation", true).excute(params); }; UtilityMethod.prototype.expandGroupsToPrincipals = function (inputs, maxCount) { if (maxCount === void 0) { maxCount = 30; } var params = { inputs: inputs, maxCount: maxCount, }; return this.create("ExpandGroupsToPrincipals", true).excute(params); }; UtilityMethod.prototype.createWikiPage = function (info) { return this.create("CreateWikiPageInContextWeb", true).excute({ parameters: info, }).then(function (r) { return { data: r, file: new files_1.File(odata_1.extractOdataId(r)), }; }); }; return UtilityMethod; }(queryable_1.Queryable)); exports.UtilityMethod = UtilityMethod; /***/ }), /* 32 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1,eval)("this"); } catch(e) { // This works if the window reference is available if(typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var collections_1 = __webpack_require__(6); /** * Class used to manage the current application settings * */ var Settings = (function () { /** * Creates a new instance of the settings class * * @constructor */ function Settings() { this._settings = new collections_1.Dictionary(); } /** * Adds a new single setting, or overwrites a previous setting with the same key * * @param {string} key The key used to store this setting * @param {string} value The setting value to store */ Settings.prototype.add = function (key, value) { this._settings.add(key, value); }; /** * Adds a JSON value to the collection as a string, you must use getJSON to rehydrate the object when read * * @param {string} key The key used to store this setting * @param {any} value The setting value to store */ Settings.prototype.addJSON = function (key, value) { this._settings.add(key, JSON.stringify(value)); }; /** * Applies the supplied hash to the setting collection overwriting any existing value, or created new values * * @param {TypedHash<any>} hash The set of values to add */ Settings.prototype.apply = function (hash) { var _this = this; return new Promise(function (resolve, reject) { try { _this._settings.merge(hash); resolve(); } catch (e) { reject(e); } }); }; /** * Loads configuration settings into the collection from the supplied provider and returns a Promise * * @param {IConfigurationProvider} provider The provider from which we will load the settings */ Settings.prototype.load = function (provider) { var _this = this; return new Promise(function (resolve, reject) { provider.getConfiguration().then(function (value) { _this._settings.merge(value); resolve(); }).catch(function (reason) { reject(reason); }); }); }; /** * Gets a value from the configuration * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {string} string value from the configuration */ Settings.prototype.get = function (key) { return this._settings.get(key); }; /** * Gets a JSON value, rehydrating the stored string to the original object * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {any} object from the configuration */ Settings.prototype.getJSON = function (key) { var o = this.get(key); if (typeof o === "undefined" || o === null) { return o; } return JSON.parse(o); }; return Settings; }()); exports.Settings = Settings; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var search_1 = __webpack_require__(27); var searchsuggest_1 = __webpack_require__(28); var site_1 = __webpack_require__(29); var webs_1 = __webpack_require__(8); var util_1 = __webpack_require__(0); var userprofiles_1 = __webpack_require__(48); var exceptions_1 = __webpack_require__(3); var utilities_1 = __webpack_require__(31); /** * Root of the SharePoint REST module */ var SPRest = (function () { function SPRest() { } /** * Executes a search against this web context * * @param query The SearchQuery definition */ SPRest.prototype.searchSuggest = function (query) { var finalQuery; if (typeof query === "string") { finalQuery = { querytext: query }; } else { finalQuery = query; } return new searchsuggest_1.SearchSuggest("").execute(finalQuery); }; /** * Executes a search against this web context * * @param query The SearchQuery definition */ SPRest.prototype.search = function (query) { var finalQuery; if (typeof query === "string") { finalQuery = { Querytext: query }; } else if (query instanceof search_1.SearchQueryBuilder) { finalQuery = query.toSearchQuery(); } else { finalQuery = query; } return new search_1.Search("").execute(finalQuery); }; Object.defineProperty(SPRest.prototype, "site", { /** * Begins a site collection scoped REST request * */ get: function () { return new site_1.Site(""); }, enumerable: true, configurable: true }); Object.defineProperty(SPRest.prototype, "web", { /** * Begins a web scoped REST request * */ get: function () { return new webs_1.Web(""); }, enumerable: true, configurable: true }); Object.defineProperty(SPRest.prototype, "profiles", { /** * Access to user profile methods * */ get: function () { return new userprofiles_1.UserProfileQuery(""); }, enumerable: true, configurable: true }); /** * Creates a new batch object for use with the Queryable.addToBatch method * */ SPRest.prototype.createBatch = function () { return this.web.createBatch(); }; Object.defineProperty(SPRest.prototype, "utility", { /** * Static utilities methods from SP.Utilities.Utility */ get: function () { return new utilities_1.UtilityMethod("", ""); }, enumerable: true, configurable: true }); /** * Begins a cross-domain, host site scoped REST request, for use in add-in webs * * @param addInWebUrl The absolute url of the add-in web * @param hostWebUrl The absolute url of the host web */ SPRest.prototype.crossDomainSite = function (addInWebUrl, hostWebUrl) { return this._cdImpl(site_1.Site, addInWebUrl, hostWebUrl, "site"); }; /** * Begins a cross-domain, host web scoped REST request, for use in add-in webs * * @param addInWebUrl The absolute url of the add-in web * @param hostWebUrl The absolute url of the host web */ SPRest.prototype.crossDomainWeb = function (addInWebUrl, hostWebUrl) { return this._cdImpl(webs_1.Web, addInWebUrl, hostWebUrl, "web"); }; /** * Implements the creation of cross domain REST urls * * @param factory The constructor of the object to create Site | Web * @param addInWebUrl The absolute url of the add-in web * @param hostWebUrl The absolute url of the host web * @param urlPart String part to append to the url "site" | "web" */ SPRest.prototype._cdImpl = function (factory, addInWebUrl, hostWebUrl, urlPart) { if (!util_1.Util.isUrlAbsolute(addInWebUrl)) { throw new exceptions_1.UrlException("The addInWebUrl parameter must be an absolute url."); } if (!util_1.Util.isUrlAbsolute(hostWebUrl)) { throw new exceptions_1.UrlException("The hostWebUrl parameter must be an absolute url."); } var url = util_1.Util.combinePaths(addInWebUrl, "_api/SP.AppContextSite(@target)"); var instance = new factory(url, urlPart); instance.query.add("@target", "'" + encodeURIComponent(hostWebUrl) + "'"); return instance; }; return SPRest; }()); exports.SPRest = SPRest; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(44)); var httpclient_1 = __webpack_require__(15); exports.HttpClient = httpclient_1.HttpClient; var sprequestexecutorclient_1 = __webpack_require__(40); exports.SPRequestExecutorClient = sprequestexecutorclient_1.SPRequestExecutorClient; var nodefetchclient_1 = __webpack_require__(39); exports.NodeFetchClient = nodefetchclient_1.NodeFetchClient; var fetchclient_1 = __webpack_require__(21); exports.FetchClient = fetchclient_1.FetchClient; __export(__webpack_require__(36)); var collections_1 = __webpack_require__(6); exports.Dictionary = collections_1.Dictionary; var util_1 = __webpack_require__(0); exports.Util = util_1.Util; __export(__webpack_require__(5)); __export(__webpack_require__(3)); /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var cachingConfigurationProvider_1 = __webpack_require__(20); exports.CachingConfigurationProvider = cachingConfigurationProvider_1.default; var spListConfigurationProvider_1 = __webpack_require__(37); exports.SPListConfigurationProvider = spListConfigurationProvider_1.default; /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var cachingConfigurationProvider_1 = __webpack_require__(20); /** * A configuration provider which loads configuration values from a SharePoint list * */ var SPListConfigurationProvider = (function () { /** * Creates a new SharePoint list based configuration provider * @constructor * @param {string} webUrl Url of the SharePoint site, where the configuration list is located * @param {string} listTitle Title of the SharePoint list, which contains the configuration settings (optional, default = "config") */ function SPListConfigurationProvider(sourceWeb, sourceListTitle) { if (sourceListTitle === void 0) { sourceListTitle = "config"; } this.sourceWeb = sourceWeb; this.sourceListTitle = sourceListTitle; } Object.defineProperty(SPListConfigurationProvider.prototype, "web", { /** * Gets the url of the SharePoint site, where the configuration list is located * * @return {string} Url address of the site */ get: function () { return this.sourceWeb; }, enumerable: true, configurable: true }); Object.defineProperty(SPListConfigurationProvider.prototype, "listTitle", { /** * Gets the title of the SharePoint list, which contains the configuration settings * * @return {string} List title */ get: function () { return this.sourceListTitle; }, enumerable: true, configurable: true }); /** * Loads the configuration values from the SharePoint list * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ SPListConfigurationProvider.prototype.getConfiguration = function () { return this.web.lists.getByTitle(this.listTitle).items.select("Title", "Value") .getAs().then(function (data) { return data.reduce(function (configuration, item) { return Object.defineProperty(configuration, item.Title, { configurable: false, enumerable: false, value: item.Value, writable: false, }); }, {}); }); }; /** * Wraps the current provider in a cache enabled provider * * @return {CachingConfigurationProvider} Caching providers which wraps the current provider */ SPListConfigurationProvider.prototype.asCaching = function () { var cacheKey = "splist_" + this.web.toUrl() + "+" + this.listTitle; return new cachingConfigurationProvider_1.default(this, cacheKey); }; return SPListConfigurationProvider; }()); exports.default = SPListConfigurationProvider; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var collections_1 = __webpack_require__(6); var util_1 = __webpack_require__(0); var odata_1 = __webpack_require__(2); var CachedDigest = (function () { function CachedDigest() { } return CachedDigest; }()); exports.CachedDigest = CachedDigest; // allows for the caching of digests across all HttpClient's which each have their own DigestCache wrapper. var digests = new collections_1.Dictionary(); var DigestCache = (function () { function DigestCache(_httpClient, _digests) { if (_digests === void 0) { _digests = digests; } this._httpClient = _httpClient; this._digests = _digests; } DigestCache.prototype.getDigest = function (webUrl) { var _this = this; var cachedDigest = this._digests.get(webUrl); if (cachedDigest !== null) { var now = new Date(); if (now < cachedDigest.expiration) { return Promise.resolve(cachedDigest.value); } } var url = util_1.Util.combinePaths(webUrl, "/_api/contextinfo"); return this._httpClient.fetchRaw(url, { cache: "no-cache", credentials: "same-origin", headers: { "Accept": "application/json;odata=verbose", "Content-type": "application/json;odata=verbose;charset=utf-8", }, method: "POST", }).then(function (response) { var parser = new odata_1.ODataDefaultParser(); return parser.parse(response).then(function (d) { return d.GetContextWebInformation; }); }).then(function (data) { var newCachedDigest = new CachedDigest(); newCachedDigest.value = data.FormDigestValue; var seconds = data.FormDigestTimeoutSeconds; var expiration = new Date(); expiration.setTime(expiration.getTime() + 1000 * seconds); newCachedDigest.expiration = expiration; _this._digests.add(webUrl, newCachedDigest); return newCachedDigest.value; }); }; DigestCache.prototype.clear = function () { this._digests.clear(); }; return DigestCache; }()); exports.DigestCache = DigestCache; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var exceptions_1 = __webpack_require__(3); /** * This module is substituted for the NodeFetchClient.ts during the packaging process. This helps to reduce the pnp.js file size by * not including all of the node dependencies */ var NodeFetchClient = (function () { function NodeFetchClient() { } /** * Always throws an error that NodeFetchClient is not supported for use in the browser */ NodeFetchClient.prototype.fetch = function () { throw new exceptions_1.NodeFetchClientUnsupportedException(); }; return NodeFetchClient; }()); exports.NodeFetchClient = NodeFetchClient; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var exceptions_1 = __webpack_require__(3); /** * Makes requests using the SP.RequestExecutor library. */ var SPRequestExecutorClient = (function () { function SPRequestExecutorClient() { /** * Converts a SharePoint REST API response to a fetch API response. */ this.convertToResponse = function (spResponse) { var responseHeaders = new Headers(); for (var h in spResponse.headers) { if (spResponse.headers[h]) { responseHeaders.append(h, spResponse.headers[h]); } } // issue #256, Cannot have an empty string body when creating a Response with status 204 var body = spResponse.statusCode === 204 ? null : spResponse.body; return new Response(body, { headers: responseHeaders, status: spResponse.statusCode, statusText: spResponse.statusText, }); }; } /** * Fetches a URL using the SP.RequestExecutor library. */ SPRequestExecutorClient.prototype.fetch = function (url, options) { var _this = this; if (typeof SP === "undefined" || typeof SP.RequestExecutor === "undefined") { throw new exceptions_1.SPRequestExecutorUndefinedException(); } var addinWebUrl = url.substring(0, url.indexOf("/_api")), executor = new SP.RequestExecutor(addinWebUrl); var headers = {}, iterator, temp; if (options.headers && options.headers instanceof Headers) { iterator = options.headers.entries(); temp = iterator.next(); while (!temp.done) { headers[temp.value[0]] = temp.value[1]; temp = iterator.next(); } } else { headers = options.headers; } return new Promise(function (resolve, reject) { var requestOptions = { error: function (error) { reject(_this.convertToResponse(error)); }, headers: headers, method: options.method, success: function (response) { resolve(_this.convertToResponse(response)); }, url: url, }; if (options.body) { requestOptions = util_1.Util.extend(requestOptions, { body: options.body }); } else { requestOptions = util_1.Util.extend(requestOptions, { binaryStringRequestBody: true }); } executor.executeAsync(requestOptions); }); }; return SPRequestExecutorClient; }()); exports.SPRequestExecutorClient = SPRequestExecutorClient; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var storage_1 = __webpack_require__(14); var configuration_1 = __webpack_require__(33); var logging_1 = __webpack_require__(5); var rest_1 = __webpack_require__(34); var pnplibconfig_1 = __webpack_require__(4); /** * Root class of the Patterns and Practices namespace, provides an entry point to the library */ /** * Utility methods */ exports.util = util_1.Util; /** * Provides access to the REST interface */ exports.sp = new rest_1.SPRest(); /** * Provides access to local and session storage */ exports.storage = new storage_1.PnPClientStorage(); /** * Global configuration instance to which providers can be added */ exports.config = new configuration_1.Settings(); /** * Global logging instance to which subscribers can be registered and messages written */ exports.log = logging_1.Logger; /** * Allows for the configuration of the library */ exports.setup = pnplibconfig_1.setRuntimeConfig; /** * Expose a subset of classes from the library for public consumption */ __export(__webpack_require__(35)); // creating this class instead of directly assigning to default fixes issue #116 var Def = { /** * Global configuration instance to which providers can be added */ config: exports.config, /** * Global logging instance to which subscribers can be registered and messages written */ log: exports.log, /** * Provides access to local and session storage */ setup: exports.setup, /** * Provides access to the REST interface */ sp: exports.sp, /** * Provides access to local and session storage */ storage: exports.storage, /** * Utility methods */ util: exports.util, }; /** * Enables use of the import pnp from syntax */ exports.default = Def; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var odata_1 = __webpack_require__(2); /** * Describes a collection of Item objects * */ var AttachmentFiles = (function (_super) { __extends(AttachmentFiles, _super); /** * Creates a new instance of the AttachmentFiles class * * @param baseUrl The url or Queryable which forms the parent of this attachments collection */ function AttachmentFiles(baseUrl, path) { if (path === void 0) { path = "AttachmentFiles"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a Attachment File by filename * * @param name The name of the file, including extension. */ AttachmentFiles.prototype.getByName = function (name) { var f = new AttachmentFile(this); f.concat("('" + name + "')"); return f; }; /** * Adds a new attachment to the collection. Not supported for batching. * * @param name The name of the file, including extension. * @param content The Base64 file content. */ AttachmentFiles.prototype.add = function (name, content) { var _this = this; return this.clone(AttachmentFiles, "add(FileName='" + name + "')").post({ body: content, }).then(function (response) { return { data: response, file: _this.getByName(name), }; }); }; /** * Adds mjultiple new attachment to the collection. Not supported for batching. * * @files name The collection of files to add */ AttachmentFiles.prototype.addMultiple = function (files) { var _this = this; // add the files in series so we don't get update conflicts return files.reduce(function (chain, file) { return chain.then(function () { return _this.clone(AttachmentFiles, "add(FileName='" + file.name + "')").post({ body: file.content, }); }); }, Promise.resolve()); }; return AttachmentFiles; }(queryable_1.QueryableCollection)); exports.AttachmentFiles = AttachmentFiles; /** * Describes a single attachment file instance * */ var AttachmentFile = (function (_super) { __extends(AttachmentFile, _super); function AttachmentFile() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the contents of the file as text * */ AttachmentFile.prototype.getText = function () { return this.clone(AttachmentFile, "$value").get(new odata_1.TextFileParser()); }; /** * Gets the contents of the file as a blob, does not work in Node.js * */ AttachmentFile.prototype.getBlob = function () { return this.clone(AttachmentFile, "$value").get(new odata_1.BlobFileParser()); }; /** * Gets the contents of a file as an ArrayBuffer, works in Node.js */ AttachmentFile.prototype.getBuffer = function () { return this.clone(AttachmentFile, "$value").get(new odata_1.BufferFileParser()); }; /** * Gets the contents of a file as an ArrayBuffer, works in Node.js */ AttachmentFile.prototype.getJSON = function () { return this.clone(AttachmentFile, "$value").get(new odata_1.JSONFileParser()); }; /** * Sets the content of a file. Not supported for batching * * @param content The value to set for the file contents */ AttachmentFile.prototype.setContent = function (content) { var _this = this; return this.clone(AttachmentFile, "$value").post({ body: content, headers: { "X-HTTP-Method": "PUT", }, }).then(function (_) { return new AttachmentFile(_this); }); }; /** * Delete this attachment file * * @param eTag Value used in the IF-Match header, by default "*" */ AttachmentFile.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; return AttachmentFile; }(queryable_1.QueryableInstance)); exports.AttachmentFile = AttachmentFile; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); /** * Describes a collection of Field objects * */ var Forms = (function (_super) { __extends(Forms, _super); /** * Creates a new instance of the Fields class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Forms(baseUrl, path) { if (path === void 0) { path = "forms"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a form by id * * @param id The guid id of the item to retrieve */ Forms.prototype.getById = function (id) { var i = new Form(this); i.concat("('" + id + "')"); return i; }; return Forms; }(queryable_1.QueryableCollection)); exports.Forms = Forms; /** * Describes a single of Form instance * */ var Form = (function (_super) { __extends(Form, _super); function Form() { return _super !== null && _super.apply(this, arguments) || this; } return Form; }(queryable_1.QueryableInstance)); exports.Form = Form; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(22)); var files_1 = __webpack_require__(7); exports.CheckinType = files_1.CheckinType; exports.WebPartsPersonalizationScope = files_1.WebPartsPersonalizationScope; exports.MoveOperations = files_1.MoveOperations; exports.TemplateFileType = files_1.TemplateFileType; var folders_1 = __webpack_require__(9); exports.Folder = folders_1.Folder; exports.Folders = folders_1.Folders; var items_1 = __webpack_require__(10); exports.Item = items_1.Item; exports.Items = items_1.Items; exports.PagedItemCollection = items_1.PagedItemCollection; var navigation_1 = __webpack_require__(25); exports.NavigationNodes = navigation_1.NavigationNodes; exports.NavigationNode = navigation_1.NavigationNode; var lists_1 = __webpack_require__(11); exports.List = lists_1.List; exports.Lists = lists_1.Lists; var odata_1 = __webpack_require__(2); exports.extractOdataId = odata_1.extractOdataId; exports.ODataParserBase = odata_1.ODataParserBase; exports.ODataDefaultParser = odata_1.ODataDefaultParser; exports.ODataRaw = odata_1.ODataRaw; exports.ODataValue = odata_1.ODataValue; exports.ODataEntity = odata_1.ODataEntity; exports.ODataEntityArray = odata_1.ODataEntityArray; exports.TextFileParser = odata_1.TextFileParser; exports.BlobFileParser = odata_1.BlobFileParser; exports.BufferFileParser = odata_1.BufferFileParser; exports.JSONFileParser = odata_1.JSONFileParser; var queryable_1 = __webpack_require__(1); exports.Queryable = queryable_1.Queryable; exports.QueryableInstance = queryable_1.QueryableInstance; exports.QueryableCollection = queryable_1.QueryableCollection; var roles_1 = __webpack_require__(17); exports.RoleDefinitionBindings = roles_1.RoleDefinitionBindings; var search_1 = __webpack_require__(27); exports.Search = search_1.Search; exports.SearchQueryBuilder = search_1.SearchQueryBuilder; exports.SearchResults = search_1.SearchResults; exports.SortDirection = search_1.SortDirection; exports.ReorderingRuleMatchType = search_1.ReorderingRuleMatchType; exports.QueryPropertyValueType = search_1.QueryPropertyValueType; exports.SearchBuiltInSourceId = search_1.SearchBuiltInSourceId; var searchsuggest_1 = __webpack_require__(28); exports.SearchSuggest = searchsuggest_1.SearchSuggest; exports.SearchSuggestResult = searchsuggest_1.SearchSuggestResult; var site_1 = __webpack_require__(29); exports.Site = site_1.Site; __export(__webpack_require__(13)); var utilities_1 = __webpack_require__(31); exports.UtilityMethod = utilities_1.UtilityMethod; var webs_1 = __webpack_require__(8); exports.Web = webs_1.Web; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var caching_1 = __webpack_require__(22); var httpclient_1 = __webpack_require__(15); var logging_1 = __webpack_require__(5); var util_1 = __webpack_require__(0); /** * Resolves the context's result value * * @param context The current context */ function returnResult(context) { logging_1.Logger.log({ data: context.result, level: logging_1.LogLevel.Verbose, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Returning result, see data property for value.", }); return Promise.resolve(context.result); } /** * Sets the result on the context */ function setResult(context, value) { return new Promise(function (resolve) { context.result = value; context.hasResult = true; resolve(context); }); } exports.setResult = setResult; /** * Invokes the next method in the provided context's pipeline * * @param c The current request context */ function next(c) { if (c.pipeline.length < 1) { return Promise.resolve(c); } return c.pipeline.shift()(c); } /** * Executes the current request context's pipeline * * @param context Current context */ function pipe(context) { return next(context) .then(function (ctx) { return returnResult(ctx); }) .catch(function (e) { logging_1.Logger.log({ data: e, level: logging_1.LogLevel.Error, message: "Error in request pipeline: " + e.message, }); throw e; }); } exports.pipe = pipe; /** * decorator factory applied to methods in the pipeline to control behavior */ function requestPipelineMethod(alwaysRun) { if (alwaysRun === void 0) { alwaysRun = false; } return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } // if we have a result already in the pipeline, pass it along and don't call the tagged method if (!alwaysRun && args.length > 0 && args[0].hasOwnProperty("hasResult") && args[0].hasResult) { logging_1.Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Skipping request pipeline method " + propertyKey + ", existing result in pipeline.", logging_1.LogLevel.Verbose); return Promise.resolve(args[0]); } // apply the tagged method logging_1.Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Calling request pipeline method " + propertyKey + ".", logging_1.LogLevel.Verbose); // then chain the next method in the context's pipeline - allows for dynamic pipeline return method.apply(target, args).then(function (ctx) { return next(ctx); }); }; }; } exports.requestPipelineMethod = requestPipelineMethod; /** * Contains the methods used within the request pipeline */ var PipelineMethods = (function () { function PipelineMethods() { } /** * Logs the start of the request */ PipelineMethods.logStart = function (context) { return new Promise(function (resolve) { logging_1.Logger.log({ data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : context, level: logging_1.LogLevel.Info, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Beginning " + context.verb + " request (" + context.requestAbsoluteUrl + ")", }); resolve(context); }); }; /** * Handles caching of the request */ PipelineMethods.caching = function (context) { return new Promise(function (resolve) { // handle caching, if applicable if (context.verb === "GET" && context.isCached) { logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Caching is enabled for request, checking cache...", logging_1.LogLevel.Info); var cacheOptions = new caching_1.CachingOptions(context.requestAbsoluteUrl.toLowerCase()); if (typeof context.cachingOptions !== "undefined") { cacheOptions = util_1.Util.extend(cacheOptions, context.cachingOptions); } // we may not have a valid store if (cacheOptions.store !== null) { // check if we have the data in cache and if so resolve the promise and return var data = cacheOptions.store.get(cacheOptions.key); if (data !== null) { // ensure we clear any help batch dependency we are resolving from the cache logging_1.Logger.log({ data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : data, level: logging_1.LogLevel.Info, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Value returned from cache.", }); context.batchDependency(); return setResult(context, data).then(function (ctx) { return resolve(ctx); }); } } logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Value not found in cache.", logging_1.LogLevel.Info); // if we don't then wrap the supplied parser in the caching parser wrapper // and send things on their way context.parser = new caching_1.CachingParserWrapper(context.parser, cacheOptions); } return resolve(context); }); }; /** * Sends the request */ PipelineMethods.send = function (context) { return new Promise(function (resolve, reject) { // send or batch the request if (context.isBatched) { // we are in a batch, so add to batch, remove dependency, and resolve with the batch's promise var p = context.batch.add(context.requestAbsoluteUrl, context.verb, context.options, context.parser); // we release the dependency here to ensure the batch does not execute until the request is added to the batch context.batchDependency(); logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Batching request in batch " + context.batch.batchId + ".", logging_1.LogLevel.Info); // we set the result as the promise which will be resolved by the batch's execution resolve(setResult(context, p)); } else { logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Sending request.", logging_1.LogLevel.Info); // we are not part of a batch, so proceed as normal var client = new httpclient_1.HttpClient(); var opts = util_1.Util.extend(context.options || {}, { method: context.verb }); client.fetch(context.requestAbsoluteUrl, opts) .then(function (response) { return context.parser.parse(response); }) .then(function (result) { return setResult(context, result); }) .then(function (ctx) { return resolve(ctx); }) .catch(function (e) { return reject(e); }); } }); }; /** * Logs the end of the request */ PipelineMethods.logEnd = function (context) { return new Promise(function (resolve) { if (context.isBatched) { logging_1.Logger.log({ data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : context, level: logging_1.LogLevel.Info, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") " + context.verb + " request will complete in batch " + context.batch.batchId + ".", }); } else { logging_1.Logger.log({ data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : context, level: logging_1.LogLevel.Info, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Completing " + context.verb + " request.", }); } resolve(context); }); }; Object.defineProperty(PipelineMethods, "default", { get: function () { return [ PipelineMethods.logStart, PipelineMethods.caching, PipelineMethods.send, PipelineMethods.logEnd, ]; }, enumerable: true, configurable: true }); return PipelineMethods; }()); __decorate([ requestPipelineMethod(true) ], PipelineMethods, "logStart", null); __decorate([ requestPipelineMethod() ], PipelineMethods, "caching", null); __decorate([ requestPipelineMethod() ], PipelineMethods, "send", null); __decorate([ requestPipelineMethod(true) ], PipelineMethods, "logEnd", null); exports.PipelineMethods = PipelineMethods; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var RelatedItemManagerImpl = (function (_super) { __extends(RelatedItemManagerImpl, _super); function RelatedItemManagerImpl(baseUrl, path) { if (path === void 0) { path = "_api/SP.RelatedItemManager"; } return _super.call(this, baseUrl, path) || this; } RelatedItemManagerImpl.FromUrl = function (url) { if (url === null) { return new RelatedItemManagerImpl(""); } var index = url.indexOf("_api/"); if (index > -1) { return new RelatedItemManagerImpl(url.substr(0, index)); } return new RelatedItemManagerImpl(url); }; RelatedItemManagerImpl.prototype.getRelatedItems = function (sourceListName, sourceItemId) { var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".GetRelatedItems"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, }), }); }; RelatedItemManagerImpl.prototype.getPageOneRelatedItems = function (sourceListName, sourceItemId) { var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".GetPageOneRelatedItems"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, }), }); }; RelatedItemManagerImpl.prototype.addSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemID, targetWebUrl, tryAddReverseLink) { if (tryAddReverseLink === void 0) { tryAddReverseLink = false; } var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".AddSingleLink"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, SourceWebUrl: sourceWebUrl, TargetItemID: targetItemID, TargetListName: targetListName, TargetWebUrl: targetWebUrl, TryAddReverseLink: tryAddReverseLink, }), }); }; /** * Adds a related item link from an item specified by list name and item id, to an item specified by url * * @param sourceListName The source list name or list id * @param sourceItemId The source item id * @param targetItemUrl The target item url * @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails) */ RelatedItemManagerImpl.prototype.addSingleLinkToUrl = function (sourceListName, sourceItemId, targetItemUrl, tryAddReverseLink) { if (tryAddReverseLink === void 0) { tryAddReverseLink = false; } var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".AddSingleLinkToUrl"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, TargetItemUrl: targetItemUrl, TryAddReverseLink: tryAddReverseLink, }), }); }; /** * Adds a related item link from an item specified by url, to an item specified by list name and item id * * @param sourceItemUrl The source item url * @param targetListName The target list name or list id * @param targetItemId The target item id * @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails) */ RelatedItemManagerImpl.prototype.addSingleLinkFromUrl = function (sourceItemUrl, targetListName, targetItemId, tryAddReverseLink) { if (tryAddReverseLink === void 0) { tryAddReverseLink = false; } var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".AddSingleLinkFromUrl"); return query.post({ body: JSON.stringify({ SourceItemUrl: sourceItemUrl, TargetItemID: targetItemId, TargetListName: targetListName, TryAddReverseLink: tryAddReverseLink, }), }); }; RelatedItemManagerImpl.prototype.deleteSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemId, targetWebUrl, tryDeleteReverseLink) { if (tryDeleteReverseLink === void 0) { tryDeleteReverseLink = false; } var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".DeleteSingleLink"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, SourceWebUrl: sourceWebUrl, TargetItemID: targetItemId, TargetListName: targetListName, TargetWebUrl: targetWebUrl, TryDeleteReverseLink: tryDeleteReverseLink, }), }); }; return RelatedItemManagerImpl; }(queryable_1.Queryable)); exports.RelatedItemManagerImpl = RelatedItemManagerImpl; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); /** * Describes a collection of webhook subscriptions * */ var Subscriptions = (function (_super) { __extends(Subscriptions, _super); /** * Creates a new instance of the Subscriptions class * * @param baseUrl - The url or Queryable which forms the parent of this webhook subscriptions collection */ function Subscriptions(baseUrl, path) { if (path === void 0) { path = "subscriptions"; } return _super.call(this, baseUrl, path) || this; } /** * Returns all the webhook subscriptions or the specified webhook subscription * * @param subscriptionId The id of a specific webhook subscription to retrieve, omit to retrieve all the webhook subscriptions */ Subscriptions.prototype.getById = function (subscriptionId) { var subscription = new Subscription(this); subscription.concat("('" + subscriptionId + "')"); return subscription; }; /** * Creates a new webhook subscription * * @param notificationUrl The url to receive the notifications * @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months) * @param clientState A client specific string (defaults to pnp-js-core-subscription when omitted) */ Subscriptions.prototype.add = function (notificationUrl, expirationDate, clientState) { var _this = this; var postBody = JSON.stringify({ "clientState": clientState || "pnp-js-core-subscription", "expirationDateTime": expirationDate, "notificationUrl": notificationUrl, "resource": this.toUrl(), }); return this.post({ body: postBody, headers: { "Content-Type": "application/json" } }).then(function (result) { return { data: result, subscription: _this.getById(result.id) }; }); }; return Subscriptions; }(queryable_1.QueryableCollection)); exports.Subscriptions = Subscriptions; /** * Describes a single webhook subscription instance * */ var Subscription = (function (_super) { __extends(Subscription, _super); function Subscription() { return _super !== null && _super.apply(this, arguments) || this; } /** * Renews this webhook subscription * * @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months) */ Subscription.prototype.update = function (expirationDate) { var _this = this; var postBody = JSON.stringify({ "expirationDateTime": expirationDate, }); return this.patch({ body: postBody, headers: { "Content-Type": "application/json" } }).then(function (data) { return { data: data, subscription: _this }; }); }; /** * Removes this webhook subscription * */ Subscription.prototype.delete = function () { return _super.prototype.delete.call(this); }; return Subscription; }(queryable_1.QueryableInstance)); exports.Subscription = Subscription; /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var files_1 = __webpack_require__(52); var odata_1 = __webpack_require__(2); var UserProfileQuery = (function (_super) { __extends(UserProfileQuery, _super); /** * Creates a new instance of the UserProfileQuery class * * @param baseUrl The url or Queryable which forms the parent of this user profile query */ function UserProfileQuery(baseUrl, path) { if (path === void 0) { path = "_api/sp.userprofiles.peoplemanager"; } var _this = _super.call(this, baseUrl, path) || this; _this.profileLoader = new ProfileLoader(baseUrl); return _this; } Object.defineProperty(UserProfileQuery.prototype, "editProfileLink", { /** * The url of the edit profile page for the current user */ get: function () { return this.clone(UserProfileQuery, "EditProfileLink").getAs(odata_1.ODataValue()); }, enumerable: true, configurable: true }); Object.defineProperty(UserProfileQuery.prototype, "isMyPeopleListPublic", { /** * A boolean value that indicates whether the current user's "People I'm Following" list is public */ get: function () { return this.clone(UserProfileQuery, "IsMyPeopleListPublic").getAs(odata_1.ODataValue()); }, enumerable: true, configurable: true }); /** * A boolean value that indicates whether the current user is being followed by the specified user * * @param loginName The account name of the user */ UserProfileQuery.prototype.amIFollowedBy = function (loginName) { var q = this.clone(UserProfileQuery, "amifollowedby(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; /** * A boolean value that indicates whether the current user is following the specified user * * @param loginName The account name of the user */ UserProfileQuery.prototype.amIFollowing = function (loginName) { var q = this.clone(UserProfileQuery, "amifollowing(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; /** * Gets tags that the current user is following * * @param maxCount The maximum number of tags to retrieve (default is 20) */ UserProfileQuery.prototype.getFollowedTags = function (maxCount) { if (maxCount === void 0) { maxCount = 20; } return this.clone(UserProfileQuery, "getfollowedtags(" + maxCount + ")", true).get(); }; /** * Gets the people who are following the specified user * * @param loginName The account name of the user */ UserProfileQuery.prototype.getFollowersFor = function (loginName) { var q = this.clone(UserProfileQuery, "getfollowersfor(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; Object.defineProperty(UserProfileQuery.prototype, "myFollowers", { /** * Gets the people who are following the current user * */ get: function () { return new queryable_1.QueryableCollection(this, "getmyfollowers"); }, enumerable: true, configurable: true }); Object.defineProperty(UserProfileQuery.prototype, "myProperties", { /** * Gets user properties for the current user * */ get: function () { return new UserProfileQuery(this, "getmyproperties"); }, enumerable: true, configurable: true }); /** * Gets the people who the specified user is following * * @param loginName The account name of the user. */ UserProfileQuery.prototype.getPeopleFollowedBy = function (loginName) { var q = this.clone(UserProfileQuery, "getpeoplefollowedby(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; /** * Gets user properties for the specified user. * * @param loginName The account name of the user. */ UserProfileQuery.prototype.getPropertiesFor = function (loginName) { var q = this.clone(UserProfileQuery, "getpropertiesfor(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; Object.defineProperty(UserProfileQuery.prototype, "trendingTags", { /** * Gets the 20 most popular hash tags over the past week, sorted so that the most popular tag appears first * */ get: function () { var q = this.clone(UserProfileQuery, null, true); q.concat(".gettrendingtags"); return q.get(); }, enumerable: true, configurable: true }); /** * Gets the specified user profile property for the specified user * * @param loginName The account name of the user * @param propertyName The case-sensitive name of the property to get */ UserProfileQuery.prototype.getUserProfilePropertyFor = function (loginName, propertyName) { var q = this.clone(UserProfileQuery, "getuserprofilepropertyfor(accountname=@v, propertyname='" + propertyName + "')", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; /** * Removes the specified user from the user's list of suggested people to follow * * @param loginName The account name of the user */ UserProfileQuery.prototype.hideSuggestion = function (loginName) { var q = this.clone(UserProfileQuery, "hidesuggestion(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.post(); }; /** * A boolean values that indicates whether the first user is following the second user * * @param follower The account name of the user who might be following the followee * @param followee The account name of the user who might be followed by the follower */ UserProfileQuery.prototype.isFollowing = function (follower, followee) { var q = this.clone(UserProfileQuery, null, true); q.concat(".isfollowing(possiblefolloweraccountname=@v, possiblefolloweeaccountname=@y)"); q.query.add("@v", "'" + encodeURIComponent(follower) + "'"); q.query.add("@y", "'" + encodeURIComponent(followee) + "'"); return q.get(); }; /** * Uploads and sets the user profile picture (Users can upload a picture to their own profile only). Not supported for batching. * * @param profilePicSource Blob data representing the user's picture in BMP, JPEG, or PNG format of up to 4.76MB */ UserProfileQuery.prototype.setMyProfilePic = function (profilePicSource) { var _this = this; return new Promise(function (resolve, reject) { files_1.readBlobAsArrayBuffer(profilePicSource).then(function (buffer) { var request = new UserProfileQuery(_this, "setmyprofilepicture"); request.post({ body: String.fromCharCode.apply(null, new Uint16Array(buffer)), }).then(function (_) { return resolve(); }); }).catch(function (e) { return reject(e); }); }); }; /** * Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only) * * @param emails The email addresses of the users to provision sites for */ UserProfileQuery.prototype.createPersonalSiteEnqueueBulk = function () { var emails = []; for (var _i = 0; _i < arguments.length; _i++) { emails[_i] = arguments[_i]; } return this.profileLoader.createPersonalSiteEnqueueBulk(emails); }; Object.defineProperty(UserProfileQuery.prototype, "ownerUserProfile", { /** * Gets the user profile of the site owner * */ get: function () { return this.profileLoader.ownerUserProfile; }, enumerable: true, configurable: true }); Object.defineProperty(UserProfileQuery.prototype, "userProfile", { /** * Gets the user profile for the current user */ get: function () { return this.profileLoader.userProfile; }, enumerable: true, configurable: true }); /** * Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files * * @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request */ UserProfileQuery.prototype.createPersonalSite = function (interactiveRequest) { if (interactiveRequest === void 0) { interactiveRequest = false; } return this.profileLoader.createPersonalSite(interactiveRequest); }; /** * Sets the privacy settings for this profile * * @param share true to make all social data public; false to make all social data private */ UserProfileQuery.prototype.shareAllSocialData = function (share) { return this.profileLoader.shareAllSocialData(share); }; return UserProfileQuery; }(queryable_1.QueryableInstance)); exports.UserProfileQuery = UserProfileQuery; var ProfileLoader = (function (_super) { __extends(ProfileLoader, _super); /** * Creates a new instance of the ProfileLoader class * * @param baseUrl The url or Queryable which forms the parent of this profile loader */ function ProfileLoader(baseUrl, path) { if (path === void 0) { path = "_api/sp.userprofiles.profileloader.getprofileloader"; } return _super.call(this, baseUrl, path) || this; } /** * Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only) * * @param emails The email addresses of the users to provision sites for */ ProfileLoader.prototype.createPersonalSiteEnqueueBulk = function (emails) { return this.clone(ProfileLoader, "createpersonalsiteenqueuebulk").post({ body: JSON.stringify({ "emailIDs": emails }), }); }; Object.defineProperty(ProfileLoader.prototype, "ownerUserProfile", { /** * Gets the user profile of the site owner. * */ get: function () { var q = this.getParent(ProfileLoader, this.parentUrl, "_api/sp.userprofiles.profileloader.getowneruserprofile"); if (this.hasBatch) { q = q.inBatch(this.batch); } return q.postAs(); }, enumerable: true, configurable: true }); Object.defineProperty(ProfileLoader.prototype, "userProfile", { /** * Gets the user profile of the current user. * */ get: function () { return this.clone(ProfileLoader, "getuserprofile", true).postAs(); }, enumerable: true, configurable: true }); /** * Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files. * * @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request */ ProfileLoader.prototype.createPersonalSite = function (interactiveRequest) { if (interactiveRequest === void 0) { interactiveRequest = false; } return this.clone(ProfileLoader, "getuserprofile/createpersonalsiteenque(" + interactiveRequest + ")", true).post(); }; /** * Sets the privacy settings for this profile * * @param share true to make all social data public; false to make all social data private. */ ProfileLoader.prototype.shareAllSocialData = function (share) { return this.clone(ProfileLoader, "getuserprofile/shareallsocialdata(" + share + ")", true).post(); }; return ProfileLoader; }(queryable_1.Queryable)); /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); /** * Describes the views available in the current context * */ var Views = (function (_super) { __extends(Views, _super); /** * Creates a new instance of the Views class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Views(baseUrl, path) { if (path === void 0) { path = "views"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a view by guid id * * @param id The GUID id of the view */ Views.prototype.getById = function (id) { var v = new View(this); v.concat("('" + id + "')"); return v; }; /** * Gets a view by title (case-sensitive) * * @param title The case-sensitive title of the view */ Views.prototype.getByTitle = function (title) { return new View(this, "getByTitle('" + title + "')"); }; /** * Adds a new view to the collection * * @param title The new views's title * @param personalView True if this is a personal view, otherwise false, default = false * @param additionalSettings Will be passed as part of the view creation body */ /*tslint:disable max-line-length */ Views.prototype.add = function (title, personalView, additionalSettings) { var _this = this; if (personalView === void 0) { personalView = false; } if (additionalSettings === void 0) { additionalSettings = {}; } var postBody = JSON.stringify(util_1.Util.extend({ "PersonalView": personalView, "Title": title, "__metadata": { "type": "SP.View" }, }, additionalSettings)); return this.clone(Views, null, true).postAs({ body: postBody }).then(function (data) { return { data: data, view: _this.getById(data.Id), }; }); }; return Views; }(queryable_1.QueryableCollection)); exports.Views = Views; /** * Describes a single View instance * */ var View = (function (_super) { __extends(View, _super); function View() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(View.prototype, "fields", { get: function () { return new ViewFields(this); }, enumerable: true, configurable: true }); /** * Updates this view intance with the supplied properties * * @param properties A plain object hash of values to update for the view */ View.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.View" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, view: _this, }; }); }; /** * Delete this view * */ View.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; /** * Returns the list view as HTML. * */ View.prototype.renderAsHtml = function () { return this.clone(queryable_1.Queryable, "renderashtml", true).get(); }; return View; }(queryable_1.QueryableInstance)); exports.View = View; var ViewFields = (function (_super) { __extends(ViewFields, _super); function ViewFields(baseUrl, path) { if (path === void 0) { path = "viewfields"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a value that specifies the XML schema that represents the collection. */ ViewFields.prototype.getSchemaXml = function () { return this.clone(queryable_1.Queryable, "schemaxml", true).get(); }; /** * Adds the field with the specified field internal name or display name to the collection. * * @param fieldTitleOrInternalName The case-sensitive internal name or display name of the field to add. */ ViewFields.prototype.add = function (fieldTitleOrInternalName) { return this.clone(ViewFields, "addviewfield('" + fieldTitleOrInternalName + "')", true).post(); }; /** * Moves the field with the specified field internal name to the specified position in the collection. * * @param fieldInternalName The case-sensitive internal name of the field to move. * @param index The zero-based index of the new position for the field. */ ViewFields.prototype.move = function (fieldInternalName, index) { return this.clone(ViewFields, "moveviewfieldto", true).post({ body: JSON.stringify({ "field": fieldInternalName, "index": index }), }); }; /** * Removes all the fields from the collection. */ ViewFields.prototype.removeAll = function () { return this.clone(ViewFields, "removeallviewfields", true).post(); }; /** * Removes the field with the specified field internal name from the collection. * * @param fieldInternalName The case-sensitive internal name of the field to remove from the view. */ ViewFields.prototype.remove = function (fieldInternalName) { return this.clone(ViewFields, "removeviewfield('" + fieldInternalName + "')", true).post(); }; return ViewFields; }(queryable_1.QueryableCollection)); exports.ViewFields = ViewFields; /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var LimitedWebPartManager = (function (_super) { __extends(LimitedWebPartManager, _super); function LimitedWebPartManager() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(LimitedWebPartManager.prototype, "webparts", { /** * Gets the set of web part definitions contained by this web part manager * */ get: function () { return new WebPartDefinitions(this, "webparts"); }, enumerable: true, configurable: true }); /** * Exports a webpart definition * * @param id the GUID id of the definition to export */ LimitedWebPartManager.prototype.export = function (id) { return this.clone(LimitedWebPartManager, "ExportWebPart", true).post({ body: JSON.stringify({ webPartId: id }), }); }; /** * Imports a webpart * * @param xml webpart definition which must be valid XML in the .dwp or .webpart format */ LimitedWebPartManager.prototype.import = function (xml) { return this.clone(LimitedWebPartManager, "ImportWebPart", true).post({ body: JSON.stringify({ webPartXml: xml }), }); }; return LimitedWebPartManager; }(queryable_1.Queryable)); exports.LimitedWebPartManager = LimitedWebPartManager; var WebPartDefinitions = (function (_super) { __extends(WebPartDefinitions, _super); function WebPartDefinitions() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a web part definition from the collection by id * * @param id GUID id of the web part definition to get */ WebPartDefinitions.prototype.getById = function (id) { return new WebPartDefinition(this, "getbyid('" + id + "')"); }; return WebPartDefinitions; }(queryable_1.QueryableCollection)); exports.WebPartDefinitions = WebPartDefinitions; var WebPartDefinition = (function (_super) { __extends(WebPartDefinition, _super); function WebPartDefinition() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(WebPartDefinition.prototype, "webpart", { /** * Gets the webpart information associated with this definition */ get: function () { return new WebPart(this); }, enumerable: true, configurable: true }); /** * Removes a webpart from a page, all settings will be lost */ WebPartDefinition.prototype.delete = function () { return this.clone(WebPartDefinition, "DeleteWebPart", true).post(); }; return WebPartDefinition; }(queryable_1.QueryableInstance)); exports.WebPartDefinition = WebPartDefinition; var WebPart = (function (_super) { __extends(WebPart, _super); /** * Creates a new instance of the WebPart class * * @param baseUrl The url or Queryable which forms the parent of this fields collection * @param path Optional, if supplied will be appended to the supplied baseUrl */ function WebPart(baseUrl, path) { if (path === void 0) { path = "webpart"; } return _super.call(this, baseUrl, path) || this; } return WebPart; }(queryable_1.QueryableInstance)); exports.WebPart = WebPart; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var logging_1 = __webpack_require__(5); function deprecated(message) { return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } logging_1.Logger.log({ data: { descriptor: descriptor, propertyKey: propertyKey, target: target, }, level: logging_1.LogLevel.Warning, message: message, }); return method.apply(this, args); }; }; } exports.deprecated = deprecated; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Reads a blob as text * * @param blob The data to read */ function readBlobAsText(blob) { return readBlobAs(blob, "string"); } exports.readBlobAsText = readBlobAsText; /** * Reads a blob into an array buffer * * @param blob The data to read */ function readBlobAsArrayBuffer(blob) { return readBlobAs(blob, "buffer"); } exports.readBlobAsArrayBuffer = readBlobAsArrayBuffer; /** * Generic method to read blob's content * * @param blob The data to read * @param mode The read mode */ function readBlobAs(blob, mode) { return new Promise(function (resolve, reject) { try { var reader = new FileReader(); reader.onload = function (e) { resolve(e.target.result); }; switch (mode) { case "string": reader.readAsText(blob); break; case "buffer": reader.readAsArrayBuffer(blob); break; } } catch (e) { reject(e); } }); } /***/ }) /******/ ]); }); //# sourceMappingURL=pnp.js.map
maruilian11/cdnjs
ajax/libs/sp-pnp-js/2.0.6-beta.1/pnp.js
JavaScript
mit
373,699
<?php /** * Register the ElggDiscussionReply class for the object/discussion_reply subtype */ if (get_subtype_id('object', 'discussion_reply')) { update_subtype('object', 'discussion_reply', 'ElggDiscussionReply'); } else { add_subtype('object', 'discussion_reply', 'ElggDiscussionReply'); }
brettp/Elgg
mod/groups/activate.php
PHP
gpl-2.0
297
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "mutationofjb/tasks/conversationtask.h" #include "mutationofjb/assets.h" #include "mutationofjb/game.h" #include "mutationofjb/gamedata.h" #include "mutationofjb/gamescreen.h" #include "mutationofjb/script.h" #include "mutationofjb/tasks/saytask.h" #include "mutationofjb/tasks/sequentialtask.h" #include "mutationofjb/tasks/taskmanager.h" #include "mutationofjb/util.h" #include "mutationofjb/widgets/conversationwidget.h" namespace MutationOfJB { void ConversationTask::start() { setState(RUNNING); Game &game = getTaskManager()->getGame(); game.getGameScreen().showConversationWidget(true); ConversationWidget &widget = game.getGameScreen().getConversationWidget(); widget.setCallback(this); _currentGroupIndex = 0; showChoicesOrPick(); } void ConversationTask::update() { if (_sayTask) { if (_sayTask->getState() == Task::FINISHED) { _sayTask.reset(); switch (_substate) { case SAYING_NO_QUESTIONS: finish(); break; case SAYING_QUESTION: { const ConversationLineList &responseList = getTaskManager()->getGame().getAssets().getResponseList(); const ConversationLineList::Line *const line = responseList.getLine(_currentItem->_response); _substate = SAYING_RESPONSE; createSayTasks(line); getTaskManager()->startTask(_sayTask); break; } case SAYING_RESPONSE: { startExtra(); if (_substate != RUNNING_EXTRA) { gotoNextGroup(); } break; } default: break; } } } if (_innerExecCtx) { Command::ExecuteResult res = _innerExecCtx->runActiveCommand(); if (res == Command::Finished) { delete _innerExecCtx; _innerExecCtx = nullptr; gotoNextGroup(); } } } void ConversationTask::onChoiceClicked(ConversationWidget *convWidget, int, uint32 data) { const ConversationInfo::Item &item = getCurrentGroup()[data]; convWidget->clearChoices(); const ConversationLineList &toSayList = getTaskManager()->getGame().getAssets().getToSayList(); const ConversationLineList::Line *line = toSayList.getLine(item._question); _substate = SAYING_QUESTION; createSayTasks(line); getTaskManager()->startTask(_sayTask); _currentItem = &item; if (!line->_speeches[0].isRepeating()) { getTaskManager()->getGame().getGameData().getCurrentScene()->addExhaustedConvItem(_convInfo._context, data + 1, _currentGroupIndex + 1); } } void ConversationTask::showChoicesOrPick() { Game &game = getTaskManager()->getGame(); GameData &gameData = game.getGameData(); Scene *const scene = gameData.getScene(_sceneId); if (!scene) { return; } Common::Array<uint32> itemsWithValidQuestions; Common::Array<uint32> itemsWithValidResponses; Common::Array<uint32> itemsWithValidNext; /* Collect valid questions (not exhausted and not empty). Collect valid responses (not exhausted and not empty). If there are at least two visible questions, we show them. If there is just one visible question, pick it automatically ONLY if this is not the first question in this conversation. Otherwise we don't start the conversation. If there are no visible questions, automatically pick the first valid response. If nothing above applies, don't start the conversation. */ const ConversationInfo::ItemGroup &currentGroup = getCurrentGroup(); for (ConversationInfo::ItemGroup::size_type i = 0; i < currentGroup.size(); ++i) { const ConversationInfo::Item &item = currentGroup[i]; if (scene->isConvItemExhausted(_convInfo._context, static_cast<uint8>(i + 1), static_cast<uint8>(_currentGroupIndex + 1))) { continue; } const uint8 toSay = item._question; const uint8 response = item._response; const uint8 next = item._nextGroupIndex; if (toSay != 0) { itemsWithValidQuestions.push_back(i); } if (response != 0) { itemsWithValidResponses.push_back(i); } if (next != 0) { itemsWithValidNext.push_back(i); } } if (itemsWithValidQuestions.size() > 1) { ConversationWidget &widget = game.getGameScreen().getConversationWidget(); const ConversationLineList &toSayList = game.getAssets().getToSayList(); for (Common::Array<uint32>::size_type i = 0; i < itemsWithValidQuestions.size() && i < ConversationWidget::CONVERSATION_MAX_CHOICES; ++i) { const ConversationInfo::Item &item = currentGroup[itemsWithValidQuestions[i]]; const ConversationLineList::Line *const line = toSayList.getLine(item._question); const Common::String widgetText = toUpperCP895(line->_speeches[0]._text); widget.setChoice(static_cast<int>(i), widgetText, itemsWithValidQuestions[i]); } _substate = IDLE; _currentItem = nullptr; _haveChoices = true; } else if (itemsWithValidQuestions.size() == 1 && _haveChoices) { const ConversationLineList &toSayList = game.getAssets().getToSayList(); const ConversationInfo::Item &item = currentGroup[itemsWithValidQuestions.front()]; const ConversationLineList::Line *const line = toSayList.getLine(item._question); _substate = SAYING_QUESTION; createSayTasks(line); getTaskManager()->startTask(_sayTask); _currentItem = &item; if (!line->_speeches[0].isRepeating()) { game.getGameData().getCurrentScene()->addExhaustedConvItem(_convInfo._context, itemsWithValidQuestions.front() + 1, _currentGroupIndex + 1); } _haveChoices = true; } else if (!itemsWithValidResponses.empty() && _haveChoices) { const ConversationLineList &responseList = game.getAssets().getResponseList(); const ConversationInfo::Item &item = currentGroup[itemsWithValidResponses.front()]; const ConversationLineList::Line *const line = responseList.getLine(item._response); _substate = SAYING_RESPONSE; createSayTasks(line); getTaskManager()->startTask(_sayTask); _currentItem = &item; _haveChoices = true; } else if (!itemsWithValidNext.empty() && _haveChoices) { _currentGroupIndex = currentGroup[itemsWithValidNext.front()]._nextGroupIndex - 1; showChoicesOrPick(); } else { if (_haveChoices) { finish(); } else { _sayTask = TaskPtr(new SayTask("Nothing to talk about.", _convInfo._color)); // TODO: This is hardcoded in executable. Load it. getTaskManager()->startTask(_sayTask); _substate = SAYING_NO_QUESTIONS; _currentItem = nullptr; } } } const ConversationInfo::ItemGroup &ConversationTask::getCurrentGroup() const { assert(_currentGroupIndex < _convInfo._itemGroups.size()); return _convInfo._itemGroups[_currentGroupIndex]; } void ConversationTask::finish() { setState(FINISHED); Game &game = getTaskManager()->getGame(); game.getGameScreen().showConversationWidget(false); ConversationWidget &widget = game.getGameScreen().getConversationWidget(); widget.setCallback(nullptr); } void ConversationTask::startExtra() { const ConversationLineList &responseList = getTaskManager()->getGame().getAssets().getResponseList(); const ConversationLineList::Line *const line = responseList.getLine(_currentItem->_response); if (!line->_extra.empty()) { _innerExecCtx = new ScriptExecutionContext(getTaskManager()->getGame()); Command *const extraCmd = _innerExecCtx->getExtra(line->_extra); if (extraCmd) { Command::ExecuteResult res = _innerExecCtx->startCommand(extraCmd); if (res == Command::InProgress) { _substate = RUNNING_EXTRA; } else { delete _innerExecCtx; _innerExecCtx = nullptr; } } else { warning("Extra '%s' not found", line->_extra.c_str()); delete _innerExecCtx; _innerExecCtx = nullptr; } } } void ConversationTask::gotoNextGroup() { if (_currentItem->_nextGroupIndex == 0) { finish(); } else { _currentGroupIndex = _currentItem->_nextGroupIndex - 1; showChoicesOrPick(); } } void ConversationTask::createSayTasks(const ConversationLineList::Line *line) { if (line->_speeches.size() == 1) { const ConversationLineList::Speech &speech = line->_speeches[0]; _sayTask = TaskPtr(new SayTask(speech._text, getSpeechColor(speech))); } else { TaskPtrs tasks; for (ConversationLineList::Speeches::const_iterator it = line->_speeches.begin(); it != line->_speeches.end(); ++it) { tasks.push_back(TaskPtr(new SayTask(it->_text, getSpeechColor(*it)))); } _sayTask = TaskPtr(new SequentialTask(tasks)); } } uint8 ConversationTask::getSpeechColor(const ConversationLineList::Speech &speech) { uint8 color = WHITE; if (_substate == SAYING_RESPONSE) { color = _convInfo._color; if (_mode == TalkCommand::RAY_AND_BUTTLEG_MODE) { if (speech.isFirstSpeaker()) { color = GREEN; } else if (speech.isSecondSpeaker()) { color = LIGHTBLUE; } } } return color; } }
alexbevi/scummvm
engines/mutationofjb/tasks/conversationtask.cpp
C++
gpl-2.0
9,462
/* JWindow.java -- Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package javax.swing; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.GraphicsConfiguration; import java.awt.LayoutManager; import java.awt.Window; import java.awt.event.KeyEvent; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; /** * Unlike JComponent derivatives, JWindow inherits from * java.awt.Window. But also lets a look-and-feel component to its work. * * @author Ronald Veldema (rveldema@cs.vu.nl) */ public class JWindow extends Window implements Accessible, RootPaneContainer { /** * Provides accessibility support for <code>JWindow</code>. */ protected class AccessibleJWindow extends Window.AccessibleAWTWindow { /** * Creates a new instance of <code>AccessibleJWindow</code>. */ protected AccessibleJWindow() { super(); // Nothing to do here. } } private static final long serialVersionUID = 5420698392125238833L; protected JRootPane rootPane; /** * @specnote rootPaneCheckingEnabled is false to comply with J2SE 5.0 */ protected boolean rootPaneCheckingEnabled = false; protected AccessibleContext accessibleContext; /** * Creates a new <code>JWindow</code> that has a shared invisible owner frame * as its parent. */ public JWindow() { super(SwingUtilities.getOwnerFrame(null)); windowInit(); } /** * Creates a new <code>JWindow</code> that uses the specified graphics * environment. This can be used to open a window on a different screen for * example. * * @param gc the graphics environment to use */ public JWindow(GraphicsConfiguration gc) { super(SwingUtilities.getOwnerFrame(null), gc); windowInit(); } /** * Creates a new <code>JWindow</code> that has the specified * <code>owner</code> frame. If <code>owner</code> is <code>null</code>, then * an invisible shared owner frame is installed as owner frame. * * @param owner the owner frame of this window; if <code>null</code> a shared * invisible owner frame is used */ public JWindow(Frame owner) { super(SwingUtilities.getOwnerFrame(owner)); windowInit(); } /** * Creates a new <code>JWindow</code> that has the specified * <code>owner</code> window. If <code>owner</code> is <code>null</code>, * then an invisible shared owner frame is installed as owner frame. * * @param owner the owner window of this window; if <code>null</code> a * shared invisible owner frame is used */ public JWindow(Window owner) { super(SwingUtilities.getOwnerFrame(owner)); windowInit(); } /** * Creates a new <code>JWindow</code> for the given graphics configuration * and that has the specified <code>owner</code> window. If * <code>owner</code> is <code>null</code>, then an invisible shared owner * frame is installed as owner frame. * * The <code>gc</code> parameter can be used to open the window on a * different screen for example. * * @param owner the owner window of this window; if <code>null</code> a * shared invisible owner frame is used * @param gc the graphics configuration to use */ public JWindow(Window owner, GraphicsConfiguration gc) { super(SwingUtilities.getOwnerFrame(owner), gc); windowInit(); } protected void windowInit() { // We need to explicitly enable events here so that our processKeyEvent() // and processWindowEvent() gets called. enableEvents(AWTEvent.KEY_EVENT_MASK); super.setLayout(new BorderLayout(1, 1)); getRootPane(); // will do set/create // Now we're done init stage, adds and layouts go to content pane. setRootPaneCheckingEnabled(true); } public Dimension getPreferredSize() { return super.getPreferredSize(); } public void setLayout(LayoutManager manager) { // Check if we're in initialization stage. If so, call super.setLayout // otherwise, valid calls go to the content pane. if (isRootPaneCheckingEnabled()) getContentPane().setLayout(manager); else super.setLayout(manager); } public void setLayeredPane(JLayeredPane layeredPane) { getRootPane().setLayeredPane(layeredPane); } public JLayeredPane getLayeredPane() { return getRootPane().getLayeredPane(); } public JRootPane getRootPane() { if (rootPane == null) setRootPane(createRootPane()); return rootPane; } protected void setRootPane(JRootPane root) { if (rootPane != null) remove(rootPane); rootPane = root; add(rootPane, BorderLayout.CENTER); } protected JRootPane createRootPane() { return new JRootPane(); } public Container getContentPane() { return getRootPane().getContentPane(); } public void setContentPane(Container contentPane) { getRootPane().setContentPane(contentPane); } public Component getGlassPane() { return getRootPane().getGlassPane(); } public void setGlassPane(Component glassPane) { getRootPane().setGlassPane(glassPane); } protected void addImpl(Component comp, Object constraints, int index) { // If we're adding in the initialization stage use super.add. // otherwise pass the add onto the content pane. if (isRootPaneCheckingEnabled()) getContentPane().add(comp, constraints, index); else super.addImpl(comp, constraints, index); } public void remove(Component comp) { // If we're removing the root pane, use super.remove. Otherwise // pass it on to the content pane instead. if (comp == rootPane) super.remove(rootPane); else getContentPane().remove(comp); } protected boolean isRootPaneCheckingEnabled() { return rootPaneCheckingEnabled; } protected void setRootPaneCheckingEnabled(boolean enabled) { rootPaneCheckingEnabled = enabled; } public void update(Graphics g) { paint(g); } protected void processKeyEvent(KeyEvent e) { super.processKeyEvent(e); } public AccessibleContext getAccessibleContext() { if (accessibleContext == null) accessibleContext = new AccessibleJWindow(); return accessibleContext; } protected String paramString() { return "JWindow"; } }
taciano-perez/JamVM-PH
src/classpath/javax/swing/JWindow.java
Java
gpl-2.0
8,145
include RbCommonHelper include RbFormHelper include ProjectsHelper class RbReleasesMultiviewController < RbApplicationController unloadable def index end def show respond_to do |format| format.html { render } end end def new @release_multiview = RbReleaseMultiview.new(:project => @project) if request.post? # Convert id's into numbers and remove blank params[:release_multiview][:release_ids]=selected_ids(params[:release_multiview][:release_ids]) @release_multiview.attributes = params[:release_multiview] if @release_multiview.save flash[:notice] = l(:notice_successful_create) redirect_to :controller => 'rb_releases', :action => 'index', :project_id => @project end end end def edit if request.post? # Convert id's into numbers and remove blank params[:release_multiview][:release_ids]=selected_ids(params[:release_multiview][:release_ids]) if @release_multiview.update_attributes(params[:release_multiview]) flash[:notice] = l(:notice_successful_update) redirect_to :controller => 'rb_releases_multiview', :action => 'show', :release_multiview_id => @release_multiview end end end def update end def destroy @release_multiview.destroy redirect_to :controller => 'rb_releases', :action => 'index', :project_id => @project end end
efigence/redmine_backlogs
app/controllers/rb_releases_multiview_controller.rb
Ruby
gpl-2.0
1,400
<?php /** * Link/Bookmark API * * @package WordPress * @subpackage Bookmark */ /** * Retrieve Bookmark data * * @since 2.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int|stdClass $bookmark * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which * correspond to an stdClass object, an associative array, or a numeric array, * respectively. Default OBJECT. * @param string $filter Optional. How to sanitize bookmark fields. Default 'raw'. * @return array|object|null Type returned depends on $output value. */ function get_bookmark( $bookmark, $output = OBJECT, $filter = 'raw' ) { global $wpdb; if ( empty( $bookmark ) ) { if ( isset( $GLOBALS['link'] ) ) { $_bookmark = & $GLOBALS['link']; } else { $_bookmark = null; } } elseif ( is_object( $bookmark ) ) { wp_cache_add( $bookmark->link_id, $bookmark, 'bookmark' ); $_bookmark = $bookmark; } else { if ( isset( $GLOBALS['link'] ) && ( $GLOBALS['link']->link_id == $bookmark ) ) { $_bookmark = & $GLOBALS['link']; } else { $_bookmark = wp_cache_get( $bookmark, 'bookmark' ); if ( ! $_bookmark ) { $_bookmark = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->links WHERE link_id = %d LIMIT 1", $bookmark ) ); if ( $_bookmark ) { $_bookmark->link_category = array_unique( wp_get_object_terms( $_bookmark->link_id, 'link_category', array( 'fields' => 'ids' ) ) ); wp_cache_add( $_bookmark->link_id, $_bookmark, 'bookmark' ); } } } } if ( ! $_bookmark ) { return $_bookmark; } $_bookmark = sanitize_bookmark( $_bookmark, $filter ); if ( OBJECT === $output ) { return $_bookmark; } elseif ( ARRAY_A === $output ) { return get_object_vars( $_bookmark ); } elseif ( ARRAY_N === $output ) { return array_values( get_object_vars( $_bookmark ) ); } else { return $_bookmark; } } /** * Retrieve single bookmark data item or field. * * @since 2.3.0 * * @param string $field The name of the data field to return. * @param int $bookmark The bookmark ID to get field. * @param string $context Optional. The context of how the field will be used. * @return string|WP_Error */ function get_bookmark_field( $field, $bookmark, $context = 'display' ) { $bookmark = (int) $bookmark; $bookmark = get_bookmark( $bookmark ); if ( is_wp_error( $bookmark ) ) { return $bookmark; } if ( ! is_object( $bookmark ) ) { return ''; } if ( ! isset( $bookmark->$field ) ) { return ''; } return sanitize_bookmark_field( $field, $bookmark->$field, $bookmark->link_id, $context ); } /** * Retrieves the list of bookmarks * * Attempts to retrieve from the cache first based on MD5 hash of arguments. If * that fails, then the query will be built from the arguments and executed. The * results will be stored to the cache. * * @since 2.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string|array $args { * Optional. String or array of arguments to retrieve bookmarks. * * @type string $orderby How to order the links by. Accepts 'id', 'link_id', 'name', 'link_name', * 'url', 'link_url', 'visible', 'link_visible', 'rating', 'link_rating', * 'owner', 'link_owner', 'updated', 'link_updated', 'notes', 'link_notes', * 'description', 'link_description', 'length' and 'rand'. * When `$orderby` is 'length', orders by the character length of * 'link_name'. Default 'name'. * @type string $order Whether to order bookmarks in ascending or descending order. * Accepts 'ASC' (ascending) or 'DESC' (descending). Default 'ASC'. * @type int $limit Amount of bookmarks to display. Accepts any positive number or * -1 for all. Default -1. * @type string $category Comma-separated list of category IDs to include links from. * Default empty. * @type string $category_name Category to retrieve links for by name. Default empty. * @type int|bool $hide_invisible Whether to show or hide links marked as 'invisible'. Accepts * 1|true or 0|false. Default 1|true. * @type int|bool $show_updated Whether to display the time the bookmark was last updated. * Accepts 1|true or 0|false. Default 0|false. * @type string $include Comma-separated list of bookmark IDs to include. Default empty. * @type string $exclude Comma-separated list of bookmark IDs to exclude. Default empty. * @type string $search Search terms. Will be SQL-formatted with wildcards before and after * and searched in 'link_url', 'link_name' and 'link_description'. * Default empty. * } * @return object[] List of bookmark row objects. */ function get_bookmarks( $args = '' ) { global $wpdb; $defaults = array( 'orderby' => 'name', 'order' => 'ASC', 'limit' => -1, 'category' => '', 'category_name' => '', 'hide_invisible' => 1, 'show_updated' => 0, 'include' => '', 'exclude' => '', 'search' => '', ); $parsed_args = wp_parse_args( $args, $defaults ); $key = md5( serialize( $parsed_args ) ); $cache = wp_cache_get( 'get_bookmarks', 'bookmark' ); if ( 'rand' !== $parsed_args['orderby'] && $cache ) { if ( is_array( $cache ) && isset( $cache[ $key ] ) ) { $bookmarks = $cache[ $key ]; /** * Filters the returned list of bookmarks. * * The first time the hook is evaluated in this file, it returns the cached * bookmarks list. The second evaluation returns a cached bookmarks list if the * link category is passed but does not exist. The third evaluation returns * the full cached results. * * @since 2.1.0 * * @see get_bookmarks() * * @param array $bookmarks List of the cached bookmarks. * @param array $parsed_args An array of bookmark query arguments. */ return apply_filters( 'get_bookmarks', $bookmarks, $parsed_args ); } } if ( ! is_array( $cache ) ) { $cache = array(); } $inclusions = ''; if ( ! empty( $parsed_args['include'] ) ) { $parsed_args['exclude'] = ''; // Ignore exclude, category, and category_name params if using include. $parsed_args['category'] = ''; $parsed_args['category_name'] = ''; $inclinks = wp_parse_id_list( $parsed_args['include'] ); if ( count( $inclinks ) ) { foreach ( $inclinks as $inclink ) { if ( empty( $inclusions ) ) { $inclusions = ' AND ( link_id = ' . $inclink . ' '; } else { $inclusions .= ' OR link_id = ' . $inclink . ' '; } } } } if ( ! empty( $inclusions ) ) { $inclusions .= ')'; } $exclusions = ''; if ( ! empty( $parsed_args['exclude'] ) ) { $exlinks = wp_parse_id_list( $parsed_args['exclude'] ); if ( count( $exlinks ) ) { foreach ( $exlinks as $exlink ) { if ( empty( $exclusions ) ) { $exclusions = ' AND ( link_id <> ' . $exlink . ' '; } else { $exclusions .= ' AND link_id <> ' . $exlink . ' '; } } } } if ( ! empty( $exclusions ) ) { $exclusions .= ')'; } if ( ! empty( $parsed_args['category_name'] ) ) { $parsed_args['category'] = get_term_by( 'name', $parsed_args['category_name'], 'link_category' ); if ( $parsed_args['category'] ) { $parsed_args['category'] = $parsed_args['category']->term_id; } else { $cache[ $key ] = array(); wp_cache_set( 'get_bookmarks', $cache, 'bookmark' ); /** This filter is documented in wp-includes/bookmark.php */ return apply_filters( 'get_bookmarks', array(), $parsed_args ); } } $search = ''; if ( ! empty( $parsed_args['search'] ) ) { $like = '%' . $wpdb->esc_like( $parsed_args['search'] ) . '%'; $search = $wpdb->prepare( ' AND ( (link_url LIKE %s) OR (link_name LIKE %s) OR (link_description LIKE %s) ) ', $like, $like, $like ); } $category_query = ''; $join = ''; if ( ! empty( $parsed_args['category'] ) ) { $incategories = wp_parse_id_list( $parsed_args['category'] ); if ( count( $incategories ) ) { foreach ( $incategories as $incat ) { if ( empty( $category_query ) ) { $category_query = ' AND ( tt.term_id = ' . $incat . ' '; } else { $category_query .= ' OR tt.term_id = ' . $incat . ' '; } } } } if ( ! empty( $category_query ) ) { $category_query .= ") AND taxonomy = 'link_category'"; $join = " INNER JOIN $wpdb->term_relationships AS tr ON ($wpdb->links.link_id = tr.object_id) INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_taxonomy_id = tr.term_taxonomy_id"; } if ( $parsed_args['show_updated'] ) { $recently_updated_test = ', IF (DATE_ADD(link_updated, INTERVAL 120 MINUTE) >= NOW(), 1,0) as recently_updated '; } else { $recently_updated_test = ''; } $get_updated = ( $parsed_args['show_updated'] ) ? ', UNIX_TIMESTAMP(link_updated) AS link_updated_f ' : ''; $orderby = strtolower( $parsed_args['orderby'] ); $length = ''; switch ( $orderby ) { case 'length': $length = ', CHAR_LENGTH(link_name) AS length'; break; case 'rand': $orderby = 'rand()'; break; case 'link_id': $orderby = "$wpdb->links.link_id"; break; default: $orderparams = array(); $keys = array( 'link_id', 'link_name', 'link_url', 'link_visible', 'link_rating', 'link_owner', 'link_updated', 'link_notes', 'link_description' ); foreach ( explode( ',', $orderby ) as $ordparam ) { $ordparam = trim( $ordparam ); if ( in_array( 'link_' . $ordparam, $keys, true ) ) { $orderparams[] = 'link_' . $ordparam; } elseif ( in_array( $ordparam, $keys, true ) ) { $orderparams[] = $ordparam; } } $orderby = implode( ',', $orderparams ); } if ( empty( $orderby ) ) { $orderby = 'link_name'; } $order = strtoupper( $parsed_args['order'] ); if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ), true ) ) { $order = 'ASC'; } $visible = ''; if ( $parsed_args['hide_invisible'] ) { $visible = "AND link_visible = 'Y'"; } $query = "SELECT * $length $recently_updated_test $get_updated FROM $wpdb->links $join WHERE 1=1 $visible $category_query"; $query .= " $exclusions $inclusions $search"; $query .= " ORDER BY $orderby $order"; if ( -1 != $parsed_args['limit'] ) { $query .= ' LIMIT ' . $parsed_args['limit']; } $results = $wpdb->get_results( $query ); if ( 'rand()' !== $orderby ) { $cache[ $key ] = $results; wp_cache_set( 'get_bookmarks', $cache, 'bookmark' ); } /** This filter is documented in wp-includes/bookmark.php */ return apply_filters( 'get_bookmarks', $results, $parsed_args ); } /** * Sanitizes all bookmark fields. * * @since 2.3.0 * * @param stdClass|array $bookmark Bookmark row. * @param string $context Optional. How to filter the fields. Default 'display'. * @return stdClass|array Same type as $bookmark but with fields sanitized. */ function sanitize_bookmark( $bookmark, $context = 'display' ) { $fields = array( 'link_id', 'link_url', 'link_name', 'link_image', 'link_target', 'link_category', 'link_description', 'link_visible', 'link_owner', 'link_rating', 'link_updated', 'link_rel', 'link_notes', 'link_rss', ); if ( is_object( $bookmark ) ) { $do_object = true; $link_id = $bookmark->link_id; } else { $do_object = false; $link_id = $bookmark['link_id']; } foreach ( $fields as $field ) { if ( $do_object ) { if ( isset( $bookmark->$field ) ) { $bookmark->$field = sanitize_bookmark_field( $field, $bookmark->$field, $link_id, $context ); } } else { if ( isset( $bookmark[ $field ] ) ) { $bookmark[ $field ] = sanitize_bookmark_field( $field, $bookmark[ $field ], $link_id, $context ); } } } return $bookmark; } /** * Sanitizes a bookmark field. * * Sanitizes the bookmark fields based on what the field name is. If the field * has a strict value set, then it will be tested for that, else a more generic * filtering is applied. After the more strict filter is applied, if the `$context` * is 'raw' then the value is immediately return. * * Hooks exist for the more generic cases. With the 'edit' context, the {@see 'edit_$field'} * filter will be called and passed the `$value` and `$bookmark_id` respectively. * * With the 'db' context, the {@see 'pre_$field'} filter is called and passed the value. * The 'display' context is the final context and has the `$field` has the filter name * and is passed the `$value`, `$bookmark_id`, and `$context`, respectively. * * @since 2.3.0 * * @param string $field The bookmark field. * @param mixed $value The bookmark field value. * @param int $bookmark_id Bookmark ID. * @param string $context How to filter the field value. Accepts 'raw', 'edit', 'db', * 'display', 'attribute', or 'js'. Default 'display'. * @return mixed The filtered value. */ function sanitize_bookmark_field( $field, $value, $bookmark_id, $context ) { $int_fields = array( 'link_id', 'link_rating' ); if ( in_array( $field, $int_fields, true ) ) { $value = (int) $value; } switch ( $field ) { case 'link_category': // array( ints ) $value = array_map( 'absint', (array) $value ); // We return here so that the categories aren't filtered. // The 'link_category' filter is for the name of a link category, not an array of a link's link categories. return $value; case 'link_visible': // bool stored as Y|N $value = preg_replace( '/[^YNyn]/', '', $value ); break; case 'link_target': // "enum" $targets = array( '_top', '_blank' ); if ( ! in_array( $value, $targets, true ) ) { $value = ''; } break; } if ( 'raw' === $context ) { return $value; } if ( 'edit' === $context ) { /** This filter is documented in wp-includes/post.php */ $value = apply_filters( "edit_{$field}", $value, $bookmark_id ); if ( 'link_notes' === $field ) { $value = esc_html( $value ); // textarea_escaped } else { $value = esc_attr( $value ); } } elseif ( 'db' === $context ) { /** This filter is documented in wp-includes/post.php */ $value = apply_filters( "pre_{$field}", $value ); } else { /** This filter is documented in wp-includes/post.php */ $value = apply_filters( "{$field}", $value, $bookmark_id, $context ); if ( 'attribute' === $context ) { $value = esc_attr( $value ); } elseif ( 'js' === $context ) { $value = esc_js( $value ); } } // Restore the type for integer fields after esc_attr(). if ( in_array( $field, $int_fields, true ) ) { $value = (int) $value; } return $value; } /** * Deletes the bookmark cache. * * @since 2.7.0 * * @param int $bookmark_id Bookmark ID. */ function clean_bookmark_cache( $bookmark_id ) { wp_cache_delete( $bookmark_id, 'bookmark' ); wp_cache_delete( 'get_bookmarks', 'bookmark' ); clean_object_term_cache( $bookmark_id, 'link' ); }
CityOfPhiladelphia/phila.gov
wp/wp-includes/bookmark.php
PHP
gpl-2.0
15,332
<?php /** * This file is part of the OpenPNE package. * (c) OpenPNE Project (http://www.openpne.jp/) * * For the full copyright and license information, please view the LICENSE * file and the NOTICE file that were distributed with this source code. */ /** * csrfError action. * * @package OpenPNE * @subpackage default * @author Kousuke Ebihara <ebihara@tejimaya.com> */ class csrfErrorAction extends sfAction { public function execute($request) { } }
smart-e/lifemap
apps/pc_backend/modules/default/actions/csrfErrorAction.class.php
PHP
apache-2.0
507
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * User: anna * Date: 09-Feb-2009 */ package com.intellij.projectImport; import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.components.StorageScheme; import com.intellij.openapi.project.Project; import javax.swing.*; public class ProjectFormatPanel { private static final String STORAGE_FORMAT_PROPERTY = "default.storage.format"; public static final String DIR_BASED = Project.DIRECTORY_STORE_FOLDER + " (directory based)"; private static final String FILE_BASED = ".ipr (file based)"; private JComboBox myStorageFormatCombo; private JPanel myWholePanel; public ProjectFormatPanel() { myStorageFormatCombo.insertItemAt(DIR_BASED, 0); myStorageFormatCombo.insertItemAt(FILE_BASED, 1); myStorageFormatCombo.setSelectedItem(PropertiesComponent.getInstance().getOrInit(STORAGE_FORMAT_PROPERTY, DIR_BASED)); } public JPanel getPanel() { return myWholePanel; } public JComboBox getStorageFormatComboBox() { return myStorageFormatCombo; } public void updateData(WizardContext context) { StorageScheme format = FILE_BASED.equals(myStorageFormatCombo.getSelectedItem()) ? StorageScheme.DEFAULT : StorageScheme.DIRECTORY_BASED; context.setProjectStorageFormat(format); setDefaultFormat(isDefault()); } public static void setDefaultFormat(boolean aDefault) { PropertiesComponent.getInstance().setValue(STORAGE_FORMAT_PROPERTY, aDefault ? FILE_BASED : DIR_BASED); } public void setVisible(boolean visible) { myWholePanel.setVisible(visible); } public boolean isDefault() { return FILE_BASED.equals(myStorageFormatCombo.getSelectedItem()); } }
Lekanich/intellij-community
java/idea-ui/src/com/intellij/projectImport/ProjectFormatPanel.java
Java
apache-2.0
2,323
/******************************************************************************* * Copyright (c) 2006 Oracle Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Oracle Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.bpel.common.ui.assist; import org.eclipse.jface.fieldassist.IContentProposalProvider; import org.eclipse.jface.fieldassist.IControlContentAdapter; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter; /** * This is a field assist adapter which extends the core SWT content * assist adapter and allows programmatic opening of the assist dialog * as well as automatic width sizing. * * @author Michal Chmielewski (michal.chmielewski@oracle.com) * @date Aug 9, 2006 * */ public class FieldAssistAdapter extends ContentAssistCommandAdapter { /** * @param control * @param controlContentAdapter * @param proposalProvider * @param commandId * @param autoActivationCharacters */ public FieldAssistAdapter(Control control, IControlContentAdapter controlContentAdapter, IContentProposalProvider proposalProvider, String commandId, char[] autoActivationCharacters) { super(control, controlContentAdapter, proposalProvider, commandId, autoActivationCharacters); } /** * @param control * @param controlContentAdapter * @param proposalProvider * @param commandId * @param autoActivationCharacters * @param installDecoration */ public FieldAssistAdapter(Control control, IControlContentAdapter controlContentAdapter, IContentProposalProvider proposalProvider, String commandId, char[] autoActivationCharacters, boolean installDecoration) { super(control, controlContentAdapter, proposalProvider, commandId, autoActivationCharacters, installDecoration); } public void openProposals () { openProposalPopup(); getControl().setFocus(); } @Override protected void openProposalPopup () { Point popupSize = getPopupSize(); popupSize.x = getProposalWidth(); super.openProposalPopup(); } public int getProposalWidth () { Point size = getControl().getSize(); return size.x + 20; } }
Drifftr/devstudio-tooling-bps
plugins/org.eclipse.bpel.common.ui/src/org/eclipse/bpel/common/ui/assist/FieldAssistAdapter.java
Java
apache-2.0
2,503
package org.nutz.dao.test.meta; import org.nutz.dao.entity.annotation.Column; import org.nutz.dao.entity.annotation.Id; import org.nutz.dao.entity.annotation.Readonly; import org.nutz.dao.entity.annotation.Table; @Table("t_simple_pojo") public class SimplePOJO { @Id private long id; @Column @Readonly private String name; @Column private String sex; public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
sdgdsffdsfff/nutz
test/org/nutz/dao/test/meta/SimplePOJO.java
Java
apache-2.0
818
/*<license> Copyright 2004 - $Date$ by PeopleWare n.v.. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </license>*/ package org.ppwcode.vernacular.semantics_VI.bean.stubs; public class StubRousseauBeanB extends StubRousseauBean { private StubRousseauBeanA $property8; public final StubRousseauBeanA getProperty8() { return $property8; } public final void setProperty8(StubRousseauBeanA property8) { $property8 = property8; } @Override public int nrOfProperties() { return 6; } }
jandppw/ppwcode-recovered-from-google-code
java/vernacular/semantics/trunk/src/test/java/org/ppwcode/vernacular/semantics_VI/bean/stubs/StubRousseauBeanB.java
Java
apache-2.0
995
/* * * Paros and its related class files. * * Paros is an HTTP/HTTPS proxy for assessing web application security. * Copyright (C) 2003-2004 Chinotec Technologies Company * * This program is free software; you can redistribute it and/or * modify it under the terms of the Clarified Artistic License * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // ZAP: 2011/08/04 Changed for cleanup // ZAP: 2011/11/20 Set order // ZAP: 2012/03/15 Changed to reset the message of the ManualRequestEditorDialog // when a new session is created. Added the key configuration to the // ManualRequestEditorDialog. // ZAP: 2012/03/17 Issue 282 Added getAuthor() // ZAP: 2012/04/25 Added @Override annotation to all appropriate methods. // ZAP: 2012/07/02 ManualRequestEditorDialog changed to receive Message instead // of HttpMessage. Changed logger to static. // ZAP: 2012/07/29 Issue 43: added sessionScopeChanged event // ZAP: 2012/08/01 Issue 332: added support for Modes // ZAP: 2012/11/21 Heavily refactored extension to support non-HTTP messages. // ZAP: 2013/01/25 Added method removeManualSendEditor(). // ZAP: 2013/02/06 Issue 499: NullPointerException while uninstalling an add-on // with a manual request editor // ZAP: 2014/03/23 Issue 1094: Change ExtensionManualRequestEditor to only add view components if in GUI mode // ZAP: 2014/08/14 Issue 1292: NullPointerException while attempting to remove an unregistered ManualRequestEditorDialog // ZAP: 2014/12/12 Issue 1449: Added help button // ZAP: 2015/03/16 Issue 1525: Further database independence changes package org.parosproxy.paros.extension.manualrequest; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.parosproxy.paros.Constant; import org.parosproxy.paros.control.Control; import org.parosproxy.paros.control.Control.Mode; import org.parosproxy.paros.extension.ExtensionAdaptor; import org.parosproxy.paros.extension.ExtensionHook; import org.parosproxy.paros.extension.ExtensionLoader; import org.parosproxy.paros.extension.SessionChangedListener; import org.parosproxy.paros.extension.ViewDelegate; import org.parosproxy.paros.extension.manualrequest.http.impl.ManualHttpRequestEditorDialog; import org.parosproxy.paros.model.Session; import org.zaproxy.zap.extension.httppanel.Message; public class ExtensionManualRequestEditor extends ExtensionAdaptor implements SessionChangedListener { private Map<Class<? extends Message>, ManualRequestEditorDialog> dialogues = new HashMap<>(); /** * Name of this extension. */ public static final String NAME = "ExtensionManualRequest"; public ExtensionManualRequestEditor() { super(); initialize(); } public ExtensionManualRequestEditor(String name) { super(name); } private void initialize() { this.setName(NAME); this.setOrder(36); } @Override public void initView(ViewDelegate view) { super.initView(view); // add default manual request editor ManualRequestEditorDialog httpSendEditorDialog = new ManualHttpRequestEditorDialog(true, "manual", "ui.dialogs.manreq"); httpSendEditorDialog.setTitle(Constant.messages.getString("manReq.dialog.title")); addManualSendEditor(httpSendEditorDialog); } /** * Should be called before extension is initialized via its * {@link #hook(ExtensionHook)} method. * * @param dialogue */ public void addManualSendEditor(ManualRequestEditorDialog dialogue) { dialogues.put(dialogue.getMessageType(), dialogue); } public void removeManualSendEditor(Class<? extends Message> messageType) { // remove from list ManualRequestEditorDialog dialogue = dialogues.remove(messageType); if (dialogue != null) { // remove from GUI dialogue.clear(); dialogue.dispose(); if (getView() != null) { // unload menu items ExtensionLoader extLoader = Control.getSingleton().getExtensionLoader(); extLoader.removeToolsMenuItem(dialogue.getMenuItem()); } } } /** * Get special manual send editor to add listeners, etc. * * @param type * @return */ public ManualRequestEditorDialog getManualSendEditor(Class<? extends Message> type) { return dialogues.get(type); } @Override public void hook(ExtensionHook extensionHook) { super.hook(extensionHook); if (getView() != null) { for (Entry<Class<? extends Message>, ManualRequestEditorDialog> dialogue : dialogues.entrySet()) { extensionHook.getHookMenu().addToolsMenuItem(dialogue.getValue().getMenuItem()); } extensionHook.addSessionListener(this); } } @Override public String getAuthor() { return Constant.PAROS_TEAM; } @Override public void sessionChanged(Session session) { for (Entry<Class<? extends Message>, ManualRequestEditorDialog> dialogue : dialogues.entrySet()) { dialogue.getValue().clear(); dialogue.getValue().setDefaultMessage(); } } @Override public void sessionAboutToChange(Session session) { } @Override public void sessionScopeChanged(Session session) { } @Override public void sessionModeChanged(Mode mode) { Boolean isEnabled = null; switch (mode) { case safe: isEnabled = false; break; case protect: case standard: case attack: isEnabled = true; break; } if (isEnabled != null) { for (Entry<Class<? extends Message>, ManualRequestEditorDialog> dialog : dialogues.entrySet()) { dialog.getValue().setEnabled(isEnabled); } } } /** * No database tables used, so all supported */ @Override public boolean supportsDb(String type) { return true; } }
0xkasun/zaproxy
src/org/parosproxy/paros/extension/manualrequest/ExtensionManualRequestEditor.java
Java
apache-2.0
6,249
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.backend.spi; import com.google.appengine.api.prospectivesearch.ProspectiveSearchService; import com.google.appengine.api.prospectivesearch.ProspectiveSearchServiceFactory; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.cloud.backend.config.StringUtility; import com.google.gson.Gson; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.logging.Logger; /** * Utility class with helper functions to decode subscription information and handle * Prospective Search API. */ public class SubscriptionUtility { protected static final String IOS_DEVICE_PREFIX = "ios_"; protected static final String GCM_KEY_SUBID = "subId"; protected static final String REQUEST_TYPE_DEVICE_SUB = "deviceSubscriptionRequest"; protected static final String REQUEST_TYPE_PSI_SUB = "PSISubscriptionRequest"; /** * A key word to indicate "query" type in Prospective Search API subscription id. */ public static final String GCM_TYPEID_QUERY = "query"; private static final ProspectiveSearchService prosSearch = ProspectiveSearchServiceFactory .getProspectiveSearchService(); private static final Logger log = Logger.getLogger(SubscriptionUtility.class.getName()); /** * An enumeration of supported mobile device type. */ public enum MobileType { ANDROID, IOS } /** * Gets the mobile type based on the subscription id provided by client. * * Subscription id is in format of <device token>:GCM_TYPEID_QUERY:<topic>. Clients prefix * device token with "ios_" if the mobile type is "iOS", while Android device * token does not have any prefix. * * @param subId Subscription ID sent by client during query subscription * @return Mobile type */ public static MobileType getMobileType(String subId) { return (subId.startsWith(IOS_DEVICE_PREFIX)) ? MobileType.IOS : MobileType.ANDROID; } /** * Extracts device registration id from subscription id. * * @param subId Subscription id sent by client during query subscription * @return Device registration id */ public static String extractRegId(String subId) { if (StringUtility.isNullOrEmpty(subId)) { throw new IllegalArgumentException("subId cannot be null or empty"); } String[] tokens = subId.split(":"); return tokens[0].replaceFirst(IOS_DEVICE_PREFIX, ""); } /** * Extracts device registration id from subscription id. * * @param subId Subscription id sent by client during query subscription * @return Device registration id as List */ public static List<String> extractRegIdAsList(String subId) { return Arrays.asList(extractRegId(subId)); } /** * Constructs subscription id based on registration id and query id. * * @param regId Registration id provided by the client * @param queryId Query id provided by the client * @return */ public static String constructSubId(String regId, String queryId) { if (StringUtility.isNullOrEmpty(regId) || StringUtility.isNullOrEmpty(queryId)) { throw new IllegalArgumentException("regId and queryId cannot be null or empty"); } // ProsSearch subId = <regId>:query:<clientSubId> return regId + ":" + GCM_TYPEID_QUERY + ":" + queryId; } /** * Clears Prospective Search API subscription and device subscription entity for listed devices. * * @param deviceIds A list of device ids for which subscriptions are to be removed */ public static void clearSubscriptionAndDeviceEntity(List<String> deviceIds) { DeviceSubscription deviceSubscription = new DeviceSubscription(); for (String deviceId : deviceIds) { Set<String> subIds = deviceSubscription.getSubscriptionIds(deviceId); // Delete all subscriptions for the device from Prospective Search API for (String subId : subIds) { try { prosSearch.unsubscribe(QueryOperations.PROS_SEARCH_DEFAULT_TOPIC, subId); } catch (IllegalArgumentException e) { log.warning("Unsubscribe " + subId + " from PSI encounters error, " + e.getMessage()); } } // Remove device from datastore deviceSubscription.delete(deviceId); } } /** * Clears Prospective Search API subscription and removes device entity for all devices. */ public static void clearAllSubscriptionAndDeviceEntity() { // Remove all device subscription and psi subscription DeviceSubscription deviceSubscription = new DeviceSubscription(); deviceSubscription.enqueueDeleteDeviceSubscription(); } /** * Enqueues subscription ids in task queue for deletion. * * @param subIds Psi subscription ids to be deleted */ protected static void enqueueDeletePsiSubscription(String[] subIds) { Queue deviceTokenCleanupQueue = QueueFactory.getQueue("subscription-removal"); deviceTokenCleanupQueue.add(TaskOptions.Builder.withMethod(TaskOptions.Method.POST) .url("/admin/push/devicesubscription/delete") .param("subIds", new Gson().toJson(subIds, String[].class)) .param("type", SubscriptionUtility.REQUEST_TYPE_PSI_SUB)); } }
kleopatra999/solutions-mobile-backend-starter-java
src/com/google/cloud/backend/spi/SubscriptionUtility.java
Java
apache-2.0
5,854
cask "osirix-quicklook" do version "6.0" sha256 :no_check url "https://www.osirix-viewer.com/Museum/OsiriXQuickLookInstaller.zip" name "OsiriX DICOM QuickLook" homepage "https://www.osirix-viewer.com/" pkg "OsiriXQuickLookInstaller.pkg" uninstall pkgutil: "com.pixmeo.osirix.osirixQuicklookPlugin.OsiriXQuickLookPlugin.pkg" end
stephenwade/homebrew-cask
Casks/osirix-quicklook.rb
Ruby
bsd-2-clause
345
cask 'sqlworkbenchj' do version '119' sha256 '8565105504e517ca972b4f3c99f4436b13e7a3caaf8f53a97f44a71a7c71efc6' url "http://www.sql-workbench.net/archive/Workbench-Build#{version}-MacJava8.tgz" name 'SQL Workbench/J' homepage 'http://www.sql-workbench.net' license :apache app 'SQLWorkbenchJ.app' caveats do depends_on_java end end
hristozov/homebrew-cask
Casks/sqlworkbenchj.rb
Ruby
bsd-2-clause
357
var leafletDirective = angular.module("leaflet-directive", []); leafletDirective.directive('leaflet', [ '$http', '$log', '$parse', '$rootScope', function ($http, $log, $parse, $rootScope) { var defaults = { maxZoom: 14, minZoom: 1, doubleClickZoom: true, tileLayer: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', tileLayerOptions: { attribution: 'Tiles &copy; Open Street Maps' }, icon: { url: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-icon.png', retinaUrl: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-icon@2x.png', size: [25, 41], anchor: [12, 40], popup: [0, -40], shadow: { url: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-shadow.png', retinaUrl: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-shadow.png', size: [41, 41], anchor: [12, 40] } }, path: { weight: 10, opacity: 1, color: '#0000ff' } }; var str_inspect_hint = 'Add testing="testing" to <leaflet> tag to inspect this object'; return { restrict: "E", replace: true, transclude: true, scope: { center: '=center', maxBounds: '=maxbounds', bounds: '=bounds', marker: '=marker', markers: '=markers', defaults: '=defaults', paths: '=paths', tiles: '=tiles', events: '=events' }, template: '<div class="angular-leaflet-map"></div>', link: function ($scope, element, attrs /*, ctrl */) { var centerModel = { lat:$parse("center.lat"), lng:$parse("center.lng"), zoom:$parse("center.zoom") }; if (attrs.width) { element.css('width', attrs.width); } if (attrs.height) { element.css('height', attrs.height); } $scope.leaflet = {}; $scope.leaflet.maxZoom = !!(attrs.defaults && $scope.defaults && $scope.defaults.maxZoom) ? parseInt($scope.defaults.maxZoom, 10) : defaults.maxZoom; $scope.leaflet.minZoom = !!(attrs.defaults && $scope.defaults && $scope.defaults.minZoom) ? parseInt($scope.defaults.minZoom, 10) : defaults.minZoom; $scope.leaflet.doubleClickZoom = !!(attrs.defaults && $scope.defaults && (typeof($scope.defaults.doubleClickZoom) == "boolean") ) ? $scope.defaults.doubleClickZoom : defaults.doubleClickZoom; var map = new L.Map(element[0], { maxZoom: $scope.leaflet.maxZoom, minZoom: $scope.leaflet.minZoom, doubleClickZoom: $scope.leaflet.doubleClickZoom }); map.setView([0, 0], 1); $scope.leaflet.tileLayer = !!(attrs.defaults && $scope.defaults && $scope.defaults.tileLayer) ? $scope.defaults.tileLayer : defaults.tileLayer; $scope.leaflet.map = !!attrs.testing ? map : str_inspect_hint; setupTiles(); setupCenter(); setupMaxBounds(); setupBounds(); setupMainMaerker(); setupMarkers(); setupPaths(); setupEvents(); // use of leafletDirectiveSetMap event is not encouraged. only use // it when there is no easy way to bind data to the directive $scope.$on('leafletDirectiveSetMap', function(event, message) { var meth = message.shift(); map[meth].apply(map, message); }); $scope.safeApply = function(fn) { var phase = this.$root.$$phase; if (phase == '$apply' || phase == '$digest') { $scope.$eval(fn); } else { $scope.$apply(fn); } }; /* * Event setup watches for callbacks set in the parent scope * * $scope.events = { * dblclick: function(){ * // doThis() * }, * click: function(){ * // doThat() * } * } * */ function setupEvents(){ if ( typeof($scope.events) != 'object'){ return false; }else{ for (var bind_to in $scope.events){ map.on(bind_to,$scope.events[bind_to]); } } } function setupTiles(){ // TODO build custom object for tiles, actually only the tile string if ($scope.defaults && $scope.defaults.tileLayerOptions) { for (var key in $scope.defaults.tileLayerOptions) { defaults.tileLayerOptions[key] = $scope.defaults.tileLayerOptions[key]; } } if ($scope.tiles) { if ($scope.tiles.tileLayer) { $scope.leaflet.tileLayer = $scope.tiles.tileLayer; } if ($scope.tiles.tileLayerOptions.attribution) { defaults.tileLayerOptions.attribution = $scope.tiles.tileLayerOptions.attribution; } } var tileLayerObj = L.tileLayer( $scope.leaflet.tileLayer, defaults.tileLayerOptions); tileLayerObj.addTo(map); $scope.leaflet.tileLayerObj = !!attrs.testing ? tileLayerObj : str_inspect_hint; } function setupMaxBounds() { if (!$scope.maxBounds) { return; } if ($scope.maxBounds.southWest && $scope.maxBounds.southWest.lat && $scope.maxBounds.southWest.lng && $scope.maxBounds.northEast && $scope.maxBounds.northEast.lat && $scope.maxBounds.northEast.lng) { map.setMaxBounds( new L.LatLngBounds( new L.LatLng($scope.maxBounds.southWest.lat, $scope.maxBounds.southWest.lng), new L.LatLng($scope.maxBounds.northEast.lat, $scope.maxBounds.northEast.lng) ) ); $scope.$watch("maxBounds", function (maxBounds) { if (maxBounds.southWest && maxBounds.northEast && maxBounds.southWest.lat && maxBounds.southWest.lng && maxBounds.northEast.lat && maxBounds.northEast.lng) { map.setMaxBounds( new L.LatLngBounds( new L.LatLng(maxBounds.southWest.lat, maxBounds.southWest.lng), new L.LatLng(maxBounds.northEast.lat, maxBounds.northEast.lng) ) ); } }); } } function tryFitBounds(bounds) { if (bounds) { var southWest = bounds.southWest; var northEast = bounds.northEast; if (southWest && northEast && southWest.lat && southWest.lng && northEast.lat && northEast.lng) { var sw_latlng = new L.LatLng(southWest.lat, southWest.lng); var ne_latlng = new L.LatLng(northEast.lat, northEast.lng); map.fitBounds(new L.LatLngBounds(sw_latlng, ne_latlng)); } } } function setupBounds() { if (!$scope.bounds) { return; } $scope.$watch('bounds', function (new_bounds) { tryFitBounds(new_bounds); }); } function setupCenter() { $scope.$watch("center", function (center) { if (!center) { $log.warn("[AngularJS - Leaflet] 'center' is undefined in the current scope, did you forget to initialize it?"); return; } if (center.lat && center.lng && center.zoom) { map.setView([center.lat, center.lng], center.zoom); } else if (center.autoDiscover === true) { map.locate({ setView: true, maxZoom: $scope.leaflet.maxZoom }); } }, true); map.on("dragend", function (/* event */) { $scope.safeApply(function (scope) { centerModel.lat.assign(scope, map.getCenter().lat); centerModel.lng.assign(scope, map.getCenter().lng); }); }); map.on("zoomend", function (/* event */) { if(angular.isUndefined($scope.center)){ $log.warn("[AngularJS - Leaflet] 'center' is undefined in the current scope, did you forget to initialize it?"); } if (angular.isUndefined($scope.center) || $scope.center.zoom !== map.getZoom()) { $scope.safeApply(function (s) { centerModel.zoom.assign(s, map.getZoom()); centerModel.lat.assign(s, map.getCenter().lat); centerModel.lng.assign(s, map.getCenter().lng); }); } }); } function setupMainMaerker() { var main_marker; if (!$scope.marker) { return; } main_marker = createMarker('marker', $scope.marker, map); $scope.leaflet.marker = !!attrs.testing ? main_marker : str_inspect_hint; main_marker.on('click', function(e) { $rootScope.$broadcast('leafletDirectiveMainMarkerClick'); }); } function setupMarkers() { var markers = {}; $scope.leaflet.markers = !!attrs.testing ? markers : str_inspect_hint; if (!$scope.markers) { return; } function genMultiMarkersClickCallback(m_name) { return function(e) { $rootScope.$broadcast('leafletDirectiveMarkersClick', m_name); }; } for (var name in $scope.markers) { markers[name] = createMarker( 'markers.'+name, $scope.markers[name], map); markers[name].on('click', genMultiMarkersClickCallback(name)); } $scope.$watch('markers', function(newMarkers) { // Delete markers from the array for (var name in markers) { if (newMarkers[name] === undefined) { delete markers[name]; } } // add new markers for (var new_name in newMarkers) { if (markers[new_name] === undefined) { markers[new_name] = createMarker( 'markers.'+new_name, newMarkers[new_name], map); markers[new_name].on('click', genMultiMarkersClickCallback(new_name)); } } }, true); } function createMarker(scope_watch_name, marker_data, map) { var marker = buildMarker(marker_data); map.addLayer(marker); if (marker_data.focus === true) { marker.openPopup(); } marker.on("dragend", function () { $scope.safeApply(function (scope) { marker_data.lat = marker.getLatLng().lat; marker_data.lng = marker.getLatLng().lng; }); if (marker_data.message) { marker.openPopup(); } }); var clearWatch = $scope.$watch(scope_watch_name, function (data, old_data) { if (!data) { map.removeLayer(marker); clearWatch(); return; } if (old_data) { if (data.draggable !== undefined && data.draggable !== old_data.draggable) { if (data.draggable === true) { marker.dragging.enable(); } else { marker.dragging.disable(); } } if (data.focus !== undefined && data.focus !== old_data.focus) { if (data.focus === true) { marker.openPopup(); } else { marker.closePopup(); } } if (data.message !== undefined && data.message !== old_data.message) { marker.bindPopup(data); } if (data.lat !== old_data.lat || data.lng !== old_data.lng) { marker.setLatLng(new L.LatLng(data.lat, data.lng)); } if (data.icon && data.icon !== old_data.icon) { marker.setIcon(data.icon); } } }, true); return marker; } function buildMarker(data) { var micon = null; if (data.icon) { micon = data.icon; } else { micon = buildIcon(); } var marker = new L.marker(data, { icon: micon, draggable: data.draggable ? true : false } ); if (data.message) { marker.bindPopup(data.message); } return marker; } function buildIcon() { return L.icon({ iconUrl: defaults.icon.url, iconRetinaUrl: defaults.icon.retinaUrl, iconSize: defaults.icon.size, iconAnchor: defaults.icon.anchor, popupAnchor: defaults.icon.popup, shadowUrl: defaults.icon.shadow.url, shadowRetinaUrl: defaults.icon.shadow.retinaUrl, shadowSize: defaults.icon.shadow.size, shadowAnchor: defaults.icon.shadow.anchor }); } function setupPaths() { var paths = {}; $scope.leaflet.paths = !!attrs.testing ? paths : str_inspect_hint; if (!$scope.paths) { return; } $log.warn("[AngularJS - Leaflet] Creating polylines and adding them to the map will break the directive's scope's inspection in AngularJS Batarang"); for (var name in $scope.paths) { paths[name] = createPath(name, $scope.paths[name], map); } $scope.$watch("paths", function (newPaths) { for (var new_name in newPaths) { if (paths[new_name] === undefined) { paths[new_name] = createPath(new_name, newPaths[new_name], map); } } // Delete paths from the array for (var name in paths) { if (newPaths[name] === undefined) { delete paths[name]; } } }, true); } function createPath(name, scopePath, map) { var polyline = new L.Polyline([], { weight: defaults.path.weight, color: defaults.path.color, opacity: defaults.path.opacity }); if (scopePath.latlngs !== undefined) { var latlngs = convertToLeafletLatLngs(scopePath.latlngs); polyline.setLatLngs(latlngs); } if (scopePath.weight !== undefined) { polyline.setStyle({ weight: scopePath.weight }); } if (scopePath.color !== undefined) { polyline.setStyle({ color: scopePath.color }); } if (scopePath.opacity !== undefined) { polyline.setStyle({ opacity: scopePath.opacity }); } map.addLayer(polyline); var clearWatch = $scope.$watch('paths.' + name, function (data, oldData) { if (!data) { map.removeLayer(polyline); clearWatch(); return; } if (oldData) { if (data.latlngs !== undefined && data.latlngs !== oldData.latlngs) { var latlngs = convertToLeafletLatLngs(data.latlngs); polyline.setLatLngs(latlngs); } if (data.weight !== undefined && data.weight !== oldData.weight) { polyline.setStyle({ weight: data.weight }); } if (data.color !== undefined && data.color !== oldData.color) { polyline.setStyle({ color: data.color }); } if (data.opacity !== undefined && data.opacity !== oldData.opacity) { polyline.setStyle({ opacity: data.opacity }); } } }, true); return polyline; } function convertToLeafletLatLngs(latlngs) { var leafletLatLngs = latlngs.filter(function (latlng) { return !!latlng.lat && !!latlng.lng; }).map(function (latlng) { return new L.LatLng(latlng.lat, latlng.lng); }); return leafletLatLngs; } } }; }]);
him2him2/cdnjs
ajax/libs/ui-leaflet/0.5.0/angular-leaflet-directive.js
JavaScript
mit
19,188
/* * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.swingset3.demos; import java.net.URL; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; /** * @author Pavel Porvatov */ public class ResourceManager { private static final Logger logger = Logger.getLogger(ResourceManager.class.getName()); private final Class<?> demoClass; // Resource bundle for internationalized and accessible text private ResourceBundle bundle = null; public ResourceManager(Class<?> demoClass) { this.demoClass = demoClass; String bundleName = demoClass.getPackage().getName() + ".resources." + demoClass.getSimpleName(); try { bundle = ResourceBundle.getBundle(bundleName); } catch (MissingResourceException e) { logger.log(Level.SEVERE, "Couldn't load bundle: " + bundleName); } } public String getString(String key) { return bundle != null ? bundle.getString(key) : key; } public char getMnemonic(String key) { return (getString(key)).charAt(0); } public ImageIcon createImageIcon(String filename, String description) { String path = "resources/images/" + filename; URL imageURL = demoClass.getResource(path); if (imageURL == null) { logger.log(Level.SEVERE, "unable to access image file: " + path); return null; } else { return new ImageIcon(imageURL, description); } } }
FauxFaux/jdk9-jdk
test/sanity/client/lib/SwingSet3/src/com/sun/swingset3/demos/ResourceManager.java
Java
gpl-2.0
2,603
<?php // $Id$ /** * @file * Default theme implementation to present all user profile data. * * This template is used when viewing a registered member's profile page, * e.g., example.com/user/123. 123 being the users ID. * * Use render($user_profile) to print all profile items, or print a subset * such as render($content['field_example']). Always call render($user_profile) * at the end in order to print all remaining items. If the item is a category, * it will contain all its profile items. By default, $user_profile['summary'] * is provided which contains data on the user's history. Other data can be * included by modules. $user_profile['user_picture'] is available * for showing the account picture. * * Available variables: * - $user_profile: An array of profile items. Use render() to print them. * - Field variables: for each field instance attached to the user a * corresponding variable is defined; e.g., $user->field_example has a * variable $field_example defined. When needing to access a field's raw * values, developers/themers are strongly encouraged to use these * variables. Otherwise they will have to explicitly specify the desired * field language, e.g. $user->field_example['en'], thus overriding any * language negotiation rule that was previously applied. * * @see user-profile-category.tpl.php * Where the html is handled for the group. * @see user-profile-item.tpl.php * Where the html is handled for each item in the group. * @see template_preprocess_user_profile() */ ?> <div class="profile"<?php print $attributes; ?>> <?php print render($user_profile); ?> </div>
danmuzyka/FooProject
modules/user/user-profile.tpl.php
PHP
gpl-2.0
1,661
/** @file AreaMemoryManager.cpp @maintainer Morgan McGuire, http://graphics.cs.williams.edu @created 2009-01-20 @edited 2009-01-20 Copyright 2000-2009, Morgan McGuire. All rights reserved. */ #include "G3D/AreaMemoryManager.h" #include "G3D/System.h" namespace G3D { AreaMemoryManager::Buffer::Buffer(size_t size) : m_size(size), m_used(0) { // Allocate space for a lot of buffers. m_first = (uint8*)::malloc(m_size); } AreaMemoryManager::Buffer::~Buffer() { ::free(m_first); } void* AreaMemoryManager::Buffer::alloc(size_t s) { if (s + m_used > m_size) { return NULL; } else { void* old = m_first + m_used; m_used += s; return old; } } bool AreaMemoryManager::isThreadsafe() const { return false; } AreaMemoryManager::Ref AreaMemoryManager::create(size_t sizeHint) { return new AreaMemoryManager(sizeHint); } AreaMemoryManager::AreaMemoryManager(size_t sizeHint) : m_sizeHint(sizeHint) { debugAssert(sizeHint > 0); } AreaMemoryManager::~AreaMemoryManager() { deallocateAll(); } size_t AreaMemoryManager::bytesAllocated() const { return m_sizeHint * m_bufferArray.size(); } void* AreaMemoryManager::alloc(size_t s) { void* n = (m_bufferArray.size() > 0) ? m_bufferArray.last()->alloc(s) : NULL; if (n == NULL) { // This buffer is full m_bufferArray.append(new Buffer(max(s, m_sizeHint))); return m_bufferArray.last()->alloc(s); } else { return n; } } void AreaMemoryManager::free(void* x) { // Intentionally empty; we block deallocate } void AreaMemoryManager::deallocateAll() { m_bufferArray.deleteAll(); m_bufferArray.clear(); } }
natedahl32/portalclassic
dep/src/g3dlite/AreaMemoryManager.cpp
C++
gpl-2.0
1,793
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # * * # ************************************************************************** */ # # /* Revised by Edward Diener (2020) */ # # /* See http://www.boost.org for most recent version. */ # # ifndef BOOST_PREPROCESSOR_SEQ_DETAIL_SPLIT_HPP # define BOOST_PREPROCESSOR_SEQ_DETAIL_SPLIT_HPP # # include <boost/preprocessor/config/config.hpp> # # /* BOOST_PP_SEQ_SPLIT */ # # define BOOST_PP_SEQ_SPLIT(n, seq) BOOST_PP_SEQ_SPLIT_D(n, seq) # # if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_MWCC() # define BOOST_PP_SEQ_SPLIT_D(n, seq) (BOOST_PP_SEQ_SPLIT_ ## n seq) # else # define BOOST_PP_SEQ_SPLIT_D(n, seq) (BOOST_PP_SEQ_SPLIT_ ## n ## seq) # endif # # if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_STRICT() # # define BOOST_PP_SEQ_SPLIT_1(x) (x), # define BOOST_PP_SEQ_SPLIT_2(x) (x) BOOST_PP_SEQ_SPLIT_1 # define BOOST_PP_SEQ_SPLIT_3(x) (x) BOOST_PP_SEQ_SPLIT_2 # define BOOST_PP_SEQ_SPLIT_4(x) (x) BOOST_PP_SEQ_SPLIT_3 # define BOOST_PP_SEQ_SPLIT_5(x) (x) BOOST_PP_SEQ_SPLIT_4 # define BOOST_PP_SEQ_SPLIT_6(x) (x) BOOST_PP_SEQ_SPLIT_5 # define BOOST_PP_SEQ_SPLIT_7(x) (x) BOOST_PP_SEQ_SPLIT_6 # define BOOST_PP_SEQ_SPLIT_8(x) (x) BOOST_PP_SEQ_SPLIT_7 # define BOOST_PP_SEQ_SPLIT_9(x) (x) BOOST_PP_SEQ_SPLIT_8 # define BOOST_PP_SEQ_SPLIT_10(x) (x) BOOST_PP_SEQ_SPLIT_9 # define BOOST_PP_SEQ_SPLIT_11(x) (x) BOOST_PP_SEQ_SPLIT_10 # define BOOST_PP_SEQ_SPLIT_12(x) (x) BOOST_PP_SEQ_SPLIT_11 # define BOOST_PP_SEQ_SPLIT_13(x) (x) BOOST_PP_SEQ_SPLIT_12 # define BOOST_PP_SEQ_SPLIT_14(x) (x) BOOST_PP_SEQ_SPLIT_13 # define BOOST_PP_SEQ_SPLIT_15(x) (x) BOOST_PP_SEQ_SPLIT_14 # define BOOST_PP_SEQ_SPLIT_16(x) (x) BOOST_PP_SEQ_SPLIT_15 # define BOOST_PP_SEQ_SPLIT_17(x) (x) BOOST_PP_SEQ_SPLIT_16 # define BOOST_PP_SEQ_SPLIT_18(x) (x) BOOST_PP_SEQ_SPLIT_17 # define BOOST_PP_SEQ_SPLIT_19(x) (x) BOOST_PP_SEQ_SPLIT_18 # define BOOST_PP_SEQ_SPLIT_20(x) (x) BOOST_PP_SEQ_SPLIT_19 # define BOOST_PP_SEQ_SPLIT_21(x) (x) BOOST_PP_SEQ_SPLIT_20 # define BOOST_PP_SEQ_SPLIT_22(x) (x) BOOST_PP_SEQ_SPLIT_21 # define BOOST_PP_SEQ_SPLIT_23(x) (x) BOOST_PP_SEQ_SPLIT_22 # define BOOST_PP_SEQ_SPLIT_24(x) (x) BOOST_PP_SEQ_SPLIT_23 # define BOOST_PP_SEQ_SPLIT_25(x) (x) BOOST_PP_SEQ_SPLIT_24 # define BOOST_PP_SEQ_SPLIT_26(x) (x) BOOST_PP_SEQ_SPLIT_25 # define BOOST_PP_SEQ_SPLIT_27(x) (x) BOOST_PP_SEQ_SPLIT_26 # define BOOST_PP_SEQ_SPLIT_28(x) (x) BOOST_PP_SEQ_SPLIT_27 # define BOOST_PP_SEQ_SPLIT_29(x) (x) BOOST_PP_SEQ_SPLIT_28 # define BOOST_PP_SEQ_SPLIT_30(x) (x) BOOST_PP_SEQ_SPLIT_29 # define BOOST_PP_SEQ_SPLIT_31(x) (x) BOOST_PP_SEQ_SPLIT_30 # define BOOST_PP_SEQ_SPLIT_32(x) (x) BOOST_PP_SEQ_SPLIT_31 # define BOOST_PP_SEQ_SPLIT_33(x) (x) BOOST_PP_SEQ_SPLIT_32 # define BOOST_PP_SEQ_SPLIT_34(x) (x) BOOST_PP_SEQ_SPLIT_33 # define BOOST_PP_SEQ_SPLIT_35(x) (x) BOOST_PP_SEQ_SPLIT_34 # define BOOST_PP_SEQ_SPLIT_36(x) (x) BOOST_PP_SEQ_SPLIT_35 # define BOOST_PP_SEQ_SPLIT_37(x) (x) BOOST_PP_SEQ_SPLIT_36 # define BOOST_PP_SEQ_SPLIT_38(x) (x) BOOST_PP_SEQ_SPLIT_37 # define BOOST_PP_SEQ_SPLIT_39(x) (x) BOOST_PP_SEQ_SPLIT_38 # define BOOST_PP_SEQ_SPLIT_40(x) (x) BOOST_PP_SEQ_SPLIT_39 # define BOOST_PP_SEQ_SPLIT_41(x) (x) BOOST_PP_SEQ_SPLIT_40 # define BOOST_PP_SEQ_SPLIT_42(x) (x) BOOST_PP_SEQ_SPLIT_41 # define BOOST_PP_SEQ_SPLIT_43(x) (x) BOOST_PP_SEQ_SPLIT_42 # define BOOST_PP_SEQ_SPLIT_44(x) (x) BOOST_PP_SEQ_SPLIT_43 # define BOOST_PP_SEQ_SPLIT_45(x) (x) BOOST_PP_SEQ_SPLIT_44 # define BOOST_PP_SEQ_SPLIT_46(x) (x) BOOST_PP_SEQ_SPLIT_45 # define BOOST_PP_SEQ_SPLIT_47(x) (x) BOOST_PP_SEQ_SPLIT_46 # define BOOST_PP_SEQ_SPLIT_48(x) (x) BOOST_PP_SEQ_SPLIT_47 # define BOOST_PP_SEQ_SPLIT_49(x) (x) BOOST_PP_SEQ_SPLIT_48 # define BOOST_PP_SEQ_SPLIT_50(x) (x) BOOST_PP_SEQ_SPLIT_49 # define BOOST_PP_SEQ_SPLIT_51(x) (x) BOOST_PP_SEQ_SPLIT_50 # define BOOST_PP_SEQ_SPLIT_52(x) (x) BOOST_PP_SEQ_SPLIT_51 # define BOOST_PP_SEQ_SPLIT_53(x) (x) BOOST_PP_SEQ_SPLIT_52 # define BOOST_PP_SEQ_SPLIT_54(x) (x) BOOST_PP_SEQ_SPLIT_53 # define BOOST_PP_SEQ_SPLIT_55(x) (x) BOOST_PP_SEQ_SPLIT_54 # define BOOST_PP_SEQ_SPLIT_56(x) (x) BOOST_PP_SEQ_SPLIT_55 # define BOOST_PP_SEQ_SPLIT_57(x) (x) BOOST_PP_SEQ_SPLIT_56 # define BOOST_PP_SEQ_SPLIT_58(x) (x) BOOST_PP_SEQ_SPLIT_57 # define BOOST_PP_SEQ_SPLIT_59(x) (x) BOOST_PP_SEQ_SPLIT_58 # define BOOST_PP_SEQ_SPLIT_60(x) (x) BOOST_PP_SEQ_SPLIT_59 # define BOOST_PP_SEQ_SPLIT_61(x) (x) BOOST_PP_SEQ_SPLIT_60 # define BOOST_PP_SEQ_SPLIT_62(x) (x) BOOST_PP_SEQ_SPLIT_61 # define BOOST_PP_SEQ_SPLIT_63(x) (x) BOOST_PP_SEQ_SPLIT_62 # define BOOST_PP_SEQ_SPLIT_64(x) (x) BOOST_PP_SEQ_SPLIT_63 # define BOOST_PP_SEQ_SPLIT_65(x) (x) BOOST_PP_SEQ_SPLIT_64 # define BOOST_PP_SEQ_SPLIT_66(x) (x) BOOST_PP_SEQ_SPLIT_65 # define BOOST_PP_SEQ_SPLIT_67(x) (x) BOOST_PP_SEQ_SPLIT_66 # define BOOST_PP_SEQ_SPLIT_68(x) (x) BOOST_PP_SEQ_SPLIT_67 # define BOOST_PP_SEQ_SPLIT_69(x) (x) BOOST_PP_SEQ_SPLIT_68 # define BOOST_PP_SEQ_SPLIT_70(x) (x) BOOST_PP_SEQ_SPLIT_69 # define BOOST_PP_SEQ_SPLIT_71(x) (x) BOOST_PP_SEQ_SPLIT_70 # define BOOST_PP_SEQ_SPLIT_72(x) (x) BOOST_PP_SEQ_SPLIT_71 # define BOOST_PP_SEQ_SPLIT_73(x) (x) BOOST_PP_SEQ_SPLIT_72 # define BOOST_PP_SEQ_SPLIT_74(x) (x) BOOST_PP_SEQ_SPLIT_73 # define BOOST_PP_SEQ_SPLIT_75(x) (x) BOOST_PP_SEQ_SPLIT_74 # define BOOST_PP_SEQ_SPLIT_76(x) (x) BOOST_PP_SEQ_SPLIT_75 # define BOOST_PP_SEQ_SPLIT_77(x) (x) BOOST_PP_SEQ_SPLIT_76 # define BOOST_PP_SEQ_SPLIT_78(x) (x) BOOST_PP_SEQ_SPLIT_77 # define BOOST_PP_SEQ_SPLIT_79(x) (x) BOOST_PP_SEQ_SPLIT_78 # define BOOST_PP_SEQ_SPLIT_80(x) (x) BOOST_PP_SEQ_SPLIT_79 # define BOOST_PP_SEQ_SPLIT_81(x) (x) BOOST_PP_SEQ_SPLIT_80 # define BOOST_PP_SEQ_SPLIT_82(x) (x) BOOST_PP_SEQ_SPLIT_81 # define BOOST_PP_SEQ_SPLIT_83(x) (x) BOOST_PP_SEQ_SPLIT_82 # define BOOST_PP_SEQ_SPLIT_84(x) (x) BOOST_PP_SEQ_SPLIT_83 # define BOOST_PP_SEQ_SPLIT_85(x) (x) BOOST_PP_SEQ_SPLIT_84 # define BOOST_PP_SEQ_SPLIT_86(x) (x) BOOST_PP_SEQ_SPLIT_85 # define BOOST_PP_SEQ_SPLIT_87(x) (x) BOOST_PP_SEQ_SPLIT_86 # define BOOST_PP_SEQ_SPLIT_88(x) (x) BOOST_PP_SEQ_SPLIT_87 # define BOOST_PP_SEQ_SPLIT_89(x) (x) BOOST_PP_SEQ_SPLIT_88 # define BOOST_PP_SEQ_SPLIT_90(x) (x) BOOST_PP_SEQ_SPLIT_89 # define BOOST_PP_SEQ_SPLIT_91(x) (x) BOOST_PP_SEQ_SPLIT_90 # define BOOST_PP_SEQ_SPLIT_92(x) (x) BOOST_PP_SEQ_SPLIT_91 # define BOOST_PP_SEQ_SPLIT_93(x) (x) BOOST_PP_SEQ_SPLIT_92 # define BOOST_PP_SEQ_SPLIT_94(x) (x) BOOST_PP_SEQ_SPLIT_93 # define BOOST_PP_SEQ_SPLIT_95(x) (x) BOOST_PP_SEQ_SPLIT_94 # define BOOST_PP_SEQ_SPLIT_96(x) (x) BOOST_PP_SEQ_SPLIT_95 # define BOOST_PP_SEQ_SPLIT_97(x) (x) BOOST_PP_SEQ_SPLIT_96 # define BOOST_PP_SEQ_SPLIT_98(x) (x) BOOST_PP_SEQ_SPLIT_97 # define BOOST_PP_SEQ_SPLIT_99(x) (x) BOOST_PP_SEQ_SPLIT_98 # define BOOST_PP_SEQ_SPLIT_100(x) (x) BOOST_PP_SEQ_SPLIT_99 # define BOOST_PP_SEQ_SPLIT_101(x) (x) BOOST_PP_SEQ_SPLIT_100 # define BOOST_PP_SEQ_SPLIT_102(x) (x) BOOST_PP_SEQ_SPLIT_101 # define BOOST_PP_SEQ_SPLIT_103(x) (x) BOOST_PP_SEQ_SPLIT_102 # define BOOST_PP_SEQ_SPLIT_104(x) (x) BOOST_PP_SEQ_SPLIT_103 # define BOOST_PP_SEQ_SPLIT_105(x) (x) BOOST_PP_SEQ_SPLIT_104 # define BOOST_PP_SEQ_SPLIT_106(x) (x) BOOST_PP_SEQ_SPLIT_105 # define BOOST_PP_SEQ_SPLIT_107(x) (x) BOOST_PP_SEQ_SPLIT_106 # define BOOST_PP_SEQ_SPLIT_108(x) (x) BOOST_PP_SEQ_SPLIT_107 # define BOOST_PP_SEQ_SPLIT_109(x) (x) BOOST_PP_SEQ_SPLIT_108 # define BOOST_PP_SEQ_SPLIT_110(x) (x) BOOST_PP_SEQ_SPLIT_109 # define BOOST_PP_SEQ_SPLIT_111(x) (x) BOOST_PP_SEQ_SPLIT_110 # define BOOST_PP_SEQ_SPLIT_112(x) (x) BOOST_PP_SEQ_SPLIT_111 # define BOOST_PP_SEQ_SPLIT_113(x) (x) BOOST_PP_SEQ_SPLIT_112 # define BOOST_PP_SEQ_SPLIT_114(x) (x) BOOST_PP_SEQ_SPLIT_113 # define BOOST_PP_SEQ_SPLIT_115(x) (x) BOOST_PP_SEQ_SPLIT_114 # define BOOST_PP_SEQ_SPLIT_116(x) (x) BOOST_PP_SEQ_SPLIT_115 # define BOOST_PP_SEQ_SPLIT_117(x) (x) BOOST_PP_SEQ_SPLIT_116 # define BOOST_PP_SEQ_SPLIT_118(x) (x) BOOST_PP_SEQ_SPLIT_117 # define BOOST_PP_SEQ_SPLIT_119(x) (x) BOOST_PP_SEQ_SPLIT_118 # define BOOST_PP_SEQ_SPLIT_120(x) (x) BOOST_PP_SEQ_SPLIT_119 # define BOOST_PP_SEQ_SPLIT_121(x) (x) BOOST_PP_SEQ_SPLIT_120 # define BOOST_PP_SEQ_SPLIT_122(x) (x) BOOST_PP_SEQ_SPLIT_121 # define BOOST_PP_SEQ_SPLIT_123(x) (x) BOOST_PP_SEQ_SPLIT_122 # define BOOST_PP_SEQ_SPLIT_124(x) (x) BOOST_PP_SEQ_SPLIT_123 # define BOOST_PP_SEQ_SPLIT_125(x) (x) BOOST_PP_SEQ_SPLIT_124 # define BOOST_PP_SEQ_SPLIT_126(x) (x) BOOST_PP_SEQ_SPLIT_125 # define BOOST_PP_SEQ_SPLIT_127(x) (x) BOOST_PP_SEQ_SPLIT_126 # define BOOST_PP_SEQ_SPLIT_128(x) (x) BOOST_PP_SEQ_SPLIT_127 # define BOOST_PP_SEQ_SPLIT_129(x) (x) BOOST_PP_SEQ_SPLIT_128 # define BOOST_PP_SEQ_SPLIT_130(x) (x) BOOST_PP_SEQ_SPLIT_129 # define BOOST_PP_SEQ_SPLIT_131(x) (x) BOOST_PP_SEQ_SPLIT_130 # define BOOST_PP_SEQ_SPLIT_132(x) (x) BOOST_PP_SEQ_SPLIT_131 # define BOOST_PP_SEQ_SPLIT_133(x) (x) BOOST_PP_SEQ_SPLIT_132 # define BOOST_PP_SEQ_SPLIT_134(x) (x) BOOST_PP_SEQ_SPLIT_133 # define BOOST_PP_SEQ_SPLIT_135(x) (x) BOOST_PP_SEQ_SPLIT_134 # define BOOST_PP_SEQ_SPLIT_136(x) (x) BOOST_PP_SEQ_SPLIT_135 # define BOOST_PP_SEQ_SPLIT_137(x) (x) BOOST_PP_SEQ_SPLIT_136 # define BOOST_PP_SEQ_SPLIT_138(x) (x) BOOST_PP_SEQ_SPLIT_137 # define BOOST_PP_SEQ_SPLIT_139(x) (x) BOOST_PP_SEQ_SPLIT_138 # define BOOST_PP_SEQ_SPLIT_140(x) (x) BOOST_PP_SEQ_SPLIT_139 # define BOOST_PP_SEQ_SPLIT_141(x) (x) BOOST_PP_SEQ_SPLIT_140 # define BOOST_PP_SEQ_SPLIT_142(x) (x) BOOST_PP_SEQ_SPLIT_141 # define BOOST_PP_SEQ_SPLIT_143(x) (x) BOOST_PP_SEQ_SPLIT_142 # define BOOST_PP_SEQ_SPLIT_144(x) (x) BOOST_PP_SEQ_SPLIT_143 # define BOOST_PP_SEQ_SPLIT_145(x) (x) BOOST_PP_SEQ_SPLIT_144 # define BOOST_PP_SEQ_SPLIT_146(x) (x) BOOST_PP_SEQ_SPLIT_145 # define BOOST_PP_SEQ_SPLIT_147(x) (x) BOOST_PP_SEQ_SPLIT_146 # define BOOST_PP_SEQ_SPLIT_148(x) (x) BOOST_PP_SEQ_SPLIT_147 # define BOOST_PP_SEQ_SPLIT_149(x) (x) BOOST_PP_SEQ_SPLIT_148 # define BOOST_PP_SEQ_SPLIT_150(x) (x) BOOST_PP_SEQ_SPLIT_149 # define BOOST_PP_SEQ_SPLIT_151(x) (x) BOOST_PP_SEQ_SPLIT_150 # define BOOST_PP_SEQ_SPLIT_152(x) (x) BOOST_PP_SEQ_SPLIT_151 # define BOOST_PP_SEQ_SPLIT_153(x) (x) BOOST_PP_SEQ_SPLIT_152 # define BOOST_PP_SEQ_SPLIT_154(x) (x) BOOST_PP_SEQ_SPLIT_153 # define BOOST_PP_SEQ_SPLIT_155(x) (x) BOOST_PP_SEQ_SPLIT_154 # define BOOST_PP_SEQ_SPLIT_156(x) (x) BOOST_PP_SEQ_SPLIT_155 # define BOOST_PP_SEQ_SPLIT_157(x) (x) BOOST_PP_SEQ_SPLIT_156 # define BOOST_PP_SEQ_SPLIT_158(x) (x) BOOST_PP_SEQ_SPLIT_157 # define BOOST_PP_SEQ_SPLIT_159(x) (x) BOOST_PP_SEQ_SPLIT_158 # define BOOST_PP_SEQ_SPLIT_160(x) (x) BOOST_PP_SEQ_SPLIT_159 # define BOOST_PP_SEQ_SPLIT_161(x) (x) BOOST_PP_SEQ_SPLIT_160 # define BOOST_PP_SEQ_SPLIT_162(x) (x) BOOST_PP_SEQ_SPLIT_161 # define BOOST_PP_SEQ_SPLIT_163(x) (x) BOOST_PP_SEQ_SPLIT_162 # define BOOST_PP_SEQ_SPLIT_164(x) (x) BOOST_PP_SEQ_SPLIT_163 # define BOOST_PP_SEQ_SPLIT_165(x) (x) BOOST_PP_SEQ_SPLIT_164 # define BOOST_PP_SEQ_SPLIT_166(x) (x) BOOST_PP_SEQ_SPLIT_165 # define BOOST_PP_SEQ_SPLIT_167(x) (x) BOOST_PP_SEQ_SPLIT_166 # define BOOST_PP_SEQ_SPLIT_168(x) (x) BOOST_PP_SEQ_SPLIT_167 # define BOOST_PP_SEQ_SPLIT_169(x) (x) BOOST_PP_SEQ_SPLIT_168 # define BOOST_PP_SEQ_SPLIT_170(x) (x) BOOST_PP_SEQ_SPLIT_169 # define BOOST_PP_SEQ_SPLIT_171(x) (x) BOOST_PP_SEQ_SPLIT_170 # define BOOST_PP_SEQ_SPLIT_172(x) (x) BOOST_PP_SEQ_SPLIT_171 # define BOOST_PP_SEQ_SPLIT_173(x) (x) BOOST_PP_SEQ_SPLIT_172 # define BOOST_PP_SEQ_SPLIT_174(x) (x) BOOST_PP_SEQ_SPLIT_173 # define BOOST_PP_SEQ_SPLIT_175(x) (x) BOOST_PP_SEQ_SPLIT_174 # define BOOST_PP_SEQ_SPLIT_176(x) (x) BOOST_PP_SEQ_SPLIT_175 # define BOOST_PP_SEQ_SPLIT_177(x) (x) BOOST_PP_SEQ_SPLIT_176 # define BOOST_PP_SEQ_SPLIT_178(x) (x) BOOST_PP_SEQ_SPLIT_177 # define BOOST_PP_SEQ_SPLIT_179(x) (x) BOOST_PP_SEQ_SPLIT_178 # define BOOST_PP_SEQ_SPLIT_180(x) (x) BOOST_PP_SEQ_SPLIT_179 # define BOOST_PP_SEQ_SPLIT_181(x) (x) BOOST_PP_SEQ_SPLIT_180 # define BOOST_PP_SEQ_SPLIT_182(x) (x) BOOST_PP_SEQ_SPLIT_181 # define BOOST_PP_SEQ_SPLIT_183(x) (x) BOOST_PP_SEQ_SPLIT_182 # define BOOST_PP_SEQ_SPLIT_184(x) (x) BOOST_PP_SEQ_SPLIT_183 # define BOOST_PP_SEQ_SPLIT_185(x) (x) BOOST_PP_SEQ_SPLIT_184 # define BOOST_PP_SEQ_SPLIT_186(x) (x) BOOST_PP_SEQ_SPLIT_185 # define BOOST_PP_SEQ_SPLIT_187(x) (x) BOOST_PP_SEQ_SPLIT_186 # define BOOST_PP_SEQ_SPLIT_188(x) (x) BOOST_PP_SEQ_SPLIT_187 # define BOOST_PP_SEQ_SPLIT_189(x) (x) BOOST_PP_SEQ_SPLIT_188 # define BOOST_PP_SEQ_SPLIT_190(x) (x) BOOST_PP_SEQ_SPLIT_189 # define BOOST_PP_SEQ_SPLIT_191(x) (x) BOOST_PP_SEQ_SPLIT_190 # define BOOST_PP_SEQ_SPLIT_192(x) (x) BOOST_PP_SEQ_SPLIT_191 # define BOOST_PP_SEQ_SPLIT_193(x) (x) BOOST_PP_SEQ_SPLIT_192 # define BOOST_PP_SEQ_SPLIT_194(x) (x) BOOST_PP_SEQ_SPLIT_193 # define BOOST_PP_SEQ_SPLIT_195(x) (x) BOOST_PP_SEQ_SPLIT_194 # define BOOST_PP_SEQ_SPLIT_196(x) (x) BOOST_PP_SEQ_SPLIT_195 # define BOOST_PP_SEQ_SPLIT_197(x) (x) BOOST_PP_SEQ_SPLIT_196 # define BOOST_PP_SEQ_SPLIT_198(x) (x) BOOST_PP_SEQ_SPLIT_197 # define BOOST_PP_SEQ_SPLIT_199(x) (x) BOOST_PP_SEQ_SPLIT_198 # define BOOST_PP_SEQ_SPLIT_200(x) (x) BOOST_PP_SEQ_SPLIT_199 # define BOOST_PP_SEQ_SPLIT_201(x) (x) BOOST_PP_SEQ_SPLIT_200 # define BOOST_PP_SEQ_SPLIT_202(x) (x) BOOST_PP_SEQ_SPLIT_201 # define BOOST_PP_SEQ_SPLIT_203(x) (x) BOOST_PP_SEQ_SPLIT_202 # define BOOST_PP_SEQ_SPLIT_204(x) (x) BOOST_PP_SEQ_SPLIT_203 # define BOOST_PP_SEQ_SPLIT_205(x) (x) BOOST_PP_SEQ_SPLIT_204 # define BOOST_PP_SEQ_SPLIT_206(x) (x) BOOST_PP_SEQ_SPLIT_205 # define BOOST_PP_SEQ_SPLIT_207(x) (x) BOOST_PP_SEQ_SPLIT_206 # define BOOST_PP_SEQ_SPLIT_208(x) (x) BOOST_PP_SEQ_SPLIT_207 # define BOOST_PP_SEQ_SPLIT_209(x) (x) BOOST_PP_SEQ_SPLIT_208 # define BOOST_PP_SEQ_SPLIT_210(x) (x) BOOST_PP_SEQ_SPLIT_209 # define BOOST_PP_SEQ_SPLIT_211(x) (x) BOOST_PP_SEQ_SPLIT_210 # define BOOST_PP_SEQ_SPLIT_212(x) (x) BOOST_PP_SEQ_SPLIT_211 # define BOOST_PP_SEQ_SPLIT_213(x) (x) BOOST_PP_SEQ_SPLIT_212 # define BOOST_PP_SEQ_SPLIT_214(x) (x) BOOST_PP_SEQ_SPLIT_213 # define BOOST_PP_SEQ_SPLIT_215(x) (x) BOOST_PP_SEQ_SPLIT_214 # define BOOST_PP_SEQ_SPLIT_216(x) (x) BOOST_PP_SEQ_SPLIT_215 # define BOOST_PP_SEQ_SPLIT_217(x) (x) BOOST_PP_SEQ_SPLIT_216 # define BOOST_PP_SEQ_SPLIT_218(x) (x) BOOST_PP_SEQ_SPLIT_217 # define BOOST_PP_SEQ_SPLIT_219(x) (x) BOOST_PP_SEQ_SPLIT_218 # define BOOST_PP_SEQ_SPLIT_220(x) (x) BOOST_PP_SEQ_SPLIT_219 # define BOOST_PP_SEQ_SPLIT_221(x) (x) BOOST_PP_SEQ_SPLIT_220 # define BOOST_PP_SEQ_SPLIT_222(x) (x) BOOST_PP_SEQ_SPLIT_221 # define BOOST_PP_SEQ_SPLIT_223(x) (x) BOOST_PP_SEQ_SPLIT_222 # define BOOST_PP_SEQ_SPLIT_224(x) (x) BOOST_PP_SEQ_SPLIT_223 # define BOOST_PP_SEQ_SPLIT_225(x) (x) BOOST_PP_SEQ_SPLIT_224 # define BOOST_PP_SEQ_SPLIT_226(x) (x) BOOST_PP_SEQ_SPLIT_225 # define BOOST_PP_SEQ_SPLIT_227(x) (x) BOOST_PP_SEQ_SPLIT_226 # define BOOST_PP_SEQ_SPLIT_228(x) (x) BOOST_PP_SEQ_SPLIT_227 # define BOOST_PP_SEQ_SPLIT_229(x) (x) BOOST_PP_SEQ_SPLIT_228 # define BOOST_PP_SEQ_SPLIT_230(x) (x) BOOST_PP_SEQ_SPLIT_229 # define BOOST_PP_SEQ_SPLIT_231(x) (x) BOOST_PP_SEQ_SPLIT_230 # define BOOST_PP_SEQ_SPLIT_232(x) (x) BOOST_PP_SEQ_SPLIT_231 # define BOOST_PP_SEQ_SPLIT_233(x) (x) BOOST_PP_SEQ_SPLIT_232 # define BOOST_PP_SEQ_SPLIT_234(x) (x) BOOST_PP_SEQ_SPLIT_233 # define BOOST_PP_SEQ_SPLIT_235(x) (x) BOOST_PP_SEQ_SPLIT_234 # define BOOST_PP_SEQ_SPLIT_236(x) (x) BOOST_PP_SEQ_SPLIT_235 # define BOOST_PP_SEQ_SPLIT_237(x) (x) BOOST_PP_SEQ_SPLIT_236 # define BOOST_PP_SEQ_SPLIT_238(x) (x) BOOST_PP_SEQ_SPLIT_237 # define BOOST_PP_SEQ_SPLIT_239(x) (x) BOOST_PP_SEQ_SPLIT_238 # define BOOST_PP_SEQ_SPLIT_240(x) (x) BOOST_PP_SEQ_SPLIT_239 # define BOOST_PP_SEQ_SPLIT_241(x) (x) BOOST_PP_SEQ_SPLIT_240 # define BOOST_PP_SEQ_SPLIT_242(x) (x) BOOST_PP_SEQ_SPLIT_241 # define BOOST_PP_SEQ_SPLIT_243(x) (x) BOOST_PP_SEQ_SPLIT_242 # define BOOST_PP_SEQ_SPLIT_244(x) (x) BOOST_PP_SEQ_SPLIT_243 # define BOOST_PP_SEQ_SPLIT_245(x) (x) BOOST_PP_SEQ_SPLIT_244 # define BOOST_PP_SEQ_SPLIT_246(x) (x) BOOST_PP_SEQ_SPLIT_245 # define BOOST_PP_SEQ_SPLIT_247(x) (x) BOOST_PP_SEQ_SPLIT_246 # define BOOST_PP_SEQ_SPLIT_248(x) (x) BOOST_PP_SEQ_SPLIT_247 # define BOOST_PP_SEQ_SPLIT_249(x) (x) BOOST_PP_SEQ_SPLIT_248 # define BOOST_PP_SEQ_SPLIT_250(x) (x) BOOST_PP_SEQ_SPLIT_249 # define BOOST_PP_SEQ_SPLIT_251(x) (x) BOOST_PP_SEQ_SPLIT_250 # define BOOST_PP_SEQ_SPLIT_252(x) (x) BOOST_PP_SEQ_SPLIT_251 # define BOOST_PP_SEQ_SPLIT_253(x) (x) BOOST_PP_SEQ_SPLIT_252 # define BOOST_PP_SEQ_SPLIT_254(x) (x) BOOST_PP_SEQ_SPLIT_253 # define BOOST_PP_SEQ_SPLIT_255(x) (x) BOOST_PP_SEQ_SPLIT_254 # define BOOST_PP_SEQ_SPLIT_256(x) (x) BOOST_PP_SEQ_SPLIT_255 # # else # # include <boost/preprocessor/config/limits.hpp> # # if BOOST_PP_LIMIT_SEQ == 256 # include <boost/preprocessor/seq/detail/limits/split_256.hpp> # elif BOOST_PP_LIMIT_SEQ == 512 # include <boost/preprocessor/seq/detail/limits/split_256.hpp> # include <boost/preprocessor/seq/detail/limits/split_512.hpp> # elif BOOST_PP_LIMIT_SEQ == 1024 # include <boost/preprocessor/seq/detail/limits/split_256.hpp> # include <boost/preprocessor/seq/detail/limits/split_512.hpp> # include <boost/preprocessor/seq/detail/limits/split_1024.hpp> # else # error Incorrect value for the BOOST_PP_LIMIT_SEQ limit # endif # # endif # # endif
BeGe78/esood
vendor/bundle/ruby/3.0.0/gems/passenger-6.0.10/src/cxx_supportlib/vendor-modified/boost/preprocessor/seq/detail/split.hpp
C++
gpl-3.0
17,434
// // detail/dev_poll_reactor.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_DETAIL_DEV_POLL_REACTOR_HPP #define BOOST_ASIO_DETAIL_DEV_POLL_REACTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_DEV_POLL) #include <cstddef> #include <vector> #include <sys/devpoll.h> #include <boost/asio/detail/dev_poll_reactor_fwd.hpp> #include <boost/asio/detail/hash_map.hpp> #include <boost/asio/detail/limits.hpp> #include <boost/asio/detail/mutex.hpp> #include <boost/asio/detail/op_queue.hpp> #include <boost/asio/detail/reactor_op.hpp> #include <boost/asio/detail/reactor_op_queue.hpp> #include <boost/asio/detail/select_interrupter.hpp> #include <boost/asio/detail/socket_types.hpp> #include <boost/asio/detail/timer_queue_base.hpp> #include <boost/asio/detail/timer_queue_fwd.hpp> #include <boost/asio/detail/timer_queue_set.hpp> #include <boost/asio/detail/wait_op.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { class dev_poll_reactor : public boost::asio::detail::service_base<dev_poll_reactor> { public: enum op_types { read_op = 0, write_op = 1, connect_op = 1, except_op = 2, max_ops = 3 }; // Per-descriptor data. struct per_descriptor_data { }; // Constructor. BOOST_ASIO_DECL dev_poll_reactor(boost::asio::io_service& io_service); // Destructor. BOOST_ASIO_DECL ~dev_poll_reactor(); // Destroy all user-defined handler objects owned by the service. BOOST_ASIO_DECL void shutdown_service(); // Recreate internal descriptors following a fork. BOOST_ASIO_DECL void fork_service( boost::asio::io_service::fork_event fork_ev); // Initialise the task. BOOST_ASIO_DECL void init_task(); // Register a socket with the reactor. Returns 0 on success, system error // code on failure. BOOST_ASIO_DECL int register_descriptor(socket_type, per_descriptor_data&); // Register a descriptor with an associated single operation. Returns 0 on // success, system error code on failure. BOOST_ASIO_DECL int register_internal_descriptor( int op_type, socket_type descriptor, per_descriptor_data& descriptor_data, reactor_op* op); // Move descriptor registration from one descriptor_data object to another. BOOST_ASIO_DECL void move_descriptor(socket_type descriptor, per_descriptor_data& target_descriptor_data, per_descriptor_data& source_descriptor_data); // Post a reactor operation for immediate completion. void post_immediate_completion(reactor_op* op, bool is_continuation) { io_service_.post_immediate_completion(op, is_continuation); } // Start a new operation. The reactor operation will be performed when the // given descriptor is flagged as ready, or an error has occurred. BOOST_ASIO_DECL void start_op(int op_type, socket_type descriptor, per_descriptor_data&, reactor_op* op, bool is_continuation, bool allow_speculative); // Cancel all operations associated with the given descriptor. The // handlers associated with the descriptor will be invoked with the // operation_aborted error. BOOST_ASIO_DECL void cancel_ops(socket_type descriptor, per_descriptor_data&); // Cancel any operations that are running against the descriptor and remove // its registration from the reactor. BOOST_ASIO_DECL void deregister_descriptor(socket_type descriptor, per_descriptor_data&, bool closing); // Cancel any operations that are running against the descriptor and remove // its registration from the reactor. BOOST_ASIO_DECL void deregister_internal_descriptor( socket_type descriptor, per_descriptor_data&); // Add a new timer queue to the reactor. template <typename Time_Traits> void add_timer_queue(timer_queue<Time_Traits>& queue); // Remove a timer queue from the reactor. template <typename Time_Traits> void remove_timer_queue(timer_queue<Time_Traits>& queue); // Schedule a new operation in the given timer queue to expire at the // specified absolute time. template <typename Time_Traits> void schedule_timer(timer_queue<Time_Traits>& queue, const typename Time_Traits::time_type& time, typename timer_queue<Time_Traits>::per_timer_data& timer, wait_op* op); // Cancel the timer operations associated with the given token. Returns the // number of operations that have been posted or dispatched. template <typename Time_Traits> std::size_t cancel_timer(timer_queue<Time_Traits>& queue, typename timer_queue<Time_Traits>::per_timer_data& timer, std::size_t max_cancelled = (std::numeric_limits<std::size_t>::max)()); // Run /dev/poll once until interrupted or events are ready to be dispatched. BOOST_ASIO_DECL void run(bool block, op_queue<operation>& ops); // Interrupt the select loop. BOOST_ASIO_DECL void interrupt(); private: // Create the /dev/poll file descriptor. Throws an exception if the descriptor // cannot be created. BOOST_ASIO_DECL static int do_dev_poll_create(); // Helper function to add a new timer queue. BOOST_ASIO_DECL void do_add_timer_queue(timer_queue_base& queue); // Helper function to remove a timer queue. BOOST_ASIO_DECL void do_remove_timer_queue(timer_queue_base& queue); // Get the timeout value for the /dev/poll DP_POLL operation. The timeout // value is returned as a number of milliseconds. A return value of -1 // indicates that the poll should block indefinitely. BOOST_ASIO_DECL int get_timeout(); // Cancel all operations associated with the given descriptor. The do_cancel // function of the handler objects will be invoked. This function does not // acquire the dev_poll_reactor's mutex. BOOST_ASIO_DECL void cancel_ops_unlocked(socket_type descriptor, const boost::system::error_code& ec); // Helper class used to reregister descriptors after a fork. class fork_helper; friend class fork_helper; // Add a pending event entry for the given descriptor. BOOST_ASIO_DECL ::pollfd& add_pending_event_change(int descriptor); // The io_service implementation used to post completions. io_service_impl& io_service_; // Mutex to protect access to internal data. boost::asio::detail::mutex mutex_; // The /dev/poll file descriptor. int dev_poll_fd_; // Vector of /dev/poll events waiting to be written to the descriptor. std::vector< ::pollfd> pending_event_changes_; // Hash map to associate a descriptor with a pending event change index. hash_map<int, std::size_t> pending_event_change_index_; // The interrupter is used to break a blocking DP_POLL operation. select_interrupter interrupter_; // The queues of read, write and except operations. reactor_op_queue<socket_type> op_queue_[max_ops]; // The timer queues. timer_queue_set timer_queues_; // Whether the service has been shut down. bool shutdown_; }; } // namespace detail } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/detail/impl/dev_poll_reactor.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/detail/impl/dev_poll_reactor.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // defined(BOOST_ASIO_HAS_DEV_POLL) #endif // BOOST_ASIO_DETAIL_DEV_POLL_REACTOR_HPP
hpl1nk/nonamegame
xray/SDK/include/boost/asio/detail/dev_poll_reactor.hpp
C++
gpl-3.0
7,641
/* * Copyright (c) 2008-2015 Emmanuel Dupuy * This program is made available under the terms of the GPLv3 License. */ package org.jd.gui.service.type; import groovyjarjarasm.asm.ClassReader; import groovyjarjarasm.asm.Opcodes; import groovyjarjarasm.asm.tree.ClassNode; import groovyjarjarasm.asm.tree.FieldNode; import groovyjarjarasm.asm.tree.InnerClassNode; import groovyjarjarasm.asm.tree.MethodNode; import org.jd.gui.api.API; import org.jd.gui.api.model.Container; import org.jd.gui.api.model.Type; import javax.swing.*; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.*; public class ClassFileTypeFactoryProvider extends AbstractTypeFactoryProvider { static { // Early class loading JavaType.class.getName(); } // Create cache protected Cache<URI, JavaType> cache = new Cache(); /** * @return local + optional external selectors */ public String[] getSelectors() { List<String> externalSelectors = getExternalSelectors(); if (externalSelectors == null) { return new String[] { "*:file:*.class" }; } else { int size = externalSelectors.size(); String[] selectors = new String[size+1]; externalSelectors.toArray(selectors); selectors[size] = "*:file:*.class"; return selectors; } } public Collection<Type> make(API api, Container.Entry entry) { return Collections.singletonList(make(api, entry, null)); } public Type make(API api, Container.Entry entry, String fragment) { URI key = entry.getUri(); if (cache.containsKey(key)) { return cache.get(key); } else { JavaType type; try (InputStream is = entry.getInputStream()) { ClassReader classReader = new ClassReader(is); if ((fragment != null) && (fragment.length() > 0)) { // Search type name in fragment. URI format : see jd.gui.api.feature.UriOpener int index = fragment.indexOf('-'); if (index != -1) { // Keep type name only fragment = fragment.substring(0, index); } if (!classReader.getClassName().equals(fragment)) { // Search entry for type name String entryTypePath = classReader.getClassName() + ".class"; String fragmentTypePath = fragment + ".class"; while (true) { if (entry.getPath().endsWith(entryTypePath)) { // Entry path ends with the internal class name String pathToFound = entry.getPath().substring(0, entry.getPath().length() - entryTypePath.length()) + fragmentTypePath; Container.Entry entryFound = null; for (Container.Entry e : entry.getParent().getChildren()) { if (e.getPath().equals(pathToFound)) { entryFound = e; break; } } if (entryFound == null) return null; entry = entryFound; try (InputStream is2 = entry.getInputStream()) { classReader = new ClassReader(is2); } catch (IOException ignore) { return null; } break; } // Truncated path ? Cut first package name and retry int firstPackageSeparatorIndex = entryTypePath.indexOf('/'); if (firstPackageSeparatorIndex == -1) { // Nothing to cut -> Stop return null; } entryTypePath = entryTypePath.substring(firstPackageSeparatorIndex + 1); fragmentTypePath = fragmentTypePath.substring(fragmentTypePath.indexOf('/') + 1); } } } type = new JavaType(entry, classReader, -1); } catch (IOException ignore) { type = null; } cache.put(key, type); return type; } } static class JavaType implements Type { protected ClassNode classNode; protected Container.Entry entry; protected int access; protected String name; protected String superName; protected String outerName; protected String displayTypeName; protected String displayInnerTypeName; protected String displayPackageName; protected List<Type> innerTypes = null; protected List<Type.Field> fields = null; protected List<Type.Method> methods = null; @SuppressWarnings("unchecked") protected JavaType(Container.Entry entry, ClassReader classReader, int outerAccess) { this.classNode = new ClassNode(); this.entry = entry; classReader.accept(classNode, ClassReader.SKIP_CODE|ClassReader.SKIP_DEBUG|ClassReader.SKIP_FRAMES); this.access = (outerAccess == -1) ? classNode.access : outerAccess; this.name = classNode.name; this.superName = ((access & Opcodes.ACC_INTERFACE) != 0) && "java/lang/Object".equals(classNode.superName) ? null : classNode.superName; this.outerName = null; this.displayInnerTypeName = null; int indexDollar = name.lastIndexOf('$'); if (indexDollar != -1) { int indexSeparator = name.lastIndexOf('/'); if (indexDollar > indexSeparator) { for (final InnerClassNode innerClassNode : (List<InnerClassNode>)classNode.innerClasses) { if (name.equals(innerClassNode.name)) { // Inner class path found if (innerClassNode.outerName != null) { this.outerName = innerClassNode.outerName; this.displayInnerTypeName = this.name.substring(this.outerName.length() + 1); } } } } } int lastPackageSeparatorIndex = name.lastIndexOf('/'); if (lastPackageSeparatorIndex == -1) { this.displayPackageName = ""; this.displayTypeName = (this.outerName == null) ? this.name : null; } else { this.displayPackageName = this.name.substring(0, lastPackageSeparatorIndex).replace('/', '.'); this.displayTypeName = (this.outerName == null) ? this.name.substring(lastPackageSeparatorIndex+1) : null; } } public int getFlags() { return access; } public String getName() { return name; } public String getSuperName() { return superName; } public String getOuterName() { return outerName; } public String getDisplayPackageName() { return displayPackageName; } public String getDisplayTypeName() { if (displayTypeName == null) { displayTypeName = getDisplayTypeName(outerName, displayPackageName.length()) + '.' + displayInnerTypeName; } return displayTypeName; } @SuppressWarnings("unchecked") protected String getDisplayTypeName(String name, int packageLength) { int indexDollar = name.lastIndexOf('$'); if (indexDollar > packageLength) { Container.Entry outerEntry = getEntry(name); if (outerEntry != null) { try (InputStream is = outerEntry.getInputStream()) { ClassReader classReader = new ClassReader(is); ClassNode classNode = new ClassNode(); classReader.accept(classNode, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); for (final InnerClassNode innerClassNode : (List<InnerClassNode>)classNode.innerClasses) { if (name.equals(innerClassNode.name)) { // Inner class path found => Recursive call return getDisplayTypeName(innerClassNode.outerName, packageLength) + '.' + innerClassNode.innerName; } } } catch (IOException ignore) { } } } return packageLength > 0 ? name.substring(packageLength+1) : name; } public String getDisplayInnerTypeName() { return displayInnerTypeName; } public Icon getIcon() { return getTypeIcon(access); } @SuppressWarnings("unchecked") public List<Type> getInnerTypes() { if (innerTypes == null) { innerTypes = new ArrayList<>(classNode.innerClasses.size()); for (final InnerClassNode innerClassNode : (List<InnerClassNode>)classNode.innerClasses) { if (((innerClassNode.access & (Opcodes.ACC_SYNTHETIC|Opcodes.ACC_BRIDGE)) == 0) && this.name.equals(innerClassNode.outerName)) { Container.Entry innerEntry = getEntry(innerClassNode.name); if (innerEntry != null) { try (InputStream is = innerEntry.getInputStream()) { ClassReader classReader = new ClassReader(is); innerTypes.add(new JavaType(innerEntry, classReader, innerClassNode.access)); } catch (IOException ignore) { } } } } } return innerTypes; } protected Container.Entry getEntry(String typeName) { String pathToFound = typeName + ".class"; for (Container.Entry e : entry.getParent().getChildren()) { if (e.getPath().equals(pathToFound)) { return e; } } return null; } @SuppressWarnings("unchecked") public List<Type.Field> getFields() { if (fields == null) { fields = new ArrayList<>(classNode.fields.size()); for (final FieldNode fieldNode : (List<FieldNode>)classNode.fields) { if ((fieldNode.access & (Opcodes.ACC_SYNTHETIC|Opcodes.ACC_ENUM)) == 0) { fields.add(new Type.Field() { public int getFlags() { return fieldNode.access; } public String getName() { return fieldNode.name; } public String getDescriptor() { return fieldNode.desc; } public Icon getIcon() { return getFieldIcon(fieldNode.access); } public String getDisplayName() { StringBuffer sb = new StringBuffer(); sb.append(fieldNode.name).append(" : "); writeSignature(sb, fieldNode.desc, fieldNode.desc.length(), 0, false); return sb.toString(); } }); } } } return fields; } @SuppressWarnings("unchecked") public List<Type.Method> getMethods() { if (methods == null) { methods = new ArrayList<>(classNode.methods.size()); for (final MethodNode methodNode : (List<MethodNode>)classNode.methods) { if ((methodNode.access & (Opcodes.ACC_SYNTHETIC|Opcodes.ACC_ENUM|Opcodes.ACC_BRIDGE)) == 0) { methods.add(new Type.Method() { public int getFlags() { return methodNode.access; } public String getName() { return methodNode.name; } public String getDescriptor() { return methodNode.desc; } public Icon getIcon() { return getMethodIcon(methodNode.access); } public String getDisplayName() { String constructorName = displayInnerTypeName; boolean isInnerClass = (constructorName != null); if (constructorName == null) constructorName = getDisplayTypeName(); StringBuffer sb = new StringBuffer(); writeMethodSignature(sb, access, methodNode.access, isInnerClass, constructorName, methodNode.name, methodNode.desc); return sb.toString(); } }); } } } return methods; } } }
trfiladelfo/jd-gui
services/src/main/java/org/jd/gui/service/type/ClassFileTypeFactoryProvider.java
Java
gpl-3.0
13,565
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Sparsemax op.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn __all__ = ["sparsemax"] def sparsemax(logits, name=None): """Computes sparsemax activations [1]. For each batch `i` and class `j` we have $$sparsemax[i, j] = max(logits[i, j] - tau(logits[i, :]), 0)$$ [1]: https://arxiv.org/abs/1602.02068 Args: logits: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `logits`. """ with ops.name_scope(name, "sparsemax", [logits]) as name: logits = ops.convert_to_tensor(logits, name="logits") obs = array_ops.shape(logits)[0] dims = array_ops.shape(logits)[1] # In the paper, they call the logits z. # The mean(logits) can be substracted from logits to make the algorithm # more numerically stable. the instability in this algorithm comes mostly # from the z_cumsum. Substacting the mean will cause z_cumsum to be close # to zero. However, in practise the numerical instability issues are very # minor and substacting the mean causes extra issues with inf and nan # input. z = logits # sort z z_sorted, _ = nn.top_k(z, k=dims) # calculate k(z) z_cumsum = math_ops.cumsum(z_sorted, axis=1) k = math_ops.range( 1, math_ops.cast(dims, logits.dtype) + 1, dtype=logits.dtype) z_check = 1 + k * z_sorted > z_cumsum # because the z_check vector is always [1,1,...1,0,0,...0] finding the # (index + 1) of the last `1` is the same as just summing the number of 1. k_z = math_ops.reduce_sum(math_ops.cast(z_check, dtypes.int32), axis=1) # calculate tau(z) # If there are inf values or all values are -inf, the k_z will be zero, # this is mathematically invalid and will also cause the gather_nd to fail. # Prevent this issue for now by setting k_z = 1 if k_z = 0, this is then # fixed later (see p_safe) by returning p = nan. This results in the same # behavior as softmax. k_z_safe = math_ops.maximum(k_z, 1) indices = array_ops.stack([math_ops.range(0, obs), k_z_safe - 1], axis=1) tau_sum = array_ops.gather_nd(z_cumsum, indices) tau_z = (tau_sum - 1) / math_ops.cast(k_z, logits.dtype) # calculate p p = math_ops.maximum( math_ops.cast(0, logits.dtype), z - tau_z[:, array_ops.newaxis]) # If k_z = 0 or if z = nan, then the input is invalid p_safe = array_ops.where( math_ops.logical_or( math_ops.equal(k_z, 0), math_ops.is_nan(z_cumsum[:, -1])), array_ops.fill([obs, dims], math_ops.cast(float("nan"), logits.dtype)), p) return p_safe
ghchinoy/tensorflow
tensorflow/contrib/sparsemax/python/ops/sparsemax.py
Python
apache-2.0
3,656
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.extension.script; import java.io.File; import java.util.ArrayList; import java.util.List; import org.parosproxy.paros.Constant; import org.zaproxy.zap.view.AbstractMultipleOptionsBaseTableModel; public class OptionsScriptTableModel extends AbstractMultipleOptionsBaseTableModel<File> { private static final long serialVersionUID = 1L; private static final String[] COLUMN_NAMES = { Constant.messages.getString("options.script.table.header.dir")}; private static final int COLUMN_COUNT = COLUMN_NAMES.length; private List<File> tokens = new ArrayList<>(0); /** * */ public OptionsScriptTableModel() { super(); } @Override public List<File> getElements() { return tokens; } /** * @param tokens The tokens to set. */ public void setTokens(List<File> files) { this.tokens = new ArrayList<>(tokens.size()); for (File file : files) { this.tokens.add(file); } fireTableDataChanged(); } @Override public String getColumnName(int col) { return COLUMN_NAMES[col]; } @Override public int getColumnCount() { return COLUMN_COUNT; } @Override public Class<?> getColumnClass(int c) { return String.class; } @Override public int getRowCount() { return tokens.size(); } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } @Override public Object getValueAt(int rowIndex, int columnIndex) { switch(columnIndex) { case 0: return getElement(rowIndex).getAbsolutePath(); } return null; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { } }
profjrr/zaproxy
src/org/zaproxy/zap/extension/script/OptionsScriptTableModel.java
Java
apache-2.0
2,653
package v1 import ( configv1 "github.com/openshift/api/config/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) var ( GroupName = "operator.openshift.io" GroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1"} schemeBuilder = runtime.NewSchemeBuilder(addKnownTypes, configv1.Install) // Install is a function which adds this version to a scheme Install = schemeBuilder.AddToScheme // SchemeGroupVersion generated code relies on this name // Deprecated SchemeGroupVersion = GroupVersion // AddToScheme exists solely to keep the old generators creating valid code // DEPRECATED AddToScheme = schemeBuilder.AddToScheme ) // Resource generated code relies on this being here, but it logically belongs to the group // DEPRECATED func Resource(resource string) schema.GroupResource { return schema.GroupResource{Group: GroupName, Resource: resource} } func addKnownTypes(scheme *runtime.Scheme) error { metav1.AddToGroupVersion(scheme, GroupVersion) scheme.AddKnownTypes(GroupVersion, &Authentication{}, &AuthenticationList{}, &DNS{}, &DNSList{}, &CloudCredential{}, &CloudCredentialList{}, &ClusterCSIDriver{}, &ClusterCSIDriverList{}, &Console{}, &ConsoleList{}, &CSISnapshotController{}, &CSISnapshotControllerList{}, &Etcd{}, &EtcdList{}, &KubeAPIServer{}, &KubeAPIServerList{}, &KubeControllerManager{}, &KubeControllerManagerList{}, &KubeScheduler{}, &KubeSchedulerList{}, &KubeStorageVersionMigrator{}, &KubeStorageVersionMigratorList{}, &Network{}, &NetworkList{}, &OpenShiftAPIServer{}, &OpenShiftAPIServerList{}, &OpenShiftControllerManager{}, &OpenShiftControllerManagerList{}, &ServiceCA{}, &ServiceCAList{}, &ServiceCatalogAPIServer{}, &ServiceCatalogAPIServerList{}, &ServiceCatalogControllerManager{}, &ServiceCatalogControllerManagerList{}, &IngressController{}, &IngressControllerList{}, &Storage{}, &StorageList{}, ) return nil }
mahak/origin
vendor/github.com/openshift/api/operator/v1/register.go
GO
apache-2.0
2,039
<?php /** * Param 'colorpicker' field * * @param $settings * @param $value * * @since 4.4 * @return string */ function vc_colorpicker_form_field( $settings, $value ) { return '<div class="color-group">' . '<input name="' . $settings['param_name'] . '" class="wpb_vc_param_value wpb-textinput ' . $settings['param_name'] . ' ' . $settings['type'] . '_field vc_color-control" type="text" value="' . $value . '"/>' . '</div>'; }
carlos09/fredrixprint
wp-content/themes/rhythm/plugins/js_composer/include/params/colorpicker/colorpicker.php
PHP
gpl-2.0
451
package ic2.api.event; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import cpw.mods.fml.common.eventhandler.Cancelable; import net.minecraftforge.event.world.WorldEvent; /** * A bunch of Events to handle the power of the Mining Laser. */ @Cancelable public class LaserEvent extends WorldEvent { // the Laser Entity public final Entity lasershot; // the following variables can be changed and the Laser will adjust to them // the Player firing the Laser. If the Laser gets "reflected" the Player could change. public EntityLivingBase owner; // Range of the Laser Shot. Determine the amount of broken blocks, as well, as each broken block will subtract ~1F from range. public float range, power; public int blockBreaks; // Determines whether the laser will explode upon hitting something public boolean explosive, smelt; public LaserEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1) { super(world1); this.lasershot = lasershot1; this.owner = owner1; this.range = range1; this.power = power1; this.blockBreaks = blockBreaks1; this.explosive = explosive1; this.smelt = smelt1; } /** * Event when the Laser is getting shot by a Player. * * The Item is the Laser Gun which the "Player" has shot */ public static class LaserShootEvent extends LaserEvent { ItemStack laseritem; public LaserShootEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1, ItemStack laseritem1) { super(world1, lasershot1, owner1, range1, power1, blockBreaks1, explosive1, smelt1); this.laseritem = laseritem1; } } /** * Event when the Laser is exploding for some Reason. * * The Laser will no longer exist after this Event is posted as it either Explodes or despawns after the Event is fired. */ public static class LaserExplodesEvent extends LaserEvent { // explosion strength, even that can be changed! public float explosionpower, explosiondroprate, explosionentitydamage; public LaserExplodesEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1, float explosionpower1, float explosiondroprate1, float explosionentitydamage1) { super(world1, lasershot1, owner1, range1, power1, blockBreaks1, explosive1, smelt1); this.explosionpower = explosionpower1; this.explosiondroprate = explosiondroprate1; this.explosionentitydamage = explosionentitydamage1; } } /** * Event when the Laser is hitting a Block * x, y and z are the Coords of the Block. * * Canceling this Event stops the Laser from attempting to break the Block, what is very useful for Glass. * Use lasershot.setDead() to remove the Shot entirely. */ public static class LaserHitsBlockEvent extends LaserEvent { // targeted block, even that can be changed! public int x, y, z; public int side; // removeBlock determines if the Block will be removed. dropBlock determines if the Block should drop something. public boolean removeBlock, dropBlock; public float dropChance; public LaserHitsBlockEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1, int x1, int y1, int z1, int side1, float dropChance1, boolean removeBlock1, boolean dropBlock1) { super(world1, lasershot1, owner1, range1, power1, blockBreaks1, explosive1, smelt1); this.x = x1; this.y = y1; this.z = z1; this.side = side1; this.removeBlock = removeBlock1; this.dropBlock = dropBlock1; this.dropChance = dropChance1; } } /** * Event when the Laser is getting at a Living Entity * * Canceling this Event ignores the Entity * Use lasershot.setDead() to remove the Shot entirely. */ public static class LaserHitsEntityEvent extends LaserEvent { // the Entity which the Laser has shot at, even the target can be changed! public Entity hitentity; public LaserHitsEntityEvent(World world1, Entity lasershot1, EntityLivingBase owner1, float range1, float power1, int blockBreaks1, boolean explosive1, boolean smelt1, Entity hitentity1) { super(world1, lasershot1, owner1, range1, power1, blockBreaks1, explosive1, smelt1); this.hitentity = hitentity1; } } }
ZanyLeonic/Balloons
src/main/java/ic2/api/event/LaserEvent.java
Java
mit
4,508
/* * Copyright (c) 1996, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.rmi.transport.tcp; import java.io.*; import java.util.*; import java.rmi.server.LogStream; import sun.rmi.runtime.Log; /** * ConnectionMultiplexer manages the transparent multiplexing of * multiple virtual connections from one endpoint to another through * one given real connection to that endpoint. The input and output * streams for the the underlying real connection must be supplied. * A callback object is also supplied to be informed of new virtual * connections opened by the remote endpoint. After creation, the * run() method must be called in a thread created for demultiplexing * the connections. The openConnection() method is called to * initiate a virtual connection from this endpoint. * * @author Peter Jones */ final class ConnectionMultiplexer { /** "multiplex" log level */ static int logLevel = LogStream.parseLevel(getLogLevel()); private static String getLogLevel() { return java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction("sun.rmi.transport.tcp.multiplex.logLevel")); } /* multiplex system log */ static final Log multiplexLog = Log.getLog("sun.rmi.transport.tcp.multiplex", "multiplex", ConnectionMultiplexer.logLevel); /** multiplexing protocol operation codes */ private final static int OPEN = 0xE1; private final static int CLOSE = 0xE2; private final static int CLOSEACK = 0xE3; private final static int REQUEST = 0xE4; private final static int TRANSMIT = 0xE5; /** object to notify for new connections from remote endpoint */ private TCPChannel channel; /** input stream for underlying single connection */ private InputStream in; /** output stream for underlying single connection */ private OutputStream out; /** true if underlying connection originated from this endpoint (used for generating unique connection IDs) */ private boolean orig; /** layered stream for reading formatted data from underlying connection */ private DataInputStream dataIn; /** layered stream for writing formatted data to underlying connection */ private DataOutputStream dataOut; /** table holding currently open connection IDs and related info */ private Hashtable connectionTable = new Hashtable(7); /** number of currently open connections */ private int numConnections = 0; /** maximum allowed open connections */ private final static int maxConnections = 256; /** ID of last connection opened */ private int lastID = 0x1001; /** true if this mechanism is still alive */ private boolean alive = true; /** * Create a new ConnectionMultiplexer using the given underlying * input/output stream pair. The run method must be called * (possibly on a new thread) to handle the demultiplexing. * @param channel object to notify when new connection is received * @param in input stream of underlying connection * @param out output stream of underlying connection * @param orig true if this endpoint intiated the underlying * connection (needs to be set differently at both ends) */ public ConnectionMultiplexer( TCPChannel channel, InputStream in, OutputStream out, boolean orig) { this.channel = channel; this.in = in; this.out = out; this.orig = orig; dataIn = new DataInputStream(in); dataOut = new DataOutputStream(out); } /** * Process multiplexing protocol received from underlying connection. */ public void run() throws IOException { try { int op, id, length; Integer idObj; MultiplexConnectionInfo info; while (true) { // read next op code from remote endpoint op = dataIn.readUnsignedByte(); switch (op) { // remote endpoint initiating new connection case OPEN: id = dataIn.readUnsignedShort(); if (multiplexLog.isLoggable(Log.VERBOSE)) { multiplexLog.log(Log.VERBOSE, "operation OPEN " + id); } idObj = new Integer(id); info = (MultiplexConnectionInfo) connectionTable.get(idObj); if (info != null) throw new IOException( "OPEN: Connection ID already exists"); info = new MultiplexConnectionInfo(id); info.in = new MultiplexInputStream(this, info, 2048); info.out = new MultiplexOutputStream(this, info, 2048); synchronized (connectionTable) { connectionTable.put(idObj, info); ++ numConnections; } sun.rmi.transport.Connection conn; conn = new TCPConnection(channel, info.in, info.out); channel.acceptMultiplexConnection(conn); break; // remote endpoint closing connection case CLOSE: id = dataIn.readUnsignedShort(); if (multiplexLog.isLoggable(Log.VERBOSE)) { multiplexLog.log(Log.VERBOSE, "operation CLOSE " + id); } idObj = new Integer(id); info = (MultiplexConnectionInfo) connectionTable.get(idObj); if (info == null) throw new IOException( "CLOSE: Invalid connection ID"); info.in.disconnect(); info.out.disconnect(); if (!info.closed) sendCloseAck(info); synchronized (connectionTable) { connectionTable.remove(idObj); -- numConnections; } break; // remote endpoint acknowledging close of connection case CLOSEACK: id = dataIn.readUnsignedShort(); if (multiplexLog.isLoggable(Log.VERBOSE)) { multiplexLog.log(Log.VERBOSE, "operation CLOSEACK " + id); } idObj = new Integer(id); info = (MultiplexConnectionInfo) connectionTable.get(idObj); if (info == null) throw new IOException( "CLOSEACK: Invalid connection ID"); if (!info.closed) throw new IOException( "CLOSEACK: Connection not closed"); info.in.disconnect(); info.out.disconnect(); synchronized (connectionTable) { connectionTable.remove(idObj); -- numConnections; } break; // remote endpoint declaring additional bytes receivable case REQUEST: id = dataIn.readUnsignedShort(); idObj = new Integer(id); info = (MultiplexConnectionInfo) connectionTable.get(idObj); if (info == null) throw new IOException( "REQUEST: Invalid connection ID"); length = dataIn.readInt(); if (multiplexLog.isLoggable(Log.VERBOSE)) { multiplexLog.log(Log.VERBOSE, "operation REQUEST " + id + ": " + length); } info.out.request(length); break; // remote endpoint transmitting data packet case TRANSMIT: id = dataIn.readUnsignedShort(); idObj = new Integer(id); info = (MultiplexConnectionInfo) connectionTable.get(idObj); if (info == null) throw new IOException("SEND: Invalid connection ID"); length = dataIn.readInt(); if (multiplexLog.isLoggable(Log.VERBOSE)) { multiplexLog.log(Log.VERBOSE, "operation TRANSMIT " + id + ": " + length); } info.in.receive(length, dataIn); break; default: throw new IOException("Invalid operation: " + Integer.toHexString(op)); } } } finally { shutDown(); } } /** * Initiate a new multiplexed connection through the underlying * connection. */ public synchronized TCPConnection openConnection() throws IOException { // generate ID that should not be already used // If all possible 32768 IDs are used, // this method will block searching for a new ID forever. int id; Integer idObj; do { lastID = (++ lastID) & 0x7FFF; id = lastID; // The orig flag (copied to the high bit of the ID) is used // to have two distinct ranges to choose IDs from for the // two endpoints. if (orig) id |= 0x8000; idObj = new Integer(id); } while (connectionTable.get(idObj) != null); // create multiplexing streams and bookkeeping information MultiplexConnectionInfo info = new MultiplexConnectionInfo(id); info.in = new MultiplexInputStream(this, info, 2048); info.out = new MultiplexOutputStream(this, info, 2048); // add to connection table if multiplexer has not died synchronized (connectionTable) { if (!alive) throw new IOException("Multiplexer connection dead"); if (numConnections >= maxConnections) throw new IOException("Cannot exceed " + maxConnections + " simultaneous multiplexed connections"); connectionTable.put(idObj, info); ++ numConnections; } // inform remote endpoint of new connection synchronized (dataOut) { try { dataOut.writeByte(OPEN); dataOut.writeShort(id); dataOut.flush(); } catch (IOException e) { multiplexLog.log(Log.BRIEF, "exception: ", e); shutDown(); throw e; } } return new TCPConnection(channel, info.in, info.out); } /** * Shut down all connections and clean up. */ public void shutDown() { // inform all associated streams synchronized (connectionTable) { // return if multiplexer already officially dead if (!alive) return; alive = false; Enumeration enum_ = connectionTable.elements(); while (enum_.hasMoreElements()) { MultiplexConnectionInfo info = (MultiplexConnectionInfo) enum_.nextElement(); info.in.disconnect(); info.out.disconnect(); } connectionTable.clear(); numConnections = 0; } // close underlying connection, if possible (and not already done) try { in.close(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } /** * Send request for more data on connection to remote endpoint. * @param info connection information structure * @param len number of more bytes that can be received */ void sendRequest(MultiplexConnectionInfo info, int len) throws IOException { synchronized (dataOut) { if (alive && !info.closed) try { dataOut.writeByte(REQUEST); dataOut.writeShort(info.id); dataOut.writeInt(len); dataOut.flush(); } catch (IOException e) { multiplexLog.log(Log.BRIEF, "exception: ", e); shutDown(); throw e; } } } /** * Send packet of requested data on connection to remote endpoint. * @param info connection information structure * @param buf array containg bytes to send * @param off offset of first array index of packet * @param len number of bytes in packet to send */ void sendTransmit(MultiplexConnectionInfo info, byte buf[], int off, int len) throws IOException { synchronized (dataOut) { if (alive && !info.closed) try { dataOut.writeByte(TRANSMIT); dataOut.writeShort(info.id); dataOut.writeInt(len); dataOut.write(buf, off, len); dataOut.flush(); } catch (IOException e) { multiplexLog.log(Log.BRIEF, "exception: ", e); shutDown(); throw e; } } } /** * Inform remote endpoint that connection has been closed. * @param info connection information structure */ void sendClose(MultiplexConnectionInfo info) throws IOException { info.out.disconnect(); synchronized (dataOut) { if (alive && !info.closed) try { dataOut.writeByte(CLOSE); dataOut.writeShort(info.id); dataOut.flush(); info.closed = true; } catch (IOException e) { multiplexLog.log(Log.BRIEF, "exception: ", e); shutDown(); throw e; } } } /** * Acknowledge remote endpoint's closing of connection. * @param info connection information structure */ void sendCloseAck(MultiplexConnectionInfo info) throws IOException { synchronized (dataOut) { if (alive && !info.closed) try { dataOut.writeByte(CLOSEACK); dataOut.writeShort(info.id); dataOut.flush(); info.closed = true; } catch (IOException e) { multiplexLog.log(Log.BRIEF, "exception: ", e); shutDown(); throw e; } } } /** * Shut down connection upon finalization. */ protected void finalize() throws Throwable { super.finalize(); shutDown(); } }
rokn/Count_Words_2015
testing/openjdk/jdk/src/share/classes/sun/rmi/transport/tcp/ConnectionMultiplexer.java
Java
mit
16,501
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file Horizontal Page Break */ // Register a plugin named "pagebreak". CKEDITOR.plugins.add( 'pagebreak', { init : function( editor ) { // Register the command. editor.addCommand( 'pagebreak', CKEDITOR.plugins.pagebreakCmd ); // Register the toolbar button. editor.ui.addButton( 'PageBreak', { label : editor.lang.pagebreak, command : 'pagebreak' }); // Add the style that renders our placeholder. editor.addCss( 'img.cke_pagebreak' + '{' + 'background-image: url(' + CKEDITOR.getUrl( this.path + 'images/pagebreak.gif' ) + ');' + 'background-position: center center;' + 'background-repeat: no-repeat;' + 'clear: both;' + 'display: block;' + 'float: none;' + 'width: 100%;' + 'border-top: #999999 1px dotted;' + 'border-bottom: #999999 1px dotted;' + 'height: 5px;' + '}' ); }, afterInit : function( editor ) { // Register a filter to displaying placeholders after mode change. var dataProcessor = editor.dataProcessor, dataFilter = dataProcessor && dataProcessor.dataFilter; if ( dataFilter ) { dataFilter.addRules( { elements : { div : function( element ) { var attributes = element.attributes, style = attributes && attributes.style, child = style && element.children.length == 1 && element.children[ 0 ], childStyle = child && ( child.name == 'span' ) && child.attributes.style; if ( childStyle && ( /page-break-after\s*:\s*always/i ).test( style ) && ( /display\s*:\s*none/i ).test( childStyle ) ) return editor.createFakeParserElement( element, 'cke_pagebreak', 'div' ); } } }); } }, requires : [ 'fakeobjects' ] }); CKEDITOR.plugins.pagebreakCmd = { exec : function( editor ) { // Create the element that represents a print break. var breakObject = CKEDITOR.dom.element.createFromHtml( '<div style="page-break-after: always;"><span style="display: none;">&nbsp;</span></div>' ); // Creates the fake image used for this element. breakObject = editor.createFakeElement( breakObject, 'cke_pagebreak', 'div' ); var ranges = editor.getSelection().getRanges(); for ( var range, i = 0 ; i < ranges.length ; i++ ) { range = ranges[ i ]; if ( i > 0 ) breakObject = breakObject.clone( true ); range.splitBlock( 'p' ); range.insertNode( breakObject ); } } };
adefreitea/expidian
web/bundles/expidian/js/ckeditor/plugins/pagebreak/plugin.js
JavaScript
mit
2,644
/** * Copyright (c) 2010-2016, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.lcn.connection; import java.util.Dictionary; import org.openhab.binding.lcn.common.LcnDefs; /** * Settings for a connection to LCN-PCHK. * * @author Tobias Jüttner */ public class ConnectionSettings { /** Unique identifier for this connection. */ private final String id; /** The user name for authentication. */ private final String username; /** The password for authentication. */ private final String password; /** The TCP/IP address or IP of the connection. */ private final String address; /** The TCP/IP port of the connection. */ private final int port; /** The dimming mode to use. */ private final LcnDefs.OutputPortDimMode dimMode; /** The status-messages mode to use. */ private final LcnDefs.OutputPortStatusMode statusMode; /** The default timeout to use for requests. Worst case: Requesting threshold 4-4 takes at least 1.8s */ private static final long DEFAULT_TIMEOUT_MSEC = 3500; /** Timeout for requests. */ private final long timeoutMSec; /** * Constructor. * * @param id the connnection's unique identifier * @param address the connection's TCP/IP address or IP * @param port the connection's TCP/IP port * @param username the user name for authentication * @param password the password for authentication * @param dimMode the dimming mode * @param statusMode the status-messages mode * @param timeout the request timeout */ private ConnectionSettings(String id, String address, int port, String username, String password, LcnDefs.OutputPortDimMode dimMode, LcnDefs.OutputPortStatusMode statusMode, int timeout) { this.id = id; this.address = address; this.port = port; this.username = username; this.password = password; this.dimMode = dimMode; this.statusMode = statusMode; this.timeoutMSec = timeout; } /** * Gets the unique identifier for the connection. * * @return the unique identifier */ public String getId() { return this.id; } /** * Gets the user name used for authentication. * * @return the user name */ public String getUsername() { return this.username; } /** * Gets the password used for authentication. * * @return the password */ public String getPassword() { return this.password; } /** * Gets the TCP/IP address or IP of the connection. * * @return the address or IP */ public String getAddress() { return this.address; } /** * Gets the TCP/IP port of the connection. * * @return the port */ public int getPort() { return this.port; } /** * Gets the dimming mode to use for the connection. * * @return the dimming mode */ public LcnDefs.OutputPortDimMode getDimMode() { return this.dimMode; } /** * Gets the status-messages mode to use for the connection. * * @return the status-messages mode */ public LcnDefs.OutputPortStatusMode getStatusMode() { return this.statusMode; } /** * Gets the request timeout. * * @return the timeout in milliseconds */ public long getTimeout() { return this.timeoutMSec; } /** * Tries to parse LCN-PCHK connection settings from the given openHAB configuration. * * @param config the binding's configuration * @param counter 0..x (1..x+1 in actual configuration file) * @return the connection settings on success or null */ public static ConnectionSettings tryParse(Dictionary<String, ?> config, int counter) { if (config == null) { return null; } String id = (String) config.get("id" + (counter + 1)); id = id == null ? "" : id.trim(); String addressWithOptPort = (String) config.get("address" + (counter + 1)); addressWithOptPort = addressWithOptPort == null ? "" : addressWithOptPort.trim(); String username = (String) config.get("username" + (counter + 1)); username = username == null ? "" : username.trim(); String password = (String) config.get("password" + (counter + 1)); password = password == null ? "" : password.trim(); String mode = (String) config.get("mode" + (counter + 1)); mode = mode == null ? "" : mode.trim(); if (id.isEmpty() || addressWithOptPort.isEmpty() || username.isEmpty() || password.isEmpty() || mode.isEmpty()) { return null; } String dataRequestTimeout = (String) config.get("timeout" + (counter + 1)); dataRequestTimeout = dataRequestTimeout == null ? Long.valueOf(DEFAULT_TIMEOUT_MSEC).toString() : dataRequestTimeout.trim(); try { String address = addressWithOptPort.contains(":") ? addressWithOptPort.split(":")[0] : addressWithOptPort; int port = addressWithOptPort.contains(":") ? Integer.parseInt(addressWithOptPort.split(":")[1]) : 4114; LcnDefs.OutputPortDimMode dimMode = mode.equalsIgnoreCase("percent200") || mode.equalsIgnoreCase("native200") ? LcnDefs.OutputPortDimMode.STEPS200 : LcnDefs.OutputPortDimMode.STEPS50; LcnDefs.OutputPortStatusMode statusMode = mode.equalsIgnoreCase("percent50") || mode.equalsIgnoreCase("percent200") ? LcnDefs.OutputPortStatusMode.PERCENT : LcnDefs.OutputPortStatusMode.NATIVE; int timeout = Integer.parseInt(dataRequestTimeout); return new ConnectionSettings(id, address, port, username, password, dimMode, statusMode, timeout); } catch (NumberFormatException ex) { } return null; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (!(o instanceof ConnectionSettings)) { return false; } ConnectionSettings other = (ConnectionSettings) o; return this.id.equals(other.id) && this.address.equals(other.address) && this.port == other.port && this.username.equals(other.username) && this.password.equals(other.password) && this.dimMode == other.dimMode && this.statusMode == other.statusMode && this.timeoutMSec == other.timeoutMSec; } }
evansj/openhab
bundles/binding/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/connection/ConnectionSettings.java
Java
epl-1.0
6,850
// license:BSD-3-Clause // copyright-holders:Brad Oliver /*************************************************************************** arkanoid.cpp Functions to emulate the video hardware of the machine. ***************************************************************************/ #include "emu.h" #include "includes/arkanoid.h" void arkanoid_state::arkanoid_videoram_w(offs_t offset, uint8_t data) { m_videoram[offset] = data; m_bg_tilemap->mark_tile_dirty(offset / 2); } void arkanoid_state::arkanoid_d008_w(uint8_t data) { int bank; /* bits 0 and 1 flip X and Y */ flip_screen_x_set(data & 0x01); flip_screen_y_set(data & 0x02); /* bit 2 selects the input paddle */ m_paddle_select = data & 0x04; /* bit 3 is coin lockout (but not the service coin) */ machine().bookkeeping().coin_lockout_w(0, !(data & 0x08)); machine().bookkeeping().coin_lockout_w(1, !(data & 0x08)); /* bit 4 is unknown */ /* bit 5 controls the graphics rom bank */ bank = (data & 0x20) >> 5; if (m_gfxbank != bank) { m_gfxbank = bank; m_bg_tilemap->mark_all_dirty(); } /* bit 6 controls the palette bank */ bank = (data & 0x40) >> 6; if (m_palettebank != bank) { m_palettebank = bank; m_bg_tilemap->mark_all_dirty(); } // bit 7 resets the MCU and semaphore flipflops // This bit is flipped early in bootup just prior to accessing the MCU for the first time. if (m_mcuintf.found()) // Bootlegs don't have the MCU but still set this bit m_mcuintf->reset_w(BIT(data, 7) ? CLEAR_LINE : ASSERT_LINE); } void arkanoid_state::brixian_d008_w(uint8_t data) { int bank; /* bits 0 and 1 flip X and Y */ flip_screen_x_set(data & 0x01); flip_screen_y_set(data & 0x02); /* bit 2 selects the input paddle */ /* - not relevant to brixian */ /* bit 3 is coin lockout (but not the service coin) */ /* - not here, means you can only play 1 game */ /* bit 4 is unknown */ /* bit 5 controls the graphics rom bank */ bank = (data & 0x20) >> 5; if (m_gfxbank != bank) { m_gfxbank = bank; m_bg_tilemap->mark_all_dirty(); } /* bit 6 controls the palette bank */ bank = (data & 0x40) >> 6; if (m_palettebank != bank) { m_palettebank = bank; m_bg_tilemap->mark_all_dirty(); } /* bit 7 is MCU reset on Arkanoid */ /* - does it reset the Brixian MCU too? */ } /* different hook-up, everything except for bits 0-1 and 7 aren't tested afaik. */ void arkanoid_state::tetrsark_d008_w(uint8_t data) { int bank; /* bits 0 and 1 flip X and Y */ flip_screen_x_set(data & 0x01); flip_screen_y_set(data & 0x02); /* bit 2 selects the input paddle? */ m_paddle_select = data & 0x04; /* bit 3-4 is unknown? */ /* bit 5 controls the graphics rom bank */ bank = (data & 0x20) >> 5; if (m_gfxbank != bank) { m_gfxbank = bank; m_bg_tilemap->mark_all_dirty(); } /* bit 6 controls the palette bank */ bank = (data & 0x40) >> 6; if (m_palettebank != bank) { m_palettebank = bank; m_bg_tilemap->mark_all_dirty(); } /* bit 7 is coin lockout (but not the service coin) */ machine().bookkeeping().coin_lockout_w(0, !(data & 0x80)); machine().bookkeeping().coin_lockout_w(1, !(data & 0x80)); } void arkanoid_state::hexa_d008_w(uint8_t data) { /* bits 0 and 1 flip X and Y */ flip_screen_x_set(data & 0x01); flip_screen_y_set(data & 0x02); /* bit 2 - 3 unknown */ /* bit 4 could be the ROM bank selector for 8000-bfff (not sure) */ membank("bank1")->set_entry(((data & 0x10) >> 4)); /* bit 5 controls the graphics rom bank */ if (m_gfxbank != ((data & 0x20) >> 5)) { m_gfxbank = (data & 0x20) >> 5; m_bg_tilemap->mark_all_dirty(); } /* bit 6 - 7 unknown */ } TILE_GET_INFO_MEMBER(arkanoid_state::get_bg_tile_info) { int offs = tile_index * 2; int code = m_videoram[offs + 1] + ((m_videoram[offs] & 0x07) << 8) + 2048 * m_gfxbank; int color = ((m_videoram[offs] & 0xf8) >> 3) + 32 * m_palettebank; tileinfo.set(0, code, color, 0); } void arkanoid_state::video_start() { m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(arkanoid_state::get_bg_tile_info)), TILEMAP_SCAN_ROWS, 8, 8, 32, 32); } void arkanoid_state::draw_sprites( bitmap_ind16 &bitmap, const rectangle &cliprect ) { int offs; for (offs = 0; offs < m_spriteram.bytes(); offs += 4) { int sx, sy, code; sx = m_spriteram[offs]; sy = 248 - m_spriteram[offs + 1]; if (flip_screen_x()) sx = 248 - sx; if (flip_screen_y()) sy = 248 - sy; code = m_spriteram[offs + 3] + ((m_spriteram[offs + 2] & 0x03) << 8) + 1024 * m_gfxbank; m_gfxdecode->gfx(0)->transpen(bitmap,cliprect, 2 * code, ((m_spriteram[offs + 2] & 0xf8) >> 3) + 32 * m_palettebank, flip_screen_x(),flip_screen_y(), sx,sy + (flip_screen_y() ? 8 : -8),0); m_gfxdecode->gfx(0)->transpen(bitmap,cliprect, 2 * code + 1, ((m_spriteram[offs + 2] & 0xf8) >> 3) + 32 * m_palettebank, flip_screen_x(),flip_screen_y(), sx,sy,0); } } uint32_t arkanoid_state::screen_update_arkanoid(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { m_bg_tilemap->draw(screen, bitmap, cliprect, 0, 0); draw_sprites(bitmap, cliprect); return 0; } uint32_t arkanoid_state::screen_update_hexa(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { m_bg_tilemap->draw(screen, bitmap, cliprect, 0, 0); return 0; }
johnparker007/mame
src/mame/video/arkanoid.cpp
C++
gpl-2.0
5,337
# -*- coding: utf-8 -*- # ########################## Copyrights and license ############################ # # # Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> # # Copyright 2012 Zearin <zearin@gonk.net> # # Copyright 2013 AKFish <akfish@gmail.com> # # Copyright 2013 Bill Mill <bill.mill@gmail.com> # # Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> # # Copyright 2013 davidbrai <davidbrai@gmail.com> # # # # This file is part of PyGithub. http://jacquev6.github.com/PyGithub/ # # # # PyGithub is free software: you can redistribute it and/or modify it under # # the terms of the GNU Lesser General Public License as published by the Free # # Software Foundation, either version 3 of the License, or (at your option) # # any later version. # # # # PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # # details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with PyGithub. If not, see <http://www.gnu.org/licenses/>. # # # # ############################################################################## import github.GithubObject class PaginatedListBase: def __init__(self): self.__elements = list() def __getitem__(self, index): assert isinstance(index, (int, slice)) if isinstance(index, (int, long)): self.__fetchToIndex(index) return self.__elements[index] else: return self._Slice(self, index) def __iter__(self): for element in self.__elements: yield element while self._couldGrow(): newElements = self._grow() for element in newElements: yield element def _isBiggerThan(self, index): return len(self.__elements) > index or self._couldGrow() def __fetchToIndex(self, index): while len(self.__elements) <= index and self._couldGrow(): self._grow() def _grow(self): newElements = self._fetchNextPage() self.__elements += newElements return newElements class _Slice: def __init__(self, theList, theSlice): self.__list = theList self.__start = theSlice.start or 0 self.__stop = theSlice.stop self.__step = theSlice.step or 1 def __iter__(self): index = self.__start while not self.__finished(index): if self.__list._isBiggerThan(index): yield self.__list[index] index += self.__step else: return def __finished(self, index): return self.__stop is not None and index >= self.__stop class PaginatedList(PaginatedListBase): """ This class abstracts the `pagination of the API <http://developer.github.com/v3/#pagination>`_. You can simply enumerate through instances of this class:: for repo in user.get_repos(): print repo.name You can also index them or take slices:: second_repo = user.get_repos()[1] first_repos = user.get_repos()[:10] If you want to iterate in reversed order, just do:: for repo in user.get_repos().reversed: print repo.name And if you really need it, you can explicitely access a specific page:: some_repos = user.get_repos().get_page(0) some_other_repos = user.get_repos().get_page(3) """ def __init__(self, contentClass, requester, firstUrl, firstParams, headers=None): PaginatedListBase.__init__(self) self.__requester = requester self.__contentClass = contentClass self.__firstUrl = firstUrl self.__firstParams = firstParams or () self.__nextUrl = firstUrl self.__nextParams = firstParams or {} self.__headers = headers if self.__requester.per_page != 30: self.__nextParams["per_page"] = self.__requester.per_page self._reversed = False self.__totalCount = None @property def totalCount(self): if not self.__totalCount: self._grow() return self.__totalCount def _getLastPageUrl(self): headers, data = self.__requester.requestJsonAndCheck( "GET", self.__firstUrl, parameters=self.__nextParams, headers=self.__headers ) links = self.__parseLinkHeader(headers) lastUrl = links.get("last") return lastUrl @property def reversed(self): r = PaginatedList(self.__contentClass, self.__requester, self.__firstUrl, self.__firstParams) r.__reverse() return r def __reverse(self): self._reversed = True lastUrl = self._getLastPageUrl() if lastUrl: self.__nextUrl = lastUrl def _couldGrow(self): return self.__nextUrl is not None def _fetchNextPage(self): headers, data = self.__requester.requestJsonAndCheck( "GET", self.__nextUrl, parameters=self.__nextParams, headers=self.__headers ) data = data if data else [] self.__nextUrl = None if len(data) > 0: links = self.__parseLinkHeader(headers) if self._reversed: if "prev" in links: self.__nextUrl = links["prev"] elif "next" in links: self.__nextUrl = links["next"] self.__nextParams = None if 'items' in data: self.__totalCount = data['total_count'] data = data["items"] content = [ self.__contentClass(self.__requester, headers, element, completed=False) for element in data if element is not None ] if self._reversed: return content[::-1] return content def __parseLinkHeader(self, headers): links = {} if "link" in headers: linkHeaders = headers["link"].split(", ") for linkHeader in linkHeaders: (url, rel) = linkHeader.split("; ") url = url[1:-1] rel = rel[5:-1] links[rel] = url return links def get_page(self, page): params = dict(self.__firstParams) if page != 0: params["page"] = page + 1 if self.__requester.per_page != 30: params["per_page"] = self.__requester.per_page headers, data = self.__requester.requestJsonAndCheck( "GET", self.__firstUrl, parameters=params, headers=self.__headers ) if 'items' in data: self.__totalCount = data['total_count'] data = data["items"] return [ self.__contentClass(self.__requester, headers, element, completed=False) for element in data ]
cytec/SickRage
lib/github/PaginatedList.py
Python
gpl-3.0
7,862
define(["dojo/_base/declare","./AnalogIndicatorBase"], function(declare, AnalogIndicatorBase) { return declare("dojox.gauges.AnalogArrowIndicator", [AnalogIndicatorBase],{ // summary: // An indicator for the AnalogGauge that draws an arrow. The arrow is drawn on the angle that corresponds // to the value of the indicator. _getShapes: function(group){ // summary: // Override of dojox.gauges.AnalogLineIndicator._getShapes if(!this._gauge){ return null; } var color = this.color ? this.color : 'black'; var strokeColor = this.strokeColor ? this.strokeColor : color; var stroke = { color: strokeColor, width: 1}; if (this.color.type && !this.strokeColor){ stroke.color = this.color.colors[0].color; } var x = Math.floor(this.width/2); var head = this.width * 5; var odd = (this.width & 1); var shapes = []; var points = [{x:-x, y:0}, {x:-x, y:-this.length+head}, {x:-2*x, y:-this.length+head}, {x:0, y:-this.length}, {x:2*x+odd,y:-this.length+head}, {x:x+odd, y:-this.length+head}, {x:x+odd, y:0}, {x:-x, y:0}]; shapes[0] = group.createPolyline(points) .setStroke(stroke) .setFill(color); shapes[1] = group.createLine({ x1:-x, y1: 0, x2: -x, y2:-this.length+head }) .setStroke({color: this.highlight}); shapes[2] = group.createLine({ x1:-x-3, y1: -this.length+head, x2: 0, y2:-this.length }) .setStroke({color: this.highlight}); shapes[3] = group.createCircle({cx: 0, cy: 0, r: this.width}) .setStroke(stroke) .setFill(color); return shapes; } }); });
avz-cmf/zaboy-middleware
www/js/dojox/gauges/AnalogArrowIndicator.js
JavaScript
gpl-3.0
1,598
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage Docs * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: DocumentListEntry.php 16971 2009-07-22 18:05:45Z mikaelkael $ */ /** * @see Zend_Gdata_EntryAtom */ require_once 'Zend/Gdata/Entry.php'; /** * Represents a Documents List entry in the Documents List data API meta feed * of a user's documents. * * @category Zend * @package Zend_Gdata * @subpackage Docs * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_Docs_DocumentListEntry extends Zend_Gdata_Entry { /** * Create a new instance of an entry representing a document. * * @param DOMElement $element (optional) DOMElement from which this * object should be constructed. */ public function __construct($element = null) { $this->registerAllNamespaces(Zend_Gdata_Docs::$namespaces); parent::__construct($element); } }
ratliff/server
vendor/ZendFramework/library/Zend/Gdata/Docs/DocumentListEntry.php
PHP
agpl-3.0
1,649
/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <seastar/core/thread.hh> #include "core/do_with.hh" #include "cql_test_env.hh" #include "cql3/query_processor.hh" #include "cql3/query_options.hh" #include "core/distributed.hh" #include "core/shared_ptr.hh" #include "utils/UUID_gen.hh" #include "service/migration_manager.hh" #include "message/messaging_service.hh" #include "service/storage_service.hh" #include "db/config.hh" #include "db/batchlog_manager.hh" #include "schema_builder.hh" #include "tmpdir.hh" // TODO: remove (#293) #include "message/messaging_service.hh" #include "gms/failure_detector.hh" #include "gms/gossiper.hh" #include "service/storage_service.hh" // TODO : remove once shutdown is ok. // Broke these test when doing horror patch for #293 // Simpler to copy the code from init.cc than trying to do clever parameterization // and whatnot. static future<> tst_init_storage_service(distributed<database>& db) { return service::init_storage_service(db).then([] { engine().at_exit([] { return service::deinit_storage_service(); }); }); } static future<> tst_init_ms_fd_gossiper(sstring listen_address, db::seed_provider_type seed_provider, sstring cluster_name = "Test Cluster") { const gms::inet_address listen(listen_address); // Init messaging_service return net::get_messaging_service().start(listen).then([]{ engine().at_exit([] { return net::get_messaging_service().stop(); }); }).then([] { // Init failure_detector return gms::get_failure_detector().start().then([] { engine().at_exit([]{ return gms::get_failure_detector().stop(); }); }); }).then([listen_address, seed_provider, cluster_name] { // Init gossiper std::set<gms::inet_address> seeds; if (seed_provider.parameters.count("seeds") > 0) { size_t begin = 0; size_t next = 0; sstring seeds_str = seed_provider.parameters.find("seeds")->second; while (begin < seeds_str.length() && begin != (next=seeds_str.find(",",begin))) { seeds.emplace(gms::inet_address(seeds_str.substr(begin,next-begin))); begin = next+1; } } if (seeds.empty()) { seeds.emplace(gms::inet_address("127.0.0.1")); } return gms::get_gossiper().start().then([seeds, cluster_name] { auto& gossiper = gms::get_local_gossiper(); gossiper.set_seeds(seeds); gossiper.set_cluster_name(cluster_name); engine().at_exit([]{ return gms::get_gossiper().stop(); }); }); }); } // END TODO future<> init_once(shared_ptr<distributed<database>> db) { static bool done = false; if (!done) { done = true; // FIXME: we leak db, since we're initializing the global storage_service with it. new shared_ptr<distributed<database>>(db); return tst_init_storage_service(*db).then([] { return tst_init_ms_fd_gossiper("127.0.0.1", db::config::seed_provider_type()); }).then([] { return db::system_keyspace::init_local_cache(); }); } else { return make_ready_future(); } } class single_node_cql_env : public cql_test_env { public: static auto constexpr ks_name = "ks"; private: ::shared_ptr<distributed<database>> _db; ::shared_ptr<distributed<cql3::query_processor>> _qp; lw_shared_ptr<tmpdir> _data_dir; private: struct core_local_state { service::client_state client_state; core_local_state() : client_state(service::client_state::for_external_calls()) { } future<> stop() { return make_ready_future<>(); } }; distributed<core_local_state> _core_local; private: auto make_query_state() { try { _core_local.local().client_state.set_keyspace(*_db, ks_name); } catch (exceptions::invalid_request_exception&) { } return ::make_shared<service::query_state>(_core_local.local().client_state); } public: single_node_cql_env() { } virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(const sstring& text) override { auto qs = make_query_state(); return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {}); } virtual future<::shared_ptr<transport::messages::result_message>> execute_cql( const sstring& text, std::unique_ptr<cql3::query_options> qo) override { auto qs = make_query_state(); auto& lqo = *qo; return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {}); } virtual future<bytes> prepare(sstring query) override { return _qp->invoke_on_all([query, this] (auto& local_qp) { auto qs = this->make_query_state(); return local_qp.prepare(query, *qs).finally([qs] {}).discard_result(); }).then([query, this] { return _qp->local().compute_id(query, ks_name); }); } virtual future<::shared_ptr<transport::messages::result_message>> execute_prepared( bytes id, std::vector<bytes_opt> values) override { auto prepared = _qp->local().get_prepared(id); assert(bool(prepared)); auto stmt = prepared->statement; assert(stmt->get_bound_terms() == values.size()); auto options = ::make_shared<cql3::query_options>(std::move(values)); options->prepare(prepared->bound_names); auto qs = make_query_state(); return _qp->local().process_statement(stmt, *qs, *options) .finally([options, qs] {}); } virtual future<> create_table(std::function<schema(const sstring&)> schema_maker) override { auto id = utils::UUID_gen::get_time_UUID(); return _db->invoke_on_all([schema_maker, id, this] (database& db) { schema_builder builder(make_lw_shared(schema_maker(ks_name))); builder.set_uuid(id); auto cf_schema = builder.build(schema_builder::compact_storage::no); auto& ks = db.find_keyspace(ks_name); auto cfg = ks.make_column_family_config(*cf_schema); db.add_column_family(std::move(cf_schema), std::move(cfg)); }); } virtual future<> require_keyspace_exists(const sstring& ks_name) override { auto& db = _db->local(); assert(db.has_keyspace(ks_name)); return make_ready_future<>(); } virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override { auto& db = _db->local(); assert(db.has_schema(ks_name, table_name)); return make_ready_future<>(); } virtual future<> require_column_has_value(const sstring& table_name, std::vector<boost::any> pk, std::vector<boost::any> ck, const sstring& column_name, boost::any expected) override { auto& db = _db->local(); auto& cf = db.find_column_family(ks_name, table_name); auto schema = cf.schema(); auto pkey = partition_key::from_deeply_exploded(*schema, pk); auto dk = dht::global_partitioner().decorate_key(*schema, pkey); auto shard = db.shard_of(dk._token); return _db->invoke_on(shard, [pkey = std::move(pkey), ck = std::move(ck), ks_name = std::move(ks_name), column_name = std::move(column_name), expected = std::move(expected), table_name = std::move(table_name)] (database& db) mutable { auto& cf = db.find_column_family(ks_name, table_name); auto schema = cf.schema(); return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) { assert(p != nullptr); auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck)); assert(row != nullptr); auto col_def = schema->get_column_definition(utf8_type->decompose(column_name)); assert(col_def != nullptr); const atomic_cell_or_collection* cell = row->find_cell(col_def->id); if (!cell) { assert(((void)"column not set", 0)); } bytes actual; if (!col_def->type->is_multi_cell()) { auto c = cell->as_atomic_cell(); assert(c.is_live()); actual = { c.value().begin(), c.value().end() }; } else { auto c = cell->as_collection_mutation(); auto type = dynamic_pointer_cast<const collection_type_impl>(col_def->type); actual = type->to_value(type->deserialize_mutation_form(c), serialization_format::internal()); } assert(col_def->type->equal(actual, col_def->type->decompose(expected))); }); }); } virtual database& local_db() override { return _db->local(); } cql3::query_processor& local_qp() override { return _qp->local(); } future<> start() { return seastar::async([this] { locator::i_endpoint_snitch::create_snitch("SimpleSnitch").get(); auto db = ::make_shared<distributed<database>>(); init_once(db).get(); auto cfg = make_lw_shared<db::config>(); _data_dir = make_lw_shared<tmpdir>(); cfg->data_file_directories() = { _data_dir->path }; boost::filesystem::create_directories((_data_dir->path + "/system").c_str()); db->start(std::move(*cfg)).get(); distributed<service::storage_proxy>& proxy = service::get_storage_proxy(); distributed<service::migration_manager>& mm = service::get_migration_manager(); distributed<db::batchlog_manager>& bm = db::get_batchlog_manager(); auto qp = ::make_shared<distributed<cql3::query_processor>>(); proxy.start(std::ref(*db)).get(); mm.start().get(); qp->start(std::ref(proxy), std::ref(*db)).get(); auto& ss = service::get_local_storage_service(); static bool storage_service_started = false; if (!storage_service_started) { storage_service_started = true; ss.init_server().get(); } bm.start(std::ref(*qp)).get(); _core_local.start().get(); _db = std::move(db); _qp = std::move(qp); auto query = sprint("create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };", sstring{ks_name}); execute_cql(query).get(); }); } virtual future<> stop() override { return _core_local.stop().then([this] { return db::get_batchlog_manager().stop().then([this] { return _qp->stop().then([this] { return service::get_migration_manager().stop().then([this] { return service::get_storage_proxy().stop().then([this] { return _db->stop().then([this] { return locator::i_endpoint_snitch::stop_snitch(); }); }); }); }); }); }); } }; future<::shared_ptr<cql_test_env>> make_env_for_test() { return seastar::async([] { auto env = ::make_shared<single_node_cql_env>(); env->start().get(); return dynamic_pointer_cast<cql_test_env>(env); }); } future<> do_with_cql_env(std::function<future<>(cql_test_env&)> func) { return make_env_for_test().then([func = std::move(func)] (auto e) mutable { return do_with(std::move(func), [e] (auto& f) { return f(*e); }).finally([e] { return e->stop().finally([e] {}); }); }); }
stamhe/scylla
tests/cql_test_env.cc
C++
agpl-3.0
12,955
/* * Copyright 2013 Orient Technologies. * Copyright 2013 Geomatys. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.core.sql.method.misc; import com.orientechnologies.orient.core.command.OCommandContext; import com.orientechnologies.orient.core.db.record.OIdentifiable; /** * Returns the value's Java type. * * @author Luca Garulli */ public class OSQLMethodJavaType extends OAbstractSQLMethod { public static final String NAME = "javatype"; public OSQLMethodJavaType() { super(NAME); } @Override public Object execute(Object iThis, OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iParams) { if (ioResult == null) { return null; } return ioResult.getClass().getName(); } }
sanyaade-g2g-repos/orientdb
core/src/main/java/com/orientechnologies/orient/core/sql/method/misc/OSQLMethodJavaType.java
Java
apache-2.0
1,305
package com.thinkaurelius.titan.graphdb.serializer; /** * @author Matthias Broecheler (me@matthiasb.com) */ public class NoDefaultConstructor { private final int i; public NoDefaultConstructor(int i) { this.i=i; } }
fengshao0907/titan
titan-test/src/test/java/com/thinkaurelius/titan/graphdb/serializer/NoDefaultConstructor.java
Java
apache-2.0
243
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\DBAL\Platforms; use Doctrine\DBAL\Schema\Sequence; /** * Platform to ensure compatibility of Doctrine with Microsoft SQL Server 2012 version. * * Differences to SQL Server 2008 and before are that sequences are introduced. * * @author Steve Müller <st.mueller@dzh-online.de> */ class SQLServer2012Platform extends SQLServer2008Platform { /** * {@inheritdoc} */ public function getAlterSequenceSQL(Sequence $sequence) { return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) . ' INCREMENT BY ' . $sequence->getAllocationSize(); } /** * {@inheritdoc} */ public function getCreateSequenceSQL(Sequence $sequence) { return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) . ' START WITH ' . $sequence->getInitialValue() . ' INCREMENT BY ' . $sequence->getAllocationSize() . ' MINVALUE ' . $sequence->getInitialValue(); } /** * {@inheritdoc} */ public function getDropSequenceSQL($sequence) { if ($sequence instanceof Sequence) { $sequence = $sequence->getQuotedName($this); } return 'DROP SEQUENCE ' . $sequence; } /** * {@inheritdoc} */ public function getListSequencesSQL($database) { return 'SELECT seq.name, CAST( seq.increment AS VARCHAR(MAX) ) AS increment, -- CAST avoids driver error for sql_variant type CAST( seq.start_value AS VARCHAR(MAX) ) AS start_value -- CAST avoids driver error for sql_variant type FROM sys.sequences AS seq'; } /** * {@inheritdoc} */ public function getSequenceNextValSQL($sequenceName) { return 'SELECT NEXT VALUE FOR ' . $sequenceName; } /** * {@inheritdoc} */ public function supportsSequences() { return true; } /** * {@inheritdoc} * * Returns Microsoft SQL Server 2012 specific keywords class */ protected function getReservedKeywordsClass() { return 'Doctrine\DBAL\Platforms\Keywords\SQLServer2012Keywords'; } /** * {@inheritdoc} */ protected function doModifyLimitQuery($query, $limit, $offset = null) { if ($limit === null && $offset === null) { return $query; } // Queries using OFFSET... FETCH MUST have an ORDER BY clause // Find the position of the last instance of ORDER BY and ensure it is not within a parenthetical statement // but can be in a newline $matches = array(); $matchesCount = preg_match_all("/[\\s]+order by /i", $query, $matches, PREG_OFFSET_CAPTURE); $orderByPos = false; if ($matchesCount > 0) { $orderByPos = $matches[0][($matchesCount - 1)][1]; } if ($orderByPos === false || substr_count($query, "(", $orderByPos) - substr_count($query, ")", $orderByPos) ) { if (stripos($query, 'SELECT DISTINCT') === 0) { // SQL Server won't let us order by a non-selected column in a DISTINCT query, // so we have to do this madness. This says, order by the first column in the // result. SQL Server's docs say that a nonordered query's result order is non- // deterministic anyway, so this won't do anything that a bunch of update and // deletes to the table wouldn't do anyway. $query .= " ORDER BY 1"; } else { // In another DBMS, we could do ORDER BY 0, but SQL Server gets angry if you // use constant expressions in the order by list. $query .= " ORDER BY (SELECT 0)"; } } if ($offset === null) { $offset = 0; } // This looks somewhat like MYSQL, but limit/offset are in inverse positions // Supposedly SQL:2008 core standard. // Per TSQL spec, FETCH NEXT n ROWS ONLY is not valid without OFFSET n ROWS. $query .= " OFFSET " . (int) $offset . " ROWS"; if ($limit !== null) { $query .= " FETCH NEXT " . (int) $limit . " ROWS ONLY"; } return $query; } }
adiIspas/Hootsuite_Backend_API
web_server/code/vendor/doctrine/dbal/lib/Doctrine/DBAL/Platforms/SQLServer2012Platform.php
PHP
mit
5,406
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; class GitHub_26417 { static int _a; [MethodImplAttribute(MethodImplOptions.NoInlining)] static void MyWriteLine(int v) { Console.WriteLine(v); if (v == 0) { throw new Exception(); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] static void Test() { _a = 1; while (_a == 1) { MyWriteLine(_a); _a = 0; } } static int Main() { int result = 100; try { Test(); } catch (Exception) { Console.WriteLine("FAILED"); result = -1; } return result; } }
krk/coreclr
tests/src/JIT/Regression/JitBlue/GitHub_26417/GitHub_26417.cs
C#
mit
961
// // detail/signal_blocker.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2014 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_DETAIL_SIGNAL_BLOCKER_HPP #define ASIO_DETAIL_SIGNAL_BLOCKER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_HAS_THREADS) || defined(ASIO_WINDOWS) \ || defined(ASIO_WINDOWS_RUNTIME) \ || defined(__CYGWIN__) || defined(__SYMBIAN32__) # include "asio/detail/null_signal_blocker.hpp" #elif defined(ASIO_HAS_PTHREADS) # include "asio/detail/posix_signal_blocker.hpp" #else # error Only Windows and POSIX are supported! #endif namespace asio { namespace detail { #if !defined(ASIO_HAS_THREADS) || defined(ASIO_WINDOWS) \ || defined(ASIO_WINDOWS_RUNTIME) \ || defined(__CYGWIN__) || defined(__SYMBIAN32__) typedef null_signal_blocker signal_blocker; #elif defined(ASIO_HAS_PTHREADS) typedef posix_signal_blocker signal_blocker; #endif } // namespace detail } // namespace asio #endif // ASIO_DETAIL_SIGNAL_BLOCKER_HPP
chances/duk-vis
vendor/Cinder/include/asio/detail/signal_blocker.hpp
C++
mit
1,259
using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; using System.Web; using System.Web.Mvc; namespace OfficeDevPnP.MSGraphAPIGroups.Controllers { public class AccountController : Controller { public void SignIn() { if (!Request.IsAuthenticated) { HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType); } } public void SignOut() { string callbackUrl = Url.Action("SignOutCallback", "Account", routeValues: null, protocol: Request.Url.Scheme); HttpContext.GetOwinContext().Authentication.SignOut( new AuthenticationProperties { RedirectUri = callbackUrl }, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); } public ActionResult SignOutCallback() { if (Request.IsAuthenticated) { // Redirect to home page if the user is authenticated. return RedirectToAction("Index", "Home"); } return View(); } } }
yagoto/PnP
Samples/MicrosoftGraph.Office365.GroupsExplorer/Controllers/AccountController.cs
C#
mit
1,101
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'save', 'af', { toolbar: 'Bewaar' } );
aodarc/flowers_room
styleguides/static/ckeditor/ckeditor/plugins/save/lang/af.js
JavaScript
mit
212
/* * The MIT License * Copyright (c) 2012 Microsoft Corporation * * 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. */ package microsoft.exchange.webservices.data.sync; import microsoft.exchange.webservices.data.attribute.EditorBrowsable; import microsoft.exchange.webservices.data.core.service.ServiceObject; import microsoft.exchange.webservices.data.core.enumeration.sync.ChangeType; import microsoft.exchange.webservices.data.core.enumeration.attribute.EditorBrowsableState; import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException; import microsoft.exchange.webservices.data.property.complex.ServiceId; /** * Represents a change as returned by a synchronization operation. */ @EditorBrowsable(state = EditorBrowsableState.Never) public abstract class Change { /** * The type of change. */ private ChangeType changeType; /** * The service object the change applies to. */ private ServiceObject serviceObject; /** * The Id of the service object the change applies to. */ private ServiceId id; /** * Initializes a new instance of Change. */ protected Change() { } /** * Initializes a new instance of Change. * * @return the service id */ public abstract ServiceId createId(); /** * Gets the type of the change. * * @return the change type */ public ChangeType getChangeType() { return this.changeType; } /** * sets the type of the change. * * @param changeType the new change type */ public void setChangeType(ChangeType changeType) { this.changeType = changeType; } /** * Gets the service object the change applies to. * * @return the service object */ public ServiceObject getServiceObject() { return this.serviceObject; } /** * Sets the service object. * * @param serviceObject the new service object */ public void setServiceObject(ServiceObject serviceObject) { this.serviceObject = serviceObject; } /** * Gets the Id of the service object the change applies to. * * @return the id * @throws ServiceLocalException the service local exception */ public ServiceId getId() throws ServiceLocalException { return this.getServiceObject() != null ? this.getServiceObject() .getId() : this.id; } /** * Sets the id. * * @param id the new id */ public void setId(ServiceId id) { this.id = id; } }
KatharineYe/ews-java-api
src/main/java/microsoft/exchange/webservices/data/sync/Change.java
Java
mit
3,475
define( //begin v1.x content { "field-sat-relative+0": "เสาร์นี้", "field-sat-relative+1": "เสาร์หน้า", "field-dayperiod": "ช่วงวัน", "field-sun-relative+-1": "อาทิตย์ที่แล้ว", "field-mon-relative+-1": "จันทร์ที่แล้ว", "field-minute": "นาที", "field-day-relative+-1": "เมื่อวาน", "field-weekday": "วันในสัปดาห์", "field-day-relative+-2": "เมื่อวานซืน", "months-standAlone-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13" ], "field-era": "สมัย", "field-hour": "ชั่วโมง", "field-sun-relative+0": "อาทิตย์นี้", "field-sun-relative+1": "อาทิตย์หน้า", "months-standAlone-abbr": [ "เมสเคอเรม", "เตเกมท", "เฮดาร์", "ทาฮ์ซัส", "เทอร์", "เยคาทิท", "เมกาบิต", "เมียเซีย", "เจนบอต", "เซเน", "ฮัมเล", "เนแฮซ", "พากูเมน" ], "field-wed-relative+-1": "พุธที่แล้ว", "field-day-relative+0": "วันนี้", "field-day-relative+1": "พรุ่งนี้", "field-day-relative+2": "มะรืนนี้", "field-tue-relative+0": "อังคารนี้", "field-zone": "เขตเวลา", "field-tue-relative+1": "อังคารหน้า", "field-week-relative+-1": "สัปดาห์ที่แล้ว", "field-year-relative+0": "ปีนี้", "field-year-relative+1": "ปีหน้า", "field-sat-relative+-1": "เสาร์ที่แล้ว", "field-year-relative+-1": "ปีที่แล้ว", "field-year": "ปี", "field-fri-relative+0": "ศุกร์นี้", "field-fri-relative+1": "ศุกร์หน้า", "months-standAlone-wide": [ "เมสเคอเรม", "เตเกมท", "เฮดาร์", "ทาฮ์ซัส", "เทอร์", "เยคาทิท", "เมกาบิต", "เมียเซีย", "เจนบอต", "เซเน", "ฮัมเล", "เนแฮซ", "พากูเมน" ], "field-week": "สัปดาห์", "field-week-relative+0": "สัปดาห์นี้", "field-week-relative+1": "สัปดาห์หน้า", "months-format-abbr": [ "เมสเคอเรม", "เตเกมท", "เฮดาร์", "ทาฮ์ซัส", "เทอร์", "เยคาทิท", "เมกาบิต", "เมียเซีย", "เจนบอต", "เซเน", "ฮัมเล", "เนแฮซ", "พากูเมน" ], "field-month-relative+0": "เดือนนี้", "field-month": "เดือน", "field-month-relative+1": "เดือนหน้า", "field-fri-relative+-1": "ศุกร์ที่แล้ว", "field-second": "วินาที", "field-tue-relative+-1": "อังคารที่แล้ว", "field-day": "วัน", "months-format-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13" ], "field-mon-relative+0": "จันทร์นี้", "field-mon-relative+1": "จันทร์หน้า", "field-thu-relative+0": "พฤหัสนี้", "field-second-relative+0": "ขณะนี้", "field-thu-relative+1": "พฤหัสหน้า", "months-format-wide": [ "เมสเคอเรม", "เตเกมท", "เฮดาร์", "ทาฮ์ซัส", "เทอร์", "เยคาทิท", "เมกาบิต", "เมียเซีย", "เจนบอต", "เซเน", "ฮัมเล", "เนแฮซ", "พากูเมน" ], "field-wed-relative+0": "พุธนี้", "field-wed-relative+1": "พุธหน้า", "field-month-relative+-1": "เดือนที่แล้ว", "field-thu-relative+-1": "พฤหัสที่แล้ว" } //end v1.x content );
srujant/MLNews
static/js/cesium/ThirdParty/dojo-release-1.10.4/dojo/cldr/nls/th/ethiopic.js
JavaScript
mit
4,368
/* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */ /** * @class The Yahoo global namespace */ var YAHOO = function() { return { /** * Yahoo presentation platform utils namespace */ util: {}, /** * Yahoo presentation platform widgets namespace */ widget: {}, /** * Yahoo presentation platform examples namespace */ example: {}, /** * Returns the namespace specified and creates it if it doesn't exist * * YAHOO.namespace("property.package"); * YAHOO.namespace("YAHOO.property.package"); * * Either of the above would create YAHOO.property, then * YAHOO.property.package * * @param {String} sNameSpace String representation of the desired * namespace * @return {Object} A reference to the namespace object */ namespace: function( sNameSpace ) { if (!sNameSpace || !sNameSpace.length) { return null; } var levels = sNameSpace.split("."); var currentNS = YAHOO; // YAHOO is implied, so it is ignored if it is included for (var i=(levels[0] == "YAHOO") ? 1 : 0; i<levels.length; ++i) { currentNS[levels[i]] = currentNS[levels[i]] || {}; currentNS = currentNS[levels[i]]; } return currentNS; } }; } ();
ArrozAlba/huayra
srh/public/js/grid/calendar/YAHOO.js
JavaScript
gpl-2.0
1,547
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "ash/ash_switches.h" #include "base/command_line.h" #include "base/logging.h" #include "base/memory/ref_counted_memory.h" #include "base/values.h" #include "chrome/browser/browser_about_handler.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.h" #include "chrome/browser/chromeos/login/enrollment/enrollment_screen_actor.h" #include "chrome/browser/chromeos/login/login_display_host_impl.h" #include "chrome/browser/chromeos/login/screen_locker.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/system/input_device_settings.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/about_ui.h" #include "chrome/browser/ui/webui/chromeos/login/app_launch_splash_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/enrollment_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/error_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/eula_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/kiosk_app_menu_handler.h" #include "chrome/browser/ui/webui/chromeos/login/kiosk_autolaunch_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/locally_managed_user_creation_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/network_dropdown_handler.h" #include "chrome/browser/ui/webui/chromeos/login/network_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/network_state_informer.h" #include "chrome/browser/ui/webui/chromeos/login/reset_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/update_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/user_image_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.h" #include "chrome/browser/ui/webui/options/chromeos/user_image_source.h" #include "chrome/browser/ui/webui/theme_source.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/url_constants.h" #include "chromeos/chromeos_constants.h" #include "chromeos/chromeos_switches.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "grit/browser_resources.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/webui/web_ui_util.h" namespace chromeos { namespace { // List of known types of OobeUI. Type added as path in chrome://oobe url, for // example chrome://oobe/user-adding. const char kOobeDisplay[] = "oobe"; const char kLoginDisplay[] = "login"; const char kLockDisplay[] = "lock"; const char kUserAddingDisplay[] = "user-adding"; const char kAppLaunchSplashDisplay[] = "app-launch-splash"; const char* kKnownDisplayTypes[] = { kOobeDisplay, kLoginDisplay, kLockDisplay, kUserAddingDisplay, kAppLaunchSplashDisplay }; const char kStringsJSPath[] = "strings.js"; const char kLoginJSPath[] = "login.js"; const char kOobeJSPath[] = "oobe.js"; const char kKeyboardUtilsJSPath[] = "keyboard_utils.js"; const char kDemoUserLoginJSPath[] = "demo_user_login.js"; // Paths for deferred resource loading. const char kEnrollmentHTMLPath[] = "enrollment.html"; const char kEnrollmentCSSPath[] = "enrollment.css"; const char kEnrollmentJSPath[] = "enrollment.js"; // Creates a WebUIDataSource for chrome://oobe content::WebUIDataSource* CreateOobeUIDataSource( const base::DictionaryValue& localized_strings, const std::string& display_type) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIOobeHost); source->SetUseJsonJSFormatV2(); source->AddLocalizedStrings(localized_strings); source->SetJsonPath(kStringsJSPath); if (chromeos::KioskModeSettings::Get()->IsKioskModeEnabled()) { source->SetDefaultResource(IDR_DEMO_USER_LOGIN_HTML); source->AddResourcePath(kDemoUserLoginJSPath, IDR_DEMO_USER_LOGIN_JS); return source; } if (display_type == kOobeDisplay) { source->SetDefaultResource(IDR_OOBE_HTML); source->AddResourcePath(kOobeJSPath, IDR_OOBE_JS); } else { source->SetDefaultResource(IDR_LOGIN_HTML); source->AddResourcePath(kLoginJSPath, IDR_LOGIN_JS); } source->AddResourcePath(kKeyboardUtilsJSPath, IDR_KEYBOARD_UTILS_JS); source->OverrideContentSecurityPolicyFrameSrc( "frame-src chrome://terms/ " "chrome-extension://mfffpogegjflfpflabcdkioaeobkgjik/;"); // Serve deferred resources. source->AddResourcePath(kEnrollmentHTMLPath, IDR_OOBE_ENROLLMENT_HTML); source->AddResourcePath(kEnrollmentCSSPath, IDR_OOBE_ENROLLMENT_CSS); source->AddResourcePath(kEnrollmentJSPath, IDR_OOBE_ENROLLMENT_JS); return source; } std::string GetDisplayType(const GURL& url) { std::string path = url.path().size() ? url.path().substr(1) : ""; if (std::find(kKnownDisplayTypes, kKnownDisplayTypes + arraysize(kKnownDisplayTypes), path) == kKnownDisplayTypes + arraysize(kKnownDisplayTypes)) { LOG(ERROR) << "Unknown display type '" << path << "'. Setting default."; return kLoginDisplay; } return path; } } // namespace // static const char OobeUI::kScreenOobeNetwork[] = "connect"; const char OobeUI::kScreenOobeEula[] = "eula"; const char OobeUI::kScreenOobeUpdate[] = "update"; const char OobeUI::kScreenOobeEnrollment[] = "oauth-enrollment"; const char OobeUI::kScreenGaiaSignin[] = "gaia-signin"; const char OobeUI::kScreenAccountPicker[] = "account-picker"; const char OobeUI::kScreenKioskAutolaunch[] = "autolaunch"; const char OobeUI::kScreenKioskEnable[] = "kiosk-enable"; const char OobeUI::kScreenErrorMessage[] = "error-message"; const char OobeUI::kScreenUserImagePicker[] = "user-image"; const char OobeUI::kScreenTpmError[] = "tpm-error-message"; const char OobeUI::kScreenPasswordChanged[] = "password-changed"; const char OobeUI::kScreenManagedUserCreationFlow[] = "managed-user-creation"; const char OobeUI::kScreenTermsOfService[] = "terms-of-service"; const char OobeUI::kScreenWrongHWID[] = "wrong-hwid"; const char OobeUI::kScreenAppLaunchSplash[] = "app-launch-splash"; const char OobeUI::kScreenConfirmPassword[] = "confirm-password"; const char OobeUI::kScreenMessageBox[] = "message-box"; OobeUI::OobeUI(content::WebUI* web_ui, const GURL& url) : WebUIController(web_ui), core_handler_(NULL), network_dropdown_handler_(NULL), update_screen_handler_(NULL), network_screen_actor_(NULL), eula_screen_actor_(NULL), reset_screen_actor_(NULL), autolaunch_screen_actor_(NULL), kiosk_enable_screen_actor_(NULL), wrong_hwid_screen_actor_(NULL), locally_managed_user_creation_screen_actor_(NULL), error_screen_handler_(NULL), signin_screen_handler_(NULL), terms_of_service_screen_actor_(NULL), user_image_screen_actor_(NULL), kiosk_app_menu_handler_(NULL), current_screen_(SCREEN_UNKNOWN), ready_(false) { display_type_ = GetDisplayType(url); InitializeScreenMaps(); network_state_informer_ = new NetworkStateInformer(); network_state_informer_->Init(); core_handler_ = new CoreOobeHandler(this); AddScreenHandler(core_handler_); core_handler_->SetDelegate(this); network_dropdown_handler_ = new NetworkDropdownHandler(); AddScreenHandler(network_dropdown_handler_); update_screen_handler_ = new UpdateScreenHandler(); AddScreenHandler(update_screen_handler_); network_dropdown_handler_->AddObserver(update_screen_handler_); if (display_type_ == kOobeDisplay) { NetworkScreenHandler* network_screen_handler = new NetworkScreenHandler(core_handler_); network_screen_actor_ = network_screen_handler; AddScreenHandler(network_screen_handler); } EulaScreenHandler* eula_screen_handler = new EulaScreenHandler(core_handler_); eula_screen_actor_ = eula_screen_handler; AddScreenHandler(eula_screen_handler); ResetScreenHandler* reset_screen_handler = new ResetScreenHandler(); reset_screen_actor_ = reset_screen_handler; AddScreenHandler(reset_screen_handler); KioskAutolaunchScreenHandler* autolaunch_screen_handler = new KioskAutolaunchScreenHandler(); autolaunch_screen_actor_ = autolaunch_screen_handler; AddScreenHandler(autolaunch_screen_handler); KioskEnableScreenHandler* kiosk_enable_screen_handler = new KioskEnableScreenHandler(); kiosk_enable_screen_actor_ = kiosk_enable_screen_handler; AddScreenHandler(kiosk_enable_screen_handler); LocallyManagedUserCreationScreenHandler* locally_managed_user_creation_screen_handler = new LocallyManagedUserCreationScreenHandler(); locally_managed_user_creation_screen_actor_ = locally_managed_user_creation_screen_handler; AddScreenHandler(locally_managed_user_creation_screen_handler); WrongHWIDScreenHandler* wrong_hwid_screen_handler = new WrongHWIDScreenHandler(); wrong_hwid_screen_actor_ = wrong_hwid_screen_handler; AddScreenHandler(wrong_hwid_screen_handler); EnrollmentScreenHandler* enrollment_screen_handler = new EnrollmentScreenHandler(); enrollment_screen_actor_ = enrollment_screen_handler; AddScreenHandler(enrollment_screen_handler); TermsOfServiceScreenHandler* terms_of_service_screen_handler = new TermsOfServiceScreenHandler; terms_of_service_screen_actor_ = terms_of_service_screen_handler; AddScreenHandler(terms_of_service_screen_handler); UserImageScreenHandler* user_image_screen_handler = new UserImageScreenHandler(); user_image_screen_actor_ = user_image_screen_handler; AddScreenHandler(user_image_screen_handler); error_screen_handler_ = new ErrorScreenHandler(network_state_informer_); AddScreenHandler(error_screen_handler_); gaia_screen_handler_ = new GaiaScreenHandler(network_state_informer_); AddScreenHandler(gaia_screen_handler_); signin_screen_handler_ = new SigninScreenHandler(network_state_informer_, error_screen_handler_, core_handler_, gaia_screen_handler_); AddScreenHandler(signin_screen_handler_); AppLaunchSplashScreenHandler* app_launch_splash_screen_handler = new AppLaunchSplashScreenHandler(network_state_informer_, error_screen_handler_); AddScreenHandler(app_launch_splash_screen_handler); app_launch_splash_screen_actor_ = app_launch_splash_screen_handler; // Initialize KioskAppMenuHandler. Note that it is NOT a screen handler. kiosk_app_menu_handler_ = new KioskAppMenuHandler; web_ui->AddMessageHandler(kiosk_app_menu_handler_); base::DictionaryValue localized_strings; GetLocalizedStrings(&localized_strings); Profile* profile = Profile::FromWebUI(web_ui); // Set up the chrome://theme/ source, for Chrome logo. ThemeSource* theme = new ThemeSource(profile); content::URLDataSource::Add(profile, theme); // Set up the chrome://terms/ data source, for EULA content. AboutUIHTMLSource* about_source = new AboutUIHTMLSource(chrome::kChromeUITermsHost, profile); content::URLDataSource::Add(profile, about_source); // Set up the chrome://oobe/ source. content::WebUIDataSource::Add(profile, CreateOobeUIDataSource(localized_strings, display_type_)); // Set up the chrome://userimage/ source. options::UserImageSource* user_image_source = new options::UserImageSource(); content::URLDataSource::Add(profile, user_image_source); } OobeUI::~OobeUI() { core_handler_->SetDelegate(NULL); network_dropdown_handler_->RemoveObserver(update_screen_handler_); } void OobeUI::ShowScreen(WizardScreen* screen) { screen->Show(); } void OobeUI::HideScreen(WizardScreen* screen) { screen->Hide(); } UpdateScreenActor* OobeUI::GetUpdateScreenActor() { return update_screen_handler_; } NetworkScreenActor* OobeUI::GetNetworkScreenActor() { return network_screen_actor_; } EulaScreenActor* OobeUI::GetEulaScreenActor() { return eula_screen_actor_; } EnrollmentScreenActor* OobeUI::GetEnrollmentScreenActor() { return enrollment_screen_actor_; } ResetScreenActor* OobeUI::GetResetScreenActor() { return reset_screen_actor_; } KioskAutolaunchScreenActor* OobeUI::GetKioskAutolaunchScreenActor() { return autolaunch_screen_actor_; } KioskEnableScreenActor* OobeUI::GetKioskEnableScreenActor() { return kiosk_enable_screen_actor_; } TermsOfServiceScreenActor* OobeUI::GetTermsOfServiceScreenActor() { return terms_of_service_screen_actor_; } WrongHWIDScreenActor* OobeUI::GetWrongHWIDScreenActor() { return wrong_hwid_screen_actor_; } UserImageScreenActor* OobeUI::GetUserImageScreenActor() { return user_image_screen_actor_; } ErrorScreenActor* OobeUI::GetErrorScreenActor() { return error_screen_handler_; } LocallyManagedUserCreationScreenHandler* OobeUI::GetLocallyManagedUserCreationScreenActor() { return locally_managed_user_creation_screen_actor_; } AppLaunchSplashScreenActor* OobeUI::GetAppLaunchSplashScreenActor() { return app_launch_splash_screen_actor_; } void OobeUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) { // Note, handlers_[0] is a GenericHandler used by the WebUI. for (size_t i = 0; i < handlers_.size(); ++i) handlers_[i]->GetLocalizedStrings(localized_strings); webui::SetFontAndTextDirection(localized_strings); kiosk_app_menu_handler_->GetLocalizedStrings(localized_strings); #if defined(GOOGLE_CHROME_BUILD) localized_strings->SetString("buildType", "chrome"); #else localized_strings->SetString("buildType", "chromium"); #endif // If we're not doing boot animation then WebUI should trigger // wallpaper load on boot. if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableBootAnimation)) { localized_strings->SetString("bootIntoWallpaper", "on"); } else { localized_strings->SetString("bootIntoWallpaper", "off"); } bool keyboard_driven_oobe = system::keyboard_settings::ForceKeyboardDrivenUINavigation(); localized_strings->SetString("highlightStrength", keyboard_driven_oobe ? "strong" : "normal"); } void OobeUI::InitializeScreenMaps() { screen_names_.resize(SCREEN_UNKNOWN); screen_names_[SCREEN_OOBE_NETWORK] = kScreenOobeNetwork; screen_names_[SCREEN_OOBE_EULA] = kScreenOobeEula; screen_names_[SCREEN_OOBE_UPDATE] = kScreenOobeUpdate; screen_names_[SCREEN_OOBE_ENROLLMENT] = kScreenOobeEnrollment; screen_names_[SCREEN_GAIA_SIGNIN] = kScreenGaiaSignin; screen_names_[SCREEN_ACCOUNT_PICKER] = kScreenAccountPicker; screen_names_[SCREEN_KIOSK_AUTOLAUNCH] = kScreenKioskAutolaunch; screen_names_[SCREEN_KIOSK_ENABLE] = kScreenKioskEnable; screen_names_[SCREEN_ERROR_MESSAGE] = kScreenErrorMessage; screen_names_[SCREEN_USER_IMAGE_PICKER] = kScreenUserImagePicker; screen_names_[SCREEN_TPM_ERROR] = kScreenTpmError; screen_names_[SCREEN_PASSWORD_CHANGED] = kScreenPasswordChanged; screen_names_[SCREEN_CREATE_MANAGED_USER_FLOW] = kScreenManagedUserCreationFlow; screen_names_[SCREEN_TERMS_OF_SERVICE] = kScreenTermsOfService; screen_names_[SCREEN_WRONG_HWID] = kScreenWrongHWID; screen_names_[SCREEN_APP_LAUNCH_SPLASH] = kScreenAppLaunchSplash; screen_names_[SCREEN_CONFIRM_PASSWORD] = kScreenConfirmPassword; screen_names_[SCREEN_MESSAGE_BOX] = kScreenMessageBox; screen_ids_.clear(); for (size_t i = 0; i < screen_names_.size(); ++i) screen_ids_[screen_names_[i]] = static_cast<Screen>(i); } void OobeUI::AddScreenHandler(BaseScreenHandler* handler) { web_ui()->AddMessageHandler(handler); handlers_.push_back(handler); } void OobeUI::InitializeHandlers() { ready_ = true; for (size_t i = 0; i < ready_callbacks_.size(); ++i) ready_callbacks_[i].Run(); ready_callbacks_.clear(); // Notify 'initialize' for synchronously loaded screens. for (size_t i = 0; i < handlers_.size(); ++i) { if (handlers_[i]->async_assets_load_id().empty()) handlers_[i]->InitializeBase(); } } void OobeUI::OnScreenAssetsLoaded(const std::string& async_assets_load_id) { DCHECK(!async_assets_load_id.empty()); for (size_t i = 0; i < handlers_.size(); ++i) { if (handlers_[i]->async_assets_load_id() == async_assets_load_id) handlers_[i]->InitializeBase(); } } bool OobeUI::IsJSReady(const base::Closure& display_is_ready_callback) { if (!ready_) ready_callbacks_.push_back(display_is_ready_callback); return ready_; } void OobeUI::ShowOobeUI(bool show) { core_handler_->ShowOobeUI(show); } void OobeUI::ShowRetailModeLoginSpinner() { signin_screen_handler_->ShowRetailModeLoginSpinner(); } void OobeUI::ShowSigninScreen(const LoginScreenContext& context, SigninScreenHandlerDelegate* delegate, NativeWindowDelegate* native_window_delegate) { signin_screen_handler_->SetDelegate(delegate); signin_screen_handler_->SetNativeWindowDelegate(native_window_delegate); LoginScreenContext actual_context(context); actual_context.set_oobe_ui(core_handler_->show_oobe_ui()); signin_screen_handler_->Show(actual_context); } void OobeUI::ResetSigninScreenHandlerDelegate() { signin_screen_handler_->SetDelegate(NULL); signin_screen_handler_->SetNativeWindowDelegate(NULL); } void OobeUI::AddObserver(Observer* observer) { observer_list_.AddObserver(observer); } void OobeUI::RemoveObserver(Observer* observer) { observer_list_.RemoveObserver(observer); } const std::string& OobeUI::GetScreenName(Screen screen) const { DCHECK(screen >= 0 && screen < SCREEN_UNKNOWN); return screen_names_[static_cast<size_t>(screen)]; } void OobeUI::OnCurrentScreenChanged(const std::string& screen) { if (screen_ids_.count(screen)) { Screen new_screen = screen_ids_[screen]; FOR_EACH_OBSERVER(Observer, observer_list_, OnCurrentScreenChanged(current_screen_, new_screen)); current_screen_ = new_screen; } else { NOTREACHED() << "Screen should be registered in InitializeScreenMaps()"; current_screen_ = SCREEN_UNKNOWN; } } } // namespace chromeos
qtekfun/htcDesire820Kernel
external/chromium_org/chrome/browser/ui/webui/chromeos/login/oobe_ui.cc
C++
gpl-2.0
18,995
// Generated by CoffeeScript 1.12.0 /* ExternalEditor Kevin Gravier <kevin@mrkmg.com> MIT */ (function() { var ReadFileError, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ReadFileError = (function(superClass) { extend(ReadFileError, superClass); ReadFileError.prototype.message = 'Failed to read temporary file'; function ReadFileError(original_error) { this.original_error = original_error; } return ReadFileError; })(Error); module.exports = ReadFileError; }).call(this);
mo-norant/FinHeartBel
website/node_modules/external-editor/main/errors/ReadFileError.js
JavaScript
gpl-3.0
800
/// \file /// \ingroup tutorial_legacy /// This script is a representation using TTasks of the Geant3 simulation program /// This example uses directly TTask objects. /// A real implementation would require one class per task derived from TTask. /// /// \macro_code /// /// \author Rene Brun void geant3tasks() { TTask *geant3 = new TTask("geant3","Geant3 simulation main program"); gROOT->GetListOfTasks()->Add(geant3); TTask *uginit = new TTask("uginit","Initialisation manager"); TTask *grun = new TTask("grun","Run manager"); TTask *uglast = new TTask("uglast","Termination manager"); geant3->Add(uginit); geant3->Add(grun); geant3->Add(uglast); TTask *ginit = new TTask("ginit","Geant3 initialisation"); TTask *ugeom = new TTask("ugeom","Geometry initialisation manager"); TTask *gphysi = new TTask("gphysi","Initialise cross-sections and energy loss tables"); TTask *ggclos = new TTask("ggclos","Geometry analyzer and optimizer"); uginit->Add(ginit); uginit->Add(ugeom); uginit->Add(gphysi); uginit->Add(ggclos); TTask *gtrigi = new TTask("gtrigi","Event initialisation"); TTask *gtrig = new TTask("gtrig","Event manager"); TTask *gtrigc = new TTask("gtrigc","Event cleaner"); grun->Add(gtrigi); grun->Add(gtrig); grun->Add(gtrigc); TTask *glast = new TTask("glast","Geant3 termination"); TTask *igend = new TTask("igend","Graphics package termination"); uglast->Add(glast); uglast->Add(igend); TTask *gukine = new TTask("gukine","Event generator manager"); TTask *gutrev = new TTask("gutrev","Event application manager"); TTask *gudigi = new TTask("gudigi","Event digitisation manager"); TTask *guout = new TTask("guout","Event termination manager"); gtrig->Add(gukine); gtrig->Add(gutrev); gtrig->Add(gudigi); gtrig->Add(guout); TTask *gtreve = new TTask("gtreve","Geant3 event manager"); gutrev->Add(gtreve); TTask *gltrac = new TTask("gltrac","Initialize tracking parameters"); TTask *gftrac = new TTask("gftrac","select next track segment from stack JTRACK"); TTask *gutrak = new TTask("gutrak","Application track manager"); gtreve->Add(gltrac); gtreve->Add(gftrac); gtreve->Add(gutrak); TTask *gtrack = new TTask("gtrack","Geant3 track manager"); gutrak->Add(gtrack); TTask *gtgama = new TTask("gtgama","photon propagator"); TTask *gtelec = new TTask("gtelec","electron propagator"); TTask *gtneut = new TTask("gtneut","neutron propagator"); TTask *gthadr = new TTask("gthadr","hadron propagator"); TTask *gtmuon = new TTask("gtmuon","muon propagator"); TTask *gtnino = new TTask("gtnino","geantino propagator"); TTask *gtckov = new TTask("gtckov","Cherenkov light propagator"); TTask *gthion = new TTask("gthion","heavy ion propagator"); TTask *gustep = new TTask("gustep","Application step manager"); TTask *gtmedi = new TTask("gtmedi","Geometry volume finder"); gtrack->Add(gtgama); gtrack->Add(gtelec); gtrack->Add(gtneut); gtrack->Add(gthadr); gtrack->Add(gtmuon); gtrack->Add(gtnino); gtrack->Add(gtckov); gtrack->Add(gthion); gtrack->Add(gustep); gtrack->Add(gtmedi); TTask *gtnext = new TTask("gtnext","Geometry bounary manager"); TTask *gpairg = new TTask("gpairg","Generate pair production"); TTask *gcomp = new TTask("gcomp","Generate Compton scattering"); TTask *gphot = new TTask("gphot","Generate photo effect"); TTask *grayl = new TTask("grayl","Generate Rayleigh effect"); TTask *gpfis = new TTask("gpfis","Generate photo fission"); gtgama->Add(gtnext); gtgama->Add(gpairg); gtgama->Add(gcomp); gtgama->Add(gphot); gtgama->Add(grayl); gtgama->Add(gpfis); TTask *guswim = new TTask("guswim","magnetic field propagator"); TTask *ggckov = new TTask("ggckov","Generate Cherenkov photons"); TTask *gsync = new TTask("gsync","Generate synchrotron radiation"); TTask *gmults = new TTask("gmults","Apply multiple scattering"); TTask *gbreme = new TTask("gbreme","Generate Bremsstrahlung"); TTask *gdray = new TTask("gdray","Generate delta ray"); TTask *ganni = new TTask("ganni","Generate Positron annihilation"); TTask *gannir = new TTask("gannir","Stopped tracks and annihilation at rest"); gtelec->Add(gtnext); gtelec->Add(guswim); gtelec->Add(ggckov); gtelec->Add(gsync); gtelec->Add(gmults); gtelec->Add(gbreme); gtelec->Add(gdray); gtelec->Add(ganni); gtelec->Add(gannir); TTask *guphad = new TTask("guphad","Hadronic cross-section manager"); TTask *guhadr = new TTask("guhadr","Hadronic cascade manager"); TTask *gdecay = new TTask("gdecay","Particle decay"); gtneut->Add(gtnext); gtneut->Add(guphad); gtneut->Add(guhadr); gtneut->Add(gdecay); gthadr->Add(gtnext); gthadr->Add(guphad); gthadr->Add(guswim); gthadr->Add(ggckov); gthadr->Add(gmults); gthadr->Add(guhadr); gthadr->Add(gdecay); gthadr->Add(gdray); TTask *gbremm = new TTask("gbremm","Generate Bremsstrahlung"); TTask *gpairm = new TTask("gpairm","Generate Pair production"); TTask *gmunu = new TTask("gmunu","Generate Nuclear interaction"); gtmuon->Add(gtnext); gtmuon->Add(guswim); gtmuon->Add(ggckov); gtmuon->Add(gmults); gtmuon->Add(gbremm); gtmuon->Add(gpairm); gtmuon->Add(gdecay); gtmuon->Add(gdray); gtmuon->Add(gmunu); gtmuon->Add(gdecay); gtnino->Add(gtnext); TTask *glisur = new TTask("glisur","Photon is reflected"); gtckov->Add(gtnext); gtckov->Add(glisur); gthion->Add(gtnext); gthion->Add(guswim); gthion->Add(gmults); gthion->Add(guhadr); gthion->Add(gdray); new TBrowser; gDebug = 2; }
karies/root
tutorials/legacy/geant3tasks.C
C++
lgpl-2.1
5,710
//// [classDeclarationBlockScoping1.ts] class C { } { class C { } } //// [classDeclarationBlockScoping1.js] var C = (function () { function C() { } return C; }()); { var C_1 = (function () { function C_1() { } return C_1; }()); }
yortus/TypeScript
tests/baselines/reference/classDeclarationBlockScoping1.js
JavaScript
apache-2.0
300
<?php include ("../jpgraph.php"); include ("../jpgraph_radar.php"); // Some data to plot $data = array(55,80,26,31,95); // Create the graph and the plot $graph = new RadarGraph(250,200,"auto"); // Add a drop shadow to the graph $graph->SetShadow(); // Create the titles for the axis $titles = $gDateLocale->GetShortMonth(); $graph->SetTitles($titles); $graph->SetColor('lightyellow'); // ADjust the position to make more room // for the legend $graph->SetCenter(0.4,0.5); // Add grid lines $graph->grid->Show(); $graph->grid->SetColor('darkred'); $graph->grid->SetLineStyle('dotted'); $plot = new RadarPlot($data); $plot->SetFillColor('lightblue'); $plot->SetLegend("QA results"); // Add the plot and display the graph $graph->Add($plot); $graph->Stroke(); ?>
walterfan/pims4php
util/jpgraph/Examples/radarex6.php
PHP
apache-2.0
769
import os import shutil import tempfile import vmprof import prof_six as six from _prof_imports import TreeStats, CallTreeStat class VmProfProfile(object): """ Wrapper class that represents VmProf Python profiling backend with API matching the cProfile. """ def __init__(self): self.stats = None self.basepath = None self.file = None self.is_enabled = False def runcall(self, func, *args, **kw): self.enable() try: return func(*args, **kw) finally: self.disable() def enable(self): if not self.is_enabled: if not os.path.exists(self.basepath): os.makedirs(self.basepath) self.file = tempfile.NamedTemporaryFile(delete=False, dir=self.basepath) try: vmprof.enable(self.file.fileno(), lines=True) except: vmprof.enable(self.file.fileno()) self.is_enabled = True def disable(self): if self.is_enabled: vmprof.disable() self.file.close() self.is_enabled = False def create_stats(self): return None def getstats(self): self.create_stats() return self.stats def dump_stats(self, file): shutil.copyfile(self.file.name, file) def _walk_tree(self, parent, node, callback): tree = callback(parent, node) for c in six.itervalues(node.children): self._walk_tree(node, c, callback) return tree def tree_stats_to_response(self, filename, response): tree_stats_to_response(filename, response) def snapshot_extension(self): return '.prof' def _walk_tree(parent, node, callback): if node is None: return None tree = callback(parent, node) for c in six.itervalues(node.children): _walk_tree(tree, c, callback) return tree def tree_stats_to_response(filename, response): stats = vmprof.read_profile(filename) response.tree_stats = TreeStats() response.tree_stats.sampling_interval = vmprof.DEFAULT_PERIOD try: tree = stats.get_tree() except vmprof.stats.EmptyProfileFile: tree = None def convert(parent, node): tstats = CallTreeStat() tstats.name = node.name tstats.count = node.count tstats.children = [] tstats.line_count = getattr(node, 'lines', {}) if parent is not None: if parent.children is None: parent.children = [] parent.children.append(tstats) return tstats response.tree_stats.call_tree = _walk_tree(None, tree, convert)
siosio/intellij-community
python/helpers/profiler/vmprof_profiler.py
Python
apache-2.0
2,691
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package apiserver import ( "fmt" "sort" "time" "k8s.io/klog" autoscaling "k8s.io/api/autoscaling/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime/schema" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/version" "k8s.io/apiserver/pkg/endpoints/discovery" "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" informers "k8s.io/apiextensions-apiserver/pkg/client/informers/internalversion/apiextensions/internalversion" listers "k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/internalversion" ) type DiscoveryController struct { versionHandler *versionDiscoveryHandler groupHandler *groupDiscoveryHandler crdLister listers.CustomResourceDefinitionLister crdsSynced cache.InformerSynced // To allow injection for testing. syncFn func(version schema.GroupVersion) error queue workqueue.RateLimitingInterface } func NewDiscoveryController(crdInformer informers.CustomResourceDefinitionInformer, versionHandler *versionDiscoveryHandler, groupHandler *groupDiscoveryHandler) *DiscoveryController { c := &DiscoveryController{ versionHandler: versionHandler, groupHandler: groupHandler, crdLister: crdInformer.Lister(), crdsSynced: crdInformer.Informer().HasSynced, queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "DiscoveryController"), } crdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: c.addCustomResourceDefinition, UpdateFunc: c.updateCustomResourceDefinition, DeleteFunc: c.deleteCustomResourceDefinition, }) c.syncFn = c.sync return c } func (c *DiscoveryController) sync(version schema.GroupVersion) error { apiVersionsForDiscovery := []metav1.GroupVersionForDiscovery{} apiResourcesForDiscovery := []metav1.APIResource{} versionsForDiscoveryMap := map[metav1.GroupVersion]bool{} crds, err := c.crdLister.List(labels.Everything()) if err != nil { return err } foundVersion := false foundGroup := false for _, crd := range crds { if !apiextensions.IsCRDConditionTrue(crd, apiextensions.Established) { continue } if crd.Spec.Group != version.Group { continue } foundThisVersion := false for _, v := range crd.Spec.Versions { if !v.Served { continue } // If there is any Served version, that means the group should show up in discovery foundGroup = true gv := metav1.GroupVersion{Group: crd.Spec.Group, Version: v.Name} if !versionsForDiscoveryMap[gv] { versionsForDiscoveryMap[gv] = true apiVersionsForDiscovery = append(apiVersionsForDiscovery, metav1.GroupVersionForDiscovery{ GroupVersion: crd.Spec.Group + "/" + v.Name, Version: v.Name, }) } if v.Name == version.Version { foundThisVersion = true } } if !foundThisVersion { continue } foundVersion = true verbs := metav1.Verbs([]string{"delete", "deletecollection", "get", "list", "patch", "create", "update", "watch"}) // if we're terminating we don't allow some verbs if apiextensions.IsCRDConditionTrue(crd, apiextensions.Terminating) { verbs = metav1.Verbs([]string{"delete", "deletecollection", "get", "list", "watch"}) } apiResourcesForDiscovery = append(apiResourcesForDiscovery, metav1.APIResource{ Name: crd.Status.AcceptedNames.Plural, SingularName: crd.Status.AcceptedNames.Singular, Namespaced: crd.Spec.Scope == apiextensions.NamespaceScoped, Kind: crd.Status.AcceptedNames.Kind, Verbs: verbs, ShortNames: crd.Status.AcceptedNames.ShortNames, Categories: crd.Status.AcceptedNames.Categories, }) subresources, err := getSubresourcesForVersion(crd, version.Version) if err != nil { return err } if subresources != nil && subresources.Status != nil { apiResourcesForDiscovery = append(apiResourcesForDiscovery, metav1.APIResource{ Name: crd.Status.AcceptedNames.Plural + "/status", Namespaced: crd.Spec.Scope == apiextensions.NamespaceScoped, Kind: crd.Status.AcceptedNames.Kind, Verbs: metav1.Verbs([]string{"get", "patch", "update"}), }) } if subresources != nil && subresources.Scale != nil { apiResourcesForDiscovery = append(apiResourcesForDiscovery, metav1.APIResource{ Group: autoscaling.GroupName, Version: "v1", Kind: "Scale", Name: crd.Status.AcceptedNames.Plural + "/scale", Namespaced: crd.Spec.Scope == apiextensions.NamespaceScoped, Verbs: metav1.Verbs([]string{"get", "patch", "update"}), }) } } if !foundGroup { c.groupHandler.unsetDiscovery(version.Group) c.versionHandler.unsetDiscovery(version) return nil } sortGroupDiscoveryByKubeAwareVersion(apiVersionsForDiscovery) apiGroup := metav1.APIGroup{ Name: version.Group, Versions: apiVersionsForDiscovery, // the preferred versions for a group is the first item in // apiVersionsForDiscovery after it put in the right ordered PreferredVersion: apiVersionsForDiscovery[0], } c.groupHandler.setDiscovery(version.Group, discovery.NewAPIGroupHandler(Codecs, apiGroup)) if !foundVersion { c.versionHandler.unsetDiscovery(version) return nil } c.versionHandler.setDiscovery(version, discovery.NewAPIVersionHandler(Codecs, version, discovery.APIResourceListerFunc(func() []metav1.APIResource { return apiResourcesForDiscovery }))) return nil } func sortGroupDiscoveryByKubeAwareVersion(gd []metav1.GroupVersionForDiscovery) { sort.Slice(gd, func(i, j int) bool { return version.CompareKubeAwareVersionStrings(gd[i].Version, gd[j].Version) > 0 }) } func (c *DiscoveryController) Run(stopCh <-chan struct{}) { defer utilruntime.HandleCrash() defer c.queue.ShutDown() defer klog.Infof("Shutting down DiscoveryController") klog.Infof("Starting DiscoveryController") if !cache.WaitForCacheSync(stopCh, c.crdsSynced) { utilruntime.HandleError(fmt.Errorf("timed out waiting for caches to sync")) return } // only start one worker thread since its a slow moving API go wait.Until(c.runWorker, time.Second, stopCh) <-stopCh } func (c *DiscoveryController) runWorker() { for c.processNextWorkItem() { } } // processNextWorkItem deals with one key off the queue. It returns false when it's time to quit. func (c *DiscoveryController) processNextWorkItem() bool { key, quit := c.queue.Get() if quit { return false } defer c.queue.Done(key) err := c.syncFn(key.(schema.GroupVersion)) if err == nil { c.queue.Forget(key) return true } utilruntime.HandleError(fmt.Errorf("%v failed with: %v", key, err)) c.queue.AddRateLimited(key) return true } func (c *DiscoveryController) enqueue(obj *apiextensions.CustomResourceDefinition) { for _, v := range obj.Spec.Versions { c.queue.Add(schema.GroupVersion{Group: obj.Spec.Group, Version: v.Name}) } } func (c *DiscoveryController) addCustomResourceDefinition(obj interface{}) { castObj := obj.(*apiextensions.CustomResourceDefinition) klog.V(4).Infof("Adding customresourcedefinition %s", castObj.Name) c.enqueue(castObj) } func (c *DiscoveryController) updateCustomResourceDefinition(oldObj, newObj interface{}) { castNewObj := newObj.(*apiextensions.CustomResourceDefinition) castOldObj := oldObj.(*apiextensions.CustomResourceDefinition) klog.V(4).Infof("Updating customresourcedefinition %s", castOldObj.Name) // Enqueue both old and new object to make sure we remove and add appropriate Versions. // The working queue will resolve any duplicates and only changes will stay in the queue. c.enqueue(castNewObj) c.enqueue(castOldObj) } func (c *DiscoveryController) deleteCustomResourceDefinition(obj interface{}) { castObj, ok := obj.(*apiextensions.CustomResourceDefinition) if !ok { tombstone, ok := obj.(cache.DeletedFinalStateUnknown) if !ok { klog.Errorf("Couldn't get object from tombstone %#v", obj) return } castObj, ok = tombstone.Obj.(*apiextensions.CustomResourceDefinition) if !ok { klog.Errorf("Tombstone contained object that is not expected %#v", obj) return } } klog.V(4).Infof("Deleting customresourcedefinition %q", castObj.Name) c.enqueue(castObj) }
sferich888/origin
vendor/k8s.io/kubernetes/staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery_controller.go
GO
apache-2.0
8,881
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring; import com.intellij.CommonBundle; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.PropertyKey; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.ResourceBundle; /** * @author ven */ public class RefactoringBundle { public static String message(@NotNull @PropertyKey(resourceBundle = BUNDLE) String key, @NotNull Object... params) { return CommonBundle.message(getBundle(), key, params); } private static Reference<ResourceBundle> ourBundle; @NonNls private static final String BUNDLE = "messages.RefactoringBundle"; private RefactoringBundle() { } public static String getSearchInCommentsAndStringsText() { return message("search.in.comments.and.strings"); } public static String getSearchForTextOccurrencesText() { return message("search.for.text.occurrences"); } public static String getVisibilityPackageLocal() { return message("visibility.package.local"); } public static String getVisibilityPrivate() { return message("visibility.private"); } public static String getVisibilityProtected() { return message("visibility.protected"); } public static String getVisibilityPublic() { return message("visibility.public"); } public static String getVisibilityAsIs() { return message("visibility.as.is"); } public static String getEscalateVisibility() { return message("visibility.escalate"); } public static String getCannotRefactorMessage(@Nullable final String message) { return message("cannot.perform.refactoring") + (message == null ? "" : "\n" + message); } public static String message(@PropertyKey(resourceBundle = BUNDLE) String key) { return CommonBundle.message(getBundle(), key); } private static ResourceBundle getBundle() { ResourceBundle bundle = com.intellij.reference.SoftReference.dereference(ourBundle); if (bundle == null) { bundle = ResourceBundle.getBundle(BUNDLE); ourBundle = new SoftReference<>(bundle); } return bundle; } }
idea4bsd/idea4bsd
platform/lang-api/src/com/intellij/refactoring/RefactoringBundle.java
Java
apache-2.0
2,776
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.elasticbeanstalk.model; import java.io.Serializable; /** * <p> * Describes the properties of an application version. * </p> */ public class ApplicationVersionDescription implements Serializable, Cloneable { /** * <p> * The name of the application associated with this release. * </p> */ private String applicationName; /** * <p> * The description of this application version. * </p> */ private String description; /** * <p> * A label uniquely identifying the version for the associated application. * </p> */ private String versionLabel; /** * <p> * The location where the source bundle is located for this version. * </p> */ private S3Location sourceBundle; /** * <p> * The creation date of the application version. * </p> */ private java.util.Date dateCreated; /** * <p> * The last modified date of the application version. * </p> */ private java.util.Date dateUpdated; /** * <p> * The name of the application associated with this release. * </p> * * @param applicationName * The name of the application associated with this release. */ public void setApplicationName(String applicationName) { this.applicationName = applicationName; } /** * <p> * The name of the application associated with this release. * </p> * * @return The name of the application associated with this release. */ public String getApplicationName() { return this.applicationName; } /** * <p> * The name of the application associated with this release. * </p> * * @param applicationName * The name of the application associated with this release. * @return Returns a reference to this object so that method calls can be * chained together. */ public ApplicationVersionDescription withApplicationName( String applicationName) { setApplicationName(applicationName); return this; } /** * <p> * The description of this application version. * </p> * * @param description * The description of this application version. */ public void setDescription(String description) { this.description = description; } /** * <p> * The description of this application version. * </p> * * @return The description of this application version. */ public String getDescription() { return this.description; } /** * <p> * The description of this application version. * </p> * * @param description * The description of this application version. * @return Returns a reference to this object so that method calls can be * chained together. */ public ApplicationVersionDescription withDescription(String description) { setDescription(description); return this; } /** * <p> * A label uniquely identifying the version for the associated application. * </p> * * @param versionLabel * A label uniquely identifying the version for the associated * application. */ public void setVersionLabel(String versionLabel) { this.versionLabel = versionLabel; } /** * <p> * A label uniquely identifying the version for the associated application. * </p> * * @return A label uniquely identifying the version for the associated * application. */ public String getVersionLabel() { return this.versionLabel; } /** * <p> * A label uniquely identifying the version for the associated application. * </p> * * @param versionLabel * A label uniquely identifying the version for the associated * application. * @return Returns a reference to this object so that method calls can be * chained together. */ public ApplicationVersionDescription withVersionLabel(String versionLabel) { setVersionLabel(versionLabel); return this; } /** * <p> * The location where the source bundle is located for this version. * </p> * * @param sourceBundle * The location where the source bundle is located for this version. */ public void setSourceBundle(S3Location sourceBundle) { this.sourceBundle = sourceBundle; } /** * <p> * The location where the source bundle is located for this version. * </p> * * @return The location where the source bundle is located for this version. */ public S3Location getSourceBundle() { return this.sourceBundle; } /** * <p> * The location where the source bundle is located for this version. * </p> * * @param sourceBundle * The location where the source bundle is located for this version. * @return Returns a reference to this object so that method calls can be * chained together. */ public ApplicationVersionDescription withSourceBundle( S3Location sourceBundle) { setSourceBundle(sourceBundle); return this; } /** * <p> * The creation date of the application version. * </p> * * @param dateCreated * The creation date of the application version. */ public void setDateCreated(java.util.Date dateCreated) { this.dateCreated = dateCreated; } /** * <p> * The creation date of the application version. * </p> * * @return The creation date of the application version. */ public java.util.Date getDateCreated() { return this.dateCreated; } /** * <p> * The creation date of the application version. * </p> * * @param dateCreated * The creation date of the application version. * @return Returns a reference to this object so that method calls can be * chained together. */ public ApplicationVersionDescription withDateCreated( java.util.Date dateCreated) { setDateCreated(dateCreated); return this; } /** * <p> * The last modified date of the application version. * </p> * * @param dateUpdated * The last modified date of the application version. */ public void setDateUpdated(java.util.Date dateUpdated) { this.dateUpdated = dateUpdated; } /** * <p> * The last modified date of the application version. * </p> * * @return The last modified date of the application version. */ public java.util.Date getDateUpdated() { return this.dateUpdated; } /** * <p> * The last modified date of the application version. * </p> * * @param dateUpdated * The last modified date of the application version. * @return Returns a reference to this object so that method calls can be * chained together. */ public ApplicationVersionDescription withDateUpdated( java.util.Date dateUpdated) { setDateUpdated(dateUpdated); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getApplicationName() != null) sb.append("ApplicationName: " + getApplicationName() + ","); if (getDescription() != null) sb.append("Description: " + getDescription() + ","); if (getVersionLabel() != null) sb.append("VersionLabel: " + getVersionLabel() + ","); if (getSourceBundle() != null) sb.append("SourceBundle: " + getSourceBundle() + ","); if (getDateCreated() != null) sb.append("DateCreated: " + getDateCreated() + ","); if (getDateUpdated() != null) sb.append("DateUpdated: " + getDateUpdated()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ApplicationVersionDescription == false) return false; ApplicationVersionDescription other = (ApplicationVersionDescription) obj; if (other.getApplicationName() == null ^ this.getApplicationName() == null) return false; if (other.getApplicationName() != null && other.getApplicationName().equals(this.getApplicationName()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getVersionLabel() == null ^ this.getVersionLabel() == null) return false; if (other.getVersionLabel() != null && other.getVersionLabel().equals(this.getVersionLabel()) == false) return false; if (other.getSourceBundle() == null ^ this.getSourceBundle() == null) return false; if (other.getSourceBundle() != null && other.getSourceBundle().equals(this.getSourceBundle()) == false) return false; if (other.getDateCreated() == null ^ this.getDateCreated() == null) return false; if (other.getDateCreated() != null && other.getDateCreated().equals(this.getDateCreated()) == false) return false; if (other.getDateUpdated() == null ^ this.getDateUpdated() == null) return false; if (other.getDateUpdated() != null && other.getDateUpdated().equals(this.getDateUpdated()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getApplicationName() == null) ? 0 : getApplicationName() .hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getVersionLabel() == null) ? 0 : getVersionLabel() .hashCode()); hashCode = prime * hashCode + ((getSourceBundle() == null) ? 0 : getSourceBundle() .hashCode()); hashCode = prime * hashCode + ((getDateCreated() == null) ? 0 : getDateCreated().hashCode()); hashCode = prime * hashCode + ((getDateUpdated() == null) ? 0 : getDateUpdated().hashCode()); return hashCode; } @Override public ApplicationVersionDescription clone() { try { return (ApplicationVersionDescription) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
sheofir/aws-sdk-java
aws-java-sdk-elasticbeanstalk/src/main/java/com/amazonaws/services/elasticbeanstalk/model/ApplicationVersionDescription.java
Java
apache-2.0
12,433
// Generated by CoffeeScript 1.4.0 (function() { "use strict"; var UserCommand, exports, _ref, __slice = [].slice; var exports = (_ref = window.chat) != null ? _ref : window.chat = {}; /* * Represents a user command, like /kick or /say. */ UserCommand = (function() { function UserCommand(name, description) { this.description = description; this.name = name; this.describe(this.description); this._hasValidArgs = false; } /* * Describe the command using the following format: * * description - a description of what the command does; used with /help * <command> * * category - what category the command falls under. This is used with /help * * params - what parameters the command takes, 'opt_<name>' for optional, * '<name>...' for variable *## * * validateArgs - returns a truthy variable if the given arguments are valid. * * requires - what the command requires to run (e.g. a connections to an IRC * server) * * usage - manually set a usage message, one will be generated if not specified * * run - the function to call when the command is run */ UserCommand.prototype.describe = function(description) { var _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7; if ((_ref1 = this._description) == null) { this._description = description.description; } if ((_ref2 = this._params) == null) { this._params = description.params; } if ((_ref3 = this._requires) == null) { this._requires = description.requires; } if ((_ref4 = this._validateArgs) == null) { this._validateArgs = description.validateArgs; } if ((_ref5 = this._usage) == null) { this._usage = description.usage; } if ((_ref6 = this.run) == null) { this.run = description.run; } return (_ref7 = this.category) != null ? _ref7 : this.category = description.category; }; /* * Try running the command. A command can fail to run if its requirements * aren't met (e.g. needs a connection to the internet) or the specified * arguments are invalid. In these cases a help message is displayed. * @param {Context} context Which server/channel the command came from. * @param {Object...} args Arguments for the command. */ UserCommand.prototype.tryToRun = function() { var args, context; context = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; this.setContext(context); if (!this.canRun()) { if (this.shouldDisplayFailedToRunMessage()) { this.displayHelp(); } return; } this.setArgs.apply(this, args); if (this._hasValidArgs) { return this.run(); } else { return this.displayHelp(); } }; UserCommand.prototype.setChat = function(chat) { this.chat = chat; }; UserCommand.prototype.setContext = function(context) { this.win = this.chat.determineWindow(context); if (this.win !== window.chat.NO_WINDOW) { this.conn = this.win.conn; return this.chan = this.win.target; } }; UserCommand.prototype.setArgs = function() { var args; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; return this._hasValidArgs = this._tryToAssignArgs(args) && (!this._validateArgs || !!this._validateArgs()); }; UserCommand.prototype._tryToAssignArgs = function(args) { var i, param, params, _i, _len; this.args = []; this._removeTrailingWhiteSpace(args); if (!this._params) { return args.length === 0; } this._resetParams(); this._truncateVariableArgs(args); params = this._truncateExtraOptionalParams(args.length); if (args.length !== params.length) { return false; } for (i = _i = 0, _len = params.length; _i < _len; i = ++_i) { param = params[i]; this[this._getParamName(param)] = args[i]; } this.args = args; return true; }; UserCommand.prototype._resetParams = function() { var param, _i, _len, _ref1, _results; _ref1 = this._params; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { param = _ref1[_i]; _results.push(this[this._getParamName(param)] = void 0); } return _results; }; UserCommand.prototype._removeTrailingWhiteSpace = function(args) { var i, _i, _ref1, _results; _results = []; for (i = _i = _ref1 = args.length - 1; _ref1 <= 0 ? _i <= 0 : _i >= 0; i = _ref1 <= 0 ? ++_i : --_i) { if (args[i] === '') { _results.push(args.splice(i, 1)); } else { break; } } return _results; }; /* * Join all arguments that fit under the variable argument param. * Note: only the last argument is allowd to be variable. */ UserCommand.prototype._truncateVariableArgs = function(args) { var _ref1; if (args.length < this._params.length) { return args; } if (this._isVariable(this._params[this._params.length - 1])) { args[this._params.length - 1] = (_ref1 = args.slice(this._params.length - 1)) != null ? _ref1.join(' ') : void 0; return args.length = this._params.length; } }; UserCommand.prototype._truncateExtraOptionalParams = function(numArgs) { var extraParams, i, param, params, _i, _ref1; extraParams = this._params.length - numArgs; if (extraParams <= 0) { return this._params; } params = []; for (i = _i = _ref1 = this._params.length - 1; _ref1 <= 0 ? _i <= 0 : _i >= 0; i = _ref1 <= 0 ? ++_i : --_i) { param = this._params[i]; if (extraParams > 0 && this._isOptional(param)) { extraParams--; } else { params.splice(0, 0, param); } } return params; }; /* * When a command can't run, determine if a helpful message should be * displayed to the user. */ UserCommand.prototype.shouldDisplayFailedToRunMessage = function() { if (this.win === window.chat.NO_WINDOW) { return false; } return this.name !== 'say'; }; /* * Commands can only run if their requirements are met (e.g. connected to the * internet, in a channel, etc) and a run method is defined. */ UserCommand.prototype.canRun = function(opt_context) { var requirement, _i, _len, _ref1; if (opt_context) { this.setContext(opt_context); } if (!this.run) { return false; } if (!this._requires) { return true; } _ref1 = this._requires; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { requirement = _ref1[_i]; if (!this._meetsRequirement(requirement)) { return false; } } return true; }; UserCommand.prototype._meetsRequirement = function(requirement) { var _ref1; switch (requirement) { case 'online': return isOnline(); case 'connection': return !!this.conn && isOnline(); case 'channel': return !!this.chan; default: return ((_ref1 = this.conn) != null ? _ref1.irc.state : void 0) === requirement; } }; UserCommand.prototype.displayHelp = function(win) { if (win == null) { win = this.win; } return win.message('', html.escape(this.getHelp()), 'notice help'); }; UserCommand.prototype.getHelp = function() { var descriptionText, usageText, _ref1; descriptionText = this._description ? ", " + this._description : ''; if (this._usage) { usageText = ' ' + this._usage; } if (usageText == null) { usageText = ((_ref1 = this._params) != null ? _ref1.length : void 0) > 0 ? " " + (this._getUsage()) : ''; } return this.name.toUpperCase() + usageText + descriptionText + '.'; }; UserCommand.prototype._getUsage = function() { var param, paramDescription, paramName, _i, _len, _ref1; paramDescription = []; _ref1 = this._params; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { param = _ref1[_i]; paramName = this._getParamName(param); if (this._isOptional(param)) { paramName = "[" + paramName + "]"; } else { paramName = "<" + paramName + ">"; } paramDescription.push(paramName); } return paramDescription.join(' '); }; UserCommand.prototype._getParamName = function(param) { if (this._isOptional(param)) { param = param.slice(4); } if (this._isVariable(param)) { param = param.slice(0, +(param.length - 4) + 1 || 9e9); } return param; }; UserCommand.prototype._isOptional = function(param) { return param.indexOf('opt_') === 0; }; UserCommand.prototype._isVariable = function(param) { return (param != null ? param.slice(param.length - 3) : void 0) === '...'; }; UserCommand.prototype.isOwnNick = function(nick) { var _ref1; if (nick == null) { nick = this.nick; } return irc.util.nicksEqual((_ref1 = this.conn) != null ? _ref1.irc.nick : void 0, nick); }; UserCommand.prototype.displayDirectMessage = function(nick, message) { var _ref1; if (nick == null) { nick = this.nick; } if (message == null) { message = this.message; } if (((_ref1 = this.conn) != null ? _ref1.windows[nick] : void 0) != null) { return this._displayDirectMessageInPrivateChannel(nick, message); } else { return this._displayDirectMessageInline(nick, message); } }; /* * Used with /msg. Displays the message in a private channel. */ UserCommand.prototype._displayDirectMessageInPrivateChannel = function(nick, message) { var context; context = { server: this.conn.name, channel: nick }; return this.chat.displayMessage('privmsg', context, this.conn.irc.nick, message); }; /* * Used with /msg. Displays the private message in the current window. * Direct messages always display inline until the user receives a response. */ UserCommand.prototype._displayDirectMessageInline = function(nick, message) { return this.displayMessageWithStyle('privmsg', nick, message, 'direct'); }; UserCommand.prototype.displayMessage = function() { var args, context, type, _ref1, _ref2; type = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; context = { server: (_ref1 = this.conn) != null ? _ref1.name : void 0, channel: this.chan }; return (_ref2 = this.chat).displayMessage.apply(_ref2, [type, context].concat(__slice.call(args))); }; /* * Displays a message with a custom style. This is useful for indicating that * a message be rendered in a special way (e.g. no pretty formatting). */ UserCommand.prototype.displayMessageWithStyle = function() { var args, e, style, type, _i, _ref1; type = arguments[0], args = 3 <= arguments.length ? __slice.call(arguments, 1, _i = arguments.length - 1) : (_i = 1, []), style = arguments[_i++]; e = (function(func, args, ctor) { ctor.prototype = func.prototype; var child = new ctor, result = func.apply(child, args); return Object(result) === result ? result : child; })(Event, ['message', type].concat(__slice.call(args)), function(){}); e.setContext((_ref1 = this.conn) != null ? _ref1.name : void 0, this.chan); e.addStyle(style); return this.chat.emit(e.type, e); }; UserCommand.prototype.handleCTCPRequest = function(nick, type) { var delimiter, message; this.displayDirectMessage(nick, "CTCP " + type); delimiter = irc.CTCPHandler.DELIMITER; message = delimiter + type + delimiter; return this.conn.irc.doCommand('PRIVMSG', nick, message); }; /* * Used to set the arguments for MODE shortcut commands. * @param {string} type E.g. /op, /voice, etc. */ UserCommand.prototype.setModeArgs = function(type) { this.nicks = [this.nick]; this.target = this.chan; return this.mode = type; }; /* * Determine if the given string is a valid mode expression. * TODO: This can be improved. (e.g. ++ and +a++ shouldn't be valid) * @param {string} mode E.g. +o, -o, +v, etc. */ UserCommand.prototype.isValidMode = function(mode) { var _ref1; return (_ref1 = mode != null ? mode[0] : void 0) === '+' || _ref1 === '-'; }; UserCommand.prototype.listInstalledScripts = function() { var names; names = this.chat.scriptHandler.getScriptNames(); if (names.length === 0) { return "No scripts are currently installed"; } else { return "Installed scripts: " + (getReadableList(names)); } }; return UserCommand; })(); exports.UserCommand = UserCommand; }).call(this);
wikijoss/circ
package/bin/chat/user_command.js
JavaScript
bsd-3-clause
13,369
import { CSSModule } from '../index'; export interface CardDeckProps extends React.HTMLAttributes<HTMLElement> { tag?: React.ReactType; className?: string; cssModule?: CSSModule; } declare const CardDeck: React.StatelessComponent<CardDeckProps>; export default CardDeck;
laurentiustamate94/DefinitelyTyped
types/reactstrap/lib/CardDeck.d.ts
TypeScript
mit
279
/*++ Copyright (c) 2012 Microsoft Corporation Module Name: FiniteDomainSort.cs Abstract: Z3 Managed API: Finite Domain Sorts Author: Christoph Wintersteiger (cwinter) 2012-11-23 Notes: --*/ using System; using System.Diagnostics.Contracts; namespace Microsoft.Z3 { /// <summary> /// Finite domain sorts. /// </summary> [ContractVerification(true)] public class FiniteDomainSort : Sort { /// <summary> /// The size of the finite domain sort. /// </summary> public ulong Size { get { ulong res = 0; Native.Z3_get_finite_domain_sort_size(Context.nCtx, NativeObject, ref res); return res; } } #region Internal internal FiniteDomainSort(Context ctx, IntPtr obj) : base(ctx, obj) { Contract.Requires(ctx != null); } internal FiniteDomainSort(Context ctx, Symbol name, ulong size) : base(ctx, Native.Z3_mk_finite_domain_sort(ctx.nCtx, name.NativeObject, size)) { Contract.Requires(ctx != null); Contract.Requires(name != null); } #endregion } }
Drup/z3
src/api/dotnet/FiniteDomainSort.cs
C#
mit
1,253
(function (factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof module === 'object' && typeof module.exports === 'object') { factory(require('jquery')); } else { factory(jQuery); } }(function (jQuery) { // Amharic jQuery.timeago.settings.strings = { prefixAgo: null, prefixFromNow: null, suffixAgo: "በፊት", suffixFromNow: "በኋላ", seconds: "ከአንድ ደቂቃ በታች", minute: "ከአንድ ደቂቃ ገደማ", minutes: "ከ%d ደቂቃ", hour: "ከአንድ ሰዓት ገደማ", hours: "ከ%d ሰዓት ገደማ", day: "ከአንድ ቀን", days: "ከ%d ቀን", month: "ከአንድ ወር ገደማ", months: "ከ%d ወር", year: "ከአንድ ዓመት ገደማ", years: "ከ%d ዓመት", wordSeparator: " ", numbers: [] }; }));
xin2015/DataCenter
src/DataCenter.Web/wwwroot/libs/timeago/locales/jquery.timeago.am.js
JavaScript
mit
906
import { changeProperties } from './property_events'; import { set } from './property_set'; /** Set a list of properties on an object. These properties are set inside a single `beginPropertyChanges` and `endPropertyChanges` batch, so observers will be buffered. ```javascript let anObject = Ember.Object.create(); anObject.setProperties({ firstName: 'Stanley', lastName: 'Stuart', age: 21 }); ``` @method setProperties @param obj @param {Object} properties @return properties @public */ export default function setProperties(obj, properties) { if (!properties || typeof properties !== 'object') { return properties; } changeProperties(() => { let props = Object.keys(properties); let propertyName; for (let i = 0; i < props.length; i++) { propertyName = props[i]; set(obj, propertyName, properties[propertyName]); } }); return properties; }
jherdman/ember.js
packages/ember-metal/lib/set_properties.js
JavaScript
mit
921
/* * JsSIP v3.0.2 * the Javascript SIP library * Copyright: 2012-2017 José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan) * Homepage: http://jssip.net * License: MIT */ (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.JsSIP = 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){ var pkg = require('../package.json'); var C = { USER_AGENT: pkg.title + ' ' + pkg.version, // SIP scheme SIP: 'sip', SIPS: 'sips', // End and Failure causes causes: { // Generic error causes CONNECTION_ERROR: 'Connection Error', REQUEST_TIMEOUT: 'Request Timeout', SIP_FAILURE_CODE: 'SIP Failure Code', INTERNAL_ERROR: 'Internal Error', // SIP error causes BUSY: 'Busy', REJECTED: 'Rejected', REDIRECTED: 'Redirected', UNAVAILABLE: 'Unavailable', NOT_FOUND: 'Not Found', ADDRESS_INCOMPLETE: 'Address Incomplete', INCOMPATIBLE_SDP: 'Incompatible SDP', MISSING_SDP: 'Missing SDP', AUTHENTICATION_ERROR: 'Authentication Error', // Session error causes BYE: 'Terminated', WEBRTC_ERROR: 'WebRTC Error', CANCELED: 'Canceled', NO_ANSWER: 'No Answer', EXPIRES: 'Expires', NO_ACK: 'No ACK', DIALOG_ERROR: 'Dialog Error', USER_DENIED_MEDIA_ACCESS: 'User Denied Media Access', BAD_MEDIA_DESCRIPTION: 'Bad Media Description', RTP_TIMEOUT: 'RTP Timeout' }, SIP_ERROR_CAUSES: { REDIRECTED: [300,301,302,305,380], BUSY: [486,600], REJECTED: [403,603], NOT_FOUND: [404,604], UNAVAILABLE: [480,410,408,430], ADDRESS_INCOMPLETE: [484, 424], INCOMPATIBLE_SDP: [488,606], AUTHENTICATION_ERROR:[401,407] }, // SIP Methods ACK: 'ACK', BYE: 'BYE', CANCEL: 'CANCEL', INFO: 'INFO', INVITE: 'INVITE', MESSAGE: 'MESSAGE', NOTIFY: 'NOTIFY', OPTIONS: 'OPTIONS', REGISTER: 'REGISTER', REFER: 'REFER', UPDATE: 'UPDATE', SUBSCRIBE: 'SUBSCRIBE', /* SIP Response Reasons * DOC: http://www.iana.org/assignments/sip-parameters * Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7 */ REASON_PHRASE: { 100: 'Trying', 180: 'Ringing', 181: 'Call Is Being Forwarded', 182: 'Queued', 183: 'Session Progress', 199: 'Early Dialog Terminated', // draft-ietf-sipcore-199 200: 'OK', 202: 'Accepted', // RFC 3265 204: 'No Notification', //RFC 5839 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Moved Temporarily', 305: 'Use Proxy', 380: 'Alternative Service', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 410: 'Gone', 412: 'Conditional Request Failed', // RFC 3903 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Unsupported URI Scheme', 417: 'Unknown Resource-Priority', // RFC 4412 420: 'Bad Extension', 421: 'Extension Required', 422: 'Session Interval Too Small', // RFC 4028 423: 'Interval Too Brief', 424: 'Bad Location Information', // RFC 6442 428: 'Use Identity Header', // RFC 4474 429: 'Provide Referrer Identity', // RFC 3892 430: 'Flow Failed', // RFC 5626 433: 'Anonymity Disallowed', // RFC 5079 436: 'Bad Identity-Info', // RFC 4474 437: 'Unsupported Certificate', // RFC 4744 438: 'Invalid Identity Header', // RFC 4744 439: 'First Hop Lacks Outbound Support', // RFC 5626 440: 'Max-Breadth Exceeded', // RFC 5393 469: 'Bad Info Package', // draft-ietf-sipcore-info-events 470: 'Consent Needed', // RFC 5360 478: 'Unresolvable Destination', // Custom code copied from Kamailio. 480: 'Temporarily Unavailable', 481: 'Call/Transaction Does Not Exist', 482: 'Loop Detected', 483: 'Too Many Hops', 484: 'Address Incomplete', 485: 'Ambiguous', 486: 'Busy Here', 487: 'Request Terminated', 488: 'Not Acceptable Here', 489: 'Bad Event', // RFC 3265 491: 'Request Pending', 493: 'Undecipherable', 494: 'Security Agreement Required', // RFC 3329 500: 'JsSIP Internal Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Server Time-out', 505: 'Version Not Supported', 513: 'Message Too Large', 580: 'Precondition Failure', // RFC 3312 600: 'Busy Everywhere', 603: 'Decline', 604: 'Does Not Exist Anywhere', 606: 'Not Acceptable' }, ALLOWED_METHODS: 'INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO', ACCEPTED_BODY_TYPES: 'application/sdp, application/dtmf-relay', MAX_FORWARDS: 69, SESSION_EXPIRES: 90, MIN_SESSION_EXPIRES: 60 }; module.exports = C; },{"../package.json":50}],2:[function(require,module,exports){ module.exports = Dialog; var C = { // Dialog states STATUS_EARLY: 1, STATUS_CONFIRMED: 2 }; /** * Expose C object. */ Dialog.C = C; /** * Dependencies. */ var debug = require('debug')('JsSIP:Dialog'); var SIPMessage = require('./SIPMessage'); var JsSIP_C = require('./Constants'); var Transactions = require('./Transactions'); var Dialog_RequestSender = require('./Dialog/RequestSender'); // RFC 3261 12.1 function Dialog(owner, message, type, state) { var contact; this.uac_pending_reply = false; this.uas_pending_reply = false; if(!message.hasHeader('contact')) { return { error: 'unable to create a Dialog without Contact header field' }; } if(message instanceof SIPMessage.IncomingResponse) { state = (message.status_code < 200) ? C.STATUS_EARLY : C.STATUS_CONFIRMED; } else { // Create confirmed dialog if state is not defined state = state || C.STATUS_CONFIRMED; } contact = message.parseHeader('contact'); // RFC 3261 12.1.1 if(type === 'UAS') { this.id = { call_id: message.call_id, local_tag: message.to_tag, remote_tag: message.from_tag, toString: function() { return this.call_id + this.local_tag + this.remote_tag; } }; this.state = state; this.remote_seqnum = message.cseq; this.local_uri = message.parseHeader('to').uri; this.remote_uri = message.parseHeader('from').uri; this.remote_target = contact.uri; this.route_set = message.getHeaders('record-route'); } // RFC 3261 12.1.2 else if(type === 'UAC') { this.id = { call_id: message.call_id, local_tag: message.from_tag, remote_tag: message.to_tag, toString: function() { return this.call_id + this.local_tag + this.remote_tag; } }; this.state = state; this.local_seqnum = message.cseq; this.local_uri = message.parseHeader('from').uri; this.remote_uri = message.parseHeader('to').uri; this.remote_target = contact.uri; this.route_set = message.getHeaders('record-route').reverse(); } this.owner = owner; owner.ua.dialogs[this.id.toString()] = this; debug('new ' + type + ' dialog created with status ' + (this.state === C.STATUS_EARLY ? 'EARLY': 'CONFIRMED')); } Dialog.prototype = { update: function(message, type) { this.state = C.STATUS_CONFIRMED; debug('dialog '+ this.id.toString() +' changed to CONFIRMED state'); if(type === 'UAC') { // RFC 3261 13.2.2.4 this.route_set = message.getHeaders('record-route').reverse(); } }, terminate: function() { debug('dialog ' + this.id.toString() + ' deleted'); delete this.owner.ua.dialogs[this.id.toString()]; }, // RFC 3261 12.2.1.1 createRequest: function(method, extraHeaders, body) { var cseq, request; extraHeaders = extraHeaders && extraHeaders.slice() || []; if(!this.local_seqnum) { this.local_seqnum = Math.floor(Math.random() * 10000); } cseq = (method === JsSIP_C.CANCEL || method === JsSIP_C.ACK) ? this.local_seqnum : this.local_seqnum += 1; request = new SIPMessage.OutgoingRequest( method, this.remote_target, this.owner.ua, { 'cseq': cseq, 'call_id': this.id.call_id, 'from_uri': this.local_uri, 'from_tag': this.id.local_tag, 'to_uri': this.remote_uri, 'to_tag': this.id.remote_tag, 'route_set': this.route_set }, extraHeaders, body); request.dialog = this; return request; }, // RFC 3261 12.2.2 checkInDialogRequest: function(request) { var self = this; if(!this.remote_seqnum) { this.remote_seqnum = request.cseq; } else if(request.cseq < this.remote_seqnum) { //Do not try to reply to an ACK request. if (request.method !== JsSIP_C.ACK) { request.reply(500); } return false; } else if(request.cseq > this.remote_seqnum) { this.remote_seqnum = request.cseq; } // RFC3261 14.2 Modifying an Existing Session -UAS BEHAVIOR- if (request.method === JsSIP_C.INVITE || (request.method === JsSIP_C.UPDATE && request.body)) { if (this.uac_pending_reply === true) { request.reply(491); } else if (this.uas_pending_reply === true) { var retryAfter = (Math.random() * 10 | 0) + 1; request.reply(500, null, ['Retry-After:'+ retryAfter]); return false; } else { this.uas_pending_reply = true; request.server_transaction.on('stateChanged', function stateChanged(){ if (this.state === Transactions.C.STATUS_ACCEPTED || this.state === Transactions.C.STATUS_COMPLETED || this.state === Transactions.C.STATUS_TERMINATED) { request.server_transaction.removeListener('stateChanged', stateChanged); self.uas_pending_reply = false; } }); } // RFC3261 12.2.2 Replace the dialog`s remote target URI if the request is accepted if(request.hasHeader('contact')) { request.server_transaction.on('stateChanged', function(){ if (this.state === Transactions.C.STATUS_ACCEPTED) { self.remote_target = request.parseHeader('contact').uri; } }); } } else if (request.method === JsSIP_C.NOTIFY) { // RFC6665 3.2 Replace the dialog`s remote target URI if the request is accepted if(request.hasHeader('contact')) { request.server_transaction.on('stateChanged', function(){ if (this.state === Transactions.C.STATUS_COMPLETED) { self.remote_target = request.parseHeader('contact').uri; } }); } } return true; }, sendRequest: function(applicant, method, options) { options = options || {}; var extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body || null, request = this.createRequest(method, extraHeaders, body), request_sender = new Dialog_RequestSender(this, applicant, request); request_sender.send(); // Return the instance of OutgoingRequest return request; }, receiveRequest: function(request) { //Check in-dialog request if(!this.checkInDialogRequest(request)) { return; } this.owner.receiveRequest(request); } }; },{"./Constants":1,"./Dialog/RequestSender":3,"./SIPMessage":18,"./Transactions":21,"debug":34}],3:[function(require,module,exports){ module.exports = DialogRequestSender; /** * Dependencies. */ var JsSIP_C = require('../Constants'); var Transactions = require('../Transactions'); var RTCSession = require('../RTCSession'); var RequestSender = require('../RequestSender'); function DialogRequestSender(dialog, applicant, request) { this.dialog = dialog; this.applicant = applicant; this.request = request; // RFC3261 14.1 Modifying an Existing Session. UAC Behavior. this.reattempt = false; this.reattemptTimer = null; } DialogRequestSender.prototype = { send: function() { var self = this, request_sender = new RequestSender(this, this.dialog.owner.ua); request_sender.send(); // RFC3261 14.2 Modifying an Existing Session -UAC BEHAVIOR- if ((this.request.method === JsSIP_C.INVITE || (this.request.method === JsSIP_C.UPDATE && this.request.body)) && request_sender.clientTransaction.state !== Transactions.C.STATUS_TERMINATED) { this.dialog.uac_pending_reply = true; request_sender.clientTransaction.on('stateChanged', function stateChanged(){ if (this.state === Transactions.C.STATUS_ACCEPTED || this.state === Transactions.C.STATUS_COMPLETED || this.state === Transactions.C.STATUS_TERMINATED) { request_sender.clientTransaction.removeListener('stateChanged', stateChanged); self.dialog.uac_pending_reply = false; } }); } }, onRequestTimeout: function() { this.applicant.onRequestTimeout(); }, onTransportError: function() { this.applicant.onTransportError(); }, receiveResponse: function(response) { var self = this; // RFC3261 12.2.1.2 408 or 481 is received for a request within a dialog. if (response.status_code === 408 || response.status_code === 481) { this.applicant.onDialogError(response); } else if (response.method === JsSIP_C.INVITE && response.status_code === 491) { if (this.reattempt) { this.applicant.receiveResponse(response); } else { this.request.cseq.value = this.dialog.local_seqnum += 1; this.reattemptTimer = setTimeout(function() { if (self.applicant.owner.status !== RTCSession.C.STATUS_TERMINATED) { self.reattempt = true; self.request_sender.send(); } }, 1000); } } else { this.applicant.receiveResponse(response); } } }; },{"../Constants":1,"../RTCSession":11,"../RequestSender":17,"../Transactions":21}],4:[function(require,module,exports){ module.exports = DigestAuthentication; /** * Dependencies. */ var debug = require('debug')('JsSIP:DigestAuthentication'); var debugerror = require('debug')('JsSIP:ERROR:DigestAuthentication'); debugerror.log = console.warn.bind(console); var Utils = require('./Utils'); function DigestAuthentication(credentials) { this.credentials = credentials; this.cnonce = null; this.nc = 0; this.ncHex = '00000000'; this.algorithm = null; this.realm = null; this.nonce = null; this.opaque = null; this.stale = null; this.qop = null; this.method = null; this.uri = null; this.ha1 = null; this.response = null; } DigestAuthentication.prototype.get = function(parameter) { switch (parameter) { case 'realm': return this.realm; case 'ha1': return this.ha1; default: debugerror('get() | cannot get "%s" parameter', parameter); return undefined; } }; /** * Performs Digest authentication given a SIP request and the challenge * received in a response to that request. * Returns true if auth was successfully generated, false otherwise. */ DigestAuthentication.prototype.authenticate = function(request, challenge) { var ha2, hex; this.algorithm = challenge.algorithm; this.realm = challenge.realm; this.nonce = challenge.nonce; this.opaque = challenge.opaque; this.stale = challenge.stale; if (this.algorithm) { if (this.algorithm !== 'MD5') { debugerror('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'); return false; } } else { this.algorithm = 'MD5'; } if (!this.nonce) { debugerror('authenticate() | challenge without Digest nonce, authentication aborted'); return false; } if (!this.realm) { debugerror('authenticate() | challenge without Digest realm, authentication aborted'); return false; } // If no plain SIP password is provided. if (!this.credentials.password) { // If ha1 is not provided we cannot authenticate. if (!this.credentials.ha1) { debugerror('authenticate() | no plain SIP password nor ha1 provided, authentication aborted'); return false; } // If the realm does not match the stored realm we cannot authenticate. if (this.credentials.realm !== this.realm) { debugerror('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]', this.credentials.realm, this.realm); return false; } } // 'qop' can contain a list of values (Array). Let's choose just one. if (challenge.qop) { if (challenge.qop.indexOf('auth') > -1) { this.qop = 'auth'; } else if (challenge.qop.indexOf('auth-int') > -1) { this.qop = 'auth-int'; } else { // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. debugerror('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'); return false; } } else { this.qop = null; } // Fill other attributes. this.method = request.method; this.uri = request.ruri; this.cnonce = Utils.createRandomToken(12); this.nc += 1; hex = Number(this.nc).toString(16); this.ncHex = '00000000'.substr(0, 8-hex.length) + hex; // nc-value = 8LHEX. Max value = 'FFFFFFFF'. if (this.nc === 4294967296) { this.nc = 1; this.ncHex = '00000001'; } // Calculate the Digest "response" value. // If we have plain SIP password then regenerate ha1. if (this.credentials.password) { // HA1 = MD5(A1) = MD5(username:realm:password) this.ha1 = Utils.calculateMD5(this.credentials.username + ':' + this.realm + ':' + this.credentials.password); // // Otherwise reuse the stored ha1. } else { this.ha1 = this.credentials.ha1; } if (this.qop === 'auth') { // HA2 = MD5(A2) = MD5(method:digestURI) ha2 = Utils.calculateMD5(this.method + ':' + this.uri); // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth:' + ha2); } else if (this.qop === 'auth-int') { // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) ha2 = Utils.calculateMD5(this.method + ':' + this.uri + ':' + Utils.calculateMD5(this.body ? this.body : '')); // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth-int:' + ha2); } else if (this.qop === null) { // HA2 = MD5(A2) = MD5(method:digestURI) ha2 = Utils.calculateMD5(this.method + ':' + this.uri); // response = MD5(HA1:nonce:HA2) this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + ha2); } debug('authenticate() | response generated'); return true; }; /** * Return the Proxy-Authorization or WWW-Authorization header value. */ DigestAuthentication.prototype.toString = function() { var auth_params = []; if (!this.response) { throw new Error('response field does not exist, cannot generate Authorization header'); } auth_params.push('algorithm=' + this.algorithm); auth_params.push('username="' + this.credentials.username + '"'); auth_params.push('realm="' + this.realm + '"'); auth_params.push('nonce="' + this.nonce + '"'); auth_params.push('uri="' + this.uri + '"'); auth_params.push('response="' + this.response + '"'); if (this.opaque) { auth_params.push('opaque="' + this.opaque + '"'); } if (this.qop) { auth_params.push('qop=' + this.qop); auth_params.push('cnonce="' + this.cnonce + '"'); auth_params.push('nc=' + this.ncHex); } return 'Digest ' + auth_params.join(', '); }; },{"./Utils":25,"debug":34}],5:[function(require,module,exports){ /** * @namespace Exceptions * @memberOf JsSIP */ var Exceptions = { /** * Exception thrown when a valid parameter is given to the JsSIP.UA constructor. * @class ConfigurationError * @memberOf JsSIP.Exceptions */ ConfigurationError: (function(){ var exception = function(parameter, value) { this.code = 1; this.name = 'CONFIGURATION_ERROR'; this.parameter = parameter; this.value = value; this.message = (!this.value)? 'Missing parameter: '+ this.parameter : 'Invalid value '+ JSON.stringify(this.value) +' for parameter "'+ this.parameter +'"'; }; exception.prototype = new Error(); return exception; }()), InvalidStateError: (function(){ var exception = function(status) { this.code = 2; this.name = 'INVALID_STATE_ERROR'; this.status = status; this.message = 'Invalid status: '+ status; }; exception.prototype = new Error(); return exception; }()), NotSupportedError: (function(){ var exception = function(message) { this.code = 3; this.name = 'NOT_SUPPORTED_ERROR'; this.message = message; }; exception.prototype = new Error(); return exception; }()), NotReadyError: (function(){ var exception = function(message) { this.code = 4; this.name = 'NOT_READY_ERROR'; this.message = message; }; exception.prototype = new Error(); return exception; }()) }; module.exports = Exceptions; },{}],6:[function(require,module,exports){ module.exports = (function(){ /* * Generated by PEG.js 0.7.0. * * http://pegjs.majda.cz/ */ function quote(s) { /* * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a * string literal except for the closing quote character, backslash, * carriage return, line separator, paragraph separator, and line feed. * Any character may appear in the form of an escape sequence. * * For portability, we also escape escape all control and non-ASCII * characters. Note that "\0" and "\v" escape sequences are not used * because JSHint does not like the first and IE the second. */ return '"' + s .replace(/\\/g, '\\\\') // backslash .replace(/"/g, '\\"') // closing quote character .replace(/\x08/g, '\\b') // backspace .replace(/\t/g, '\\t') // horizontal tab .replace(/\n/g, '\\n') // line feed .replace(/\f/g, '\\f') // form feed .replace(/\r/g, '\\r') // carriage return .replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape) + '"'; } var result = { /* * Parses the input with a generated parser. If the parsing is successfull, * returns a value explicitly or implicitly specified by the grammar from * which the parser was generated (see |PEG.buildParser|). If the parsing is * unsuccessful, throws |PEG.parser.SyntaxError| describing the error. */ parse: function(input, startRule) { var parseFunctions = { "CRLF": parse_CRLF, "DIGIT": parse_DIGIT, "ALPHA": parse_ALPHA, "HEXDIG": parse_HEXDIG, "WSP": parse_WSP, "OCTET": parse_OCTET, "DQUOTE": parse_DQUOTE, "SP": parse_SP, "HTAB": parse_HTAB, "alphanum": parse_alphanum, "reserved": parse_reserved, "unreserved": parse_unreserved, "mark": parse_mark, "escaped": parse_escaped, "LWS": parse_LWS, "SWS": parse_SWS, "HCOLON": parse_HCOLON, "TEXT_UTF8_TRIM": parse_TEXT_UTF8_TRIM, "TEXT_UTF8char": parse_TEXT_UTF8char, "UTF8_NONASCII": parse_UTF8_NONASCII, "UTF8_CONT": parse_UTF8_CONT, "LHEX": parse_LHEX, "token": parse_token, "token_nodot": parse_token_nodot, "separators": parse_separators, "word": parse_word, "STAR": parse_STAR, "SLASH": parse_SLASH, "EQUAL": parse_EQUAL, "LPAREN": parse_LPAREN, "RPAREN": parse_RPAREN, "RAQUOT": parse_RAQUOT, "LAQUOT": parse_LAQUOT, "COMMA": parse_COMMA, "SEMI": parse_SEMI, "COLON": parse_COLON, "LDQUOT": parse_LDQUOT, "RDQUOT": parse_RDQUOT, "comment": parse_comment, "ctext": parse_ctext, "quoted_string": parse_quoted_string, "quoted_string_clean": parse_quoted_string_clean, "qdtext": parse_qdtext, "quoted_pair": parse_quoted_pair, "SIP_URI_noparams": parse_SIP_URI_noparams, "SIP_URI": parse_SIP_URI, "uri_scheme": parse_uri_scheme, "uri_scheme_sips": parse_uri_scheme_sips, "uri_scheme_sip": parse_uri_scheme_sip, "userinfo": parse_userinfo, "user": parse_user, "user_unreserved": parse_user_unreserved, "password": parse_password, "hostport": parse_hostport, "host": parse_host, "hostname": parse_hostname, "domainlabel": parse_domainlabel, "toplabel": parse_toplabel, "IPv6reference": parse_IPv6reference, "IPv6address": parse_IPv6address, "h16": parse_h16, "ls32": parse_ls32, "IPv4address": parse_IPv4address, "dec_octet": parse_dec_octet, "port": parse_port, "uri_parameters": parse_uri_parameters, "uri_parameter": parse_uri_parameter, "transport_param": parse_transport_param, "user_param": parse_user_param, "method_param": parse_method_param, "ttl_param": parse_ttl_param, "maddr_param": parse_maddr_param, "lr_param": parse_lr_param, "other_param": parse_other_param, "pname": parse_pname, "pvalue": parse_pvalue, "paramchar": parse_paramchar, "param_unreserved": parse_param_unreserved, "headers": parse_headers, "header": parse_header, "hname": parse_hname, "hvalue": parse_hvalue, "hnv_unreserved": parse_hnv_unreserved, "Request_Response": parse_Request_Response, "Request_Line": parse_Request_Line, "Request_URI": parse_Request_URI, "absoluteURI": parse_absoluteURI, "hier_part": parse_hier_part, "net_path": parse_net_path, "abs_path": parse_abs_path, "opaque_part": parse_opaque_part, "uric": parse_uric, "uric_no_slash": parse_uric_no_slash, "path_segments": parse_path_segments, "segment": parse_segment, "param": parse_param, "pchar": parse_pchar, "scheme": parse_scheme, "authority": parse_authority, "srvr": parse_srvr, "reg_name": parse_reg_name, "query": parse_query, "SIP_Version": parse_SIP_Version, "INVITEm": parse_INVITEm, "ACKm": parse_ACKm, "OPTIONSm": parse_OPTIONSm, "BYEm": parse_BYEm, "CANCELm": parse_CANCELm, "REGISTERm": parse_REGISTERm, "SUBSCRIBEm": parse_SUBSCRIBEm, "NOTIFYm": parse_NOTIFYm, "REFERm": parse_REFERm, "Method": parse_Method, "Status_Line": parse_Status_Line, "Status_Code": parse_Status_Code, "extension_code": parse_extension_code, "Reason_Phrase": parse_Reason_Phrase, "Allow_Events": parse_Allow_Events, "Call_ID": parse_Call_ID, "Contact": parse_Contact, "contact_param": parse_contact_param, "name_addr": parse_name_addr, "display_name": parse_display_name, "contact_params": parse_contact_params, "c_p_q": parse_c_p_q, "c_p_expires": parse_c_p_expires, "delta_seconds": parse_delta_seconds, "qvalue": parse_qvalue, "generic_param": parse_generic_param, "gen_value": parse_gen_value, "Content_Disposition": parse_Content_Disposition, "disp_type": parse_disp_type, "disp_param": parse_disp_param, "handling_param": parse_handling_param, "Content_Encoding": parse_Content_Encoding, "Content_Length": parse_Content_Length, "Content_Type": parse_Content_Type, "media_type": parse_media_type, "m_type": parse_m_type, "discrete_type": parse_discrete_type, "composite_type": parse_composite_type, "extension_token": parse_extension_token, "x_token": parse_x_token, "m_subtype": parse_m_subtype, "m_parameter": parse_m_parameter, "m_value": parse_m_value, "CSeq": parse_CSeq, "CSeq_value": parse_CSeq_value, "Expires": parse_Expires, "Event": parse_Event, "event_type": parse_event_type, "From": parse_From, "from_param": parse_from_param, "tag_param": parse_tag_param, "Max_Forwards": parse_Max_Forwards, "Min_Expires": parse_Min_Expires, "Name_Addr_Header": parse_Name_Addr_Header, "Proxy_Authenticate": parse_Proxy_Authenticate, "challenge": parse_challenge, "other_challenge": parse_other_challenge, "auth_param": parse_auth_param, "digest_cln": parse_digest_cln, "realm": parse_realm, "realm_value": parse_realm_value, "domain": parse_domain, "URI": parse_URI, "nonce": parse_nonce, "nonce_value": parse_nonce_value, "opaque": parse_opaque, "stale": parse_stale, "algorithm": parse_algorithm, "qop_options": parse_qop_options, "qop_value": parse_qop_value, "Proxy_Require": parse_Proxy_Require, "Record_Route": parse_Record_Route, "rec_route": parse_rec_route, "Reason": parse_Reason, "reason_param": parse_reason_param, "reason_cause": parse_reason_cause, "Require": parse_Require, "Route": parse_Route, "route_param": parse_route_param, "Subscription_State": parse_Subscription_State, "substate_value": parse_substate_value, "subexp_params": parse_subexp_params, "event_reason_value": parse_event_reason_value, "Subject": parse_Subject, "Supported": parse_Supported, "To": parse_To, "to_param": parse_to_param, "Via": parse_Via, "via_param": parse_via_param, "via_params": parse_via_params, "via_ttl": parse_via_ttl, "via_maddr": parse_via_maddr, "via_received": parse_via_received, "via_branch": parse_via_branch, "response_port": parse_response_port, "sent_protocol": parse_sent_protocol, "protocol_name": parse_protocol_name, "transport": parse_transport, "sent_by": parse_sent_by, "via_host": parse_via_host, "via_port": parse_via_port, "ttl": parse_ttl, "WWW_Authenticate": parse_WWW_Authenticate, "Session_Expires": parse_Session_Expires, "s_e_expires": parse_s_e_expires, "s_e_params": parse_s_e_params, "s_e_refresher": parse_s_e_refresher, "extension_header": parse_extension_header, "header_value": parse_header_value, "message_body": parse_message_body, "uuid_URI": parse_uuid_URI, "uuid": parse_uuid, "hex4": parse_hex4, "hex8": parse_hex8, "hex12": parse_hex12, "Refer_To": parse_Refer_To, "Replaces": parse_Replaces, "call_id": parse_call_id, "replaces_param": parse_replaces_param, "to_tag": parse_to_tag, "from_tag": parse_from_tag, "early_flag": parse_early_flag }; if (startRule !== undefined) { if (parseFunctions[startRule] === undefined) { throw new Error("Invalid rule name: " + quote(startRule) + "."); } } else { startRule = "CRLF"; } var pos = 0; var reportFailures = 0; var rightmostFailuresPos = 0; var rightmostFailuresExpected = []; function padLeft(input, padding, length) { var result = input; var padLength = length - input.length; for (var i = 0; i < padLength; i++) { result = padding + result; } return result; } function escape(ch) { var charCode = ch.charCodeAt(0); var escapeChar; var length; if (charCode <= 0xFF) { escapeChar = 'x'; length = 2; } else { escapeChar = 'u'; length = 4; } return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length); } function matchFailed(failure) { if (pos < rightmostFailuresPos) { return; } if (pos > rightmostFailuresPos) { rightmostFailuresPos = pos; rightmostFailuresExpected = []; } rightmostFailuresExpected.push(failure); } function parse_CRLF() { var result0; if (input.substr(pos, 2) === "\r\n") { result0 = "\r\n"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"\\r\\n\""); } } return result0; } function parse_DIGIT() { var result0; if (/^[0-9]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[0-9]"); } } return result0; } function parse_ALPHA() { var result0; if (/^[a-zA-Z]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z]"); } } return result0; } function parse_HEXDIG() { var result0; if (/^[0-9a-fA-F]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[0-9a-fA-F]"); } } return result0; } function parse_WSP() { var result0; result0 = parse_SP(); if (result0 === null) { result0 = parse_HTAB(); } return result0; } function parse_OCTET() { var result0; if (/^[\0-\xFF]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\0-\\xFF]"); } } return result0; } function parse_DQUOTE() { var result0; if (/^["]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\"]"); } } return result0; } function parse_SP() { var result0; if (input.charCodeAt(pos) === 32) { result0 = " "; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\" \""); } } return result0; } function parse_HTAB() { var result0; if (input.charCodeAt(pos) === 9) { result0 = "\t"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"\\t\""); } } return result0; } function parse_alphanum() { var result0; if (/^[a-zA-Z0-9]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z0-9]"); } } return result0; } function parse_reserved() { var result0; if (input.charCodeAt(pos) === 59) { result0 = ";"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 64) { result0 = "@"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } } } } return result0; } function parse_unreserved() { var result0; result0 = parse_alphanum(); if (result0 === null) { result0 = parse_mark(); } return result0; } function parse_mark() { var result0; if (input.charCodeAt(pos) === 45) { result0 = "-"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 95) { result0 = "_"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 46) { result0 = "."; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 33) { result0 = "!"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 126) { result0 = "~"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 42) { result0 = "*"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 39) { result0 = "'"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 40) { result0 = "("; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 41) { result0 = ")"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\")\""); } } } } } } } } } } return result0; } function parse_escaped() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.charCodeAt(pos) === 37) { result0 = "%"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result0 !== null) { result1 = parse_HEXDIG(); if (result1 !== null) { result2 = parse_HEXDIG(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, escaped) {return escaped.join(''); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_LWS() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; pos2 = pos; result0 = []; result1 = parse_WSP(); while (result1 !== null) { result0.push(result1); result1 = parse_WSP(); } if (result0 !== null) { result1 = parse_CRLF(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos2; } } else { result0 = null; pos = pos2; } result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result2 = parse_WSP(); if (result2 !== null) { result1 = []; while (result2 !== null) { result1.push(result2); result2 = parse_WSP(); } } else { result1 = null; } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return " "; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_SWS() { var result0; result0 = parse_LWS(); result0 = result0 !== null ? result0 : ""; return result0; } function parse_HCOLON() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = []; result1 = parse_SP(); if (result1 === null) { result1 = parse_HTAB(); } while (result1 !== null) { result0.push(result1); result1 = parse_SP(); if (result1 === null) { result1 = parse_HTAB(); } } if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ':'; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_TEXT_UTF8_TRIM() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result1 = parse_TEXT_UTF8char(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_TEXT_UTF8char(); } } else { result0 = null; } if (result0 !== null) { result1 = []; pos2 = pos; result2 = []; result3 = parse_LWS(); while (result3 !== null) { result2.push(result3); result3 = parse_LWS(); } if (result2 !== null) { result3 = parse_TEXT_UTF8char(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = []; result3 = parse_LWS(); while (result3 !== null) { result2.push(result3); result3 = parse_LWS(); } if (result2 !== null) { result3 = parse_TEXT_UTF8char(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_TEXT_UTF8char() { var result0; if (/^[!-~]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[!-~]"); } } if (result0 === null) { result0 = parse_UTF8_NONASCII(); } return result0; } function parse_UTF8_NONASCII() { var result0; if (/^[\x80-\uFFFF]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\x80-\\uFFFF]"); } } return result0; } function parse_UTF8_CONT() { var result0; if (/^[\x80-\xBF]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\x80-\\xBF]"); } } return result0; } function parse_LHEX() { var result0; result0 = parse_DIGIT(); if (result0 === null) { if (/^[a-f]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[a-f]"); } } } return result0; } function parse_token() { var result0, result1; var pos0; pos0 = pos; result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } } } } } } } } } } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } } } } } } } } } } } } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_token_nodot() { var result0, result1; var pos0; pos0 = pos; result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } } } } } } } } } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } } } } } } } } } } } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_separators() { var result0; if (input.charCodeAt(pos) === 40) { result0 = "("; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 41) { result0 = ")"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\")\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 60) { result0 = "<"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"<\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 62) { result0 = ">"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\">\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 64) { result0 = "@"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 59) { result0 = ";"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 92) { result0 = "\\"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"\\\\\""); } } if (result0 === null) { result0 = parse_DQUOTE(); if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 91) { result0 = "["; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 93) { result0 = "]"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 123) { result0 = "{"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"{\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 125) { result0 = "}"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"}\""); } } if (result0 === null) { result0 = parse_SP(); if (result0 === null) { result0 = parse_HTAB(); } } } } } } } } } } } } } } } } } } return result0; } function parse_word() { var result0, result1; var pos0; pos0 = pos; result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 40) { result1 = "("; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 41) { result1 = ")"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\")\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 60) { result1 = "<"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"<\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 62) { result1 = ">"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\">\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 92) { result1 = "\\"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"\\\\\""); } } if (result1 === null) { result1 = parse_DQUOTE(); if (result1 === null) { if (input.charCodeAt(pos) === 47) { result1 = "/"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 91) { result1 = "["; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 93) { result1 = "]"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 63) { result1 = "?"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 123) { result1 = "{"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"{\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 125) { result1 = "}"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"}\""); } } } } } } } } } } } } } } } } } } } } } } } } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 40) { result1 = "("; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 41) { result1 = ")"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\")\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 60) { result1 = "<"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"<\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 62) { result1 = ">"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\">\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 92) { result1 = "\\"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"\\\\\""); } } if (result1 === null) { result1 = parse_DQUOTE(); if (result1 === null) { if (input.charCodeAt(pos) === 47) { result1 = "/"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 91) { result1 = "["; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 93) { result1 = "]"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 63) { result1 = "?"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 123) { result1 = "{"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"{\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 125) { result1 = "}"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"}\""); } } } } } } } } } } } } } } } } } } } } } } } } } } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_STAR() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "*"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_SLASH() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 47) { result1 = "/"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "/"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_EQUAL() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "="; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_LPAREN() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 40) { result1 = "("; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "("; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_RPAREN() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 41) { result1 = ")"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\")\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ")"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_RAQUOT() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.charCodeAt(pos) === 62) { result0 = ">"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\">\""); } } if (result0 !== null) { result1 = parse_SWS(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ">"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_LAQUOT() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 60) { result1 = "<"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"<\""); } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "<"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_COMMA() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ","; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_SEMI() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ";"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_COLON() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ":"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_LDQUOT() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { result1 = parse_DQUOTE(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "\""; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_RDQUOT() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_DQUOTE(); if (result0 !== null) { result1 = parse_SWS(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "\""; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_comment() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_LPAREN(); if (result0 !== null) { result1 = []; result2 = parse_ctext(); if (result2 === null) { result2 = parse_quoted_pair(); if (result2 === null) { result2 = parse_comment(); } } while (result2 !== null) { result1.push(result2); result2 = parse_ctext(); if (result2 === null) { result2 = parse_quoted_pair(); if (result2 === null) { result2 = parse_comment(); } } } if (result1 !== null) { result2 = parse_RPAREN(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_ctext() { var result0; if (/^[!-']/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[!-']"); } } if (result0 === null) { if (/^[*-[]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[*-[]"); } } if (result0 === null) { if (/^[\]-~]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\]-~]"); } } if (result0 === null) { result0 = parse_UTF8_NONASCII(); if (result0 === null) { result0 = parse_LWS(); } } } } return result0; } function parse_quoted_string() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { result1 = parse_DQUOTE(); if (result1 !== null) { result2 = []; result3 = parse_qdtext(); if (result3 === null) { result3 = parse_quoted_pair(); } while (result3 !== null) { result2.push(result3); result3 = parse_qdtext(); if (result3 === null) { result3 = parse_quoted_pair(); } } if (result2 !== null) { result3 = parse_DQUOTE(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_quoted_string_clean() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { result1 = parse_DQUOTE(); if (result1 !== null) { result2 = []; result3 = parse_qdtext(); if (result3 === null) { result3 = parse_quoted_pair(); } while (result3 !== null) { result2.push(result3); result3 = parse_qdtext(); if (result3 === null) { result3 = parse_quoted_pair(); } } if (result2 !== null) { result3 = parse_DQUOTE(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos-1, offset+1); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_qdtext() { var result0; result0 = parse_LWS(); if (result0 === null) { if (input.charCodeAt(pos) === 33) { result0 = "!"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result0 === null) { if (/^[#-[]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[#-[]"); } } if (result0 === null) { if (/^[\]-~]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\]-~]"); } } if (result0 === null) { result0 = parse_UTF8_NONASCII(); } } } } return result0; } function parse_quoted_pair() { var result0, result1; var pos0; pos0 = pos; if (input.charCodeAt(pos) === 92) { result0 = "\\"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"\\\\\""); } } if (result0 !== null) { if (/^[\0-\t]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[\\0-\\t]"); } } if (result1 === null) { if (/^[\x0B-\f]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[\\x0B-\\f]"); } } if (result1 === null) { if (/^[\x0E-]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[\\x0E-]"); } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_SIP_URI_noparams() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_uri_scheme(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_userinfo(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_hostport(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { try { data.uri = new URI(data.scheme, data.user, data.host, data.port); delete data.scheme; delete data.user; delete data.host; delete data.host_type; delete data.port; } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_SIP_URI() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_uri_scheme(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_userinfo(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_hostport(); if (result3 !== null) { result4 = parse_uri_parameters(); if (result4 !== null) { result5 = parse_headers(); result5 = result5 !== null ? result5 : ""; if (result5 !== null) { result0 = [result0, result1, result2, result3, result4, result5]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var header; try { data.uri = new URI(data.scheme, data.user, data.host, data.port, data.uri_params, data.uri_headers); delete data.scheme; delete data.user; delete data.host; delete data.host_type; delete data.port; delete data.uri_params; if (startRule === 'SIP_URI') { data = data.uri;} } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_uri_scheme() { var result0; result0 = parse_uri_scheme_sips(); if (result0 === null) { result0 = parse_uri_scheme_sip(); } return result0; } function parse_uri_scheme_sips() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 4).toLowerCase() === "sips") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"sips\""); } } if (result0 !== null) { result0 = (function(offset, scheme) { data.scheme = scheme.toLowerCase(); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_uri_scheme_sip() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 3).toLowerCase() === "sip") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"sip\""); } } if (result0 !== null) { result0 = (function(offset, scheme) { data.scheme = scheme.toLowerCase(); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_userinfo() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_user(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_password(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { if (input.charCodeAt(pos) === 64) { result2 = "@"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.user = decodeURIComponent(input.substring(pos-1, offset));})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_user() { var result0, result1; result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { result1 = parse_user_unreserved(); } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { result1 = parse_user_unreserved(); } } } } else { result0 = null; } return result0; } function parse_user_unreserved() { var result0; if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 59) { result0 = ";"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } } } } } } } } return result0; } function parse_password() { var result0, result1; var pos0; pos0 = pos; result0 = []; result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { if (input.charCodeAt(pos) === 38) { result1 = "&"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 36) { result1 = "$"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } while (result1 !== null) { result0.push(result1); result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { if (input.charCodeAt(pos) === 38) { result1 = "&"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 36) { result1 = "$"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } } if (result0 !== null) { result0 = (function(offset) { data.password = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_hostport() { var result0, result1, result2; var pos0, pos1; pos0 = pos; result0 = parse_host(); if (result0 !== null) { pos1 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_port(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos1; } } else { result1 = null; pos = pos1; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_host() { var result0; var pos0; pos0 = pos; result0 = parse_hostname(); if (result0 === null) { result0 = parse_IPv4address(); if (result0 === null) { result0 = parse_IPv6reference(); } } if (result0 !== null) { result0 = (function(offset) { data.host = input.substring(pos, offset).toLowerCase(); return data.host; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_hostname() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = []; pos2 = pos; result1 = parse_domainlabel(); if (result1 !== null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } while (result1 !== null) { result0.push(result1); pos2 = pos; result1 = parse_domainlabel(); if (result1 !== null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } } if (result0 !== null) { result1 = parse_toplabel(); if (result1 !== null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.host_type = 'domain'; return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_domainlabel() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_alphanum(); if (result0 !== null) { result1 = []; result2 = parse_alphanum(); if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 95) { result2 = "_"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } } } while (result2 !== null) { result1.push(result2); result2 = parse_alphanum(); if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 95) { result2 = "_"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_toplabel() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_ALPHA(); if (result0 !== null) { result1 = []; result2 = parse_alphanum(); if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 95) { result2 = "_"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } } } while (result2 !== null) { result1.push(result2); result2 = parse_alphanum(); if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 95) { result2 = "_"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_IPv6reference() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.charCodeAt(pos) === 91) { result0 = "["; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result0 !== null) { result1 = parse_IPv6address(); if (result1 !== null) { if (input.charCodeAt(pos) === 93) { result2 = "]"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.host_type = 'IPv6'; return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_IPv6address() { var result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_h16(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { if (input.charCodeAt(pos) === 58) { result7 = ":"; pos++; } else { result7 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result7 !== null) { result8 = parse_h16(); if (result8 !== null) { if (input.charCodeAt(pos) === 58) { result9 = ":"; pos++; } else { result9 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result9 !== null) { result10 = parse_h16(); if (result10 !== null) { if (input.charCodeAt(pos) === 58) { result11 = ":"; pos++; } else { result11 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result11 !== null) { result12 = parse_ls32(); if (result12 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { if (input.charCodeAt(pos) === 58) { result8 = ":"; pos++; } else { result8 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result8 !== null) { result9 = parse_h16(); if (result9 !== null) { if (input.charCodeAt(pos) === 58) { result10 = ":"; pos++; } else { result10 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result10 !== null) { result11 = parse_ls32(); if (result11 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { if (input.charCodeAt(pos) === 58) { result8 = ":"; pos++; } else { result8 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result8 !== null) { result9 = parse_ls32(); if (result9 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_ls32(); if (result7 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_ls32(); if (result5 !== null) { result0 = [result0, result1, result2, result3, result4, result5]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_ls32(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_ls32(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { if (input.substr(pos, 2) === "::") { result1 = "::"; pos += 2; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { if (input.charCodeAt(pos) === 58) { result7 = ":"; pos++; } else { result7 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result7 !== null) { result8 = parse_h16(); if (result8 !== null) { if (input.charCodeAt(pos) === 58) { result9 = ":"; pos++; } else { result9 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result9 !== null) { result10 = parse_ls32(); if (result10 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { if (input.substr(pos, 2) === "::") { result2 = "::"; pos += 2; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { if (input.charCodeAt(pos) === 58) { result8 = ":"; pos++; } else { result8 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result8 !== null) { result9 = parse_ls32(); if (result9 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { if (input.substr(pos, 2) === "::") { result3 = "::"; pos += 2; } else { result3 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { if (input.charCodeAt(pos) === 58) { result7 = ":"; pos++; } else { result7 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result7 !== null) { result8 = parse_ls32(); if (result8 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos2; } } else { result3 = null; pos = pos2; } result3 = result3 !== null ? result3 : ""; if (result3 !== null) { if (input.substr(pos, 2) === "::") { result4 = "::"; pos += 2; } else { result4 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_ls32(); if (result7 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos2; } } else { result3 = null; pos = pos2; } result3 = result3 !== null ? result3 : ""; if (result3 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos2; } } else { result4 = null; pos = pos2; } result4 = result4 !== null ? result4 : ""; if (result4 !== null) { if (input.substr(pos, 2) === "::") { result5 = "::"; pos += 2; } else { result5 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result5 !== null) { result6 = parse_ls32(); if (result6 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos2; } } else { result3 = null; pos = pos2; } result3 = result3 !== null ? result3 : ""; if (result3 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos2; } } else { result4 = null; pos = pos2; } result4 = result4 !== null ? result4 : ""; if (result4 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } result5 = result5 !== null ? result5 : ""; if (result5 !== null) { if (input.substr(pos, 2) === "::") { result6 = "::"; pos += 2; } else { result6 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos2; } } else { result3 = null; pos = pos2; } result3 = result3 !== null ? result3 : ""; if (result3 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos2; } } else { result4 = null; pos = pos2; } result4 = result4 !== null ? result4 : ""; if (result4 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } result5 = result5 !== null ? result5 : ""; if (result5 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { result6 = [result6, result7]; } else { result6 = null; pos = pos2; } } else { result6 = null; pos = pos2; } result6 = result6 !== null ? result6 : ""; if (result6 !== null) { if (input.substr(pos, 2) === "::") { result7 = "::"; pos += 2; } else { result7 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result7 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } } } } } } } } } } } } } } if (result0 !== null) { result0 = (function(offset) { data.host_type = 'IPv6'; return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_h16() { var result0, result1, result2, result3; var pos0; pos0 = pos; result0 = parse_HEXDIG(); if (result0 !== null) { result1 = parse_HEXDIG(); result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result2 = parse_HEXDIG(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_HEXDIG(); result3 = result3 !== null ? result3 : ""; if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_ls32() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_h16(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { result0 = parse_IPv4address(); } return result0; } function parse_IPv4address() { var result0, result1, result2, result3, result4, result5, result6; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_dec_octet(); if (result0 !== null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 !== null) { result2 = parse_dec_octet(); if (result2 !== null) { if (input.charCodeAt(pos) === 46) { result3 = "."; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result3 !== null) { result4 = parse_dec_octet(); if (result4 !== null) { if (input.charCodeAt(pos) === 46) { result5 = "."; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result5 !== null) { result6 = parse_dec_octet(); if (result6 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.host_type = 'IPv4'; return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_dec_octet() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 2) === "25") { result0 = "25"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"25\""); } } if (result0 !== null) { if (/^[0-5]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[0-5]"); } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { pos0 = pos; if (input.charCodeAt(pos) === 50) { result0 = "2"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"2\""); } } if (result0 !== null) { if (/^[0-4]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[0-4]"); } } if (result1 !== null) { result2 = parse_DIGIT(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { pos0 = pos; if (input.charCodeAt(pos) === 49) { result0 = "1"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"1\""); } } if (result0 !== null) { result1 = parse_DIGIT(); if (result1 !== null) { result2 = parse_DIGIT(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { pos0 = pos; if (/^[1-9]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[1-9]"); } } if (result0 !== null) { result1 = parse_DIGIT(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { result0 = parse_DIGIT(); } } } } return result0; } function parse_port() { var result0, result1, result2, result3, result4; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_DIGIT(); result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result1 = parse_DIGIT(); result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result2 = parse_DIGIT(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_DIGIT(); result3 = result3 !== null ? result3 : ""; if (result3 !== null) { result4 = parse_DIGIT(); result4 = result4 !== null ? result4 : ""; if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, port) { port = parseInt(port.join('')); data.port = port; return port; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_uri_parameters() { var result0, result1, result2; var pos0; result0 = []; pos0 = pos; if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 !== null) { result2 = parse_uri_parameter(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos0; } } else { result1 = null; pos = pos0; } while (result1 !== null) { result0.push(result1); pos0 = pos; if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 !== null) { result2 = parse_uri_parameter(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos0; } } else { result1 = null; pos = pos0; } } return result0; } function parse_uri_parameter() { var result0; result0 = parse_transport_param(); if (result0 === null) { result0 = parse_user_param(); if (result0 === null) { result0 = parse_method_param(); if (result0 === null) { result0 = parse_ttl_param(); if (result0 === null) { result0 = parse_maddr_param(); if (result0 === null) { result0 = parse_lr_param(); if (result0 === null) { result0 = parse_other_param(); } } } } } } return result0; } function parse_transport_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 10).toLowerCase() === "transport=") { result0 = input.substr(pos, 10); pos += 10; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"transport=\""); } } if (result0 !== null) { if (input.substr(pos, 3).toLowerCase() === "udp") { result1 = input.substr(pos, 3); pos += 3; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"udp\""); } } if (result1 === null) { if (input.substr(pos, 3).toLowerCase() === "tcp") { result1 = input.substr(pos, 3); pos += 3; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"tcp\""); } } if (result1 === null) { if (input.substr(pos, 4).toLowerCase() === "sctp") { result1 = input.substr(pos, 4); pos += 4; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"sctp\""); } } if (result1 === null) { if (input.substr(pos, 3).toLowerCase() === "tls") { result1 = input.substr(pos, 3); pos += 3; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"tls\""); } } if (result1 === null) { result1 = parse_token(); } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, transport) { if(!data.uri_params) data.uri_params={}; data.uri_params['transport'] = transport.toLowerCase(); })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_user_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "user=") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"user=\""); } } if (result0 !== null) { if (input.substr(pos, 5).toLowerCase() === "phone") { result1 = input.substr(pos, 5); pos += 5; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"phone\""); } } if (result1 === null) { if (input.substr(pos, 2).toLowerCase() === "ip") { result1 = input.substr(pos, 2); pos += 2; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"ip\""); } } if (result1 === null) { result1 = parse_token(); } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, user) { if(!data.uri_params) data.uri_params={}; data.uri_params['user'] = user.toLowerCase(); })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_method_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 7).toLowerCase() === "method=") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"method=\""); } } if (result0 !== null) { result1 = parse_Method(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, method) { if(!data.uri_params) data.uri_params={}; data.uri_params['method'] = method; })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_ttl_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 4).toLowerCase() === "ttl=") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"ttl=\""); } } if (result0 !== null) { result1 = parse_ttl(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, ttl) { if(!data.params) data.params={}; data.params['ttl'] = ttl; })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_maddr_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6).toLowerCase() === "maddr=") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"maddr=\""); } } if (result0 !== null) { result1 = parse_host(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, maddr) { if(!data.uri_params) data.uri_params={}; data.uri_params['maddr'] = maddr; })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_lr_param() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; if (input.substr(pos, 2).toLowerCase() === "lr") { result0 = input.substr(pos, 2); pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"lr\""); } } if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { if(!data.uri_params) data.uri_params={}; data.uri_params['lr'] = undefined; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_other_param() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_pname(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 !== null) { result2 = parse_pvalue(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, param, value) { if(!data.uri_params) data.uri_params = {}; if (typeof value === 'undefined'){ value = undefined; } else { value = value[1]; } data.uri_params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_pname() { var result0, result1; var pos0; pos0 = pos; result1 = parse_paramchar(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_paramchar(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, pname) {return pname.join(''); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_pvalue() { var result0, result1; var pos0; pos0 = pos; result1 = parse_paramchar(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_paramchar(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, pvalue) {return pvalue.join(''); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_paramchar() { var result0; result0 = parse_param_unreserved(); if (result0 === null) { result0 = parse_unreserved(); if (result0 === null) { result0 = parse_escaped(); } } return result0; } function parse_param_unreserved() { var result0; if (input.charCodeAt(pos) === 91) { result0 = "["; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 93) { result0 = "]"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } } } } } } } return result0; } function parse_headers() { var result0, result1, result2, result3, result4; var pos0, pos1; pos0 = pos; if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 !== null) { result1 = parse_header(); if (result1 !== null) { result2 = []; pos1 = pos; if (input.charCodeAt(pos) === 38) { result3 = "&"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result3 !== null) { result4 = parse_header(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos1; } } else { result3 = null; pos = pos1; } while (result3 !== null) { result2.push(result3); pos1 = pos; if (input.charCodeAt(pos) === 38) { result3 = "&"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result3 !== null) { result4 = parse_header(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos1; } } else { result3 = null; pos = pos1; } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_header() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_hname(); if (result0 !== null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 !== null) { result2 = parse_hvalue(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, hname, hvalue) { hname = hname.join('').toLowerCase(); hvalue = hvalue.join(''); if(!data.uri_headers) data.uri_headers = {}; if (!data.uri_headers[hname]) { data.uri_headers[hname] = [hvalue]; } else { data.uri_headers[hname].push(hvalue); }})(pos0, result0[0], result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_hname() { var result0, result1; result1 = parse_hnv_unreserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_hnv_unreserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); } } } } else { result0 = null; } return result0; } function parse_hvalue() { var result0, result1; result0 = []; result1 = parse_hnv_unreserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); } } while (result1 !== null) { result0.push(result1); result1 = parse_hnv_unreserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); } } } return result0; } function parse_hnv_unreserved() { var result0; if (input.charCodeAt(pos) === 91) { result0 = "["; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 93) { result0 = "]"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } } } } } } } return result0; } function parse_Request_Response() { var result0; result0 = parse_Status_Line(); if (result0 === null) { result0 = parse_Request_Line(); } return result0; } function parse_Request_Line() { var result0, result1, result2, result3, result4; var pos0; pos0 = pos; result0 = parse_Method(); if (result0 !== null) { result1 = parse_SP(); if (result1 !== null) { result2 = parse_Request_URI(); if (result2 !== null) { result3 = parse_SP(); if (result3 !== null) { result4 = parse_SIP_Version(); if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Request_URI() { var result0; result0 = parse_SIP_URI(); if (result0 === null) { result0 = parse_absoluteURI(); } return result0; } function parse_absoluteURI() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_scheme(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_hier_part(); if (result2 === null) { result2 = parse_opaque_part(); } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_hier_part() { var result0, result1, result2; var pos0, pos1; pos0 = pos; result0 = parse_net_path(); if (result0 === null) { result0 = parse_abs_path(); } if (result0 !== null) { pos1 = pos; if (input.charCodeAt(pos) === 63) { result1 = "?"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result1 !== null) { result2 = parse_query(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos1; } } else { result1 = null; pos = pos1; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_net_path() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 2) === "//") { result0 = "//"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"//\""); } } if (result0 !== null) { result1 = parse_authority(); if (result1 !== null) { result2 = parse_abs_path(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_abs_path() { var result0, result1; var pos0; pos0 = pos; if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 !== null) { result1 = parse_path_segments(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_opaque_part() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_uric_no_slash(); if (result0 !== null) { result1 = []; result2 = parse_uric(); while (result2 !== null) { result1.push(result2); result2 = parse_uric(); } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_uric() { var result0; result0 = parse_reserved(); if (result0 === null) { result0 = parse_unreserved(); if (result0 === null) { result0 = parse_escaped(); } } return result0; } function parse_uric_no_slash() { var result0; result0 = parse_unreserved(); if (result0 === null) { result0 = parse_escaped(); if (result0 === null) { if (input.charCodeAt(pos) === 59) { result0 = ";"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 64) { result0 = "@"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } } } } } return result0; } function parse_path_segments() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_segment(); if (result0 !== null) { result1 = []; pos1 = pos; if (input.charCodeAt(pos) === 47) { result2 = "/"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result2 !== null) { result3 = parse_segment(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; if (input.charCodeAt(pos) === 47) { result2 = "/"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result2 !== null) { result3 = parse_segment(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_segment() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = []; result1 = parse_pchar(); while (result1 !== null) { result0.push(result1); result1 = parse_pchar(); } if (result0 !== null) { result1 = []; pos1 = pos; if (input.charCodeAt(pos) === 59) { result2 = ";"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result2 !== null) { result3 = parse_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; if (input.charCodeAt(pos) === 59) { result2 = ";"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result2 !== null) { result3 = parse_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_param() { var result0, result1; result0 = []; result1 = parse_pchar(); while (result1 !== null) { result0.push(result1); result1 = parse_pchar(); } return result0; } function parse_pchar() { var result0; result0 = parse_unreserved(); if (result0 === null) { result0 = parse_escaped(); if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 64) { result0 = "@"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } } } return result0; } function parse_scheme() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_ALPHA(); if (result0 !== null) { result1 = []; result2 = parse_ALPHA(); if (result2 === null) { result2 = parse_DIGIT(); if (result2 === null) { if (input.charCodeAt(pos) === 43) { result2 = "+"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } } } } } while (result2 !== null) { result1.push(result2); result2 = parse_ALPHA(); if (result2 === null) { result2 = parse_DIGIT(); if (result2 === null) { if (input.charCodeAt(pos) === 43) { result2 = "+"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } } } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.scheme= input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_authority() { var result0; result0 = parse_srvr(); if (result0 === null) { result0 = parse_reg_name(); } return result0; } function parse_srvr() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_userinfo(); if (result0 !== null) { if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result1 = parse_hostport(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } result0 = result0 !== null ? result0 : ""; return result0; } function parse_reg_name() { var result0, result1; result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { if (input.charCodeAt(pos) === 36) { result1 = "$"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 38) { result1 = "&"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } } } } } } } } } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { if (input.charCodeAt(pos) === 36) { result1 = "$"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 38) { result1 = "&"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } } } } } } } } } } } } else { result0 = null; } return result0; } function parse_query() { var result0, result1; result0 = []; result1 = parse_uric(); while (result1 !== null) { result0.push(result1); result1 = parse_uric(); } return result0; } function parse_SIP_Version() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 3).toLowerCase() === "sip") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SIP\""); } } if (result0 !== null) { if (input.charCodeAt(pos) === 47) { result1 = "/"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result1 !== null) { result3 = parse_DIGIT(); if (result3 !== null) { result2 = []; while (result3 !== null) { result2.push(result3); result3 = parse_DIGIT(); } } else { result2 = null; } if (result2 !== null) { if (input.charCodeAt(pos) === 46) { result3 = "."; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result3 !== null) { result5 = parse_DIGIT(); if (result5 !== null) { result4 = []; while (result5 !== null) { result4.push(result5); result5 = parse_DIGIT(); } } else { result4 = null; } if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.sip_version = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_INVITEm() { var result0; if (input.substr(pos, 6) === "INVITE") { result0 = "INVITE"; pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"INVITE\""); } } return result0; } function parse_ACKm() { var result0; if (input.substr(pos, 3) === "ACK") { result0 = "ACK"; pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"ACK\""); } } return result0; } function parse_OPTIONSm() { var result0; if (input.substr(pos, 7) === "OPTIONS") { result0 = "OPTIONS"; pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"OPTIONS\""); } } return result0; } function parse_BYEm() { var result0; if (input.substr(pos, 3) === "BYE") { result0 = "BYE"; pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"BYE\""); } } return result0; } function parse_CANCELm() { var result0; if (input.substr(pos, 6) === "CANCEL") { result0 = "CANCEL"; pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"CANCEL\""); } } return result0; } function parse_REGISTERm() { var result0; if (input.substr(pos, 8) === "REGISTER") { result0 = "REGISTER"; pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"REGISTER\""); } } return result0; } function parse_SUBSCRIBEm() { var result0; if (input.substr(pos, 9) === "SUBSCRIBE") { result0 = "SUBSCRIBE"; pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SUBSCRIBE\""); } } return result0; } function parse_NOTIFYm() { var result0; if (input.substr(pos, 6) === "NOTIFY") { result0 = "NOTIFY"; pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"NOTIFY\""); } } return result0; } function parse_REFERm() { var result0; if (input.substr(pos, 5) === "REFER") { result0 = "REFER"; pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"REFER\""); } } return result0; } function parse_Method() { var result0; var pos0; pos0 = pos; result0 = parse_INVITEm(); if (result0 === null) { result0 = parse_ACKm(); if (result0 === null) { result0 = parse_OPTIONSm(); if (result0 === null) { result0 = parse_BYEm(); if (result0 === null) { result0 = parse_CANCELm(); if (result0 === null) { result0 = parse_REGISTERm(); if (result0 === null) { result0 = parse_SUBSCRIBEm(); if (result0 === null) { result0 = parse_NOTIFYm(); if (result0 === null) { result0 = parse_REFERm(); if (result0 === null) { result0 = parse_token(); } } } } } } } } } if (result0 !== null) { result0 = (function(offset) { data.method = input.substring(pos, offset); return data.method; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Status_Line() { var result0, result1, result2, result3, result4; var pos0; pos0 = pos; result0 = parse_SIP_Version(); if (result0 !== null) { result1 = parse_SP(); if (result1 !== null) { result2 = parse_Status_Code(); if (result2 !== null) { result3 = parse_SP(); if (result3 !== null) { result4 = parse_Reason_Phrase(); if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Status_Code() { var result0; var pos0; pos0 = pos; result0 = parse_extension_code(); if (result0 !== null) { result0 = (function(offset, status_code) { data.status_code = parseInt(status_code.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_extension_code() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_DIGIT(); if (result0 !== null) { result1 = parse_DIGIT(); if (result1 !== null) { result2 = parse_DIGIT(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Reason_Phrase() { var result0, result1; var pos0; pos0 = pos; result0 = []; result1 = parse_reserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { result1 = parse_UTF8_NONASCII(); if (result1 === null) { result1 = parse_UTF8_CONT(); if (result1 === null) { result1 = parse_SP(); if (result1 === null) { result1 = parse_HTAB(); } } } } } } while (result1 !== null) { result0.push(result1); result1 = parse_reserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { result1 = parse_UTF8_NONASCII(); if (result1 === null) { result1 = parse_UTF8_CONT(); if (result1 === null) { result1 = parse_SP(); if (result1 === null) { result1 = parse_HTAB(); } } } } } } } if (result0 !== null) { result0 = (function(offset) { data.reason_phrase = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Allow_Events() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_event_type(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_event_type(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_event_type(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Call_ID() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_word(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 !== null) { result2 = parse_word(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Contact() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; result0 = parse_STAR(); if (result0 === null) { pos1 = pos; result0 = parse_contact_param(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_contact_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_contact_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } if (result0 !== null) { result0 = (function(offset) { var idx, length; length = data.multi_header.length; for (idx = 0; idx < length; idx++) { if (data.multi_header[idx].parsed === null) { data = null; break; } } if (data !== null) { data = data.multi_header; } else { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_contact_param() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_SIP_URI_noparams(); if (result0 === null) { result0 = parse_name_addr(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_contact_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_contact_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var header; if(!data.multi_header) data.multi_header = []; try { header = new NameAddrHeader(data.uri, data.display_name, data.params); delete data.uri; delete data.display_name; delete data.params; } catch(e) { header = null; } data.multi_header.push( { 'possition': pos, 'offset': offset, 'parsed': header });})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_name_addr() { var result0, result1, result2, result3; var pos0; pos0 = pos; result0 = parse_display_name(); result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result1 = parse_LAQUOT(); if (result1 !== null) { result2 = parse_SIP_URI(); if (result2 !== null) { result3 = parse_RAQUOT(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_display_name() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_LWS(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_LWS(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { result0 = parse_quoted_string(); } if (result0 !== null) { result0 = (function(offset, display_name) { display_name = input.substring(pos, offset).trim(); if (display_name[0] === '\"') { display_name = display_name.substring(1, display_name.length-1); } data.display_name = display_name; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_contact_params() { var result0; result0 = parse_c_p_q(); if (result0 === null) { result0 = parse_c_p_expires(); if (result0 === null) { result0 = parse_generic_param(); } } return result0; } function parse_c_p_q() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 1).toLowerCase() === "q") { result0 = input.substr(pos, 1); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"q\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_qvalue(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, q) { if(!data.params) data.params = {}; data.params['q'] = q; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_c_p_expires() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 7).toLowerCase() === "expires") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"expires\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_delta_seconds(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, expires) { if(!data.params) data.params = {}; data.params['expires'] = expires; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_delta_seconds() { var result0, result1; var pos0; pos0 = pos; result1 = parse_DIGIT(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_DIGIT(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, delta_seconds) { return parseInt(delta_seconds.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_qvalue() { var result0, result1, result2, result3, result4; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; if (input.charCodeAt(pos) === 48) { result0 = "0"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"0\""); } } if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 !== null) { result2 = parse_DIGIT(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_DIGIT(); result3 = result3 !== null ? result3 : ""; if (result3 !== null) { result4 = parse_DIGIT(); result4 = result4 !== null ? result4 : ""; if (result4 !== null) { result1 = [result1, result2, result3, result4]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { return parseFloat(input.substring(pos, offset)); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_generic_param() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_token(); if (result0 !== null) { pos2 = pos; result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_gen_value(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, param, value) { if(!data.params) data.params = {}; if (typeof value === 'undefined'){ value = undefined; } else { value = value[1]; } data.params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_gen_value() { var result0; result0 = parse_token(); if (result0 === null) { result0 = parse_host(); if (result0 === null) { result0 = parse_quoted_string(); } } return result0; } function parse_Content_Disposition() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_disp_type(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_disp_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_disp_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_disp_type() { var result0; if (input.substr(pos, 6).toLowerCase() === "render") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"render\""); } } if (result0 === null) { if (input.substr(pos, 7).toLowerCase() === "session") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"session\""); } } if (result0 === null) { if (input.substr(pos, 4).toLowerCase() === "icon") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"icon\""); } } if (result0 === null) { if (input.substr(pos, 5).toLowerCase() === "alert") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"alert\""); } } if (result0 === null) { result0 = parse_token(); } } } } return result0; } function parse_disp_param() { var result0; result0 = parse_handling_param(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_handling_param() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 8).toLowerCase() === "handling") { result0 = input.substr(pos, 8); pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"handling\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { if (input.substr(pos, 8).toLowerCase() === "optional") { result2 = input.substr(pos, 8); pos += 8; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"optional\""); } } if (result2 === null) { if (input.substr(pos, 8).toLowerCase() === "required") { result2 = input.substr(pos, 8); pos += 8; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"required\""); } } if (result2 === null) { result2 = parse_token(); } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Content_Encoding() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Content_Length() { var result0, result1; var pos0; pos0 = pos; result1 = parse_DIGIT(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_DIGIT(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, length) { data = parseInt(length.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Content_Type() { var result0; var pos0; pos0 = pos; result0 = parse_media_type(); if (result0 !== null) { result0 = (function(offset) { data = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_media_type() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; result0 = parse_m_type(); if (result0 !== null) { result1 = parse_SLASH(); if (result1 !== null) { result2 = parse_m_subtype(); if (result2 !== null) { result3 = []; pos1 = pos; result4 = parse_SEMI(); if (result4 !== null) { result5 = parse_m_parameter(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } while (result4 !== null) { result3.push(result4); pos1 = pos; result4 = parse_SEMI(); if (result4 !== null) { result5 = parse_m_parameter(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } } if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_m_type() { var result0; result0 = parse_discrete_type(); if (result0 === null) { result0 = parse_composite_type(); } return result0; } function parse_discrete_type() { var result0; if (input.substr(pos, 4).toLowerCase() === "text") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"text\""); } } if (result0 === null) { if (input.substr(pos, 5).toLowerCase() === "image") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"image\""); } } if (result0 === null) { if (input.substr(pos, 5).toLowerCase() === "audio") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"audio\""); } } if (result0 === null) { if (input.substr(pos, 5).toLowerCase() === "video") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"video\""); } } if (result0 === null) { if (input.substr(pos, 11).toLowerCase() === "application") { result0 = input.substr(pos, 11); pos += 11; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"application\""); } } if (result0 === null) { result0 = parse_extension_token(); } } } } } return result0; } function parse_composite_type() { var result0; if (input.substr(pos, 7).toLowerCase() === "message") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"message\""); } } if (result0 === null) { if (input.substr(pos, 9).toLowerCase() === "multipart") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"multipart\""); } } if (result0 === null) { result0 = parse_extension_token(); } } return result0; } function parse_extension_token() { var result0; result0 = parse_token(); if (result0 === null) { result0 = parse_x_token(); } return result0; } function parse_x_token() { var result0, result1; var pos0; pos0 = pos; if (input.substr(pos, 2).toLowerCase() === "x-") { result0 = input.substr(pos, 2); pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"x-\""); } } if (result0 !== null) { result1 = parse_token(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_m_subtype() { var result0; result0 = parse_extension_token(); if (result0 === null) { result0 = parse_token(); } return result0; } function parse_m_parameter() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_m_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_m_value() { var result0; result0 = parse_token(); if (result0 === null) { result0 = parse_quoted_string(); } return result0; } function parse_CSeq() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_CSeq_value(); if (result0 !== null) { result1 = parse_LWS(); if (result1 !== null) { result2 = parse_Method(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_CSeq_value() { var result0, result1; var pos0; pos0 = pos; result1 = parse_DIGIT(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_DIGIT(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, cseq_value) { data.value=parseInt(cseq_value.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Expires() { var result0; var pos0; pos0 = pos; result0 = parse_delta_seconds(); if (result0 !== null) { result0 = (function(offset, expires) {data = expires; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Event() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_event_type(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, event_type) { data.event = event_type.join('').toLowerCase(); })(pos0, result0[0]); } if (result0 === null) { pos = pos0; } return result0; } function parse_event_type() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token_nodot(); if (result0 !== null) { result1 = []; pos1 = pos; if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result2 !== null) { result3 = parse_token_nodot(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result2 !== null) { result3 = parse_token_nodot(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_From() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_SIP_URI_noparams(); if (result0 === null) { result0 = parse_name_addr(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_from_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_from_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var tag = data.tag; try { data = new NameAddrHeader(data.uri, data.display_name, data.params); if (tag) {data.setParam('tag',tag)} } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_from_param() { var result0; result0 = parse_tag_param(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_tag_param() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 3).toLowerCase() === "tag") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"tag\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, tag) {data.tag = tag; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_Max_Forwards() { var result0, result1; var pos0; pos0 = pos; result1 = parse_DIGIT(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_DIGIT(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, forwards) { data = parseInt(forwards.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Min_Expires() { var result0; var pos0; pos0 = pos; result0 = parse_delta_seconds(); if (result0 !== null) { result0 = (function(offset, min_expires) {data = min_expires; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Name_Addr_Header() { var result0, result1, result2, result3, result4, result5, result6; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = []; result1 = parse_display_name(); while (result1 !== null) { result0.push(result1); result1 = parse_display_name(); } if (result0 !== null) { result1 = parse_LAQUOT(); if (result1 !== null) { result2 = parse_SIP_URI(); if (result2 !== null) { result3 = parse_RAQUOT(); if (result3 !== null) { result4 = []; pos2 = pos; result5 = parse_SEMI(); if (result5 !== null) { result6 = parse_generic_param(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } while (result5 !== null) { result4.push(result5); pos2 = pos; result5 = parse_SEMI(); if (result5 !== null) { result6 = parse_generic_param(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } } if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { try { data = new NameAddrHeader(data.uri, data.display_name, data.params); } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Proxy_Authenticate() { var result0; result0 = parse_challenge(); return result0; } function parse_challenge() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; if (input.substr(pos, 6).toLowerCase() === "digest") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"Digest\""); } } if (result0 !== null) { result1 = parse_LWS(); if (result1 !== null) { result2 = parse_digest_cln(); if (result2 !== null) { result3 = []; pos1 = pos; result4 = parse_COMMA(); if (result4 !== null) { result5 = parse_digest_cln(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } while (result4 !== null) { result3.push(result4); pos1 = pos; result4 = parse_COMMA(); if (result4 !== null) { result5 = parse_digest_cln(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } } if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { result0 = parse_other_challenge(); } return result0; } function parse_other_challenge() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = parse_LWS(); if (result1 !== null) { result2 = parse_auth_param(); if (result2 !== null) { result3 = []; pos1 = pos; result4 = parse_COMMA(); if (result4 !== null) { result5 = parse_auth_param(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } while (result4 !== null) { result3.push(result4); pos1 = pos; result4 = parse_COMMA(); if (result4 !== null) { result5 = parse_auth_param(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } } if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_auth_param() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 === null) { result2 = parse_quoted_string(); } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_digest_cln() { var result0; result0 = parse_realm(); if (result0 === null) { result0 = parse_domain(); if (result0 === null) { result0 = parse_nonce(); if (result0 === null) { result0 = parse_opaque(); if (result0 === null) { result0 = parse_stale(); if (result0 === null) { result0 = parse_algorithm(); if (result0 === null) { result0 = parse_qop_options(); if (result0 === null) { result0 = parse_auth_param(); } } } } } } } return result0; } function parse_realm() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 5).toLowerCase() === "realm") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"realm\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_realm_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_realm_value() { var result0; var pos0; pos0 = pos; result0 = parse_quoted_string_clean(); if (result0 !== null) { result0 = (function(offset, realm) { data.realm = realm; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_domain() { var result0, result1, result2, result3, result4, result5, result6; var pos0, pos1; pos0 = pos; if (input.substr(pos, 6).toLowerCase() === "domain") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"domain\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_LDQUOT(); if (result2 !== null) { result3 = parse_URI(); if (result3 !== null) { result4 = []; pos1 = pos; result6 = parse_SP(); if (result6 !== null) { result5 = []; while (result6 !== null) { result5.push(result6); result6 = parse_SP(); } } else { result5 = null; } if (result5 !== null) { result6 = parse_URI(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos1; } } else { result5 = null; pos = pos1; } while (result5 !== null) { result4.push(result5); pos1 = pos; result6 = parse_SP(); if (result6 !== null) { result5 = []; while (result6 !== null) { result5.push(result6); result6 = parse_SP(); } } else { result5 = null; } if (result5 !== null) { result6 = parse_URI(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos1; } } else { result5 = null; pos = pos1; } } if (result4 !== null) { result5 = parse_RDQUOT(); if (result5 !== null) { result0 = [result0, result1, result2, result3, result4, result5]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_URI() { var result0; result0 = parse_absoluteURI(); if (result0 === null) { result0 = parse_abs_path(); } return result0; } function parse_nonce() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 5).toLowerCase() === "nonce") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"nonce\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_nonce_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_nonce_value() { var result0; var pos0; pos0 = pos; result0 = parse_quoted_string_clean(); if (result0 !== null) { result0 = (function(offset, nonce) { data.nonce=nonce; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_opaque() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6).toLowerCase() === "opaque") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"opaque\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_quoted_string_clean(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, opaque) { data.opaque=opaque; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_stale() { var result0, result1, result2; var pos0, pos1; pos0 = pos; if (input.substr(pos, 5).toLowerCase() === "stale") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"stale\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { pos1 = pos; if (input.substr(pos, 4).toLowerCase() === "true") { result2 = input.substr(pos, 4); pos += 4; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"true\""); } } if (result2 !== null) { result2 = (function(offset) { data.stale=true; })(pos1); } if (result2 === null) { pos = pos1; } if (result2 === null) { pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "false") { result2 = input.substr(pos, 5); pos += 5; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"false\""); } } if (result2 !== null) { result2 = (function(offset) { data.stale=false; })(pos1); } if (result2 === null) { pos = pos1; } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_algorithm() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 9).toLowerCase() === "algorithm") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"algorithm\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { if (input.substr(pos, 3).toLowerCase() === "md5") { result2 = input.substr(pos, 3); pos += 3; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"MD5\""); } } if (result2 === null) { if (input.substr(pos, 8).toLowerCase() === "md5-sess") { result2 = input.substr(pos, 8); pos += 8; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"MD5-sess\""); } } if (result2 === null) { result2 = parse_token(); } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, algorithm) { data.algorithm=algorithm.toUpperCase(); })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_qop_options() { var result0, result1, result2, result3, result4, result5, result6; var pos0, pos1, pos2; pos0 = pos; if (input.substr(pos, 3).toLowerCase() === "qop") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"qop\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_LDQUOT(); if (result2 !== null) { pos1 = pos; result3 = parse_qop_value(); if (result3 !== null) { result4 = []; pos2 = pos; if (input.charCodeAt(pos) === 44) { result5 = ","; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result5 !== null) { result6 = parse_qop_value(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } while (result5 !== null) { result4.push(result5); pos2 = pos; if (input.charCodeAt(pos) === 44) { result5 = ","; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result5 !== null) { result6 = parse_qop_value(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } } if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos1; } } else { result3 = null; pos = pos1; } if (result3 !== null) { result4 = parse_RDQUOT(); if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_qop_value() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 8).toLowerCase() === "auth-int") { result0 = input.substr(pos, 8); pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"auth-int\""); } } if (result0 === null) { if (input.substr(pos, 4).toLowerCase() === "auth") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"auth\""); } } if (result0 === null) { result0 = parse_token(); } } if (result0 !== null) { result0 = (function(offset, qop_value) { data.qop || (data.qop=[]); data.qop.push(qop_value.toLowerCase()); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Proxy_Require() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Record_Route() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_rec_route(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_rec_route(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_rec_route(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var idx, length; length = data.multi_header.length; for (idx = 0; idx < length; idx++) { if (data.multi_header[idx].parsed === null) { data = null; break; } } if (data !== null) { data = data.multi_header; } else { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_rec_route() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_name_addr(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var header; if(!data.multi_header) data.multi_header = []; try { header = new NameAddrHeader(data.uri, data.display_name, data.params); delete data.uri; delete data.display_name; delete data.params; } catch(e) { header = null; } data.multi_header.push( { 'possition': pos, 'offset': offset, 'parsed': header });})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Reason() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; if (input.substr(pos, 3).toLowerCase() === "sip") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SIP\""); } } if (result0 === null) { result0 = parse_token(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_reason_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_reason_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, protocol) { data.protocol = protocol.toLowerCase(); if (!data.params) data.params = {}; if (data.params.text && data.params.text[0] === '"') { var text = data.params.text; data.text = text.substring(1, text.length-1); delete data.params.text; } })(pos0, result0[0]); } if (result0 === null) { pos = pos0; } return result0; } function parse_reason_param() { var result0; result0 = parse_reason_cause(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_reason_cause() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "cause") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"cause\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result3 = parse_DIGIT(); if (result3 !== null) { result2 = []; while (result3 !== null) { result2.push(result3); result3 = parse_DIGIT(); } } else { result2 = null; } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, cause) { data.cause = parseInt(cause.join('')); })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_Require() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Route() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_route_param(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_route_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_route_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_route_param() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_name_addr(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Subscription_State() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_substate_value(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_subexp_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_subexp_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_substate_value() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 6).toLowerCase() === "active") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"active\""); } } if (result0 === null) { if (input.substr(pos, 7).toLowerCase() === "pending") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"pending\""); } } if (result0 === null) { if (input.substr(pos, 10).toLowerCase() === "terminated") { result0 = input.substr(pos, 10); pos += 10; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"terminated\""); } } if (result0 === null) { result0 = parse_token(); } } } if (result0 !== null) { result0 = (function(offset) { data.state = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_subexp_params() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6).toLowerCase() === "reason") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"reason\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_event_reason_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, reason) { if (typeof reason !== 'undefined') data.reason = reason; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } if (result0 === null) { pos0 = pos; pos1 = pos; if (input.substr(pos, 7).toLowerCase() === "expires") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"expires\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_delta_seconds(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, expires) { if (typeof expires !== 'undefined') data.expires = expires; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } if (result0 === null) { pos0 = pos; pos1 = pos; if (input.substr(pos, 11).toLowerCase() === "retry_after") { result0 = input.substr(pos, 11); pos += 11; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"retry_after\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_delta_seconds(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, retry_after) { if (typeof retry_after !== 'undefined') data.retry_after = retry_after; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } if (result0 === null) { result0 = parse_generic_param(); } } } return result0; } function parse_event_reason_value() { var result0; if (input.substr(pos, 11).toLowerCase() === "deactivated") { result0 = input.substr(pos, 11); pos += 11; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"deactivated\""); } } if (result0 === null) { if (input.substr(pos, 9).toLowerCase() === "probation") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"probation\""); } } if (result0 === null) { if (input.substr(pos, 8).toLowerCase() === "rejected") { result0 = input.substr(pos, 8); pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"rejected\""); } } if (result0 === null) { if (input.substr(pos, 7).toLowerCase() === "timeout") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"timeout\""); } } if (result0 === null) { if (input.substr(pos, 6).toLowerCase() === "giveup") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"giveup\""); } } if (result0 === null) { if (input.substr(pos, 10).toLowerCase() === "noresource") { result0 = input.substr(pos, 10); pos += 10; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"noresource\""); } } if (result0 === null) { if (input.substr(pos, 9).toLowerCase() === "invariant") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"invariant\""); } } if (result0 === null) { result0 = parse_token(); } } } } } } } return result0; } function parse_Subject() { var result0; result0 = parse_TEXT_UTF8_TRIM(); result0 = result0 !== null ? result0 : ""; return result0; } function parse_Supported() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } result0 = result0 !== null ? result0 : ""; return result0; } function parse_To() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_SIP_URI_noparams(); if (result0 === null) { result0 = parse_name_addr(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_to_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_to_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var tag = data.tag; try { data = new NameAddrHeader(data.uri, data.display_name, data.params); if (tag) {data.setParam('tag',tag)} } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_to_param() { var result0; result0 = parse_tag_param(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_Via() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_via_param(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_via_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_via_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_via_param() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; result0 = parse_sent_protocol(); if (result0 !== null) { result1 = parse_LWS(); if (result1 !== null) { result2 = parse_sent_by(); if (result2 !== null) { result3 = []; pos1 = pos; result4 = parse_SEMI(); if (result4 !== null) { result5 = parse_via_params(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } while (result4 !== null) { result3.push(result4); pos1 = pos; result4 = parse_SEMI(); if (result4 !== null) { result5 = parse_via_params(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } } if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_via_params() { var result0; result0 = parse_via_ttl(); if (result0 === null) { result0 = parse_via_maddr(); if (result0 === null) { result0 = parse_via_received(); if (result0 === null) { result0 = parse_via_branch(); if (result0 === null) { result0 = parse_response_port(); if (result0 === null) { result0 = parse_generic_param(); } } } } } return result0; } function parse_via_ttl() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 3).toLowerCase() === "ttl") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"ttl\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_ttl(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_ttl_value) { data.ttl = via_ttl_value; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_via_maddr() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "maddr") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"maddr\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_host(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_maddr) { data.maddr = via_maddr; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_via_received() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 8).toLowerCase() === "received") { result0 = input.substr(pos, 8); pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"received\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_IPv4address(); if (result2 === null) { result2 = parse_IPv6address(); } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_received) { data.received = via_received; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_via_branch() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6).toLowerCase() === "branch") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"branch\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_branch) { data.branch = via_branch; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_response_port() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "rport") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"rport\""); } } if (result0 !== null) { pos2 = pos; result1 = parse_EQUAL(); if (result1 !== null) { result2 = []; result3 = parse_DIGIT(); while (result3 !== null) { result2.push(result3); result3 = parse_DIGIT(); } if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { if(typeof response_port !== 'undefined') data.rport = response_port.join(''); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_sent_protocol() { var result0, result1, result2, result3, result4; var pos0; pos0 = pos; result0 = parse_protocol_name(); if (result0 !== null) { result1 = parse_SLASH(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result3 = parse_SLASH(); if (result3 !== null) { result4 = parse_transport(); if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_protocol_name() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 3).toLowerCase() === "sip") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SIP\""); } } if (result0 === null) { result0 = parse_token(); } if (result0 !== null) { result0 = (function(offset, via_protocol) { data.protocol = via_protocol; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_transport() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 3).toLowerCase() === "udp") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"UDP\""); } } if (result0 === null) { if (input.substr(pos, 3).toLowerCase() === "tcp") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"TCP\""); } } if (result0 === null) { if (input.substr(pos, 3).toLowerCase() === "tls") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"TLS\""); } } if (result0 === null) { if (input.substr(pos, 4).toLowerCase() === "sctp") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SCTP\""); } } if (result0 === null) { result0 = parse_token(); } } } } if (result0 !== null) { result0 = (function(offset, via_transport) { data.transport = via_transport; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_sent_by() { var result0, result1, result2; var pos0, pos1; pos0 = pos; result0 = parse_via_host(); if (result0 !== null) { pos1 = pos; result1 = parse_COLON(); if (result1 !== null) { result2 = parse_via_port(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos1; } } else { result1 = null; pos = pos1; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_via_host() { var result0; var pos0; pos0 = pos; result0 = parse_IPv4address(); if (result0 === null) { result0 = parse_IPv6reference(); if (result0 === null) { result0 = parse_hostname(); } } if (result0 !== null) { result0 = (function(offset) { data.host = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_via_port() { var result0, result1, result2, result3, result4; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_DIGIT(); result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result1 = parse_DIGIT(); result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result2 = parse_DIGIT(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_DIGIT(); result3 = result3 !== null ? result3 : ""; if (result3 !== null) { result4 = parse_DIGIT(); result4 = result4 !== null ? result4 : ""; if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_sent_by_port) { data.port = parseInt(via_sent_by_port.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_ttl() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_DIGIT(); if (result0 !== null) { result1 = parse_DIGIT(); result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result2 = parse_DIGIT(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, ttl) { return parseInt(ttl.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_WWW_Authenticate() { var result0; result0 = parse_challenge(); return result0; } function parse_Session_Expires() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_s_e_expires(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_s_e_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_s_e_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_s_e_expires() { var result0; var pos0; pos0 = pos; result0 = parse_delta_seconds(); if (result0 !== null) { result0 = (function(offset, expires) { data.expires = expires; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_s_e_params() { var result0; result0 = parse_s_e_refresher(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_s_e_refresher() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 9).toLowerCase() === "refresher") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"refresher\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { if (input.substr(pos, 3).toLowerCase() === "uac") { result2 = input.substr(pos, 3); pos += 3; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"uac\""); } } if (result2 === null) { if (input.substr(pos, 3).toLowerCase() === "uas") { result2 = input.substr(pos, 3); pos += 3; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"uas\""); } } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, s_e_refresher_value) { data.refresher = s_e_refresher_value.toLowerCase(); })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_extension_header() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = parse_HCOLON(); if (result1 !== null) { result2 = parse_header_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_header_value() { var result0, result1; result0 = []; result1 = parse_TEXT_UTF8char(); if (result1 === null) { result1 = parse_UTF8_CONT(); if (result1 === null) { result1 = parse_LWS(); } } while (result1 !== null) { result0.push(result1); result1 = parse_TEXT_UTF8char(); if (result1 === null) { result1 = parse_UTF8_CONT(); if (result1 === null) { result1 = parse_LWS(); } } } return result0; } function parse_message_body() { var result0, result1; result0 = []; result1 = parse_OCTET(); while (result1 !== null) { result0.push(result1); result1 = parse_OCTET(); } return result0; } function parse_uuid_URI() { var result0, result1; var pos0; pos0 = pos; if (input.substr(pos, 5) === "uuid:") { result0 = "uuid:"; pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"uuid:\""); } } if (result0 !== null) { result1 = parse_uuid(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_uuid() { var result0, result1, result2, result3, result4, result5, result6, result7, result8; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_hex8(); if (result0 !== null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 !== null) { result2 = parse_hex4(); if (result2 !== null) { if (input.charCodeAt(pos) === 45) { result3 = "-"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result3 !== null) { result4 = parse_hex4(); if (result4 !== null) { if (input.charCodeAt(pos) === 45) { result5 = "-"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result5 !== null) { result6 = parse_hex4(); if (result6 !== null) { if (input.charCodeAt(pos) === 45) { result7 = "-"; pos++; } else { result7 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result7 !== null) { result8 = parse_hex12(); if (result8 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, uuid) { data = input.substring(pos+5, offset); })(pos0, result0[0]); } if (result0 === null) { pos = pos0; } return result0; } function parse_hex4() { var result0, result1, result2, result3; var pos0; pos0 = pos; result0 = parse_HEXDIG(); if (result0 !== null) { result1 = parse_HEXDIG(); if (result1 !== null) { result2 = parse_HEXDIG(); if (result2 !== null) { result3 = parse_HEXDIG(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_hex8() { var result0, result1; var pos0; pos0 = pos; result0 = parse_hex4(); if (result0 !== null) { result1 = parse_hex4(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_hex12() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_hex4(); if (result0 !== null) { result1 = parse_hex4(); if (result1 !== null) { result2 = parse_hex4(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Refer_To() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_SIP_URI_noparams(); if (result0 === null) { result0 = parse_name_addr(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { try { data = new NameAddrHeader(data.uri, data.display_name, data.params); } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Replaces() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_call_id(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_replaces_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_replaces_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_call_id() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_word(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 !== null) { result2 = parse_word(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.call_id = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_replaces_param() { var result0; result0 = parse_to_tag(); if (result0 === null) { result0 = parse_from_tag(); if (result0 === null) { result0 = parse_early_flag(); if (result0 === null) { result0 = parse_generic_param(); } } } return result0; } function parse_to_tag() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6) === "to-tag") { result0 = "to-tag"; pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"to-tag\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, to_tag) { data.to_tag = to_tag; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_from_tag() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 8) === "from-tag") { result0 = "from-tag"; pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"from-tag\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, from_tag) { data.from_tag = from_tag; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_early_flag() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 10) === "early-only") { result0 = "early-only"; pos += 10; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"early-only\""); } } if (result0 !== null) { result0 = (function(offset) { data.early_only = true; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function cleanupExpected(expected) { expected.sort(); var lastExpected = null; var cleanExpected = []; for (var i = 0; i < expected.length; i++) { if (expected[i] !== lastExpected) { cleanExpected.push(expected[i]); lastExpected = expected[i]; } } return cleanExpected; } function computeErrorPosition() { /* * The first idea was to use |String.split| to break the input up to the * error position along newlines and derive the line and column from * there. However IE's |split| implementation is so broken that it was * enough to prevent it. */ var line = 1; var column = 1; var seenCR = false; for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) { var ch = input.charAt(i); if (ch === "\n") { if (!seenCR) { line++; } column = 1; seenCR = false; } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { line++; column = 1; seenCR = true; } else { column++; seenCR = false; } } return { line: line, column: column }; } var URI = require('./URI'); var NameAddrHeader = require('./NameAddrHeader'); var data = {}; var result = parseFunctions[startRule](); /* * The parser is now in one of the following three states: * * 1. The parser successfully parsed the whole input. * * - |result !== null| * - |pos === input.length| * - |rightmostFailuresExpected| may or may not contain something * * 2. The parser successfully parsed only a part of the input. * * - |result !== null| * - |pos < input.length| * - |rightmostFailuresExpected| may or may not contain something * * 3. The parser did not successfully parse any part of the input. * * - |result === null| * - |pos === 0| * - |rightmostFailuresExpected| contains at least one failure * * All code following this comment (including called functions) must * handle these states. */ if (result === null || pos !== input.length) { var offset = Math.max(pos, rightmostFailuresPos); var found = offset < input.length ? input.charAt(offset) : null; var errorPosition = computeErrorPosition(); new this.SyntaxError( cleanupExpected(rightmostFailuresExpected), found, offset, errorPosition.line, errorPosition.column ); return -1; } return data; }, /* Returns the parser source code. */ toSource: function() { return this._source; } }; /* Thrown when a parser encounters a syntax error. */ result.SyntaxError = function(expected, found, offset, line, column) { function buildMessage(expected, found) { var expectedHumanized, foundHumanized; switch (expected.length) { case 0: expectedHumanized = "end of input"; break; case 1: expectedHumanized = expected[0]; break; default: expectedHumanized = expected.slice(0, expected.length - 1).join(", ") + " or " + expected[expected.length - 1]; } foundHumanized = found ? quote(found) : "end of input"; return "Expected " + expectedHumanized + " but " + foundHumanized + " found."; } this.name = "SyntaxError"; this.expected = expected; this.found = found; this.message = buildMessage(expected, found); this.offset = offset; this.line = line; this.column = column; }; result.SyntaxError.prototype = Error.prototype; return result; })(); },{"./NameAddrHeader":9,"./URI":24}],7:[function(require,module,exports){ /** * Dependencies. */ var debug = require('debug')('JsSIP'); var adapter = require('webrtc-adapter'); var pkg = require('../package.json'); debug('version %s', pkg.version); var C = require('./Constants'); var Exceptions = require('./Exceptions'); var Utils = require('./Utils'); var UA = require('./UA'); var URI = require('./URI'); var NameAddrHeader = require('./NameAddrHeader'); var Grammar = require('./Grammar'); var WebSocketInterface = require('./WebSocketInterface'); /** * Expose the JsSIP module. */ var JsSIP = module.exports = { C: C, Exceptions: Exceptions, Utils: Utils, UA: UA, URI: URI, NameAddrHeader: NameAddrHeader, WebSocketInterface: WebSocketInterface, Grammar: Grammar, // Expose the debug module. debug: require('debug'), // Expose the adapter module. adapter: adapter }; Object.defineProperties(JsSIP, { name: { get: function() { return pkg.title; } }, version: { get: function() { return pkg.version; } } }); },{"../package.json":50,"./Constants":1,"./Exceptions":5,"./Grammar":6,"./NameAddrHeader":9,"./UA":23,"./URI":24,"./Utils":25,"./WebSocketInterface":26,"debug":34,"webrtc-adapter":41}],8:[function(require,module,exports){ module.exports = Message; /** * Dependencies. */ var util = require('util'); var events = require('events'); var JsSIP_C = require('./Constants'); var SIPMessage = require('./SIPMessage'); var Utils = require('./Utils'); var RequestSender = require('./RequestSender'); var Transactions = require('./Transactions'); var Exceptions = require('./Exceptions'); function Message(ua) { this.ua = ua; // Custom message empty object for high level use this.data = {}; events.EventEmitter.call(this); } util.inherits(Message, events.EventEmitter); Message.prototype.send = function(target, body, options) { var request_sender, event, contentType, eventHandlers, extraHeaders, originalTarget = target; if (target === undefined || body === undefined) { throw new TypeError('Not enough arguments'); } // Check target validity target = this.ua.normalizeTarget(target); if (!target) { throw new TypeError('Invalid target: '+ originalTarget); } // Get call options options = options || {}; extraHeaders = options.extraHeaders && options.extraHeaders.slice() || []; eventHandlers = options.eventHandlers || {}; contentType = options.contentType || 'text/plain'; this.content_type = contentType; // Set event handlers for (event in eventHandlers) { this.on(event, eventHandlers[event]); } this.closed = false; this.ua.applicants[this] = this; extraHeaders.push('Content-Type: '+ contentType); this.request = new SIPMessage.OutgoingRequest(JsSIP_C.MESSAGE, target, this.ua, null, extraHeaders); if(body) { this.request.body = body; this.content = body; } else { this.content = null; } request_sender = new RequestSender(this, this.ua); this.newMessage('local', this.request); request_sender.send(); }; Message.prototype.receiveResponse = function(response) { var cause; if(this.closed) { return; } switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): delete this.ua.applicants[this]; this.emit('succeeded', { originator: 'remote', response: response }); break; default: delete this.ua.applicants[this]; cause = Utils.sipErrorCause(response.status_code); this.emit('failed', { originator: 'remote', response: response, cause: cause }); break; } }; Message.prototype.onRequestTimeout = function() { if(this.closed) { return; } this.emit('failed', { originator: 'system', cause: JsSIP_C.causes.REQUEST_TIMEOUT }); }; Message.prototype.onTransportError = function() { if(this.closed) { return; } this.emit('failed', { originator: 'system', cause: JsSIP_C.causes.CONNECTION_ERROR }); }; Message.prototype.close = function() { this.closed = true; delete this.ua.applicants[this]; }; Message.prototype.init_incoming = function(request) { var transaction; this.request = request; this.content_type = request.getHeader('Content-Type'); if (request.body) { this.content = request.body; } else { this.content = null; } this.newMessage('remote', request); transaction = this.ua.transactions.nist[request.via_branch]; if (transaction && (transaction.state === Transactions.C.STATUS_TRYING || transaction.state === Transactions.C.STATUS_PROCEEDING)) { request.reply(200); } }; /** * Accept the incoming Message * Only valid for incoming Messages */ Message.prototype.accept = function(options) { options = options || {}; var extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body; if (this.direction !== 'incoming') { throw new Exceptions.NotSupportedError('"accept" not supported for outgoing Message'); } this.request.reply(200, null, extraHeaders, body); }; /** * Reject the incoming Message * Only valid for incoming Messages */ Message.prototype.reject = function(options) { options = options || {}; var status_code = options.status_code || 480, reason_phrase = options.reason_phrase, extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body; if (this.direction !== 'incoming') { throw new Exceptions.NotSupportedError('"reject" not supported for outgoing Message'); } if (status_code < 300 || status_code >= 700) { throw new TypeError('Invalid status_code: '+ status_code); } this.request.reply(status_code, reason_phrase, extraHeaders, body); }; /** * Internal Callbacks */ Message.prototype.newMessage = function(originator, request) { if (originator === 'remote') { this.direction = 'incoming'; this.local_identity = request.to; this.remote_identity = request.from; } else if (originator === 'local'){ this.direction = 'outgoing'; this.local_identity = request.from; this.remote_identity = request.to; } this.ua.newMessage({ originator: originator, message: this, request: request }); }; },{"./Constants":1,"./Exceptions":5,"./RequestSender":17,"./SIPMessage":18,"./Transactions":21,"./Utils":25,"events":28,"util":32}],9:[function(require,module,exports){ module.exports = NameAddrHeader; /** * Dependencies. */ var URI = require('./URI'); var Grammar = require('./Grammar'); function NameAddrHeader(uri, display_name, parameters) { var param; // Checks if(!uri || !(uri instanceof URI)) { throw new TypeError('missing or invalid "uri" parameter'); } // Initialize parameters this.uri = uri; this.parameters = {}; for (param in parameters) { this.setParam(param, parameters[param]); } Object.defineProperties(this, { display_name: { get: function() { return display_name; }, set: function(value) { display_name = (value === 0) ? '0' : value; } } }); } NameAddrHeader.prototype = { setParam: function(key, value) { if (key) { this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString(); } }, getParam: function(key) { if(key) { return this.parameters[key.toLowerCase()]; } }, hasParam: function(key) { if(key) { return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false; } }, deleteParam: function(parameter) { var value; parameter = parameter.toLowerCase(); if (this.parameters.hasOwnProperty(parameter)) { value = this.parameters[parameter]; delete this.parameters[parameter]; return value; } }, clearParams: function() { this.parameters = {}; }, clone: function() { return new NameAddrHeader( this.uri.clone(), this.display_name, JSON.parse(JSON.stringify(this.parameters))); }, toString: function() { var body, parameter; body = (this.display_name || this.display_name === 0) ? '"' + this.display_name + '" ' : ''; body += '<' + this.uri.toString() + '>'; for (parameter in this.parameters) { body += ';' + parameter; if (this.parameters[parameter] !== null) { body += '='+ this.parameters[parameter]; } } return body; } }; /** * Parse the given string and returns a NameAddrHeader instance or undefined if * it is an invalid NameAddrHeader. */ NameAddrHeader.parse = function(name_addr_header) { name_addr_header = Grammar.parse(name_addr_header,'Name_Addr_Header'); if (name_addr_header !== -1) { return name_addr_header; } else { return undefined; } }; },{"./Grammar":6,"./URI":24}],10:[function(require,module,exports){ var Parser = {}; module.exports = Parser; /** * Dependencies. */ var debugerror = require('debug')('JsSIP:ERROR:Parser'); debugerror.log = console.warn.bind(console); var Grammar = require('./Grammar'); var SIPMessage = require('./SIPMessage'); /** * Extract and parse every header of a SIP message. */ function getHeader(data, headerStart) { var // 'start' position of the header. start = headerStart, // 'end' position of the header. end = 0, // 'partial end' position of the header. partialEnd = 0; //End of message. if (data.substring(start, start + 2).match(/(^\r\n)/)) { return -2; } while(end === 0) { // Partial End of Header. partialEnd = data.indexOf('\r\n', start); // 'indexOf' returns -1 if the value to be found never occurs. if (partialEnd === -1) { return partialEnd; } if(!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && data.charAt(partialEnd + 2).match(/(^\s+)/)) { // Not the end of the message. Continue from the next position. start = partialEnd + 2; } else { end = partialEnd; } } return end; } function parseHeader(message, data, headerStart, headerEnd) { var header, idx, length, parsed, hcolonIndex = data.indexOf(':', headerStart), headerName = data.substring(headerStart, hcolonIndex).trim(), headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); // If header-field is well-known, parse it. switch(headerName.toLowerCase()) { case 'via': case 'v': message.addHeader('via', headerValue); if(message.getHeaders('via').length === 1) { parsed = message.parseHeader('Via'); if(parsed) { message.via = parsed; message.via_branch = parsed.branch; } } else { parsed = 0; } break; case 'from': case 'f': message.setHeader('from', headerValue); parsed = message.parseHeader('from'); if(parsed) { message.from = parsed; message.from_tag = parsed.getParam('tag'); } break; case 'to': case 't': message.setHeader('to', headerValue); parsed = message.parseHeader('to'); if(parsed) { message.to = parsed; message.to_tag = parsed.getParam('tag'); } break; case 'record-route': parsed = Grammar.parse(headerValue, 'Record_Route'); if (parsed === -1) { parsed = undefined; } else { length = parsed.length; for (idx = 0; idx < length; idx++) { header = parsed[idx]; message.addHeader('record-route', headerValue.substring(header.possition, header.offset)); message.headers['Record-Route'][message.getHeaders('record-route').length - 1].parsed = header.parsed; } } break; case 'call-id': case 'i': message.setHeader('call-id', headerValue); parsed = message.parseHeader('call-id'); if(parsed) { message.call_id = headerValue; } break; case 'contact': case 'm': parsed = Grammar.parse(headerValue, 'Contact'); if (parsed === -1) { parsed = undefined; } else { length = parsed.length; for (idx = 0; idx < length; idx++) { header = parsed[idx]; message.addHeader('contact', headerValue.substring(header.possition, header.offset)); message.headers.Contact[message.getHeaders('contact').length - 1].parsed = header.parsed; } } break; case 'content-length': case 'l': message.setHeader('content-length', headerValue); parsed = message.parseHeader('content-length'); break; case 'content-type': case 'c': message.setHeader('content-type', headerValue); parsed = message.parseHeader('content-type'); break; case 'cseq': message.setHeader('cseq', headerValue); parsed = message.parseHeader('cseq'); if(parsed) { message.cseq = parsed.value; } if(message instanceof SIPMessage.IncomingResponse) { message.method = parsed.method; } break; case 'max-forwards': message.setHeader('max-forwards', headerValue); parsed = message.parseHeader('max-forwards'); break; case 'www-authenticate': message.setHeader('www-authenticate', headerValue); parsed = message.parseHeader('www-authenticate'); break; case 'proxy-authenticate': message.setHeader('proxy-authenticate', headerValue); parsed = message.parseHeader('proxy-authenticate'); break; case 'session-expires': case 'x': message.setHeader('session-expires', headerValue); parsed = message.parseHeader('session-expires'); if (parsed) { message.session_expires = parsed.expires; message.session_expires_refresher = parsed.refresher; } break; case 'refer-to': case 'r': message.setHeader('refer-to', headerValue); parsed = message.parseHeader('refer-to'); if(parsed) { message.refer_to = parsed; } break; case 'replaces': message.setHeader('replaces', headerValue); parsed = message.parseHeader('replaces'); if(parsed) { message.replaces = parsed; } break; case 'event': case 'o': message.setHeader('event', headerValue); parsed = message.parseHeader('event'); if(parsed) { message.event = parsed; } break; default: // Do not parse this header. message.setHeader(headerName, headerValue); parsed = 0; } if (parsed === undefined) { return { error: 'error parsing header "'+ headerName +'"' }; } else { return true; } } /** * Parse SIP Message */ Parser.parseMessage = function(data, ua) { var message, firstLine, contentLength, bodyStart, parsed, headerStart = 0, headerEnd = data.indexOf('\r\n'); if(headerEnd === -1) { debugerror('parseMessage() | no CRLF found, not a SIP message'); return; } // Parse first line. Check if it is a Request or a Reply. firstLine = data.substring(0, headerEnd); parsed = Grammar.parse(firstLine, 'Request_Response'); if(parsed === -1) { debugerror('parseMessage() | error parsing first line of SIP message: "' + firstLine + '"'); return; } else if(!parsed.status_code) { message = new SIPMessage.IncomingRequest(ua); message.method = parsed.method; message.ruri = parsed.uri; } else { message = new SIPMessage.IncomingResponse(); message.status_code = parsed.status_code; message.reason_phrase = parsed.reason_phrase; } message.data = data; headerStart = headerEnd + 2; /* Loop over every line in data. Detect the end of each header and parse * it or simply add to the headers collection. */ while(true) { headerEnd = getHeader(data, headerStart); // The SIP message has normally finished. if(headerEnd === -2) { bodyStart = headerStart + 2; break; } // data.indexOf returned -1 due to a malformed message. else if(headerEnd === -1) { debugerror('parseMessage() | malformed message'); return; } parsed = parseHeader(message, data, headerStart, headerEnd); if(parsed !== true) { debugerror('parseMessage() |', parsed.error); return; } headerStart = headerEnd + 2; } /* RFC3261 18.3. * If there are additional bytes in the transport packet * beyond the end of the body, they MUST be discarded. */ if(message.hasHeader('content-length')) { contentLength = message.getHeader('content-length'); message.body = data.substr(bodyStart, contentLength); } else { message.body = data.substring(bodyStart); } return message; }; },{"./Grammar":6,"./SIPMessage":18,"debug":34}],11:[function(require,module,exports){ /* globals RTCPeerConnection: false, RTCSessionDescription: false */ module.exports = RTCSession; var C = { // RTCSession states STATUS_NULL: 0, STATUS_INVITE_SENT: 1, STATUS_1XX_RECEIVED: 2, STATUS_INVITE_RECEIVED: 3, STATUS_WAITING_FOR_ANSWER: 4, STATUS_ANSWERED: 5, STATUS_WAITING_FOR_ACK: 6, STATUS_CANCELED: 7, STATUS_TERMINATED: 8, STATUS_CONFIRMED: 9 }; /** * Expose C object. */ RTCSession.C = C; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debug = require('debug')('JsSIP:RTCSession'); var debugerror = require('debug')('JsSIP:ERROR:RTCSession'); debugerror.log = console.warn.bind(console); var sdp_transform = require('sdp-transform'); var JsSIP_C = require('./Constants'); var Exceptions = require('./Exceptions'); var Transactions = require('./Transactions'); var Utils = require('./Utils'); var Timers = require('./Timers'); var SIPMessage = require('./SIPMessage'); var Dialog = require('./Dialog'); var RequestSender = require('./RequestSender'); var RTCSession_Request = require('./RTCSession/Request'); var RTCSession_DTMF = require('./RTCSession/DTMF'); var RTCSession_ReferNotifier = require('./RTCSession/ReferNotifier'); var RTCSession_ReferSubscriber = require('./RTCSession/ReferSubscriber'); /** * Local variables. */ var holdMediaTypes = ['audio', 'video']; function RTCSession(ua) { debug('new'); this.ua = ua; this.status = C.STATUS_NULL; this.dialog = null; this.earlyDialogs = {}; this.connection = null; // The RTCPeerConnection instance (public attribute). // RTCSession confirmation flag this.is_confirmed = false; // is late SDP being negotiated this.late_sdp = false; // Default rtcOfferConstraints and rtcAnswerConstrainsts (passed in connect() or answer()). this.rtcOfferConstraints = null; this.rtcAnswerConstraints = null; // Local MediaStream. this.localMediaStream = null; this.localMediaStreamLocallyGenerated = false; // Flag to indicate PeerConnection ready for new actions. this.rtcReady = true; // SIP Timers this.timers = { ackTimer: null, expiresTimer: null, invite2xxTimer: null, userNoAnswerTimer: null }; // Session info this.direction = null; this.local_identity = null; this.remote_identity = null; this.start_time = null; this.end_time = null; this.tones = null; // Mute/Hold state this.audioMuted = false; this.videoMuted = false; this.localHold = false; this.remoteHold = false; // Session Timers (RFC 4028) this.sessionTimers = { enabled: this.ua.configuration.session_timers, defaultExpires: JsSIP_C.SESSION_EXPIRES, currentExpires: null, running: false, refresher: false, timer: null // A setTimeout. }; // Map of ReferSubscriber instances indexed by the REFER's CSeq number this.referSubscribers = {}; // Custom session empty object for high level use this.data = {}; // Expose session failed/ended causes as a property of the RTCSession instance this.causes = JsSIP_C.causes; events.EventEmitter.call(this); } util.inherits(RTCSession, events.EventEmitter); /** * User API */ RTCSession.prototype.isInProgress = function() { switch(this.status) { case C.STATUS_NULL: case C.STATUS_INVITE_SENT: case C.STATUS_1XX_RECEIVED: case C.STATUS_INVITE_RECEIVED: case C.STATUS_WAITING_FOR_ANSWER: return true; default: return false; } }; RTCSession.prototype.isEstablished = function() { switch(this.status) { case C.STATUS_ANSWERED: case C.STATUS_WAITING_FOR_ACK: case C.STATUS_CONFIRMED: return true; default: return false; } }; RTCSession.prototype.isEnded = function() { switch(this.status) { case C.STATUS_CANCELED: case C.STATUS_TERMINATED: return true; default: return false; } }; RTCSession.prototype.isMuted = function() { return { audio: this.audioMuted, video: this.videoMuted }; }; RTCSession.prototype.isOnHold = function() { return { local: this.localHold, remote: this.remoteHold }; }; /** * Check if RTCSession is ready for an outgoing re-INVITE or UPDATE with SDP. */ RTCSession.prototype.isReadyToReOffer = function() { if (! this.rtcReady) { debug('isReadyToReOffer() | internal WebRTC status not ready'); return false; } // No established yet. if (! this.dialog) { debug('isReadyToReOffer() | session not established yet'); return false; } // Another INVITE transaction is in progress if (this.dialog.uac_pending_reply === true || this.dialog.uas_pending_reply === true) { debug('isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress'); return false; } return true; }; RTCSession.prototype.connect = function(target, options, initCallback) { debug('connect()'); options = options || {}; var event, requestParams, originalTarget = target, eventHandlers = options.eventHandlers || {}, extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], mediaConstraints = options.mediaConstraints || {audio: true, video: true}, mediaStream = options.mediaStream || null, pcConfig = options.pcConfig || {iceServers:[]}, rtcConstraints = options.rtcConstraints || null, rtcOfferConstraints = options.rtcOfferConstraints || null; this.rtcOfferConstraints = rtcOfferConstraints; this.rtcAnswerConstraints = options.rtcAnswerConstraints || null; // Session Timers. if (this.sessionTimers.enabled) { if (Utils.isDecimal(options.sessionTimersExpires)) { if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) { this.sessionTimers.defaultExpires = options.sessionTimersExpires; } else { this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES; } } } this.data = options.data || this.data; if (target === undefined) { throw new TypeError('Not enough arguments'); } // Check WebRTC support. if (!window.RTCPeerConnection) { throw new Exceptions.NotSupportedError('WebRTC not supported'); } // Check target validity target = this.ua.normalizeTarget(target); if (!target) { throw new TypeError('Invalid target: '+ originalTarget); } // Check Session Status if (this.status !== C.STATUS_NULL) { throw new Exceptions.InvalidStateError(this.status); } // Set event handlers for (event in eventHandlers) { this.on(event, eventHandlers[event]); } // Session parameter initialization this.from_tag = Utils.newTag(); // Set anonymous property this.anonymous = options.anonymous || false; // OutgoingSession specific parameters this.isCanceled = false; requestParams = {from_tag: this.from_tag}; this.contact = this.ua.contact.toString({ anonymous: this.anonymous, outbound: true }); if (this.anonymous) { requestParams.from_display_name = 'Anonymous'; requestParams.from_uri = 'sip:anonymous@anonymous.invalid'; extraHeaders.push('P-Preferred-Identity: '+ this.ua.configuration.uri.toString()); extraHeaders.push('Privacy: id'); } extraHeaders.push('Contact: '+ this.contact); extraHeaders.push('Content-Type: application/sdp'); if (this.sessionTimers.enabled) { extraHeaders.push('Session-Expires: ' + this.sessionTimers.defaultExpires); } this.request = new SIPMessage.OutgoingRequest(JsSIP_C.INVITE, target, this.ua, requestParams, extraHeaders); this.id = this.request.call_id + this.from_tag; // Create a new RTCPeerConnection instance. createRTCConnection.call(this, pcConfig, rtcConstraints); // Save the session into the ua sessions collection. this.ua.sessions[this.id] = this; // Set internal properties this.direction = 'outgoing'; this.local_identity = this.request.from; this.remote_identity = this.request.to; // User explicitly provided a newRTCSession callback for this session if (initCallback) { initCallback(this); } else { newRTCSession.call(this, 'local', this.request); } sendInitialRequest.call(this, mediaConstraints, rtcOfferConstraints, mediaStream); }; RTCSession.prototype.init_incoming = function(request, initCallback) { debug('init_incoming()'); var expires, self = this, contentType = request.getHeader('Content-Type'); // Check body and content type if (request.body && (contentType !== 'application/sdp')) { request.reply(415); return; } // Session parameter initialization this.status = C.STATUS_INVITE_RECEIVED; this.from_tag = request.from_tag; this.id = request.call_id + this.from_tag; this.request = request; this.contact = this.ua.contact.toString(); // Save the session into the ua sessions collection. this.ua.sessions[this.id] = this; // Get the Expires header value if exists if (request.hasHeader('expires')) { expires = request.getHeader('expires') * 1000; } /* Set the to_tag before * replying a response code that will create a dialog. */ request.to_tag = Utils.newTag(); // An error on dialog creation will fire 'failed' event if (! createDialog.call(this, request, 'UAS', true)) { request.reply(500, 'Missing Contact header field'); return; } if (request.body) { this.late_sdp = false; } else { this.late_sdp = true; } this.status = C.STATUS_WAITING_FOR_ANSWER; // Set userNoAnswerTimer this.timers.userNoAnswerTimer = setTimeout(function() { request.reply(408); failed.call(self, 'local',null, JsSIP_C.causes.NO_ANSWER); }, this.ua.configuration.no_answer_timeout ); /* Set expiresTimer * RFC3261 13.3.1 */ if (expires) { this.timers.expiresTimer = setTimeout(function() { if(self.status === C.STATUS_WAITING_FOR_ANSWER) { request.reply(487); failed.call(self, 'system', null, JsSIP_C.causes.EXPIRES); } }, expires ); } // Set internal properties this.direction = 'incoming'; this.local_identity = request.to; this.remote_identity = request.from; // A init callback was specifically defined if (initCallback) { initCallback(this); // Fire 'newRTCSession' event. } else { newRTCSession.call(this, 'remote', request); } // The user may have rejected the call in the 'newRTCSession' event. if (this.status === C.STATUS_TERMINATED) { return; } // Reply 180. request.reply(180, null, ['Contact: ' + self.contact]); // Fire 'progress' event. // TODO: Document that 'response' field in 'progress' event is null for // incoming calls. progress.call(self, 'local', null); }; /** * Answer the call. */ RTCSession.prototype.answer = function(options) { debug('answer()'); options = options || {}; var idx, length, sdp, tracks, peerHasAudioLine = false, peerHasVideoLine = false, peerOffersFullAudio = false, peerOffersFullVideo = false, self = this, request = this.request, extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], mediaConstraints = options.mediaConstraints || {}, mediaStream = options.mediaStream || null, pcConfig = options.pcConfig || {iceServers:[]}, rtcConstraints = options.rtcConstraints || null, rtcAnswerConstraints = options.rtcAnswerConstraints || null; this.rtcAnswerConstraints = rtcAnswerConstraints; this.rtcOfferConstraints = options.rtcOfferConstraints || null; // Session Timers. if (this.sessionTimers.enabled) { if (Utils.isDecimal(options.sessionTimersExpires)) { if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) { this.sessionTimers.defaultExpires = options.sessionTimersExpires; } else { this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES; } } } this.data = options.data || this.data; // Check Session Direction and Status if (this.direction !== 'incoming') { throw new Exceptions.NotSupportedError('"answer" not supported for outgoing RTCSession'); } else if (this.status !== C.STATUS_WAITING_FOR_ANSWER) { throw new Exceptions.InvalidStateError(this.status); } this.status = C.STATUS_ANSWERED; // An error on dialog creation will fire 'failed' event if (! createDialog.call(this, request, 'UAS')) { request.reply(500, 'Error creating dialog'); return; } clearTimeout(this.timers.userNoAnswerTimer); extraHeaders.unshift('Contact: ' + self.contact); // Determine incoming media from incoming SDP offer (if any). sdp = request.parseSDP(); // Make sure sdp.media is an array, not the case if there is only one media if (! Array.isArray(sdp.media)) { sdp.media = [sdp.media]; } // Go through all medias in SDP to find offered capabilities to answer with idx = sdp.media.length; while(idx--) { var m = sdp.media[idx]; if (m.type === 'audio') { peerHasAudioLine = true; if (!m.direction || m.direction === 'sendrecv') { peerOffersFullAudio = true; } } if (m.type === 'video') { peerHasVideoLine = true; if (!m.direction || m.direction === 'sendrecv') { peerOffersFullVideo = true; } } } // Remove audio from mediaStream if suggested by mediaConstraints if (mediaStream && mediaConstraints.audio === false) { tracks = mediaStream.getAudioTracks(); length = tracks.length; for (idx=0; idx<length; idx++) { mediaStream.removeTrack(tracks[idx]); } } // Remove video from mediaStream if suggested by mediaConstraints if (mediaStream && mediaConstraints.video === false) { tracks = mediaStream.getVideoTracks(); length = tracks.length; for (idx=0; idx<length; idx++) { mediaStream.removeTrack(tracks[idx]); } } // Set audio constraints based on incoming stream if not supplied if (!mediaStream && mediaConstraints.audio === undefined) { mediaConstraints.audio = peerOffersFullAudio; } // Set video constraints based on incoming stream if not supplied if (!mediaStream && mediaConstraints.video === undefined) { mediaConstraints.video = peerOffersFullVideo; } // Don't ask for audio if the incoming offer has no audio section if (!mediaStream && !peerHasAudioLine) { mediaConstraints.audio = false; } // Don't ask for video if the incoming offer has no video section if (!mediaStream && !peerHasVideoLine) { mediaConstraints.video = false; } // Create a new RTCPeerConnection instance. // TODO: This may throw an error, should react. createRTCConnection.call(this, pcConfig, rtcConstraints); // If a local MediaStream is given use it. if (mediaStream) { userMediaSucceeded(mediaStream); // If at least audio or video is requested prompt getUserMedia. } else if (mediaConstraints.audio || mediaConstraints.video) { self.localMediaStreamLocallyGenerated = true; navigator.mediaDevices.getUserMedia(mediaConstraints) .then(userMediaSucceeded) .catch(function(error) { userMediaFailed(error); self.emit('getusermediafailed', error); }); // Otherwise don't prompt getUserMedia. } else { userMediaSucceeded(null); } // User media succeeded function userMediaSucceeded(stream) { if (self.status === C.STATUS_TERMINATED) { return; } self.localMediaStream = stream; if (stream) { self.connection.addStream(stream); } // If it's an incoming INVITE without SDP notify the app with the // RTCPeerConnection so it can do stuff on it before generating the offer. if (! self.request.body) { self.emit('peerconnection', { peerconnection: self.connection }); } if (! self.late_sdp) { var e = {originator:'remote', type:'offer', sdp:request.body}; var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp}); self.emit('sdp', e); self.connection.setRemoteDescription(offer) .then(remoteDescriptionSucceededOrNotNeeded) .catch(function(error) { request.reply(488); failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR); self.emit('peerconnection:setremotedescriptionfailed', error); }); } else { remoteDescriptionSucceededOrNotNeeded(); } } // User media failed function userMediaFailed() { if (self.status === C.STATUS_TERMINATED) { return; } request.reply(480); failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS); } function remoteDescriptionSucceededOrNotNeeded() { connecting.call(self, request); if (! self.late_sdp) { createLocalDescription.call(self, 'answer', rtcSucceeded, rtcFailed, rtcAnswerConstraints); } else { createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, self.rtcOfferConstraints); } } function rtcSucceeded(desc) { if (self.status === C.STATUS_TERMINATED) { return; } // run for reply success callback function replySucceeded() { self.status = C.STATUS_WAITING_FOR_ACK; setInvite2xxTimer.call(self, request, desc); setACKTimer.call(self); accepted.call(self, 'local'); } // run for reply failure callback function replyFailed() { failed.call(self, 'system', null, JsSIP_C.causes.CONNECTION_ERROR); } handleSessionTimersInIncomingRequest.call(self, request, extraHeaders); request.reply(200, null, extraHeaders, desc, replySucceeded, replyFailed ); } function rtcFailed() { if (self.status === C.STATUS_TERMINATED) { return; } request.reply(500); failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR); } }; /** * Terminate the call. */ RTCSession.prototype.terminate = function(options) { debug('terminate()'); options = options || {}; var cancel_reason, dialog, cause = options.cause || JsSIP_C.causes.BYE, status_code = options.status_code, reason_phrase = options.reason_phrase, extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body, self = this; // Check Session Status if (this.status === C.STATUS_TERMINATED) { throw new Exceptions.InvalidStateError(this.status); } switch(this.status) { // - UAC - case C.STATUS_NULL: case C.STATUS_INVITE_SENT: case C.STATUS_1XX_RECEIVED: debug('canceling session'); if (status_code && (status_code < 200 || status_code >= 700)) { throw new TypeError('Invalid status_code: '+ status_code); } else if (status_code) { reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || ''; cancel_reason = 'SIP ;cause=' + status_code + ' ;text="' + reason_phrase + '"'; } // Check Session Status if (this.status === C.STATUS_NULL) { this.isCanceled = true; this.cancelReason = cancel_reason; } else if (this.status === C.STATUS_INVITE_SENT) { this.isCanceled = true; this.cancelReason = cancel_reason; } else if(this.status === C.STATUS_1XX_RECEIVED) { this.request.cancel(cancel_reason); } this.status = C.STATUS_CANCELED; failed.call(this, 'local', null, JsSIP_C.causes.CANCELED); break; // - UAS - case C.STATUS_WAITING_FOR_ANSWER: case C.STATUS_ANSWERED: debug('rejecting session'); status_code = status_code || 480; if (status_code < 300 || status_code >= 700) { throw new TypeError('Invalid status_code: '+ status_code); } this.request.reply(status_code, reason_phrase, extraHeaders, body); failed.call(this, 'local', null, JsSIP_C.causes.REJECTED); break; case C.STATUS_WAITING_FOR_ACK: case C.STATUS_CONFIRMED: debug('terminating session'); reason_phrase = options.reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || ''; if (status_code && (status_code < 200 || status_code >= 700)) { throw new TypeError('Invalid status_code: '+ status_code); } else if (status_code) { extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"'); } /* RFC 3261 section 15 (Terminating a session): * * "...the callee's UA MUST NOT send a BYE on a confirmed dialog * until it has received an ACK for its 2xx response or until the server * transaction times out." */ if (this.status === C.STATUS_WAITING_FOR_ACK && this.direction === 'incoming' && this.request.server_transaction.state !== Transactions.C.STATUS_TERMINATED) { // Save the dialog for later restoration dialog = this.dialog; // Send the BYE as soon as the ACK is received... this.receiveRequest = function(request) { if(request.method === JsSIP_C.ACK) { sendRequest.call(this, JsSIP_C.BYE, { extraHeaders: extraHeaders, body: body }); dialog.terminate(); } }; // .., or when the INVITE transaction times out this.request.server_transaction.on('stateChanged', function(){ if (this.state === Transactions.C.STATUS_TERMINATED) { sendRequest.call(self, JsSIP_C.BYE, { extraHeaders: extraHeaders, body: body }); dialog.terminate(); } }); ended.call(this, 'local', null, cause); // Restore the dialog into 'this' in order to be able to send the in-dialog BYE :-) this.dialog = dialog; // Restore the dialog into 'ua' so the ACK can reach 'this' session this.ua.dialogs[dialog.id.toString()] = dialog; } else { sendRequest.call(this, JsSIP_C.BYE, { extraHeaders: extraHeaders, body: body }); ended.call(this, 'local', null, cause); } } }; RTCSession.prototype.close = function() { debug('close()'); var idx; if (this.status === C.STATUS_TERMINATED) { return; } // Terminate RTC. if (this.connection) { try { this.connection.close(); } catch(error) { debugerror('close() | error closing the RTCPeerConnection: %o', error); } } // Close local MediaStream if it was not given by the user. if (this.localMediaStream && this.localMediaStreamLocallyGenerated) { debug('close() | closing local MediaStream'); Utils.closeMediaStream(this.localMediaStream); } // Terminate signaling. // Clear SIP timers for(idx in this.timers) { clearTimeout(this.timers[idx]); } // Clear Session Timers. clearTimeout(this.sessionTimers.timer); // Terminate confirmed dialog if (this.dialog) { this.dialog.terminate(); delete this.dialog; } // Terminate early dialogs for(idx in this.earlyDialogs) { this.earlyDialogs[idx].terminate(); delete this.earlyDialogs[idx]; } this.status = C.STATUS_TERMINATED; delete this.ua.sessions[this.id]; }; RTCSession.prototype.sendDTMF = function(tones, options) { debug('sendDTMF() | tones: %s', tones); var duration, interToneGap, position = 0, self = this; options = options || {}; duration = options.duration || null; interToneGap = options.interToneGap || null; if (tones === undefined) { throw new TypeError('Not enough arguments'); } // Check Session Status if (this.status !== C.STATUS_CONFIRMED && this.status !== C.STATUS_WAITING_FOR_ACK) { throw new Exceptions.InvalidStateError(this.status); } // Convert to string if(typeof tones === 'number') { tones = tones.toString(); } // Check tones if (!tones || typeof tones !== 'string' || !tones.match(/^[0-9A-DR#*,]+$/i)) { throw new TypeError('Invalid tones: '+ tones); } // Check duration if (duration && !Utils.isDecimal(duration)) { throw new TypeError('Invalid tone duration: '+ duration); } else if (!duration) { duration = RTCSession_DTMF.C.DEFAULT_DURATION; } else if (duration < RTCSession_DTMF.C.MIN_DURATION) { debug('"duration" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_DURATION+ ' milliseconds'); duration = RTCSession_DTMF.C.MIN_DURATION; } else if (duration > RTCSession_DTMF.C.MAX_DURATION) { debug('"duration" value is greater than the maximum allowed, setting it to '+ RTCSession_DTMF.C.MAX_DURATION +' milliseconds'); duration = RTCSession_DTMF.C.MAX_DURATION; } else { duration = Math.abs(duration); } options.duration = duration; // Check interToneGap if (interToneGap && !Utils.isDecimal(interToneGap)) { throw new TypeError('Invalid interToneGap: '+ interToneGap); } else if (!interToneGap) { interToneGap = RTCSession_DTMF.C.DEFAULT_INTER_TONE_GAP; } else if (interToneGap < RTCSession_DTMF.C.MIN_INTER_TONE_GAP) { debug('"interToneGap" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_INTER_TONE_GAP +' milliseconds'); interToneGap = RTCSession_DTMF.C.MIN_INTER_TONE_GAP; } else { interToneGap = Math.abs(interToneGap); } if (this.tones) { // Tones are already queued, just add to the queue this.tones += tones; return; } this.tones = tones; // Send the first tone _sendDTMF(); function _sendDTMF() { var tone, timeout; if (self.status === C.STATUS_TERMINATED || !self.tones || position >= self.tones.length) { // Stop sending DTMF self.tones = null; return; } tone = self.tones[position]; position += 1; if (tone === ',') { timeout = 2000; } else { var dtmf = new RTCSession_DTMF(self); options.eventHandlers = { onFailed: function() { self.tones = null; } }; dtmf.send(tone, options); timeout = duration + interToneGap; } // Set timeout for the next tone setTimeout(_sendDTMF, timeout); } }; /** * Mute */ RTCSession.prototype.mute = function(options) { debug('mute()'); options = options || {audio:true, video:false}; var audioMuted = false, videoMuted = false; if (this.audioMuted === false && options.audio) { audioMuted = true; this.audioMuted = true; toogleMuteAudio.call(this, true); } if (this.videoMuted === false && options.video) { videoMuted = true; this.videoMuted = true; toogleMuteVideo.call(this, true); } if (audioMuted === true || videoMuted === true) { onmute.call(this, { audio: audioMuted, video: videoMuted }); } }; /** * Unmute */ RTCSession.prototype.unmute = function(options) { debug('unmute()'); options = options || {audio:true, video:true}; var audioUnMuted = false, videoUnMuted = false; if (this.audioMuted === true && options.audio) { audioUnMuted = true; this.audioMuted = false; if (this.localHold === false) { toogleMuteAudio.call(this, false); } } if (this.videoMuted === true && options.video) { videoUnMuted = true; this.videoMuted = false; if (this.localHold === false) { toogleMuteVideo.call(this, false); } } if (audioUnMuted === true || videoUnMuted === true) { onunmute.call(this, { audio: audioUnMuted, video: videoUnMuted }); } }; /** * Hold */ RTCSession.prototype.hold = function(options, done) { debug('hold()'); options = options || {}; var self = this, eventHandlers; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } if (this.localHold === true) { return false; } if (! this.isReadyToReOffer()) { return false; } this.localHold = true; onhold.call(this, 'local'); eventHandlers = { succeeded: function() { if (done) { done(); } }, failed: function() { self.terminate({ cause: JsSIP_C.causes.WEBRTC_ERROR, status_code: 500, reason_phrase: 'Hold Failed' }); } }; if (options.useUpdate) { sendUpdate.call(this, { sdpOffer: true, eventHandlers: eventHandlers, extraHeaders: options.extraHeaders }); } else { sendReinvite.call(this, { eventHandlers: eventHandlers, extraHeaders: options.extraHeaders }); } return true; }; RTCSession.prototype.unhold = function(options, done) { debug('unhold()'); options = options || {}; var self = this, eventHandlers; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } if (this.localHold === false) { return false; } if (! this.isReadyToReOffer()) { return false; } this.localHold = false; onunhold.call(this, 'local'); eventHandlers = { succeeded: function() { if (done) { done(); } }, failed: function() { self.terminate({ cause: JsSIP_C.causes.WEBRTC_ERROR, status_code: 500, reason_phrase: 'Unhold Failed' }); } }; if (options.useUpdate) { sendUpdate.call(this, { sdpOffer: true, eventHandlers: eventHandlers, extraHeaders: options.extraHeaders }); } else { sendReinvite.call(this, { eventHandlers: eventHandlers, extraHeaders: options.extraHeaders }); } return true; }; RTCSession.prototype.renegotiate = function(options, done) { debug('renegotiate()'); options = options || {}; var self = this, eventHandlers, rtcOfferConstraints = options.rtcOfferConstraints || null; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } if (! this.isReadyToReOffer()) { return false; } eventHandlers = { succeeded: function() { if (done) { done(); } }, failed: function() { self.terminate({ cause: JsSIP_C.causes.WEBRTC_ERROR, status_code: 500, reason_phrase: 'Media Renegotiation Failed' }); } }; setLocalMediaStatus.call(this); if (options.useUpdate) { sendUpdate.call(this, { sdpOffer: true, eventHandlers: eventHandlers, rtcOfferConstraints: rtcOfferConstraints, extraHeaders: options.extraHeaders }); } else { sendReinvite.call(this, { eventHandlers: eventHandlers, rtcOfferConstraints: rtcOfferConstraints, extraHeaders: options.extraHeaders }); } return true; }; /** * Refer */ RTCSession.prototype.refer = function(target, options) { debug('refer()'); var self = this, originalTarget = target, referSubscriber, id; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } // Check target validity target = this.ua.normalizeTarget(target); if (!target) { throw new TypeError('Invalid target: '+ originalTarget); } referSubscriber = new RTCSession_ReferSubscriber(this); referSubscriber.sendRefer(target, options); // Store in the map id = referSubscriber.outgoingRequest.cseq; this.referSubscribers[id] = referSubscriber; // Listen for ending events so we can remove it from the map referSubscriber.on('requestFailed', function() { delete self.referSubscribers[id]; }); referSubscriber.on('accepted', function() { delete self.referSubscribers[id]; }); referSubscriber.on('failed', function() { delete self.referSubscribers[id]; }); return referSubscriber; }; /** * In dialog Request Reception */ RTCSession.prototype.receiveRequest = function(request) { debug('receiveRequest()'); var contentType, self = this; if(request.method === JsSIP_C.CANCEL) { /* RFC3261 15 States that a UAS may have accepted an invitation while a CANCEL * was in progress and that the UAC MAY continue with the session established by * any 2xx response, or MAY terminate with BYE. JsSIP does continue with the * established session. So the CANCEL is processed only if the session is not yet * established. */ /* * Terminate the whole session in case the user didn't accept (or yet send the answer) * nor reject the request opening the session. */ if(this.status === C.STATUS_WAITING_FOR_ANSWER || this.status === C.STATUS_ANSWERED) { this.status = C.STATUS_CANCELED; this.request.reply(487); failed.call(this, 'remote', request, JsSIP_C.causes.CANCELED); } } else { // Requests arriving here are in-dialog requests. switch(request.method) { case JsSIP_C.ACK: if (this.status !== C.STATUS_WAITING_FOR_ACK) { return; } // Update signaling status. this.status = C.STATUS_CONFIRMED; clearTimeout(this.timers.ackTimer); clearTimeout(this.timers.invite2xxTimer); if (this.late_sdp) { if (!request.body) { this.terminate({ cause: JsSIP_C.causes.MISSING_SDP, status_code: 400 }); break; } var e = {originator:'remote', type:'answer', sdp:request.body}; var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp}); this.emit('sdp', e); this.connection.setRemoteDescription(answer) .then(function() { if (!self.is_confirmed) { confirmed.call(self, 'remote', request); } }) .catch(function(error) { self.terminate({ cause: JsSIP_C.causes.BAD_MEDIA_DESCRIPTION, status_code: 488 }); self.emit('peerconnection:setremotedescriptionfailed', error); }); } else { if (!this.is_confirmed) { confirmed.call(this, 'remote', request); } } break; case JsSIP_C.BYE: if(this.status === C.STATUS_CONFIRMED) { request.reply(200); ended.call(this, 'remote', request, JsSIP_C.causes.BYE); } else if (this.status === C.STATUS_INVITE_RECEIVED) { request.reply(200); this.request.reply(487, 'BYE Received'); ended.call(this, 'remote', request, JsSIP_C.causes.BYE); } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.INVITE: if(this.status === C.STATUS_CONFIRMED) { if (request.hasHeader('replaces')) { receiveReplaces.call(this, request); } else { receiveReinvite.call(this, request); } } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.INFO: if(this.status === C.STATUS_CONFIRMED || this.status === C.STATUS_WAITING_FOR_ACK || this.status === C.STATUS_INVITE_RECEIVED) { contentType = request.getHeader('content-type'); if (contentType && (contentType.match(/^application\/dtmf-relay/i))) { new RTCSession_DTMF(this).init_incoming(request); } else { request.reply(415); } } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.UPDATE: if(this.status === C.STATUS_CONFIRMED) { receiveUpdate.call(this, request); } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.REFER: if(this.status === C.STATUS_CONFIRMED) { receiveRefer.call(this, request); } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.NOTIFY: if(this.status === C.STATUS_CONFIRMED) { receiveNotify.call(this, request); } else { request.reply(403, 'Wrong Status'); } break; default: request.reply(501); } } }; /** * Session Callbacks */ RTCSession.prototype.onTransportError = function() { debugerror('onTransportError()'); if(this.status !== C.STATUS_TERMINATED) { this.terminate({ status_code: 500, reason_phrase: JsSIP_C.causes.CONNECTION_ERROR, cause: JsSIP_C.causes.CONNECTION_ERROR }); } }; RTCSession.prototype.onRequestTimeout = function() { debug('onRequestTimeout'); if(this.status !== C.STATUS_TERMINATED) { this.terminate({ status_code: 408, reason_phrase: JsSIP_C.causes.REQUEST_TIMEOUT, cause: JsSIP_C.causes.REQUEST_TIMEOUT }); } }; RTCSession.prototype.onDialogError = function() { debugerror('onDialogError()'); if(this.status !== C.STATUS_TERMINATED) { this.terminate({ status_code: 500, reason_phrase: JsSIP_C.causes.DIALOG_ERROR, cause: JsSIP_C.causes.DIALOG_ERROR }); } }; // Called from DTMF handler. RTCSession.prototype.newDTMF = function(data) { debug('newDTMF()'); this.emit('newDTMF', data); }; RTCSession.prototype.resetLocalMedia = function() { debug('resetLocalMedia()'); // Reset all but remoteHold. this.localHold = false; this.audioMuted = false; this.videoMuted = false; setLocalMediaStatus.call(this); }; /** * Private API. */ /** * RFC3261 13.3.1.4 * Response retransmissions cannot be accomplished by transaction layer * since it is destroyed when receiving the first 2xx answer */ function setInvite2xxTimer(request, body) { var self = this, timeout = Timers.T1; this.timers.invite2xxTimer = setTimeout(function invite2xxRetransmission() { if (self.status !== C.STATUS_WAITING_FOR_ACK) { return; } request.reply(200, null, ['Contact: '+ self.contact], body); if (timeout < Timers.T2) { timeout = timeout * 2; if (timeout > Timers.T2) { timeout = Timers.T2; } } self.timers.invite2xxTimer = setTimeout( invite2xxRetransmission, timeout ); }, timeout); } /** * RFC3261 14.2 * If a UAS generates a 2xx response and never receives an ACK, * it SHOULD generate a BYE to terminate the dialog. */ function setACKTimer() { var self = this; this.timers.ackTimer = setTimeout(function() { if(self.status === C.STATUS_WAITING_FOR_ACK) { debug('no ACK received, terminating the session'); clearTimeout(self.timers.invite2xxTimer); sendRequest.call(self, JsSIP_C.BYE); ended.call(self, 'remote', null, JsSIP_C.causes.NO_ACK); } }, Timers.TIMER_H); } function createRTCConnection(pcConfig, rtcConstraints) { var self = this; this.connection = new RTCPeerConnection(pcConfig, rtcConstraints); this.connection.addEventListener('iceconnectionstatechange', function() { var state = self.connection.iceConnectionState; // TODO: Do more with different states. if (state === 'failed') { self.terminate({ cause: JsSIP_C.causes.RTP_TIMEOUT, status_code: 200, reason_phrase: JsSIP_C.causes.RTP_TIMEOUT }); } }); } function createLocalDescription(type, onSuccess, onFailure, constraints) { debug('createLocalDescription()'); var self = this; var connection = this.connection; this.rtcReady = false; if (type === 'offer') { connection.createOffer(constraints) .then(createSucceeded) .catch(function(error) { self.rtcReady = true; if (onFailure) { onFailure(error); } self.emit('peerconnection:createofferfailed', error); }); } else if (type === 'answer') { connection.createAnswer(constraints) .then(createSucceeded) .catch(function(error) { self.rtcReady = true; if (onFailure) { onFailure(error); } self.emit('peerconnection:createanswerfailed', error); }); } else { throw new Error('createLocalDescription() | type must be "offer" or "answer", but "' +type+ '" was given'); } // createAnswer or createOffer succeeded function createSucceeded(desc) { var listener; connection.addEventListener('icecandidate', listener = function(event) { var candidate = event.candidate; if (! candidate) { connection.removeEventListener('icecandidate', listener); self.rtcReady = true; if (onSuccess) { var e = {originator:'local', type:type, sdp:connection.localDescription.sdp}; self.emit('sdp', e); onSuccess(e.sdp); } onSuccess = null; } }); connection.setLocalDescription(desc) .then(function() { if (connection.iceGatheringState === 'complete') { self.rtcReady = true; if (onSuccess) { var e = {originator:'local', type:type, sdp:connection.localDescription.sdp}; self.emit('sdp', e); onSuccess(e.sdp); onSuccess = null; } } }) .catch(function(error) { self.rtcReady = true; if (onFailure) { onFailure(error); } self.emit('peerconnection:setlocaldescriptionfailed', error); }); } } /** * Dialog Management */ function createDialog(message, type, early) { var dialog, early_dialog, local_tag = (type === 'UAS') ? message.to_tag : message.from_tag, remote_tag = (type === 'UAS') ? message.from_tag : message.to_tag, id = message.call_id + local_tag + remote_tag; early_dialog = this.earlyDialogs[id]; // Early Dialog if (early) { if (early_dialog) { return true; } else { early_dialog = new Dialog(this, message, type, Dialog.C.STATUS_EARLY); // Dialog has been successfully created. if(early_dialog.error) { debug(early_dialog.error); failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR); return false; } else { this.earlyDialogs[id] = early_dialog; return true; } } } // Confirmed Dialog else { this.from_tag = message.from_tag; this.to_tag = message.to_tag; // In case the dialog is in _early_ state, update it if (early_dialog) { early_dialog.update(message, type); this.dialog = early_dialog; delete this.earlyDialogs[id]; return true; } // Otherwise, create a _confirmed_ dialog dialog = new Dialog(this, message, type); if(dialog.error) { debug(dialog.error); failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR); return false; } else { this.dialog = dialog; return true; } } } /** * In dialog INVITE Reception */ function receiveReinvite(request) { debug('receiveReinvite()'); var sdp, idx, direction, m, self = this, contentType = request.getHeader('Content-Type'), hold = false, rejected = false, data = { request: request, callback: undefined, reject: reject.bind(this) }; function reject(options) { options = options || {}; rejected = true; var status_code = options.status_code || 403, reason_phrase = options.reason_phrase || '', extraHeaders = options.extraHeaders && options.extraHeaders.slice() || []; if (this.status !== C.STATUS_CONFIRMED) { return false; } if (status_code < 300 || status_code >= 700) { throw new TypeError('Invalid status_code: '+ status_code); } request.reply(status_code, reason_phrase, extraHeaders); } // Emit 'reinvite'. this.emit('reinvite', data); if (rejected) { return; } if (request.body) { this.late_sdp = false; if (contentType !== 'application/sdp') { debug('invalid Content-Type'); request.reply(415); return; } sdp = request.parseSDP(); for (idx=0; idx < sdp.media.length; idx++) { m = sdp.media[idx]; if (holdMediaTypes.indexOf(m.type) === -1) { continue; } direction = m.direction || sdp.direction || 'sendrecv'; if (direction === 'sendonly' || direction === 'inactive') { hold = true; } // If at least one of the streams is active don't emit 'hold'. else { hold = false; break; } } var e = {originator:'remote', type:'offer', sdp:request.body}; var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp}); this.emit('sdp', e); this.connection.setRemoteDescription(offer) .then(doAnswer) .catch(function(error) { request.reply(488); self.emit('peerconnection:setremotedescriptionfailed', error); }); } else { this.late_sdp = true; doAnswer(); } function doAnswer() { createSdp( // onSuccess function(sdp) { var extraHeaders = ['Contact: ' + self.contact]; handleSessionTimersInIncomingRequest.call(self, request, extraHeaders); if (self.late_sdp) { sdp = mangleOffer.call(self, sdp); } request.reply(200, null, extraHeaders, sdp, function() { self.status = C.STATUS_WAITING_FOR_ACK; setInvite2xxTimer.call(self, request, sdp); setACKTimer.call(self); } ); // If callback is given execute it. if (typeof data.callback === 'function') { data.callback(); } }, // onFailure function() { request.reply(500); } ); } function createSdp(onSuccess, onFailure) { if (! self.late_sdp) { if (self.remoteHold === true && hold === false) { self.remoteHold = false; onunhold.call(self, 'remote'); } else if (self.remoteHold === false && hold === true) { self.remoteHold = true; onhold.call(self, 'remote'); } createLocalDescription.call(self, 'answer', onSuccess, onFailure, self.rtcAnswerConstraints); } else { createLocalDescription.call(self, 'offer', onSuccess, onFailure, self.rtcOfferConstraints); } } } /** * In dialog UPDATE Reception */ function receiveUpdate(request) { debug('receiveUpdate()'); var sdp, idx, direction, m, self = this, contentType = request.getHeader('Content-Type'), rejected = false, hold = false, data = { request: request, callback: undefined, reject: reject.bind(this) }; function reject(options) { options = options || {}; rejected = true; var status_code = options.status_code || 403, reason_phrase = options.reason_phrase || '', extraHeaders = options.extraHeaders && options.extraHeaders.slice() || []; if (this.status !== C.STATUS_CONFIRMED) { return false; } if (status_code < 300 || status_code >= 700) { throw new TypeError('Invalid status_code: '+ status_code); } request.reply(status_code, reason_phrase, extraHeaders); } // Emit 'update'. this.emit('update', data); if (rejected) { return; } if (! request.body) { var extraHeaders = []; handleSessionTimersInIncomingRequest.call(this, request, extraHeaders); request.reply(200, null, extraHeaders); return; } if (contentType !== 'application/sdp') { debug('invalid Content-Type'); request.reply(415); return; } sdp = request.parseSDP(); for (idx=0; idx < sdp.media.length; idx++) { m = sdp.media[idx]; if (holdMediaTypes.indexOf(m.type) === -1) { continue; } direction = m.direction || sdp.direction || 'sendrecv'; if (direction === 'sendonly' || direction === 'inactive') { hold = true; } // If at least one of the streams is active don't emit 'hold'. else { hold = false; break; } } var e = {originator:'remote', type:'offer', sdp:request.body}; var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp}); this.emit('sdp', e); this.connection.setRemoteDescription(offer) .then(function() { if (self.remoteHold === true && hold === false) { self.remoteHold = false; onunhold.call(self, 'remote'); } else if (self.remoteHold === false && hold === true) { self.remoteHold = true; onhold.call(self, 'remote'); } createLocalDescription.call(self, 'answer', // success function(sdp) { var extraHeaders = ['Contact: ' + self.contact]; handleSessionTimersInIncomingRequest.call(self, request, extraHeaders); request.reply(200, null, extraHeaders, sdp); // If callback is given execute it. if (typeof data.callback === 'function') { data.callback(); } }, // failure function() { request.reply(500); } ); }) .catch(function(error) { request.reply(488); self.emit('peerconnection:setremotedescriptionfailed', error); }); } /** * In dialog Refer Reception */ function receiveRefer(request) { debug('receiveRefer()'); var notifier, self = this; function accept(initCallback, options) { var session, replaces; options = options || {}; initCallback = (typeof initCallback === 'function')? initCallback : null; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } session = new RTCSession(this.ua); session.on('progress', function(e) { notifier.notify(e.response.status_code, e.response.reason_phrase); }); session.on('accepted', function(e) { notifier.notify(e.response.status_code, e.response.reason_phrase); }); session.on('failed', function(e) { if (e.message) { notifier.notify(e.message.status_code, e.message.reason_phrase); } else { notifier.notify(487, e.cause); } }); // Consider the Replaces header present in the Refer-To URI if (request.refer_to.uri.hasHeader('replaces')) { replaces = decodeURIComponent(request.refer_to.uri.getHeader('replaces')); options.extraHeaders = options.extraHeaders || []; options.extraHeaders.push('Replaces: '+ replaces); } session.connect(request.refer_to.uri.toAor(), options, initCallback); } function reject() { notifier.notify(603); } if (typeof request.refer_to === undefined) { debug('no Refer-To header field present in REFER'); request.reply(400); return; } if (request.refer_to.uri.scheme !== JsSIP_C.SIP) { debug('Refer-To header field points to a non-SIP URI scheme'); request.reply(416); return; } // reply before the transaction timer expires request.reply(202); notifier = new RTCSession_ReferNotifier(this, request.cseq); // Emit 'refer'. this.emit('refer', { request: request, accept: function(initCallback, options) { accept.call(self, initCallback, options); }, reject: function() { reject.call(self); } }); } /** * In dialog Notify Reception */ function receiveNotify(request) { debug('receiveNotify()'); if (typeof request.event === undefined) { request.reply(400); } switch (request.event.event) { case 'refer': { var id = request.event.params.id; var referSubscriber = this.referSubscribers[id]; if (!referSubscriber) { request.reply(481, 'Subscription does not exist'); return; } referSubscriber.receiveNotify(request); request.reply(200); break; } default: { request.reply(489); } } } /** * INVITE with Replaces Reception */ function receiveReplaces(request) { debug('receiveReplaces()'); var self = this; function accept(initCallback) { var session; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } session = new RTCSession(this.ua); // terminate the current session when the new one is confirmed session.on('confirmed', function() { self.terminate(); }); session.init_incoming(request, initCallback); } function reject() { debug('Replaced INVITE rejected by the user'); request.reply(486); } // Emit 'replace'. this.emit('replaces', { request: request, accept: function(initCallback) { accept.call(self, initCallback); }, reject: function() { reject.call(self); } }); } /** * Initial Request Sender */ function sendInitialRequest(mediaConstraints, rtcOfferConstraints, mediaStream) { var self = this; var request_sender = new RequestSender(self, this.ua); this.receiveResponse = function(response) { receiveInviteResponse.call(self, response); }; // If a local MediaStream is given use it. if (mediaStream) { // Wait a bit so the app can set events such as 'peerconnection' and 'connecting'. setTimeout(function() { userMediaSucceeded(mediaStream); }); // If at least audio or video is requested prompt getUserMedia. } else if (mediaConstraints.audio || mediaConstraints.video) { this.localMediaStreamLocallyGenerated = true; navigator.mediaDevices.getUserMedia(mediaConstraints) .then(userMediaSucceeded) .catch(function(error) { userMediaFailed(error); self.emit('getusermediafailed', error); }); // Otherwise don't prompt getUserMedia. } else { userMediaSucceeded(null); } // User media succeeded function userMediaSucceeded(stream) { if (self.status === C.STATUS_TERMINATED) { return; } self.localMediaStream = stream; if (stream) { self.connection.addStream(stream); } // Notify the app with the RTCPeerConnection so it can do stuff on it // before generating the offer. self.emit('peerconnection', { peerconnection: self.connection }); connecting.call(self, self.request); createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, rtcOfferConstraints); } // User media failed function userMediaFailed() { if (self.status === C.STATUS_TERMINATED) { return; } failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS); } function rtcSucceeded(desc) { if (self.isCanceled || self.status === C.STATUS_TERMINATED) { return; } self.request.body = desc; self.status = C.STATUS_INVITE_SENT; // Emit 'sending' so the app can mangle the body before the request // is sent. self.emit('sending', { request: self.request }); request_sender.send(); } function rtcFailed() { if (self.status === C.STATUS_TERMINATED) { return; } failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR); } } /** * Reception of Response for Initial INVITE */ function receiveInviteResponse(response) { debug('receiveInviteResponse()'); var cause, dialog, e, self = this; // Handle 2XX retransmissions and responses from forked requests if (this.dialog && (response.status_code >=200 && response.status_code <=299)) { /* * If it is a retransmission from the endpoint that established * the dialog, send an ACK */ if (this.dialog.id.call_id === response.call_id && this.dialog.id.local_tag === response.from_tag && this.dialog.id.remote_tag === response.to_tag) { sendRequest.call(this, JsSIP_C.ACK); return; } // If not, send an ACK and terminate else { dialog = new Dialog(this, response, 'UAC'); if (dialog.error !== undefined) { debug(dialog.error); return; } dialog.sendRequest({ owner: {status: C.STATUS_TERMINATED}, onRequestTimeout: function(){}, onTransportError: function(){}, onDialogError: function(){}, receiveResponse: function(){} }, JsSIP_C.ACK); dialog.sendRequest({ owner: {status: C.STATUS_TERMINATED}, onRequestTimeout: function(){}, onTransportError: function(){}, onDialogError: function(){}, receiveResponse: function(){} }, JsSIP_C.BYE); return; } } // Proceed to cancellation if the user requested. if(this.isCanceled) { // Remove the flag. We are done. this.isCanceled = false; if(response.status_code >= 100 && response.status_code < 200) { this.request.cancel(this.cancelReason); } else if(response.status_code >= 200 && response.status_code < 299) { acceptAndTerminate.call(this, response); } return; } if(this.status !== C.STATUS_INVITE_SENT && this.status !== C.STATUS_1XX_RECEIVED) { return; } switch(true) { case /^100$/.test(response.status_code): this.status = C.STATUS_1XX_RECEIVED; break; case /^1[0-9]{2}$/.test(response.status_code): // Do nothing with 1xx responses without To tag. if (!response.to_tag) { debug('1xx response received without to tag'); break; } // Create Early Dialog if 1XX comes with contact if (response.hasHeader('contact')) { // An error on dialog creation will fire 'failed' event if(! createDialog.call(this, response, 'UAC', true)) { break; } } this.status = C.STATUS_1XX_RECEIVED; progress.call(this, 'remote', response); if (!response.body) { break; } e = {originator:'remote', type:'pranswer', sdp:response.body}; this.emit('sdp', e); var pranswer = new RTCSessionDescription({type:'pranswer', sdp:e.sdp}); this.connection.setRemoteDescription(pranswer) .catch(function(error) { self.emit('peerconnection:setremotedescriptionfailed', error); }); break; case /^2[0-9]{2}$/.test(response.status_code): this.status = C.STATUS_CONFIRMED; if(!response.body) { acceptAndTerminate.call(this, response, 400, JsSIP_C.causes.MISSING_SDP); failed.call(this, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION); break; } // An error on dialog creation will fire 'failed' event if (! createDialog.call(this, response, 'UAC')) { break; } e = {originator:'remote', type:'answer', sdp:response.body}; this.emit('sdp', e); var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp}); this.connection.setRemoteDescription(answer) .then(function() { // Handle Session Timers. handleSessionTimersInIncomingResponse.call(self, response); accepted.call(self, 'remote', response); sendRequest.call(self, JsSIP_C.ACK); confirmed.call(self, 'local', null); }) .catch(function(error) { acceptAndTerminate.call(self, response, 488, 'Not Acceptable Here'); failed.call(self, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION); self.emit('peerconnection:setremotedescriptionfailed', error); }); break; default: cause = Utils.sipErrorCause(response.status_code); failed.call(this, 'remote', response, cause); } } /** * Send Re-INVITE */ function sendReinvite(options) { debug('sendReinvite()'); options = options || {}; var self = this, extraHeaders = options.extraHeaders || [], eventHandlers = options.eventHandlers || {}, rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null, succeeded = false; extraHeaders.push('Contact: ' + this.contact); extraHeaders.push('Content-Type: application/sdp'); // Session Timers. if (this.sessionTimers.running) { extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas')); } createLocalDescription.call(this, 'offer', // success function(sdp) { sdp = mangleOffer.call(self, sdp); var request = new RTCSession_Request(self, JsSIP_C.INVITE); request.send({ extraHeaders: extraHeaders, body: sdp, eventHandlers: { onSuccessResponse: function(response) { onSucceeded(response); succeeded = true; }, onErrorResponse: function(response) { onFailed(response); }, onTransportError: function() { self.onTransportError(); // Do nothing because session ends. }, onRequestTimeout: function() { self.onRequestTimeout(); // Do nothing because session ends. }, onDialogError: function() { self.onDialogError(); // Do nothing because session ends. } } }); }, // failure function() { onFailed(); }, // RTC constraints. rtcOfferConstraints ); function onSucceeded(response) { if (self.status === C.STATUS_TERMINATED) { return; } sendRequest.call(self, JsSIP_C.ACK); // If it is a 2XX retransmission exit now. if (succeeded) { return; } // Handle Session Timers. handleSessionTimersInIncomingResponse.call(self, response); // Must have SDP answer. if(! response.body) { onFailed(); return; } else if (response.getHeader('Content-Type') !== 'application/sdp') { onFailed(); return; } var e = {originator:'remote', type:'answer', sdp:response.body}; var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp}); self.emit('sdp', e); self.connection.setRemoteDescription(answer) .then(function() { if (eventHandlers.succeeded) { eventHandlers.succeeded(response); } }) .catch(function(error) { onFailed(); self.emit('peerconnection:setremotedescriptionfailed', error); }); } function onFailed(response) { if (eventHandlers.failed) { eventHandlers.failed(response); } } } /** * Send UPDATE */ function sendUpdate(options) { debug('sendUpdate()'); options = options || {}; var self = this, extraHeaders = options.extraHeaders || [], eventHandlers = options.eventHandlers || {}, rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null, sdpOffer = options.sdpOffer || false, succeeded = false; extraHeaders.push('Contact: ' + this.contact); // Session Timers. if (this.sessionTimers.running) { extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas')); } if (sdpOffer) { extraHeaders.push('Content-Type: application/sdp'); createLocalDescription.call(this, 'offer', // success function(sdp) { sdp = mangleOffer.call(self, sdp); var request = new RTCSession_Request(self, JsSIP_C.UPDATE); request.send({ extraHeaders: extraHeaders, body: sdp, eventHandlers: { onSuccessResponse: function(response) { onSucceeded(response); succeeded = true; }, onErrorResponse: function(response) { onFailed(response); }, onTransportError: function() { self.onTransportError(); // Do nothing because session ends. }, onRequestTimeout: function() { self.onRequestTimeout(); // Do nothing because session ends. }, onDialogError: function() { self.onDialogError(); // Do nothing because session ends. } } }); }, // failure function() { onFailed(); }, // RTC constraints. rtcOfferConstraints ); } // No SDP. else { var request = new RTCSession_Request(self, JsSIP_C.UPDATE); request.send({ extraHeaders: extraHeaders, eventHandlers: { onSuccessResponse: function(response) { onSucceeded(response); }, onErrorResponse: function(response) { onFailed(response); }, onTransportError: function() { self.onTransportError(); // Do nothing because session ends. }, onRequestTimeout: function() { self.onRequestTimeout(); // Do nothing because session ends. }, onDialogError: function() { self.onDialogError(); // Do nothing because session ends. } } }); } function onSucceeded(response) { if (self.status === C.STATUS_TERMINATED) { return; } // If it is a 2XX retransmission exit now. if (succeeded) { return; } // Handle Session Timers. handleSessionTimersInIncomingResponse.call(self, response); // Must have SDP answer. if (sdpOffer) { if(! response.body) { onFailed(); return; } else if (response.getHeader('Content-Type') !== 'application/sdp') { onFailed(); return; } var e = {originator:'remote', type:'answer', sdp:response.body}; var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp}); self.emit('sdp', e); self.connection.setRemoteDescription(answer) .then(function() { if (eventHandlers.succeeded) { eventHandlers.succeeded(response); } }) .catch(function(error) { onFailed(); self.emit('peerconnection:setremotedescriptionfailed', error); }); } // No SDP answer. else { if (eventHandlers.succeeded) { eventHandlers.succeeded(response); } } } function onFailed(response) { if (eventHandlers.failed) { eventHandlers.failed(response); } } } function acceptAndTerminate(response, status_code, reason_phrase) { debug('acceptAndTerminate()'); var extraHeaders = []; if (status_code) { reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || ''; extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"'); } // An error on dialog creation will fire 'failed' event if (this.dialog || createDialog.call(this, response, 'UAC')) { sendRequest.call(this, JsSIP_C.ACK); sendRequest.call(this, JsSIP_C.BYE, { extraHeaders: extraHeaders }); } // Update session status. this.status = C.STATUS_TERMINATED; } /** * Send a generic in-dialog Request */ function sendRequest(method, options) { debug('sendRequest()'); var request = new RTCSession_Request(this, method); request.send(options); } /** * Correctly set the SDP direction attributes if the call is on local hold */ function mangleOffer(sdp) { var idx, length, m; if (! this.localHold && ! this.remoteHold) { return sdp; } sdp = sdp_transform.parse(sdp); // Local hold. if (this.localHold && ! this.remoteHold) { debug('mangleOffer() | me on hold, mangling offer'); length = sdp.media.length; for (idx=0; idx<length; idx++) { m = sdp.media[idx]; if (holdMediaTypes.indexOf(m.type) === -1) { continue; } if (!m.direction) { m.direction = 'sendonly'; } else if (m.direction === 'sendrecv') { m.direction = 'sendonly'; } else if (m.direction === 'recvonly') { m.direction = 'inactive'; } } } // Local and remote hold. else if (this.localHold && this.remoteHold) { debug('mangleOffer() | both on hold, mangling offer'); length = sdp.media.length; for (idx=0; idx<length; idx++) { m = sdp.media[idx]; if (holdMediaTypes.indexOf(m.type) === -1) { continue; } m.direction = 'inactive'; } } // Remote hold. else if (this.remoteHold) { debug('mangleOffer() | remote on hold, mangling offer'); length = sdp.media.length; for (idx=0; idx<length; idx++) { m = sdp.media[idx]; if (holdMediaTypes.indexOf(m.type) === -1) { continue; } if (!m.direction) { m.direction = 'recvonly'; } else if (m.direction === 'sendrecv') { m.direction = 'recvonly'; } else if (m.direction === 'recvonly') { m.direction = 'inactive'; } } } return sdp_transform.write(sdp); } function setLocalMediaStatus() { var enableAudio = true, enableVideo = true; if (this.localHold || this.remoteHold) { enableAudio = false; enableVideo = false; } if (this.audioMuted) { enableAudio = false; } if (this.videoMuted) { enableVideo = false; } toogleMuteAudio.call(this, !enableAudio); toogleMuteVideo.call(this, !enableVideo); } /** * Handle SessionTimers for an incoming INVITE or UPDATE. * @param {IncomingRequest} request * @param {Array} responseExtraHeaders Extra headers for the 200 response. */ function handleSessionTimersInIncomingRequest(request, responseExtraHeaders) { if (! this.sessionTimers.enabled) { return; } var session_expires_refresher; if (request.session_expires && request.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) { this.sessionTimers.currentExpires = request.session_expires; session_expires_refresher = request.session_expires_refresher || 'uas'; } else { this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires; session_expires_refresher = 'uas'; } responseExtraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + session_expires_refresher); this.sessionTimers.refresher = (session_expires_refresher === 'uas'); runSessionTimer.call(this); } /** * Handle SessionTimers for an incoming response to INVITE or UPDATE. * @param {IncomingResponse} response */ function handleSessionTimersInIncomingResponse(response) { if (! this.sessionTimers.enabled) { return; } var session_expires_refresher; if (response.session_expires && response.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) { this.sessionTimers.currentExpires = response.session_expires; session_expires_refresher = response.session_expires_refresher || 'uac'; } else { this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires; session_expires_refresher = 'uac'; } this.sessionTimers.refresher = (session_expires_refresher === 'uac'); runSessionTimer.call(this); } function runSessionTimer() { var self = this; var expires = this.sessionTimers.currentExpires; this.sessionTimers.running = true; clearTimeout(this.sessionTimers.timer); // I'm the refresher. if (this.sessionTimers.refresher) { this.sessionTimers.timer = setTimeout(function() { if (self.status === C.STATUS_TERMINATED) { return; } debug('runSessionTimer() | sending session refresh request'); sendUpdate.call(self, { eventHandlers: { succeeded: function(response) { handleSessionTimersInIncomingResponse.call(self, response); } } }); }, expires * 500); // Half the given interval (as the RFC states). } // I'm not the refresher. else { this.sessionTimers.timer = setTimeout(function() { if (self.status === C.STATUS_TERMINATED) { return; } debugerror('runSessionTimer() | timer expired, terminating the session'); self.terminate({ cause: JsSIP_C.causes.REQUEST_TIMEOUT, status_code: 408, reason_phrase: 'Session Timer Expired' }); }, expires * 1100); } } function toogleMuteAudio(mute) { var streamIdx, trackIdx, streamsLength, tracksLength, tracks, localStreams = this.connection.getLocalStreams(); streamsLength = localStreams.length; for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) { tracks = localStreams[streamIdx].getAudioTracks(); tracksLength = tracks.length; for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) { tracks[trackIdx].enabled = !mute; } } } function toogleMuteVideo(mute) { var streamIdx, trackIdx, streamsLength, tracksLength, tracks, localStreams = this.connection.getLocalStreams(); streamsLength = localStreams.length; for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) { tracks = localStreams[streamIdx].getVideoTracks(); tracksLength = tracks.length; for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) { tracks[trackIdx].enabled = !mute; } } } function newRTCSession(originator, request) { debug('newRTCSession'); this.ua.newRTCSession({ originator: originator, session: this, request: request }); } function connecting(request) { debug('session connecting'); this.emit('connecting', { request: request }); } function progress(originator, response) { debug('session progress'); this.emit('progress', { originator: originator, response: response || null }); } function accepted(originator, message) { debug('session accepted'); this.start_time = new Date(); this.emit('accepted', { originator: originator, response: message || null }); } function confirmed(originator, ack) { debug('session confirmed'); this.is_confirmed = true; this.emit('confirmed', { originator: originator, ack: ack || null }); } function ended(originator, message, cause) { debug('session ended'); this.end_time = new Date(); this.close(); this.emit('ended', { originator: originator, message: message || null, cause: cause }); } function failed(originator, message, cause) { debug('session failed'); this.close(); this.emit('failed', { originator: originator, message: message || null, cause: cause }); } function onhold(originator) { debug('session onhold'); setLocalMediaStatus.call(this); this.emit('hold', { originator: originator }); } function onunhold(originator) { debug('session onunhold'); setLocalMediaStatus.call(this); this.emit('unhold', { originator: originator }); } function onmute(options) { debug('session onmute'); setLocalMediaStatus.call(this); this.emit('muted', { audio: options.audio, video: options.video }); } function onunmute(options) { debug('session onunmute'); setLocalMediaStatus.call(this); this.emit('unmuted', { audio: options.audio, video: options.video }); } },{"./Constants":1,"./Dialog":2,"./Exceptions":5,"./RTCSession/DTMF":12,"./RTCSession/ReferNotifier":13,"./RTCSession/ReferSubscriber":14,"./RTCSession/Request":15,"./RequestSender":17,"./SIPMessage":18,"./Timers":20,"./Transactions":21,"./Utils":25,"debug":34,"events":28,"sdp-transform":37,"util":32}],12:[function(require,module,exports){ module.exports = DTMF; var C = { MIN_DURATION: 70, MAX_DURATION: 6000, DEFAULT_DURATION: 100, MIN_INTER_TONE_GAP: 50, DEFAULT_INTER_TONE_GAP: 500 }; /** * Expose C object. */ DTMF.C = C; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debug = require('debug')('JsSIP:RTCSession:DTMF'); var debugerror = require('debug')('JsSIP:ERROR:RTCSession:DTMF'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('../Constants'); var Exceptions = require('../Exceptions'); var RTCSession = require('../RTCSession'); function DTMF(session) { this.owner = session; this.direction = null; this.tone = null; this.duration = null; events.EventEmitter.call(this); } util.inherits(DTMF, events.EventEmitter); DTMF.prototype.send = function(tone, options) { var extraHeaders, body; if (tone === undefined) { throw new TypeError('Not enough arguments'); } this.direction = 'outgoing'; // Check RTCSession Status if (this.owner.status !== RTCSession.C.STATUS_CONFIRMED && this.owner.status !== RTCSession.C.STATUS_WAITING_FOR_ACK) { throw new Exceptions.InvalidStateError(this.owner.status); } // Get DTMF options options = options || {}; extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; this.eventHandlers = options.eventHandlers || {}; // Check tone type if (typeof tone === 'string' ) { tone = tone.toUpperCase(); } else if (typeof tone === 'number') { tone = tone.toString(); } else { throw new TypeError('Invalid tone: '+ tone); } // Check tone value if (!tone.match(/^[0-9A-DR#*]$/)) { throw new TypeError('Invalid tone: '+ tone); } else { this.tone = tone; } // Duration is checked/corrected in RTCSession this.duration = options.duration; extraHeaders.push('Content-Type: application/dtmf-relay'); body = 'Signal=' + this.tone + '\r\n'; body += 'Duration=' + this.duration; this.owner.newDTMF({ originator: 'local', dtmf: this, request: this.request }); this.owner.dialog.sendRequest(this, JsSIP_C.INFO, { extraHeaders: extraHeaders, body: body }); }; DTMF.prototype.receiveResponse = function(response) { switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): this.emit('succeeded', { originator: 'remote', response: response }); break; default: if (this.eventHandlers.onFailed) { this.eventHandlers.onFailed(); } this.emit('failed', { originator: 'remote', response: response }); break; } }; DTMF.prototype.onRequestTimeout = function() { debugerror('onRequestTimeout'); this.owner.onRequestTimeout(); }; DTMF.prototype.onTransportError = function() { debugerror('onTransportError'); this.owner.onTransportError(); }; DTMF.prototype.onDialogError = function() { debugerror('onDialogError'); this.owner.onDialogError(); }; DTMF.prototype.init_incoming = function(request) { var body, reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/, reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; this.direction = 'incoming'; this.request = request; request.reply(200); if (request.body) { body = request.body.split('\n'); if (body.length >= 1) { if (reg_tone.test(body[0])) { this.tone = body[0].replace(reg_tone,'$2'); } } if (body.length >=2) { if (reg_duration.test(body[1])) { this.duration = parseInt(body[1].replace(reg_duration,'$2'), 10); } } } if (!this.duration) { this.duration = C.DEFAULT_DURATION; } if (!this.tone) { debug('invalid INFO DTMF received, discarded'); } else { this.owner.newDTMF({ originator: 'remote', dtmf: this, request: request }); } }; },{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":34,"events":28,"util":32}],13:[function(require,module,exports){ module.exports = ReferNotifier; var C = { event_type: 'refer', body_type: 'message/sipfrag;version=2.0', expires: 300 }; /** * Dependencies. */ var debug = require('debug')('JsSIP:RTCSession:ReferNotifier'); var JsSIP_C = require('../Constants'); var RTCSession_Request = require('./Request'); function ReferNotifier(session, id, expires) { this.session = session; this.id = id; this.expires = expires || C.expires; this.active = true; // The creation of a Notifier results in an immediate NOTIFY this.notify(100); } ReferNotifier.prototype.notify = function(code, reason) { debug('notify()'); var state, self = this; if (this.active === false) { return; } reason = reason || JsSIP_C.REASON_PHRASE[code] || ''; if (code >= 200) { state = 'terminated;reason=noresource'; } else { state = 'active;expires='+ this.expires; } // put this in a try/catch block var request = new RTCSession_Request(this.session, JsSIP_C.NOTIFY); request.send({ extraHeaders: [ 'Event: '+ C.event_type +';id='+ self.id, 'Subscription-State: '+ state, 'Content-Type: '+ C.body_type ], body: 'SIP/2.0 ' + code + ' ' + reason, eventHandlers: { // if a negative response is received, subscription is canceled onErrorResponse: function() { self.active = false; } } }); }; },{"../Constants":1,"./Request":15,"debug":34}],14:[function(require,module,exports){ module.exports = ReferSubscriber; var C = { expires: 120 }; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debug = require('debug')('JsSIP:RTCSession:ReferSubscriber'); var JsSIP_C = require('../Constants'); var Grammar = require('../Grammar'); var RTCSession_Request = require('./Request'); function ReferSubscriber(session) { this.session = session; this.timer = null; // Instance of REFER OutgoingRequest this.outgoingRequest = null; events.EventEmitter.call(this); } util.inherits(ReferSubscriber, events.EventEmitter); ReferSubscriber.prototype.sendRefer = function(target, options) { debug('sendRefer()'); var extraHeaders, eventHandlers, referTo, replaces = null, self = this; // Get REFER options options = options || {}; extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; eventHandlers = options.eventHandlers || {}; // Set event handlers for (var event in eventHandlers) { this.on(event, eventHandlers[event]); } // Replaces URI header field if (options.replaces) { replaces = options.replaces.request.call_id; replaces += ';to-tag='+ options.replaces.to_tag; replaces += ';from-tag='+ options.replaces.from_tag; replaces = encodeURIComponent(replaces); } // Refer-To header field referTo = 'Refer-To: <'+ target + (replaces?'?Replaces='+ replaces:'') +'>'; extraHeaders.push(referTo); var request = new RTCSession_Request(this.session, JsSIP_C.REFER); this.timer = setTimeout(function() { removeSubscriber.call(self); }, C.expires * 1000); request.send({ extraHeaders: extraHeaders, eventHandlers: { onSuccessResponse: function(response) { self.emit('requestSucceeded', { response: response }); }, onErrorResponse: function(response) { self.emit('requestFailed', { response: response, cause: JsSIP_C.causes.REJECTED }); }, onTransportError: function() { removeSubscriber.call(self); self.emit('requestFailed', { response: null, cause: JsSIP_C.causes.CONNECTION_ERROR }); }, onRequestTimeout: function() { removeSubscriber.call(self); self.emit('requestFailed', { response: null, cause: JsSIP_C.causes.REQUEST_TIMEOUT }); }, onDialogError: function() { removeSubscriber.call(self); self.emit('requestFailed', { response: null, cause: JsSIP_C.causes.DIALOG_ERROR }); } } }); this.outgoingRequest = request.outgoingRequest; }; ReferSubscriber.prototype.receiveNotify = function(request) { debug('receiveNotify()'); var status_line; if (!request.body) { return; } status_line = Grammar.parse(request.body, 'Status_Line'); if(status_line === -1) { debug('receiveNotify() | error parsing NOTIFY body: "' + request.body + '"'); return; } switch(true) { case /^100$/.test(status_line.status_code): this.emit('trying', { request: request, status_line: status_line }); break; case /^1[0-9]{2}$/.test(status_line.status_code): this.emit('progress', { request: request, status_line: status_line }); break; case /^2[0-9]{2}$/.test(status_line.status_code): removeSubscriber.call(this); this.emit('accepted', { request: request, status_line: status_line }); break; default: removeSubscriber.call(this); this.emit('failed', { request: request, status_line: status_line }); break; } }; // remove refer subscriber from the session function removeSubscriber() { console.log('removeSubscriber()'); clearTimeout(this.timer); this.session.referSubscriber = null; } },{"../Constants":1,"../Grammar":6,"./Request":15,"debug":34,"events":28,"util":32}],15:[function(require,module,exports){ module.exports = Request; /** * Dependencies. */ var debug = require('debug')('JsSIP:RTCSession:Request'); var debugerror = require('debug')('JsSIP:ERROR:RTCSession:Request'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('../Constants'); var Exceptions = require('../Exceptions'); var RTCSession = require('../RTCSession'); function Request(session, method) { debug('new | %s', method); this.session = session; this.method = method; // Instance of OutgoingRequest this.outgoingRequest = null; // Check RTCSession Status if (this.session.status !== RTCSession.C.STATUS_1XX_RECEIVED && this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ANSWER && this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ACK && this.session.status !== RTCSession.C.STATUS_CONFIRMED && this.session.status !== RTCSession.C.STATUS_TERMINATED) { throw new Exceptions.InvalidStateError(this.session.status); } /* * Allow sending BYE in TERMINATED status since the RTCSession * could had been terminated before the ACK had arrived. * RFC3261 Section 15, Paragraph 2 */ else if (this.session.status === RTCSession.C.STATUS_TERMINATED && method !== JsSIP_C.BYE) { throw new Exceptions.InvalidStateError(this.session.status); } } Request.prototype.send = function(options) { options = options || {}; var extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body || null; this.eventHandlers = options.eventHandlers || {}; this.outgoingRequest = this.session.dialog.sendRequest(this, this.method, { extraHeaders: extraHeaders, body: body }); }; Request.prototype.receiveResponse = function(response) { switch(true) { case /^1[0-9]{2}$/.test(response.status_code): debug('onProgressResponse'); if (this.eventHandlers.onProgressResponse) { this.eventHandlers.onProgressResponse(response); } break; case /^2[0-9]{2}$/.test(response.status_code): debug('onSuccessResponse'); if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); } break; default: debug('onErrorResponse'); if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); } break; } }; Request.prototype.onRequestTimeout = function() { debugerror('onRequestTimeout'); if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); } }; Request.prototype.onTransportError = function() { debugerror('onTransportError'); if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); } }; Request.prototype.onDialogError = function() { debugerror('onDialogError'); if (this.eventHandlers.onDialogError) { this.eventHandlers.onDialogError(); } }; },{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":34}],16:[function(require,module,exports){ module.exports = Registrator; /** * Dependecies */ var debug = require('debug')('JsSIP:Registrator'); var Utils = require('./Utils'); var JsSIP_C = require('./Constants'); var SIPMessage = require('./SIPMessage'); var RequestSender = require('./RequestSender'); function Registrator(ua, transport) { var reg_id=1; //Force reg_id to 1. this.ua = ua; this.transport = transport; this.registrar = ua.configuration.registrar_server; this.expires = ua.configuration.register_expires; // Call-ID and CSeq values RFC3261 10.2 this.call_id = Utils.createRandomToken(22); this.cseq = 0; // this.to_uri this.to_uri = ua.configuration.uri; this.registrationTimer = null; // Set status this.registered = false; // Contact header this.contact = this.ua.contact.toString(); // sip.ice media feature tag (RFC 5768) this.contact += ';+sip.ice'; // Custom headers for REGISTER and un-REGISTER. this.extraHeaders = []; // Custom Contact header params for REGISTER and un-REGISTER. this.extraContactParams = ''; if(reg_id) { this.contact += ';reg-id='+ reg_id; this.contact += ';+sip.instance="<urn:uuid:'+ this.ua.configuration.instance_id+'>"'; } } Registrator.prototype = { setExtraHeaders: function(extraHeaders) { if (! Array.isArray(extraHeaders)) { extraHeaders = []; } this.extraHeaders = extraHeaders.slice(); }, setExtraContactParams: function(extraContactParams) { if (! (extraContactParams instanceof Object)) { extraContactParams = {}; } // Reset it. this.extraContactParams = ''; for(var param_key in extraContactParams) { var param_value = extraContactParams[param_key]; this.extraContactParams += (';' + param_key); if (param_value) { this.extraContactParams += ('=' + param_value); } } }, register: function() { var request_sender, cause, extraHeaders, self = this; extraHeaders = this.extraHeaders.slice(); extraHeaders.push('Contact: ' + this.contact + ';expires=' + this.expires + this.extraContactParams); extraHeaders.push('Expires: '+ this.expires); this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, { 'to_uri': this.to_uri, 'call_id': this.call_id, 'cseq': (this.cseq += 1) }, extraHeaders); request_sender = new RequestSender(this, this.ua); this.receiveResponse = function(response) { var contact, expires, contacts = response.getHeaders('contact').length; // Discard responses to older REGISTER/un-REGISTER requests. if(response.cseq !== this.cseq) { return; } // Clear registration timer if (this.registrationTimer !== null) { clearTimeout(this.registrationTimer); this.registrationTimer = null; } switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): if(response.hasHeader('expires')) { expires = response.getHeader('expires'); } // Search the Contact pointing to us and update the expires value accordingly. if (!contacts) { debug('no Contact header in response to REGISTER, response ignored'); break; } while(contacts--) { contact = response.parseHeader('contact', contacts); if(contact.uri.user === this.ua.contact.uri.user) { expires = contact.getParam('expires'); break; } else { contact = null; } } if (!contact) { debug('no Contact header pointing to us, response ignored'); break; } if(!expires) { expires = this.expires; } // Re-Register before the expiration interval has elapsed. // For that, decrease the expires value. ie: 3 seconds this.registrationTimer = setTimeout(function() { self.registrationTimer = null; self.register(); }, (expires * 1000) - 3000); //Save gruu values if (contact.hasParam('temp-gruu')) { this.ua.contact.temp_gruu = contact.getParam('temp-gruu').replace(/"/g,''); } if (contact.hasParam('pub-gruu')) { this.ua.contact.pub_gruu = contact.getParam('pub-gruu').replace(/"/g,''); } if (! this.registered) { this.registered = true; this.ua.registered({ response: response }); } break; // Interval too brief RFC3261 10.2.8 case /^423$/.test(response.status_code): if(response.hasHeader('min-expires')) { // Increase our registration interval to the suggested minimum this.expires = response.getHeader('min-expires'); // Attempt the registration again immediately this.register(); } else { //This response MUST contain a Min-Expires header field debug('423 response received for REGISTER without Min-Expires'); this.registrationFailure(response, JsSIP_C.causes.SIP_FAILURE_CODE); } break; default: cause = Utils.sipErrorCause(response.status_code); this.registrationFailure(response, cause); } }; this.onRequestTimeout = function() { this.registrationFailure(null, JsSIP_C.causes.REQUEST_TIMEOUT); }; this.onTransportError = function() { this.registrationFailure(null, JsSIP_C.causes.CONNECTION_ERROR); }; request_sender.send(); }, unregister: function(options) { var extraHeaders; if(!this.registered) { debug('already unregistered'); return; } options = options || {}; this.registered = false; // Clear the registration timer. if (this.registrationTimer !== null) { clearTimeout(this.registrationTimer); this.registrationTimer = null; } extraHeaders = this.extraHeaders.slice(); if(options.all) { extraHeaders.push('Contact: *' + this.extraContactParams); extraHeaders.push('Expires: 0'); this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, { 'to_uri': this.to_uri, 'call_id': this.call_id, 'cseq': (this.cseq += 1) }, extraHeaders); } else { extraHeaders.push('Contact: '+ this.contact + ';expires=0' + this.extraContactParams); extraHeaders.push('Expires: 0'); this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, { 'to_uri': this.to_uri, 'call_id': this.call_id, 'cseq': (this.cseq += 1) }, extraHeaders); } var request_sender = new RequestSender(this, this.ua); this.receiveResponse = function(response) { var cause; switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): this.unregistered(response); break; default: cause = Utils.sipErrorCause(response.status_code); this.unregistered(response, cause); } }; this.onRequestTimeout = function() { this.unregistered(null, JsSIP_C.causes.REQUEST_TIMEOUT); }; this.onTransportError = function() { this.unregistered(null, JsSIP_C.causes.CONNECTION_ERROR); }; request_sender.send(); }, registrationFailure: function(response, cause) { this.ua.registrationFailed({ response: response || null, cause: cause }); if (this.registered) { this.registered = false; this.ua.unregistered({ response: response || null, cause: cause }); } }, unregistered: function(response, cause) { this.registered = false; this.ua.unregistered({ response: response || null, cause: cause || null }); }, onTransportClosed: function() { if (this.registrationTimer !== null) { clearTimeout(this.registrationTimer); this.registrationTimer = null; } if(this.registered) { this.registered = false; this.ua.unregistered({}); } }, close: function() { if (this.registered) { this.unregister(); } } }; },{"./Constants":1,"./RequestSender":17,"./SIPMessage":18,"./Utils":25,"debug":34}],17:[function(require,module,exports){ module.exports = RequestSender; /** * Dependencies. */ var debug = require('debug')('JsSIP:RequestSender'); var JsSIP_C = require('./Constants'); var UA = require('./UA'); var DigestAuthentication = require('./DigestAuthentication'); var Transactions = require('./Transactions'); function RequestSender(applicant, ua) { this.ua = ua; this.applicant = applicant; this.method = applicant.request.method; this.request = applicant.request; this.auth = null; this.challenged = false; this.staled = false; // If ua is in closing process or even closed just allow sending Bye and ACK if (ua.status === UA.C.STATUS_USER_CLOSED && (this.method !== JsSIP_C.BYE || this.method !== JsSIP_C.ACK)) { this.onTransportError(); } } /** * Create the client transaction and send the message. */ RequestSender.prototype = { send: function() { switch(this.method) { case 'INVITE': this.clientTransaction = new Transactions.InviteClientTransaction(this, this.request, this.ua.transport); break; case 'ACK': this.clientTransaction = new Transactions.AckClientTransaction(this, this.request, this.ua.transport); break; default: this.clientTransaction = new Transactions.NonInviteClientTransaction(this, this.request, this.ua.transport); } this.clientTransaction.send(); }, /** * Callback fired when receiving a request timeout error from the client transaction. * To be re-defined by the applicant. */ onRequestTimeout: function() { this.applicant.onRequestTimeout(); }, /** * Callback fired when receiving a transport error from the client transaction. * To be re-defined by the applicant. */ onTransportError: function() { this.applicant.onTransportError(); }, /** * Called from client transaction when receiving a correct response to the request. * Authenticate request if needed or pass the response back to the applicant. */ receiveResponse: function(response) { var cseq, challenge, authorization_header_name, status_code = response.status_code; /* * Authentication * Authenticate once. _challenged_ flag used to avoid infinite authentications. */ if ((status_code === 401 || status_code === 407) && (this.ua.configuration.password !== null || this.ua.configuration.ha1 !== null)) { // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. if (response.status_code === 401) { challenge = response.parseHeader('www-authenticate'); authorization_header_name = 'authorization'; } else { challenge = response.parseHeader('proxy-authenticate'); authorization_header_name = 'proxy-authorization'; } // Verify it seems a valid challenge. if (!challenge) { debug(response.status_code + ' with wrong or missing challenge, cannot authenticate'); this.applicant.receiveResponse(response); return; } if (!this.challenged || (!this.staled && challenge.stale === true)) { if (!this.auth) { this.auth = new DigestAuthentication({ username : this.ua.configuration.authorization_user, password : this.ua.configuration.password, realm : this.ua.configuration.realm, ha1 : this.ua.configuration.ha1 }); } // Verify that the challenge is really valid. if (!this.auth.authenticate(this.request, challenge)) { this.applicant.receiveResponse(response); return; } this.challenged = true; // Update ha1 and realm in the UA. this.ua.set('realm', this.auth.get('realm')); this.ua.set('ha1', this.auth.get('ha1')); if (challenge.stale) { this.staled = true; } if (response.method === JsSIP_C.REGISTER) { cseq = this.applicant.cseq += 1; } else if (this.request.dialog) { cseq = this.request.dialog.local_seqnum += 1; } else { cseq = this.request.cseq + 1; } this.request = this.applicant.request = this.request.clone(); this.request.cseq = cseq; this.request.setHeader('cseq', cseq +' '+ this.method); this.request.setHeader(authorization_header_name, this.auth.toString()); this.send(); } else { this.applicant.receiveResponse(response); } } else { this.applicant.receiveResponse(response); } } }; },{"./Constants":1,"./DigestAuthentication":4,"./Transactions":21,"./UA":23,"debug":34}],18:[function(require,module,exports){ module.exports = { OutgoingRequest: OutgoingRequest, IncomingRequest: IncomingRequest, IncomingResponse: IncomingResponse }; /** * Dependencies. */ var debug = require('debug')('JsSIP:SIPMessage'); var sdp_transform = require('sdp-transform'); var JsSIP_C = require('./Constants'); var Utils = require('./Utils'); var NameAddrHeader = require('./NameAddrHeader'); var Grammar = require('./Grammar'); /** * -param {String} method request method * -param {String} ruri request uri * -param {UA} ua * -param {Object} params parameters that will have priority over ua.configuration parameters: * <br> * - cseq, call_id, from_tag, from_uri, from_display_name, to_uri, to_tag, route_set * -param {Object} [headers] extra headers * -param {String} [body] */ function OutgoingRequest(method, ruri, ua, params, extraHeaders, body) { var to, from, call_id, cseq; params = params || {}; // Mandatory parameters check if(!method || !ruri || !ua) { return null; } this.ua = ua; this.headers = {}; this.method = method; this.ruri = ruri; this.body = body; this.extraHeaders = extraHeaders && extraHeaders.slice() || []; // Fill the Common SIP Request Headers // Route if (params.route_set) { this.setHeader('route', params.route_set); } else if (ua.configuration.use_preloaded_route) { this.setHeader('route', '<' + ua.transport.sip_uri + ';lr>'); } // Via // Empty Via header. Will be filled by the client transaction. this.setHeader('via', ''); // Max-Forwards this.setHeader('max-forwards', JsSIP_C.MAX_FORWARDS); // To to = (params.to_display_name || params.to_display_name === 0) ? '"' + params.to_display_name + '" ' : ''; to += '<' + (params.to_uri || ruri) + '>'; to += params.to_tag ? ';tag=' + params.to_tag : ''; this.to = new NameAddrHeader.parse(to); this.setHeader('to', to); // From if (params.from_display_name || params.from_display_name === 0) { from = '"' + params.from_display_name + '" '; } else if (ua.configuration.display_name) { from = '"' + ua.configuration.display_name + '" '; } else { from = ''; } from += '<' + (params.from_uri || ua.configuration.uri) + '>;tag='; from += params.from_tag || Utils.newTag(); this.from = new NameAddrHeader.parse(from); this.setHeader('from', from); // Call-ID call_id = params.call_id || (ua.configuration.jssip_id + Utils.createRandomToken(15)); this.call_id = call_id; this.setHeader('call-id', call_id); // CSeq cseq = params.cseq || Math.floor(Math.random() * 10000); this.cseq = cseq; this.setHeader('cseq', cseq + ' ' + method); } OutgoingRequest.prototype = { /** * Replace the the given header by the given value. * -param {String} name header name * -param {String | Array} value header value */ setHeader: function(name, value) { var regexp, idx; // Remove the header from extraHeaders if present. regexp = new RegExp('^\\s*'+ name +'\\s*:','i'); for (idx=0; idx<this.extraHeaders.length; idx++) { if (regexp.test(this.extraHeaders[idx])) { this.extraHeaders.splice(idx, 1); } } this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value]; }, /** * Get the value of the given header name at the given position. * -param {String} name header name * -returns {String|undefined} Returns the specified header, null if header doesn't exist. */ getHeader: function(name) { var regexp, idx, length = this.extraHeaders.length, header = this.headers[Utils.headerize(name)]; if(header) { if(header[0]) { return header[0]; } } else { regexp = new RegExp('^\\s*'+ name +'\\s*:','i'); for (idx=0; idx<length; idx++) { header = this.extraHeaders[idx]; if (regexp.test(header)) { return header.substring(header.indexOf(':')+1).trim(); } } } return; }, /** * Get the header/s of the given name. * -param {String} name header name * -returns {Array} Array with all the headers of the specified name. */ getHeaders: function(name) { var idx, length, regexp, header = this.headers[Utils.headerize(name)], result = []; if (header) { length = header.length; for (idx = 0; idx < length; idx++) { result.push(header[idx]); } return result; } else { length = this.extraHeaders.length; regexp = new RegExp('^\\s*'+ name +'\\s*:','i'); for (idx=0; idx<length; idx++) { header = this.extraHeaders[idx]; if (regexp.test(header)) { result.push(header.substring(header.indexOf(':')+1).trim()); } } return result; } }, /** * Verify the existence of the given header. * -param {String} name header name * -returns {boolean} true if header with given name exists, false otherwise */ hasHeader: function(name) { var regexp, idx, length = this.extraHeaders.length; if (this.headers[Utils.headerize(name)]) { return true; } else { regexp = new RegExp('^\\s*'+ name +'\\s*:','i'); for (idx=0; idx<length; idx++) { if (regexp.test(this.extraHeaders[idx])) { return true; } } } return false; }, /** * Parse the current body as a SDP and store the resulting object * into this.sdp. * -param {Boolean} force: Parse even if this.sdp already exists. * * Returns this.sdp. */ parseSDP: function(force) { if (!force && this.sdp) { return this.sdp; } else { this.sdp = sdp_transform.parse(this.body || ''); return this.sdp; } }, toString: function() { var msg = '', header, length, idx, supported = []; msg += this.method + ' ' + this.ruri + ' SIP/2.0\r\n'; for (header in this.headers) { length = this.headers[header].length; for (idx = 0; idx < length; idx++) { msg += header + ': ' + this.headers[header][idx] + '\r\n'; } } length = this.extraHeaders.length; for (idx = 0; idx < length; idx++) { msg += this.extraHeaders[idx].trim() +'\r\n'; } // Supported switch (this.method) { case JsSIP_C.REGISTER: supported.push('path', 'gruu'); break; case JsSIP_C.INVITE: if (this.ua.configuration.session_timers) { supported.push('timer'); } if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) { supported.push('gruu'); } supported.push('ice','replaces'); break; case JsSIP_C.UPDATE: if (this.ua.configuration.session_timers) { supported.push('timer'); } supported.push('ice'); break; } supported.push('outbound'); // Allow msg += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n'; msg += 'Supported: ' + supported +'\r\n'; msg += 'User-Agent: ' + JsSIP_C.USER_AGENT +'\r\n'; if (this.body) { length = Utils.str_utf8_length(this.body); msg += 'Content-Length: ' + length + '\r\n\r\n'; msg += this.body; } else { msg += 'Content-Length: 0\r\n\r\n'; } return msg; }, clone: function() { var request = new OutgoingRequest(this.method, this.ruri, this.ua); Object.keys(this.headers).forEach(function(name) { request.headers[name] = this.headers[name].slice(); }, this); request.body = this.body; request.extraHeaders = this.extraHeaders && this.extraHeaders.slice() || []; request.to = this.to; request.from = this.from; request.call_id = this.call_id; request.cseq = this.cseq; return request; } }; function IncomingMessage(){ this.data = null; this.headers = null; this.method = null; this.via = null; this.via_branch = null; this.call_id = null; this.cseq = null; this.from = null; this.from_tag = null; this.to = null; this.to_tag = null; this.body = null; this.sdp = null; } IncomingMessage.prototype = { /** * Insert a header of the given name and value into the last position of the * header array. */ addHeader: function(name, value) { var header = { raw: value }; name = Utils.headerize(name); if(this.headers[name]) { this.headers[name].push(header); } else { this.headers[name] = [header]; } }, /** * Get the value of the given header name at the given position. */ getHeader: function(name) { var header = this.headers[Utils.headerize(name)]; if(header) { if(header[0]) { return header[0].raw; } } else { return; } }, /** * Get the header/s of the given name. */ getHeaders: function(name) { var idx, length, header = this.headers[Utils.headerize(name)], result = []; if(!header) { return []; } length = header.length; for (idx = 0; idx < length; idx++) { result.push(header[idx].raw); } return result; }, /** * Verify the existence of the given header. */ hasHeader: function(name) { return(this.headers[Utils.headerize(name)]) ? true : false; }, /** * Parse the given header on the given index. * -param {String} name header name * -param {Number} [idx=0] header index * -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error. */ parseHeader: function(name, idx) { var header, value, parsed; name = Utils.headerize(name); idx = idx || 0; if(!this.headers[name]) { debug('header "' + name + '" not present'); return; } else if(idx >= this.headers[name].length) { debug('not so many "' + name + '" headers present'); return; } header = this.headers[name][idx]; value = header.raw; if(header.parsed) { return header.parsed; } //substitute '-' by '_' for grammar rule matching. parsed = Grammar.parse(value, name.replace(/-/g, '_')); if(parsed === -1) { this.headers[name].splice(idx, 1); //delete from headers debug('error parsing "' + name + '" header field with value "' + value + '"'); return; } else { header.parsed = parsed; return parsed; } }, /** * Message Header attribute selector. Alias of parseHeader. * -param {String} name header name * -param {Number} [idx=0] header index * -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error. * * -example * message.s('via',3).port */ s: function(name, idx) { return this.parseHeader(name, idx); }, /** * Replace the value of the given header by the value. * -param {String} name header name * -param {String} value header value */ setHeader: function(name, value) { var header = { raw: value }; this.headers[Utils.headerize(name)] = [header]; }, /** * Parse the current body as a SDP and store the resulting object * into this.sdp. * -param {Boolean} force: Parse even if this.sdp already exists. * * Returns this.sdp. */ parseSDP: function(force) { if (!force && this.sdp) { return this.sdp; } else { this.sdp = sdp_transform.parse(this.body || ''); return this.sdp; } }, toString: function() { return this.data; } }; function IncomingRequest(ua) { this.ua = ua; this.headers = {}; this.ruri = null; this.transport = null; this.server_transaction = null; } IncomingRequest.prototype = new IncomingMessage(); /** * Stateful reply. * -param {Number} code status code * -param {String} reason reason phrase * -param {Object} headers extra headers * -param {String} body body * -param {Function} [onSuccess] onSuccess callback * -param {Function} [onFailure] onFailure callback */ IncomingRequest.prototype.reply = function(code, reason, extraHeaders, body, onSuccess, onFailure) { var rr, vias, length, idx, response, supported = [], to = this.getHeader('To'), r = 0, v = 0; code = code || null; reason = reason || null; // Validate code and reason values if (!code || (code < 100 || code > 699)) { throw new TypeError('Invalid status_code: '+ code); } else if (reason && typeof reason !== 'string' && !(reason instanceof String)) { throw new TypeError('Invalid reason_phrase: '+ reason); } reason = reason || JsSIP_C.REASON_PHRASE[code] || ''; extraHeaders = extraHeaders && extraHeaders.slice() || []; response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n'; if(this.method === JsSIP_C.INVITE && code > 100 && code <= 200) { rr = this.getHeaders('record-route'); length = rr.length; for(r; r < length; r++) { response += 'Record-Route: ' + rr[r] + '\r\n'; } } vias = this.getHeaders('via'); length = vias.length; for(v; v < length; v++) { response += 'Via: ' + vias[v] + '\r\n'; } if(!this.to_tag && code > 100) { to += ';tag=' + Utils.newTag(); } else if(this.to_tag && !this.s('to').hasParam('tag')) { to += ';tag=' + this.to_tag; } response += 'To: ' + to + '\r\n'; response += 'From: ' + this.getHeader('From') + '\r\n'; response += 'Call-ID: ' + this.call_id + '\r\n'; response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n'; length = extraHeaders.length; for (idx = 0; idx < length; idx++) { response += extraHeaders[idx].trim() +'\r\n'; } // Supported switch (this.method) { case JsSIP_C.INVITE: if (this.ua.configuration.session_timers) { supported.push('timer'); } if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) { supported.push('gruu'); } supported.push('ice','replaces'); break; case JsSIP_C.UPDATE: if (this.ua.configuration.session_timers) { supported.push('timer'); } if (body) { supported.push('ice'); } supported.push('replaces'); } supported.push('outbound'); // Allow and Accept if (this.method === JsSIP_C.OPTIONS) { response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n'; response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n'; } else if (code === 405) { response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n'; } else if (code === 415 ) { response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n'; } response += 'Supported: ' + supported +'\r\n'; if(body) { length = Utils.str_utf8_length(body); response += 'Content-Type: application/sdp\r\n'; response += 'Content-Length: ' + length + '\r\n\r\n'; response += body; } else { response += 'Content-Length: ' + 0 + '\r\n\r\n'; } this.server_transaction.receiveResponse(code, response, onSuccess, onFailure); }; /** * Stateless reply. * -param {Number} code status code * -param {String} reason reason phrase */ IncomingRequest.prototype.reply_sl = function(code, reason) { var to, response, v = 0, vias = this.getHeaders('via'), length = vias.length; code = code || null; reason = reason || null; // Validate code and reason values if (!code || (code < 100 || code > 699)) { throw new TypeError('Invalid status_code: '+ code); } else if (reason && typeof reason !== 'string' && !(reason instanceof String)) { throw new TypeError('Invalid reason_phrase: '+ reason); } reason = reason || JsSIP_C.REASON_PHRASE[code] || ''; response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n'; for(v; v < length; v++) { response += 'Via: ' + vias[v] + '\r\n'; } to = this.getHeader('To'); if(!this.to_tag && code > 100) { to += ';tag=' + Utils.newTag(); } else if(this.to_tag && !this.s('to').hasParam('tag')) { to += ';tag=' + this.to_tag; } response += 'To: ' + to + '\r\n'; response += 'From: ' + this.getHeader('From') + '\r\n'; response += 'Call-ID: ' + this.call_id + '\r\n'; response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n'; response += 'Content-Length: ' + 0 + '\r\n\r\n'; this.transport.send(response); }; function IncomingResponse() { this.headers = {}; this.status_code = null; this.reason_phrase = null; } IncomingResponse.prototype = new IncomingMessage(); },{"./Constants":1,"./Grammar":6,"./NameAddrHeader":9,"./Utils":25,"debug":34,"sdp-transform":37}],19:[function(require,module,exports){ module.exports = Socket; /** * Interface documentation: http://jssip.net/documentation/$last_version/api/socket/ * * interface Socket { * attribute String via_transport * attribute String url * attribute String sip_uri * * method connect(); * method disconnect(); * method send(data); * * attribute EventHandler onconnect * attribute EventHandler ondisconnect * attribute EventHandler ondata * } * */ /** * Dependencies. */ var Utils = require('./Utils'); var Grammar = require('./Grammar'); var debugerror = require('debug')('JsSIP:ERROR:Socket'); debugerror.log = console.warn.bind(console); function Socket() {} Socket.isSocket = function(socket) { // Ignore if an array is given if (Array.isArray(socket)) { return false; } if (typeof socket === 'undefined') { debugerror('undefined JsSIP.Socket instance'); return false; } // Check Properties try { if (!Utils.isString(socket.url)) { debugerror('missing or invalid JsSIP.Socket url property'); throw new Error(); } if (!Utils.isString(socket.via_transport)) { debugerror('missing or invalid JsSIP.Socket via_transport property'); throw new Error(); } if (Grammar.parse(socket.sip_uri, 'SIP_URI') === -1) { debugerror('missing or invalid JsSIP.Socket sip_uri property'); throw new Error(); } } catch(e) { return false; } // Check Methods try { ['connect', 'disconnect', 'send'].forEach(function(method) { if (!Utils.isFunction(socket[method])) { debugerror('missing or invalid JsSIP.Socket method: ' + method); throw new Error(); } }); } catch(e) { return false; } return true; }; },{"./Grammar":6,"./Utils":25,"debug":34}],20:[function(require,module,exports){ var T1 = 500, T2 = 4000, T4 = 5000; var Timers = { T1: T1, T2: T2, T4: T4, TIMER_B: 64 * T1, TIMER_D: 0 * T1, TIMER_F: 64 * T1, TIMER_H: 64 * T1, TIMER_I: 0 * T1, TIMER_J: 0 * T1, TIMER_K: 0 * T4, TIMER_L: 64 * T1, TIMER_M: 64 * T1, PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 }; module.exports = Timers; },{}],21:[function(require,module,exports){ module.exports = { C: null, NonInviteClientTransaction: NonInviteClientTransaction, InviteClientTransaction: InviteClientTransaction, AckClientTransaction: AckClientTransaction, NonInviteServerTransaction: NonInviteServerTransaction, InviteServerTransaction: InviteServerTransaction, checkTransaction: checkTransaction }; var C = { // Transaction states STATUS_TRYING: 1, STATUS_PROCEEDING: 2, STATUS_CALLING: 3, STATUS_ACCEPTED: 4, STATUS_COMPLETED: 5, STATUS_TERMINATED: 6, STATUS_CONFIRMED: 7, // Transaction types NON_INVITE_CLIENT: 'nict', NON_INVITE_SERVER: 'nist', INVITE_CLIENT: 'ict', INVITE_SERVER: 'ist' }; /** * Expose C object. */ module.exports.C = C; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debugnict = require('debug')('JsSIP:NonInviteClientTransaction'); var debugict = require('debug')('JsSIP:InviteClientTransaction'); var debugact = require('debug')('JsSIP:AckClientTransaction'); var debugnist = require('debug')('JsSIP:NonInviteServerTransaction'); var debugist = require('debug')('JsSIP:InviteServerTransaction'); var JsSIP_C = require('./Constants'); var Timers = require('./Timers'); function NonInviteClientTransaction(request_sender, request, transport) { var via; this.type = C.NON_INVITE_CLIENT; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; via = 'SIP/2.0/' + transport.via_transport; via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; this.request.setHeader('via', via); this.request_sender.ua.newTransaction(this); events.EventEmitter.call(this); } util.inherits(NonInviteClientTransaction, events.EventEmitter); NonInviteClientTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged'); }; NonInviteClientTransaction.prototype.send = function() { var tr = this; this.stateChanged(C.STATUS_TRYING); this.F = setTimeout(function() {tr.timer_F();}, Timers.TIMER_F); if(!this.transport.send(this.request)) { this.onTransportError(); } }; NonInviteClientTransaction.prototype.onTransportError = function() { debugnict('transport error occurred, deleting transaction ' + this.id); clearTimeout(this.F); clearTimeout(this.K); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); this.request_sender.onTransportError(); }; NonInviteClientTransaction.prototype.timer_F = function() { debugnict('Timer F expired for transaction ' + this.id); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); this.request_sender.onRequestTimeout(); }; NonInviteClientTransaction.prototype.timer_K = function() { this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); }; NonInviteClientTransaction.prototype.receiveResponse = function(response) { var tr = this, status_code = response.status_code; if(status_code < 200) { switch(this.state) { case C.STATUS_TRYING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_PROCEEDING); this.request_sender.receiveResponse(response); break; } } else { switch(this.state) { case C.STATUS_TRYING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_COMPLETED); clearTimeout(this.F); if(status_code === 408) { this.request_sender.onRequestTimeout(); } else { this.request_sender.receiveResponse(response); } this.K = setTimeout(function() {tr.timer_K();}, Timers.TIMER_K); break; case C.STATUS_COMPLETED: break; } } }; function InviteClientTransaction(request_sender, request, transport) { var via, tr = this; this.type = C.INVITE_CLIENT; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; via = 'SIP/2.0/' + transport.via_transport; via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; this.request.setHeader('via', via); this.request_sender.ua.newTransaction(this); // TODO: Adding here the cancel() method is a hack that must be fixed. // Add the cancel property to the request. //Will be called from the request instance, not the transaction itself. this.request.cancel = function(reason) { tr.cancel_request(tr, reason); }; events.EventEmitter.call(this); } util.inherits(InviteClientTransaction, events.EventEmitter); InviteClientTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged'); }; InviteClientTransaction.prototype.send = function() { var tr = this; this.stateChanged(C.STATUS_CALLING); this.B = setTimeout(function() { tr.timer_B(); }, Timers.TIMER_B); if(!this.transport.send(this.request)) { this.onTransportError(); } }; InviteClientTransaction.prototype.onTransportError = function() { clearTimeout(this.B); clearTimeout(this.D); clearTimeout(this.M); if (this.state !== C.STATUS_ACCEPTED) { debugict('transport error occurred, deleting transaction ' + this.id); this.request_sender.onTransportError(); } this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); }; // RFC 6026 7.2 InviteClientTransaction.prototype.timer_M = function() { debugict('Timer M expired for transaction ' + this.id); if(this.state === C.STATUS_ACCEPTED) { clearTimeout(this.B); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); } }; // RFC 3261 17.1.1 InviteClientTransaction.prototype.timer_B = function() { debugict('Timer B expired for transaction ' + this.id); if(this.state === C.STATUS_CALLING) { this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); this.request_sender.onRequestTimeout(); } }; InviteClientTransaction.prototype.timer_D = function() { debugict('Timer D expired for transaction ' + this.id); clearTimeout(this.B); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); }; InviteClientTransaction.prototype.sendACK = function(response) { var tr = this; this.ack = 'ACK ' + this.request.ruri + ' SIP/2.0\r\n'; this.ack += 'Via: ' + this.request.headers.Via.toString() + '\r\n'; if(this.request.headers.Route) { this.ack += 'Route: ' + this.request.headers.Route.toString() + '\r\n'; } this.ack += 'To: ' + response.getHeader('to') + '\r\n'; this.ack += 'From: ' + this.request.headers.From.toString() + '\r\n'; this.ack += 'Call-ID: ' + this.request.headers['Call-ID'].toString() + '\r\n'; this.ack += 'CSeq: ' + this.request.headers.CSeq.toString().split(' ')[0]; this.ack += ' ACK\r\n'; this.ack += 'Content-Length: 0\r\n\r\n'; this.D = setTimeout(function() {tr.timer_D();}, Timers.TIMER_D); this.transport.send(this.ack); }; InviteClientTransaction.prototype.cancel_request = function(tr, reason) { var request = tr.request; this.cancel = JsSIP_C.CANCEL + ' ' + request.ruri + ' SIP/2.0\r\n'; this.cancel += 'Via: ' + request.headers.Via.toString() + '\r\n'; if(this.request.headers.Route) { this.cancel += 'Route: ' + request.headers.Route.toString() + '\r\n'; } this.cancel += 'To: ' + request.headers.To.toString() + '\r\n'; this.cancel += 'From: ' + request.headers.From.toString() + '\r\n'; this.cancel += 'Call-ID: ' + request.headers['Call-ID'].toString() + '\r\n'; this.cancel += 'CSeq: ' + request.headers.CSeq.toString().split(' ')[0] + ' CANCEL\r\n'; if(reason) { this.cancel += 'Reason: ' + reason + '\r\n'; } this.cancel += 'Content-Length: 0\r\n\r\n'; // Send only if a provisional response (>100) has been received. if(this.state === C.STATUS_PROCEEDING) { this.transport.send(this.cancel); } }; InviteClientTransaction.prototype.receiveResponse = function(response) { var tr = this, status_code = response.status_code; if(status_code >= 100 && status_code <= 199) { switch(this.state) { case C.STATUS_CALLING: this.stateChanged(C.STATUS_PROCEEDING); this.request_sender.receiveResponse(response); break; case C.STATUS_PROCEEDING: this.request_sender.receiveResponse(response); break; } } else if(status_code >= 200 && status_code <= 299) { switch(this.state) { case C.STATUS_CALLING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_ACCEPTED); this.M = setTimeout(function() { tr.timer_M(); }, Timers.TIMER_M); this.request_sender.receiveResponse(response); break; case C.STATUS_ACCEPTED: this.request_sender.receiveResponse(response); break; } } else if(status_code >= 300 && status_code <= 699) { switch(this.state) { case C.STATUS_CALLING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_COMPLETED); this.sendACK(response); this.request_sender.receiveResponse(response); break; case C.STATUS_COMPLETED: this.sendACK(response); break; } } }; function AckClientTransaction(request_sender, request, transport) { var via; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; via = 'SIP/2.0/' + transport.via_transport; via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; this.request.setHeader('via', via); events.EventEmitter.call(this); } util.inherits(AckClientTransaction, events.EventEmitter); AckClientTransaction.prototype.send = function() { if(!this.transport.send(this.request)) { this.onTransportError(); } }; AckClientTransaction.prototype.onTransportError = function() { debugact('transport error occurred for transaction ' + this.id); this.request_sender.onTransportError(); }; function NonInviteServerTransaction(request, ua) { this.type = C.NON_INVITE_SERVER; this.id = request.via_branch; this.request = request; this.transport = request.transport; this.ua = ua; this.last_response = ''; request.server_transaction = this; this.state = C.STATUS_TRYING; ua.newTransaction(this); events.EventEmitter.call(this); } util.inherits(NonInviteServerTransaction, events.EventEmitter); NonInviteServerTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged'); }; NonInviteServerTransaction.prototype.timer_J = function() { debugnist('Timer J expired for transaction ' + this.id); this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); }; NonInviteServerTransaction.prototype.onTransportError = function() { if (!this.transportError) { this.transportError = true; debugnist('transport error occurred, deleting transaction ' + this.id); clearTimeout(this.J); this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); } }; NonInviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) { var tr = this; if(status_code === 100) { /* RFC 4320 4.1 * 'A SIP element MUST NOT * send any provisional response with a * Status-Code other than 100 to a non-INVITE request.' */ switch(this.state) { case C.STATUS_TRYING: this.stateChanged(C.STATUS_PROCEEDING); if(!this.transport.send(response)) { this.onTransportError(); } break; case C.STATUS_PROCEEDING: this.last_response = response; if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else if (onSuccess) { onSuccess(); } break; } } else if(status_code >= 200 && status_code <= 699) { switch(this.state) { case C.STATUS_TRYING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_COMPLETED); this.last_response = response; this.J = setTimeout(function() { tr.timer_J(); }, Timers.TIMER_J); if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else if (onSuccess) { onSuccess(); } break; case C.STATUS_COMPLETED: break; } } }; function InviteServerTransaction(request, ua) { this.type = C.INVITE_SERVER; this.id = request.via_branch; this.request = request; this.transport = request.transport; this.ua = ua; this.last_response = ''; request.server_transaction = this; this.state = C.STATUS_PROCEEDING; ua.newTransaction(this); this.resendProvisionalTimer = null; request.reply(100); events.EventEmitter.call(this); } util.inherits(InviteServerTransaction, events.EventEmitter); InviteServerTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged'); }; InviteServerTransaction.prototype.timer_H = function() { debugist('Timer H expired for transaction ' + this.id); if(this.state === C.STATUS_COMPLETED) { debugist('ACK not received, dialog will be terminated'); } this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); }; InviteServerTransaction.prototype.timer_I = function() { this.stateChanged(C.STATUS_TERMINATED); }; // RFC 6026 7.1 InviteServerTransaction.prototype.timer_L = function() { debugist('Timer L expired for transaction ' + this.id); if(this.state === C.STATUS_ACCEPTED) { this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); } }; InviteServerTransaction.prototype.onTransportError = function() { if (!this.transportError) { this.transportError = true; debugist('transport error occurred, deleting transaction ' + this.id); if (this.resendProvisionalTimer !== null) { clearInterval(this.resendProvisionalTimer); this.resendProvisionalTimer = null; } clearTimeout(this.L); clearTimeout(this.H); clearTimeout(this.I); this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); } }; InviteServerTransaction.prototype.resend_provisional = function() { if(!this.transport.send(this.last_response)) { this.onTransportError(); } }; // INVITE Server Transaction RFC 3261 17.2.1 InviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) { var tr = this; if(status_code >= 100 && status_code <= 199) { switch(this.state) { case C.STATUS_PROCEEDING: if(!this.transport.send(response)) { this.onTransportError(); } this.last_response = response; break; } } if(status_code > 100 && status_code <= 199 && this.state === C.STATUS_PROCEEDING) { // Trigger the resendProvisionalTimer only for the first non 100 provisional response. if(this.resendProvisionalTimer === null) { this.resendProvisionalTimer = setInterval(function() { tr.resend_provisional();}, Timers.PROVISIONAL_RESPONSE_INTERVAL); } } else if(status_code >= 200 && status_code <= 299) { switch(this.state) { case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_ACCEPTED); this.last_response = response; this.L = setTimeout(function() { tr.timer_L(); }, Timers.TIMER_L); if (this.resendProvisionalTimer !== null) { clearInterval(this.resendProvisionalTimer); this.resendProvisionalTimer = null; } /* falls through */ case C.STATUS_ACCEPTED: // Note that this point will be reached for proceeding tr.state also. if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else if (onSuccess) { onSuccess(); } break; } } else if(status_code >= 300 && status_code <= 699) { switch(this.state) { case C.STATUS_PROCEEDING: if (this.resendProvisionalTimer !== null) { clearInterval(this.resendProvisionalTimer); this.resendProvisionalTimer = null; } if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else { this.stateChanged(C.STATUS_COMPLETED); this.H = setTimeout(function() { tr.timer_H(); }, Timers.TIMER_H); if (onSuccess) { onSuccess(); } } break; } } }; /** * INVITE: * _true_ if retransmission * _false_ new request * * ACK: * _true_ ACK to non2xx response * _false_ ACK must be passed to TU (accepted state) * ACK to 2xx response * * CANCEL: * _true_ no matching invite transaction * _false_ matching invite transaction and no final response sent * * OTHER: * _true_ retransmission * _false_ new request */ function checkTransaction(ua, request) { var tr; switch(request.method) { case JsSIP_C.INVITE: tr = ua.transactions.ist[request.via_branch]; if(tr) { switch(tr.state) { case C.STATUS_PROCEEDING: tr.transport.send(tr.last_response); break; // RFC 6026 7.1 Invite retransmission //received while in C.STATUS_ACCEPTED state. Absorb it. case C.STATUS_ACCEPTED: break; } return true; } break; case JsSIP_C.ACK: tr = ua.transactions.ist[request.via_branch]; // RFC 6026 7.1 if(tr) { if(tr.state === C.STATUS_ACCEPTED) { return false; } else if(tr.state === C.STATUS_COMPLETED) { tr.state = C.STATUS_CONFIRMED; tr.I = setTimeout(function() {tr.timer_I();}, Timers.TIMER_I); return true; } } // ACK to 2XX Response. else { return false; } break; case JsSIP_C.CANCEL: tr = ua.transactions.ist[request.via_branch]; if(tr) { request.reply_sl(200); if(tr.state === C.STATUS_PROCEEDING) { return false; } else { return true; } } else { request.reply_sl(481); return true; } break; default: // Non-INVITE Server Transaction RFC 3261 17.2.2 tr = ua.transactions.nist[request.via_branch]; if(tr) { switch(tr.state) { case C.STATUS_TRYING: break; case C.STATUS_PROCEEDING: case C.STATUS_COMPLETED: tr.transport.send(tr.last_response); break; } return true; } break; } } },{"./Constants":1,"./Timers":20,"debug":34,"events":28,"util":32}],22:[function(require,module,exports){ module.exports = Transport; /** * Dependencies. */ var Socket = require('./Socket'); var debug = require('debug')('JsSIP:Transport'); var debugerror = require('debug')('JsSIP:ERROR:Transport'); /** * Constants */ var C = { // Transport status STATUS_CONNECTED: 0, STATUS_CONNECTING: 1, STATUS_DISCONNECTED: 2, // Socket status SOCKET_STATUS_READY: 0, SOCKET_STATUS_ERROR: 1, // Recovery options recovery_options: { min_interval: 2, // minimum interval in seconds between recover attempts max_interval: 30 // maximum interval in seconds between recover attempts } }; /* * Manages one or multiple JsSIP.Socket instances. * Is reponsible for transport recovery logic among all socket instances. * * @socket JsSIP::Socket instance */ function Transport(sockets, recovery_options) { debug('new()'); this.status = C.STATUS_DISCONNECTED; // current socket this.socket = null; // socket collection this.sockets = []; this.recovery_options = recovery_options || C.recovery_options; this.recover_attempts = 0; this.recovery_timer = null; this.close_requested = false; if (typeof sockets === 'undefined') { throw new TypeError('Invalid argument.' + ' undefined \'sockets\' argument'); } if (!(sockets instanceof Array)) { sockets = [ sockets ]; } sockets.forEach(function(socket) { if (!Socket.isSocket(socket.socket)) { throw new TypeError('Invalid argument.' + ' invalid \'JsSIP.Socket\' instance'); } if (socket.weight && !Number(socket.weight)) { throw new TypeError('Invalid argument.' + ' \'weight\' attribute is not a number'); } this.sockets.push({ socket: socket.socket, weight: socket.weight || 0, status: C.SOCKET_STATUS_READY }); }, this); // read only properties Object.defineProperties(this, { via_transport: { get: function() { return this.socket.via_transport; } }, url: { get: function() { return this.socket.url; } }, sip_uri: { get: function() { return this.socket.sip_uri; } } }); // get the socket with higher weight getSocket.call(this); } /** * Instance Methods */ Transport.prototype.connect = function() { debug('connect()'); if (this.isConnected()) { debug('Transport is already connected'); return; } else if (this.isConnecting()) { debug('Transport is connecting'); return; } this.close_requested = false; this.status = C.STATUS_CONNECTING; this.onconnecting({ socket:this.socket, attempts:this.recover_attempts }); if (!this.close_requested) { // bind socket event callbacks this.socket.onconnect = onConnect.bind(this); this.socket.ondisconnect = onDisconnect.bind(this); this.socket.ondata = onData.bind(this); this.socket.connect(); } return; }; Transport.prototype.disconnect = function() { debug('close()'); this.close_requested = true; this.recover_attempts = 0; this.status = C.STATUS_DISCONNECTED; // clear recovery_timer if (this.recovery_timer !== null) { clearTimeout(this.recovery_timer); this.recovery_timer = null; } // unbind socket event callbacks this.socket.onconnect = function() {}; this.socket.ondisconnect = function() {}; this.socket.ondata = function() {}; this.socket.disconnect(); this.ondisconnect(); }; Transport.prototype.send = function(data) { debug('send()'); if (!this.isConnected()) { debugerror('unable to send message, transport is not connected'); return false; } var message = data.toString(); debug('sending message:\n\n' + message + '\n'); return this.socket.send(message); }; Transport.prototype.isConnected = function() { return this.status === C.STATUS_CONNECTED; }; Transport.prototype.isConnecting = function() { return this.status === C.STATUS_CONNECTING; }; /** * Socket Event Handlers */ function onConnect() { this.recover_attempts = 0; this.status = C.STATUS_CONNECTED; // clear recovery_timer if (this.recovery_timer !== null) { clearTimeout(this.recovery_timer); this.recovery_timer = null; } this.onconnect( {socket:this} ); } function onDisconnect(error, code, reason) { this.status = C.STATUS_DISCONNECTED; this.ondisconnect({ socket:this.socket, error:error, code:code, reason:reason }); if (this.close_requested) { return; } // update socket status else { this.sockets.forEach(function(socket) { if (this.socket === socket.socket) { socket.status = C.SOCKET_STATUS_ERROR; } }, this); } reconnect.call(this, error); } function onData(data) { // CRLF Keep Alive response from server. Ignore it. if(data === '\r\n') { debug('received message with CRLF Keep Alive response'); return; } // binary message. else if (typeof data !== 'string') { try { data = String.fromCharCode.apply(null, new Uint8Array(data)); } catch(evt) { debug('received binary message failed to be converted into string,' + ' message discarded'); return; } debug('received binary message:\n\n' + data + '\n'); } // text message. else { debug('received text message:\n\n' + data + '\n'); } this.ondata({ transport:this, message:data }); } function reconnect() { var k, self = this; this.recover_attempts+=1; k = Math.floor((Math.random() * Math.pow(2,this.recover_attempts)) +1); if (k < this.recovery_options.min_interval) { k = this.recovery_options.min_interval; } else if (k > this.recovery_options.max_interval) { k = this.recovery_options.max_interval; } debug('reconnection attempt: '+ this.recover_attempts + '. next connection attempt in '+ k +' seconds'); this.recovery_timer = setTimeout(function() { if (!self.close_requested && !(self.isConnected() || self.isConnecting())) { // get the next available socket with higher weight getSocket.call(self); // connect the socket self.connect(); } }, k * 1000); } /** * get the next available socket with higher weight */ function getSocket() { var candidates = []; this.sockets.forEach(function(socket) { if (socket.status === C.SOCKET_STATUS_ERROR) { return; // continue the array iteration } else if (candidates.length === 0) { candidates.push(socket); } else if (socket.weight > candidates[0].weight) { candidates = [socket]; } else if (socket.weight === candidates[0].weight) { candidates.push(socket); } }); if (candidates.length === 0) { // all sockets have failed. reset sockets status this.sockets.forEach(function(socket) { socket.status = C.SOCKET_STATUS_READY; }); // get next available socket getSocket.call(this); return; } var idx = Math.floor((Math.random()* candidates.length)); this.socket = candidates[idx].socket; } },{"./Socket":19,"debug":34}],23:[function(require,module,exports){ module.exports = UA; var C = { // UA status codes STATUS_INIT : 0, STATUS_READY: 1, STATUS_USER_CLOSED: 2, STATUS_NOT_READY: 3, // UA error codes CONFIGURATION_ERROR: 1, NETWORK_ERROR: 2 }; /** * Expose C object. */ UA.C = C; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debug = require('debug')('JsSIP:UA'); var debugerror = require('debug')('JsSIP:ERROR:UA'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('./Constants'); var Registrator = require('./Registrator'); var RTCSession = require('./RTCSession'); var Message = require('./Message'); var Transactions = require('./Transactions'); var Transport = require('./Transport'); var Socket = require('./Socket'); var Utils = require('./Utils'); var Exceptions = require('./Exceptions'); var URI = require('./URI'); var Grammar = require('./Grammar'); var Parser = require('./Parser'); var SIPMessage = require('./SIPMessage'); var sanityCheck = require('./sanityCheck'); /** * The User-Agent class. * @class JsSIP.UA * @param {Object} configuration Configuration parameters. * @throws {JsSIP.Exceptions.ConfigurationError} If a configuration parameter is invalid. * @throws {TypeError} If no configuration is given. */ function UA(configuration) { debug('new() [configuration:%o]', configuration); this.cache = { credentials: {} }; this.configuration = {}; this.dynConfiguration = {}; this.dialogs = {}; //User actions outside any session/dialog (MESSAGE) this.applicants = {}; this.sessions = {}; this.transport = null; this.contact = null; this.status = C.STATUS_INIT; this.error = null; this.transactions = { nist: {}, nict: {}, ist: {}, ict: {} }; // Custom UA empty object for high level use this.data = {}; this.closeTimer = null; Object.defineProperties(this, { transactionsCount: { get: function() { var type, transactions = ['nist','nict','ist','ict'], count = 0; for (type in transactions) { count += Object.keys(this.transactions[transactions[type]]).length; } return count; } }, nictTransactionsCount: { get: function() { return Object.keys(this.transactions.nict).length; } }, nistTransactionsCount: { get: function() { return Object.keys(this.transactions.nist).length; } }, ictTransactionsCount: { get: function() { return Object.keys(this.transactions.ict).length; } }, istTransactionsCount: { get: function() { return Object.keys(this.transactions.ist).length; } } }); /** * Load configuration */ if(configuration === undefined) { throw new TypeError('Not enough arguments'); } try { this.loadConfig(configuration); } catch(e) { this.status = C.STATUS_NOT_READY; this.error = C.CONFIGURATION_ERROR; throw e; } // Initialize registrator this._registrator = new Registrator(this); events.EventEmitter.call(this); } util.inherits(UA, events.EventEmitter); //================= // High Level API //================= /** * Connect to the server if status = STATUS_INIT. * Resume UA after being closed. */ UA.prototype.start = function() { debug('start()'); if (this.status === C.STATUS_INIT) { this.transport.connect(); } else if(this.status === C.STATUS_USER_CLOSED) { debug('restarting UA'); // disconnect if (this.closeTimer !== null) { clearTimeout(this.closeTimer); this.closeTimer = null; this.transport.disconnect(); } // reconnect this.status = C.STATUS_INIT; this.transport.connect(); } else if (this.status === C.STATUS_READY) { debug('UA is in READY status, not restarted'); } else { debug('ERROR: connection is down, Auto-Recovery system is trying to reconnect'); } // Set dynamic configuration. this.dynConfiguration.register = this.configuration.register; }; /** * Register. */ UA.prototype.register = function() { debug('register()'); this.dynConfiguration.register = true; this._registrator.register(); }; /** * Unregister. */ UA.prototype.unregister = function(options) { debug('unregister()'); this.dynConfiguration.register = false; this._registrator.unregister(options); }; /** * Get the Registrator instance. */ UA.prototype.registrator = function() { return this._registrator; }; /** * Registration state. */ UA.prototype.isRegistered = function() { if(this._registrator.registered) { return true; } else { return false; } }; /** * Connection state. */ UA.prototype.isConnected = function() { return this.transport.isConnected(); }; /** * Make an outgoing call. * * -param {String} target * -param {Object} views * -param {Object} [options] * * -throws {TypeError} * */ UA.prototype.call = function(target, options) { debug('call()'); var session; session = new RTCSession(this); session.connect(target, options); return session; }; /** * Send a message. * * -param {String} target * -param {String} body * -param {Object} [options] * * -throws {TypeError} * */ UA.prototype.sendMessage = function(target, body, options) { debug('sendMessage()'); var message; message = new Message(this); message.send(target, body, options); return message; }; /** * Terminate ongoing sessions. */ UA.prototype.terminateSessions = function(options) { debug('terminateSessions()'); for(var idx in this.sessions) { if (!this.sessions[idx].isEnded()) { this.sessions[idx].terminate(options); } } }; /** * Gracefully close. * */ UA.prototype.stop = function() { debug('stop()'); var session; var applicant; var num_sessions; var ua = this; // Remove dynamic settings. this.dynConfiguration = {}; if(this.status === C.STATUS_USER_CLOSED) { debug('UA already closed'); return; } // Close registrator this._registrator.close(); // If there are session wait a bit so CANCEL/BYE can be sent and their responses received. num_sessions = Object.keys(this.sessions).length; // Run _terminate_ on every Session for(session in this.sessions) { debug('closing session ' + session); try { this.sessions[session].terminate(); } catch(error) {} } // Run _close_ on every applicant for(applicant in this.applicants) { try { this.applicants[applicant].close(); } catch(error) {} } this.status = C.STATUS_USER_CLOSED; if (this.nistTransactionsCount === 0 && this.nictTransactionsCount === 0 && this.ictTransactionsCount === 0 && this.istTransactionsCount === 0 && num_sessions === 0) { ua.transport.disconnect(); } else { this.closeTimer = setTimeout(function() { ua.closeTimer = null; ua.transport.disconnect(); }, 2000); } }; /** * Normalice a string into a valid SIP request URI * -param {String} target * -returns {JsSIP.URI|undefined} */ UA.prototype.normalizeTarget = function(target) { return Utils.normalizeTarget(target, this.configuration.hostport_params); }; /** * Allow retrieving configuration and autogenerated fields in runtime. */ UA.prototype.get = function(parameter) { switch(parameter) { case 'realm': return this.configuration.realm; case 'ha1': return this.configuration.ha1; default: debugerror('get() | cannot get "%s" parameter in runtime', parameter); return undefined; } return true; }; /** * Allow configuration changes in runtime. * Returns true if the parameter could be set. */ UA.prototype.set = function(parameter, value) { switch(parameter) { case 'password': { this.configuration.password = String(value); break; } case 'realm': { this.configuration.realm = String(value); break; } case 'ha1': { this.configuration.ha1 = String(value); // Delete the plain SIP password. this.configuration.password = null; break; } case 'display_name': { if (Grammar.parse('"' + value + '"', 'display_name') === -1) { debugerror('set() | wrong "display_name"'); return false; } this.configuration.display_name = value; break; } default: debugerror('set() | cannot set "%s" parameter in runtime', parameter); return false; } return true; }; //=============================== // Private (For internal use) //=============================== // UA.prototype.saveCredentials = function(credentials) { // this.cache.credentials[credentials.realm] = this.cache.credentials[credentials.realm] || {}; // this.cache.credentials[credentials.realm][credentials.uri] = credentials; // }; // UA.prototype.getCredentials = function(request) { // var realm, credentials; // realm = request.ruri.host; // if (this.cache.credentials[realm] && this.cache.credentials[realm][request.ruri]) { // credentials = this.cache.credentials[realm][request.ruri]; // credentials.method = request.method; // } // return credentials; // }; //========================== // Event Handlers //========================== /** * new Transaction */ UA.prototype.newTransaction = function(transaction) { this.transactions[transaction.type][transaction.id] = transaction; this.emit('newTransaction', { transaction: transaction }); }; /** * Transaction destroyed. */ UA.prototype.destroyTransaction = function(transaction) { delete this.transactions[transaction.type][transaction.id]; this.emit('transactionDestroyed', { transaction: transaction }); }; /** * new Message */ UA.prototype.newMessage = function(data) { this.emit('newMessage', data); }; /** * new RTCSession */ UA.prototype.newRTCSession = function(data) { this.emit('newRTCSession', data); }; /** * Registered */ UA.prototype.registered = function(data) { this.emit('registered', data); }; /** * Unregistered */ UA.prototype.unregistered = function(data) { this.emit('unregistered', data); }; /** * Registration Failed */ UA.prototype.registrationFailed = function(data) { this.emit('registrationFailed', data); }; //========================= // receiveRequest //========================= /** * Request reception */ UA.prototype.receiveRequest = function(request) { var dialog, session, message, replaces, method = request.method; // Check that request URI points to us if(request.ruri.user !== this.configuration.uri.user && request.ruri.user !== this.contact.uri.user) { debug('Request-URI does not point to us'); if (request.method !== JsSIP_C.ACK) { request.reply_sl(404); } return; } // Check request URI scheme if(request.ruri.scheme === JsSIP_C.SIPS) { request.reply_sl(416); return; } // Check transaction if(Transactions.checkTransaction(this, request)) { return; } // Create the server transaction if(method === JsSIP_C.INVITE) { new Transactions.InviteServerTransaction(request, this); } else if(method !== JsSIP_C.ACK && method !== JsSIP_C.CANCEL) { new Transactions.NonInviteServerTransaction(request, this); } /* RFC3261 12.2.2 * Requests that do not change in any way the state of a dialog may be * received within a dialog (for example, an OPTIONS request). * They are processed as if they had been received outside the dialog. */ if(method === JsSIP_C.OPTIONS) { request.reply(200); } else if (method === JsSIP_C.MESSAGE) { if (this.listeners('newMessage').length === 0) { request.reply(405); return; } message = new Message(this); message.init_incoming(request); } else if (method === JsSIP_C.INVITE) { // Initial INVITE if(!request.to_tag && this.listeners('newRTCSession').length === 0) { request.reply(405); return; } } // Initial Request if(!request.to_tag) { switch(method) { case JsSIP_C.INVITE: if (window.RTCPeerConnection) { // TODO if (request.hasHeader('replaces')) { replaces = request.replaces; dialog = this.findDialog(replaces.call_id, replaces.from_tag, replaces.to_tag); if (dialog) { session = dialog.owner; if (!session.isEnded()) { session.receiveRequest(request); } else { request.reply(603); } } else { request.reply(481); } } else { session = new RTCSession(this); session.init_incoming(request); } } else { debugerror('INVITE received but WebRTC is not supported'); request.reply(488); } break; case JsSIP_C.BYE: // Out of dialog BYE received request.reply(481); break; case JsSIP_C.CANCEL: session = this.findSession(request); if (session) { session.receiveRequest(request); } else { debug('received CANCEL request for a non existent session'); } break; case JsSIP_C.ACK: /* Absorb it. * ACK request without a corresponding Invite Transaction * and without To tag. */ break; default: request.reply(405); break; } } // In-dialog request else { dialog = this.findDialog(request.call_id, request.from_tag, request.to_tag); if(dialog) { dialog.receiveRequest(request); } else if (method === JsSIP_C.NOTIFY) { session = this.findSession(request); if(session) { session.receiveRequest(request); } else { debug('received NOTIFY request for a non existent subscription'); request.reply(481, 'Subscription does not exist'); } } /* RFC3261 12.2.2 * Request with to tag, but no matching dialog found. * Exception: ACK for an Invite request for which a dialog has not * been created. */ else { if(method !== JsSIP_C.ACK) { request.reply(481); } } } }; //================= // Utils //================= /** * Get the session to which the request belongs to, if any. */ UA.prototype.findSession = function(request) { var sessionIDa = request.call_id + request.from_tag, sessionA = this.sessions[sessionIDa], sessionIDb = request.call_id + request.to_tag, sessionB = this.sessions[sessionIDb]; if(sessionA) { return sessionA; } else if(sessionB) { return sessionB; } else { return null; } }; /** * Get the dialog to which the request belongs to, if any. */ UA.prototype.findDialog = function(call_id, from_tag, to_tag) { var id = call_id + from_tag + to_tag, dialog = this.dialogs[id]; if(dialog) { return dialog; } else { id = call_id + to_tag + from_tag; dialog = this.dialogs[id]; if(dialog) { return dialog; } else { return null; } } }; UA.prototype.loadConfig = function(configuration) { // Settings and default values var parameter, value, checked_value, hostport_params, registrar_server, settings = { /* Host address * Value to be set in Via sent_by and host part of Contact FQDN */ via_host: Utils.createRandomToken(12) + '.invalid', // SIP Contact URI contact_uri: null, // SIP authentication password password: null, // SIP authentication realm realm: null, // SIP authentication HA1 hash ha1: null, // Registration parameters register_expires: 600, register: true, registrar_server: null, use_preloaded_route: false, // Session parameters no_answer_timeout: 60, session_timers: true, }; // Pre-Configuration // Check Mandatory parameters for(parameter in UA.configuration_check.mandatory) { if(!configuration.hasOwnProperty(parameter)) { throw new Exceptions.ConfigurationError(parameter); } else { value = configuration[parameter]; checked_value = UA.configuration_check.mandatory[parameter].call(this, value); if (checked_value !== undefined) { settings[parameter] = checked_value; } else { throw new Exceptions.ConfigurationError(parameter, value); } } } // Check Optional parameters for(parameter in UA.configuration_check.optional) { if(configuration.hasOwnProperty(parameter)) { value = configuration[parameter]; /* If the parameter value is null, empty string, undefined, empty array * or it's a number with NaN value, then apply its default value. */ if (Utils.isEmpty(value)) { continue; } checked_value = UA.configuration_check.optional[parameter].call(this, value, configuration); if (checked_value !== undefined) { settings[parameter] = checked_value; } else { throw new Exceptions.ConfigurationError(parameter, value); } } } // Post Configuration Process // Allow passing 0 number as display_name. if (settings.display_name === 0) { settings.display_name = '0'; } // Instance-id for GRUU. if (!settings.instance_id) { settings.instance_id = Utils.newUUID(); } // jssip_id instance parameter. Static random tag of length 5. settings.jssip_id = Utils.createRandomToken(5); // String containing settings.uri without scheme and user. hostport_params = settings.uri.clone(); hostport_params.user = null; settings.hostport_params = hostport_params.toString().replace(/^sip:/i, ''); // Transport var sockets = []; if (settings.sockets && Array.isArray(settings.sockets)) { sockets = sockets.concat(settings.sockets); } if (sockets.length === 0) { throw new Exceptions.ConfigurationError('sockets'); } try { this.transport = new Transport(sockets, { /* recovery options */ max_interval: settings.connection_recovery_max_interval, min_interval: settings.connection_recovery_min_interval }); // Transport event callbacks this.transport.onconnecting = onTransportConnecting.bind(this); this.transport.onconnect = onTransportConnect.bind(this); this.transport.ondisconnect = onTransportDisconnect.bind(this); this.transport.ondata = onTransportData.bind(this); // transport options not needed here anymore delete settings.connection_recovery_max_interval; delete settings.connection_recovery_min_interval; delete settings.sockets; } catch (e) { debugerror(e); throw new Exceptions.ConfigurationError('sockets', sockets); } // Check whether authorization_user is explicitly defined. // Take 'settings.uri.user' value if not. if (!settings.authorization_user) { settings.authorization_user = settings.uri.user; } // If no 'registrar_server' is set use the 'uri' value without user portion and // without URI params/headers. if (!settings.registrar_server) { registrar_server = settings.uri.clone(); registrar_server.user = null; registrar_server.clearParams(); registrar_server.clearHeaders(); settings.registrar_server = registrar_server; } // User no_answer_timeout. settings.no_answer_timeout = settings.no_answer_timeout * 1000; // Via Host if (settings.contact_uri) { settings.via_host = settings.contact_uri.host; } // Contact URI else { settings.contact_uri = new URI('sip', Utils.createRandomToken(8), settings.via_host, null, {transport: 'ws'}); } this.contact = { pub_gruu: null, temp_gruu: null, uri: settings.contact_uri, toString: function(options) { options = options || {}; var anonymous = options.anonymous || null, outbound = options.outbound || null, contact = '<'; if (anonymous) { contact += this.temp_gruu || 'sip:anonymous@anonymous.invalid;transport=ws'; } else { contact += this.pub_gruu || this.uri.toString(); } if (outbound && (anonymous ? !this.temp_gruu : !this.pub_gruu)) { contact += ';ob'; } contact += '>'; return contact; } }; // Fill the value of the configuration_skeleton for(parameter in settings) { UA.configuration_skeleton[parameter].value = settings[parameter]; } Object.defineProperties(this.configuration, UA.configuration_skeleton); // Clean UA.configuration_skeleton for(parameter in settings) { UA.configuration_skeleton[parameter].value = ''; } debug('configuration parameters after validation:'); for(parameter in settings) { switch(parameter) { case 'uri': case 'registrar_server': debug('- ' + parameter + ': ' + settings[parameter]); break; case 'password': case 'ha1': debug('- ' + parameter + ': ' + 'NOT SHOWN'); break; default: debug('- ' + parameter + ': ' + JSON.stringify(settings[parameter])); } } return; }; /** * Configuration Object skeleton. */ UA.configuration_skeleton = (function() { var idx, parameter, writable, skeleton = {}, parameters = [ // Internal parameters 'jssip_id', 'hostport_params', // Mandatory user configurable parameters 'uri', // Optional user configurable parameters 'authorization_user', 'contact_uri', 'display_name', 'instance_id', 'no_answer_timeout', // 30 seconds 'session_timers', // true 'password', 'realm', 'ha1', 'register_expires', // 600 seconds 'registrar_server', 'sockets', 'use_preloaded_route', // Post-configuration generated parameters 'via_core_value', 'via_host' ]; var writable_parameters = [ 'password', 'realm', 'ha1', 'display_name' ]; for(idx in parameters) { parameter = parameters[idx]; if (writable_parameters.indexOf(parameter) !== -1) { writable = true; } else { writable = false; } skeleton[parameter] = { value: '', writable: writable, configurable: false }; } skeleton.register = { value: '', writable: true, configurable: false }; return skeleton; }()); /** * Configuration checker. */ UA.configuration_check = { mandatory: { uri: function(uri) { var parsed; if (!/^sip:/i.test(uri)) { uri = JsSIP_C.SIP + ':' + uri; } parsed = URI.parse(uri); if(!parsed) { return; } else if(!parsed.user) { return; } else { return parsed; } } }, optional: { authorization_user: function(authorization_user) { if(Grammar.parse('"'+ authorization_user +'"', 'quoted_string') === -1) { return; } else { return authorization_user; } }, connection_recovery_max_interval: function(connection_recovery_max_interval) { var value; if(Utils.isDecimal(connection_recovery_max_interval)) { value = Number(connection_recovery_max_interval); if(value > 0) { return value; } } }, connection_recovery_min_interval: function(connection_recovery_min_interval) { var value; if(Utils.isDecimal(connection_recovery_min_interval)) { value = Number(connection_recovery_min_interval); if(value > 0) { return value; } } }, contact_uri: function(contact_uri) { if (typeof contact_uri === 'string') { var uri = Grammar.parse(contact_uri,'SIP_URI'); if (uri !== -1) { return uri; } } }, display_name: function(display_name) { if (Grammar.parse('"' + display_name + '"', 'display_name') === -1) { return; } else { return display_name; } }, instance_id: function(instance_id) { if ((/^uuid:/i.test(instance_id))) { instance_id = instance_id.substr(5); } if(Grammar.parse(instance_id, 'uuid') === -1) { return; } else { return instance_id; } }, no_answer_timeout: function(no_answer_timeout) { var value; if (Utils.isDecimal(no_answer_timeout)) { value = Number(no_answer_timeout); if (value > 0) { return value; } } }, session_timers: function(session_timers) { if (typeof session_timers === 'boolean') { return session_timers; } }, password: function(password) { return String(password); }, realm: function(realm) { return String(realm); }, ha1: function(ha1) { return String(ha1); }, register: function(register) { if (typeof register === 'boolean') { return register; } }, register_expires: function(register_expires) { var value; if (Utils.isDecimal(register_expires)) { value = Number(register_expires); if (value > 0) { return value; } } }, registrar_server: function(registrar_server) { var parsed; if (!/^sip:/i.test(registrar_server)) { registrar_server = JsSIP_C.SIP + ':' + registrar_server; } parsed = URI.parse(registrar_server); if(!parsed) { return; } else if(parsed.user) { return; } else { return parsed; } }, sockets: function(sockets) { var idx, length; /* Allow defining sockets parameter as: * Socket: socket * Array of Socket: [socket1, socket2] * Array of Objects: [{socket: socket1, weight:1}, {socket: Socket2, weight:0}] * Array of Objects and Socket: [{socket: socket1}, socket2] */ if (Socket.isSocket(sockets)) { sockets = [{socket: sockets}]; } else if (Array.isArray(sockets) && sockets.length) { length = sockets.length; for (idx = 0; idx < length; idx++) { if (Socket.isSocket(sockets[idx])) { sockets[idx] = {socket: sockets[idx]}; } } } else { return; } return sockets; }, use_preloaded_route: function(use_preloaded_route) { if (typeof use_preloaded_route === 'boolean') { return use_preloaded_route; } } } }; /** * Transport event handlers */ // Transport connecting event function onTransportConnecting(data) { this.emit('connecting', data); } // Transport connected event. function onTransportConnect(data) { if(this.status === C.STATUS_USER_CLOSED) { return; } this.status = C.STATUS_READY; this.error = null; this.emit('connected', data); if(this.dynConfiguration.register) { this._registrator.register(); } } // Transport disconnected event. function onTransportDisconnect(data) { // Run _onTransportError_ callback on every client transaction using _transport_ var type, idx, length, client_transactions = ['nict', 'ict', 'nist', 'ist']; length = client_transactions.length; for (type = 0; type < length; type++) { for(idx in this.transactions[client_transactions[type]]) { this.transactions[client_transactions[type]][idx].onTransportError(); } } this.emit('disconnected', data); // Call registrator _onTransportClosed_ this._registrator.onTransportClosed(); if (this.status !== C.STATUS_USER_CLOSED) { this.status = C.STATUS_NOT_READY; this.error = C.NETWORK_ERROR; } } // Transport data event function onTransportData(data) { var transaction, transport = data.transport, message = data.message; message = Parser.parseMessage(message, this); if (! message) { return; } if (this.status === UA.C.STATUS_USER_CLOSED && message instanceof SIPMessage.IncomingRequest) { return; } // Do some sanity check if(! sanityCheck(message, this, transport)) { return; } if(message instanceof SIPMessage.IncomingRequest) { message.transport = transport; this.receiveRequest(message); } else if(message instanceof SIPMessage.IncomingResponse) { /* Unike stated in 18.1.2, if a response does not match * any transaction, it is discarded here and no passed to the core * in order to be discarded there. */ switch(message.method) { case JsSIP_C.INVITE: transaction = this.transactions.ict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; case JsSIP_C.ACK: // Just in case ;-) break; default: transaction = this.transactions.nict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; } } } },{"./Constants":1,"./Exceptions":5,"./Grammar":6,"./Message":8,"./Parser":10,"./RTCSession":11,"./Registrator":16,"./SIPMessage":18,"./Socket":19,"./Transactions":21,"./Transport":22,"./URI":24,"./Utils":25,"./sanityCheck":27,"debug":34,"events":28,"util":32}],24:[function(require,module,exports){ module.exports = URI; /** * Dependencies. */ var JsSIP_C = require('./Constants'); var Utils = require('./Utils'); var Grammar = require('./Grammar'); /** * -param {String} [scheme] * -param {String} [user] * -param {String} host * -param {String} [port] * -param {Object} [parameters] * -param {Object} [headers] * */ function URI(scheme, user, host, port, parameters, headers) { var param, header; // Checks if(!host) { throw new TypeError('missing or invalid "host" parameter'); } // Initialize parameters scheme = scheme || JsSIP_C.SIP; this.parameters = {}; this.headers = {}; for (param in parameters) { this.setParam(param, parameters[param]); } for (header in headers) { this.setHeader(header, headers[header]); } Object.defineProperties(this, { scheme: { get: function(){ return scheme; }, set: function(value){ scheme = value.toLowerCase(); } }, user: { get: function(){ return user; }, set: function(value){ user = value; } }, host: { get: function(){ return host; }, set: function(value){ host = value.toLowerCase(); } }, port: { get: function(){ return port; }, set: function(value){ port = value === 0 ? value : (parseInt(value,10) || null); } } }); } URI.prototype = { setParam: function(key, value) { if(key) { this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString(); } }, getParam: function(key) { if(key) { return this.parameters[key.toLowerCase()]; } }, hasParam: function(key) { if(key) { return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false; } }, deleteParam: function(parameter) { var value; parameter = parameter.toLowerCase(); if (this.parameters.hasOwnProperty(parameter)) { value = this.parameters[parameter]; delete this.parameters[parameter]; return value; } }, clearParams: function() { this.parameters = {}; }, setHeader: function(name, value) { this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value]; }, getHeader: function(name) { if(name) { return this.headers[Utils.headerize(name)]; } }, hasHeader: function(name) { if(name) { return (this.headers.hasOwnProperty(Utils.headerize(name)) && true) || false; } }, deleteHeader: function(header) { var value; header = Utils.headerize(header); if(this.headers.hasOwnProperty(header)) { value = this.headers[header]; delete this.headers[header]; return value; } }, clearHeaders: function() { this.headers = {}; }, clone: function() { return new URI( this.scheme, this.user, this.host, this.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); }, toString: function(){ var header, parameter, idx, uri, headers = []; uri = this.scheme + ':'; if (this.user) { uri += Utils.escapeUser(this.user) + '@'; } uri += this.host; if (this.port || this.port === 0) { uri += ':' + this.port; } for (parameter in this.parameters) { uri += ';' + parameter; if (this.parameters[parameter] !== null) { uri += '='+ this.parameters[parameter]; } } for(header in this.headers) { for(idx = 0; idx < this.headers[header].length; idx++) { headers.push(header + '=' + this.headers[header][idx]); } } if (headers.length > 0) { uri += '?' + headers.join('&'); } return uri; }, toAor: function(show_port){ var aor; aor = this.scheme + ':'; if (this.user) { aor += Utils.escapeUser(this.user) + '@'; } aor += this.host; if (show_port && (this.port || this.port === 0)) { aor += ':' + this.port; } return aor; } }; /** * Parse the given string and returns a JsSIP.URI instance or undefined if * it is an invalid URI. */ URI.parse = function(uri) { uri = Grammar.parse(uri,'SIP_URI'); if (uri !== -1) { return uri; } else { return undefined; } }; },{"./Constants":1,"./Grammar":6,"./Utils":25}],25:[function(require,module,exports){ var Utils = {}; module.exports = Utils; /** * Dependencies. */ var JsSIP_C = require('./Constants'); var URI = require('./URI'); var Grammar = require('./Grammar'); Utils.str_utf8_length = function(string) { return unescape(encodeURIComponent(string)).length; }; Utils.isFunction = function(fn) { if (fn !== undefined) { return (Object.prototype.toString.call(fn) === '[object Function]')? true : false; } else { return false; } }; Utils.isString = function(str) { if (str !== undefined) { return (Object.prototype.toString.call(str) === '[object String]')? true : false; } else { return false; } }; Utils.isDecimal = function(num) { return !isNaN(num) && (parseFloat(num) === parseInt(num,10)); }; Utils.isEmpty = function(value) { if (value === null || value === '' || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof(value) === 'number' && isNaN(value))) { return true; } }; Utils.hasMethods = function(obj /*, method list as strings */){ var i = 1, methodName; while((methodName = arguments[i++])){ if(this.isFunction(obj[methodName])) { return false; } } return true; }; Utils.createRandomToken = function(size, base) { var i, r, token = ''; base = base || 32; for( i=0; i < size; i++ ) { r = Math.random() * base|0; token += r.toString(base); } return token; }; Utils.newTag = function() { return Utils.createRandomToken(10); }; // http://stackoverflow.com/users/109538/broofa Utils.newUUID = function() { var UUID = '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); }); return UUID; }; Utils.hostType = function(host) { if (!host) { return; } else { host = Grammar.parse(host,'host'); if (host !== -1) { return host.host_type; } } }; /** * Normalize SIP URI. * NOTE: It does not allow a SIP URI without username. * Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'. * Detects the domain part (if given) and properly hex-escapes the user portion. * If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators. */ Utils.normalizeTarget = function(target, domain) { var uri, target_array, target_user, target_domain; // If no target is given then raise an error. if (!target) { return; // If a URI instance is given then return it. } else if (target instanceof URI) { return target; // If a string is given split it by '@': // - Last fragment is the desired domain. // - Otherwise append the given domain argument. } else if (typeof target === 'string') { target_array = target.split('@'); switch(target_array.length) { case 1: if (!domain) { return; } target_user = target; target_domain = domain; break; case 2: target_user = target_array[0]; target_domain = target_array[1]; break; default: target_user = target_array.slice(0, target_array.length-1).join('@'); target_domain = target_array[target_array.length-1]; } // Remove the URI scheme (if present). target_user = target_user.replace(/^(sips?|tel):/i, ''); // Remove 'tel' visual separators if the user portion just contains 'tel' number symbols. if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(target_user)) { target_user = target_user.replace(/[\-\.\(\)]/g, ''); } // Build the complete SIP URI. target = JsSIP_C.SIP + ':' + Utils.escapeUser(target_user) + '@' + target_domain; // Finally parse the resulting URI. if ((uri = URI.parse(target))) { return uri; } else { return; } } else { return; } }; /** * Hex-escape a SIP URI user. */ Utils.escapeUser = function(user) { // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). return encodeURIComponent(decodeURIComponent(user)).replace(/%3A/ig, ':').replace(/%2B/ig, '+').replace(/%3F/ig, '?').replace(/%2F/ig, '/'); }; Utils.headerize = function(string) { var exceptions = { 'Call-Id': 'Call-ID', 'Cseq': 'CSeq', 'Www-Authenticate': 'WWW-Authenticate' }, name = string.toLowerCase().replace(/_/g,'-').split('-'), hname = '', parts = name.length, part; for (part = 0; part < parts; part++) { if (part !== 0) { hname +='-'; } hname += name[part].charAt(0).toUpperCase()+name[part].substring(1); } if (exceptions[hname]) { hname = exceptions[hname]; } return hname; }; Utils.sipErrorCause = function(status_code) { var cause; for (cause in JsSIP_C.SIP_ERROR_CAUSES) { if (JsSIP_C.SIP_ERROR_CAUSES[cause].indexOf(status_code) !== -1) { return JsSIP_C.causes[cause]; } } return JsSIP_C.causes.SIP_FAILURE_CODE; }; /** * Generate a random Test-Net IP (http://tools.ietf.org/html/rfc5735) */ Utils.getRandomTestNetIP = function() { function getOctet(from,to) { return Math.floor(Math.random()*(to-from+1)+from); } return '192.0.2.' + getOctet(1, 254); }; // MD5 (Message-Digest Algorithm) http://www.webtoolkit.info Utils.calculateMD5 = function(string) { function rotateLeft(lValue, iShiftBits) { return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits)); } function addUnsigned(lX,lY) { var lX4,lY4,lX8,lY8,lResult; lX8 = (lX & 0x80000000); lY8 = (lY & 0x80000000); lX4 = (lX & 0x40000000); lY4 = (lY & 0x40000000); lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF); if (lX4 & lY4) { return (lResult ^ 0x80000000 ^ lX8 ^ lY8); } if (lX4 | lY4) { if (lResult & 0x40000000) { return (lResult ^ 0xC0000000 ^ lX8 ^ lY8); } else { return (lResult ^ 0x40000000 ^ lX8 ^ lY8); } } else { return (lResult ^ lX8 ^ lY8); } } function doF(x,y,z) { return (x & y) | ((~x) & z); } function doG(x,y,z) { return (x & z) | (y & (~z)); } function doH(x,y,z) { return (x ^ y ^ z); } function doI(x,y,z) { return (y ^ (x | (~z))); } function doFF(a,b,c,d,x,s,ac) { a = addUnsigned(a, addUnsigned(addUnsigned(doF(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); } function doGG(a,b,c,d,x,s,ac) { a = addUnsigned(a, addUnsigned(addUnsigned(doG(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); } function doHH(a,b,c,d,x,s,ac) { a = addUnsigned(a, addUnsigned(addUnsigned(doH(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); } function doII(a,b,c,d,x,s,ac) { a = addUnsigned(a, addUnsigned(addUnsigned(doI(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); } function convertToWordArray(string) { var lWordCount; var lMessageLength = string.length; var lNumberOfWords_temp1=lMessageLength + 8; var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64; var lNumberOfWords = (lNumberOfWords_temp2+1)*16; var lWordArray = new Array(lNumberOfWords-1); var lBytePosition = 0; var lByteCount = 0; while ( lByteCount < lMessageLength ) { lWordCount = (lByteCount-(lByteCount % 4))/4; lBytePosition = (lByteCount % 4)*8; lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition)); lByteCount++; } lWordCount = (lByteCount-(lByteCount % 4))/4; lBytePosition = (lByteCount % 4)*8; lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition); lWordArray[lNumberOfWords-2] = lMessageLength<<3; lWordArray[lNumberOfWords-1] = lMessageLength>>>29; return lWordArray; } function wordToHex(lValue) { var wordToHexValue='',wordToHexValue_temp='',lByte,lCount; for (lCount = 0;lCount<=3;lCount++) { lByte = (lValue>>>(lCount*8)) & 255; wordToHexValue_temp = '0' + lByte.toString(16); wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length-2,2); } return wordToHexValue; } function utf8Encode(string) { string = string.replace(/\r\n/g, '\n'); var utftext = ''; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } var x=[]; var k,AA,BB,CC,DD,a,b,c,d; var S11=7, S12=12, S13=17, S14=22; var S21=5, S22=9 , S23=14, S24=20; var S31=4, S32=11, S33=16, S34=23; var S41=6, S42=10, S43=15, S44=21; string = utf8Encode(string); x = convertToWordArray(string); a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; for (k=0;k<x.length;k+=16) { AA=a; BB=b; CC=c; DD=d; a=doFF(a,b,c,d,x[k+0], S11,0xD76AA478); d=doFF(d,a,b,c,x[k+1], S12,0xE8C7B756); c=doFF(c,d,a,b,x[k+2], S13,0x242070DB); b=doFF(b,c,d,a,x[k+3], S14,0xC1BDCEEE); a=doFF(a,b,c,d,x[k+4], S11,0xF57C0FAF); d=doFF(d,a,b,c,x[k+5], S12,0x4787C62A); c=doFF(c,d,a,b,x[k+6], S13,0xA8304613); b=doFF(b,c,d,a,x[k+7], S14,0xFD469501); a=doFF(a,b,c,d,x[k+8], S11,0x698098D8); d=doFF(d,a,b,c,x[k+9], S12,0x8B44F7AF); c=doFF(c,d,a,b,x[k+10],S13,0xFFFF5BB1); b=doFF(b,c,d,a,x[k+11],S14,0x895CD7BE); a=doFF(a,b,c,d,x[k+12],S11,0x6B901122); d=doFF(d,a,b,c,x[k+13],S12,0xFD987193); c=doFF(c,d,a,b,x[k+14],S13,0xA679438E); b=doFF(b,c,d,a,x[k+15],S14,0x49B40821); a=doGG(a,b,c,d,x[k+1], S21,0xF61E2562); d=doGG(d,a,b,c,x[k+6], S22,0xC040B340); c=doGG(c,d,a,b,x[k+11],S23,0x265E5A51); b=doGG(b,c,d,a,x[k+0], S24,0xE9B6C7AA); a=doGG(a,b,c,d,x[k+5], S21,0xD62F105D); d=doGG(d,a,b,c,x[k+10],S22,0x2441453); c=doGG(c,d,a,b,x[k+15],S23,0xD8A1E681); b=doGG(b,c,d,a,x[k+4], S24,0xE7D3FBC8); a=doGG(a,b,c,d,x[k+9], S21,0x21E1CDE6); d=doGG(d,a,b,c,x[k+14],S22,0xC33707D6); c=doGG(c,d,a,b,x[k+3], S23,0xF4D50D87); b=doGG(b,c,d,a,x[k+8], S24,0x455A14ED); a=doGG(a,b,c,d,x[k+13],S21,0xA9E3E905); d=doGG(d,a,b,c,x[k+2], S22,0xFCEFA3F8); c=doGG(c,d,a,b,x[k+7], S23,0x676F02D9); b=doGG(b,c,d,a,x[k+12],S24,0x8D2A4C8A); a=doHH(a,b,c,d,x[k+5], S31,0xFFFA3942); d=doHH(d,a,b,c,x[k+8], S32,0x8771F681); c=doHH(c,d,a,b,x[k+11],S33,0x6D9D6122); b=doHH(b,c,d,a,x[k+14],S34,0xFDE5380C); a=doHH(a,b,c,d,x[k+1], S31,0xA4BEEA44); d=doHH(d,a,b,c,x[k+4], S32,0x4BDECFA9); c=doHH(c,d,a,b,x[k+7], S33,0xF6BB4B60); b=doHH(b,c,d,a,x[k+10],S34,0xBEBFBC70); a=doHH(a,b,c,d,x[k+13],S31,0x289B7EC6); d=doHH(d,a,b,c,x[k+0], S32,0xEAA127FA); c=doHH(c,d,a,b,x[k+3], S33,0xD4EF3085); b=doHH(b,c,d,a,x[k+6], S34,0x4881D05); a=doHH(a,b,c,d,x[k+9], S31,0xD9D4D039); d=doHH(d,a,b,c,x[k+12],S32,0xE6DB99E5); c=doHH(c,d,a,b,x[k+15],S33,0x1FA27CF8); b=doHH(b,c,d,a,x[k+2], S34,0xC4AC5665); a=doII(a,b,c,d,x[k+0], S41,0xF4292244); d=doII(d,a,b,c,x[k+7], S42,0x432AFF97); c=doII(c,d,a,b,x[k+14],S43,0xAB9423A7); b=doII(b,c,d,a,x[k+5], S44,0xFC93A039); a=doII(a,b,c,d,x[k+12],S41,0x655B59C3); d=doII(d,a,b,c,x[k+3], S42,0x8F0CCC92); c=doII(c,d,a,b,x[k+10],S43,0xFFEFF47D); b=doII(b,c,d,a,x[k+1], S44,0x85845DD1); a=doII(a,b,c,d,x[k+8], S41,0x6FA87E4F); d=doII(d,a,b,c,x[k+15],S42,0xFE2CE6E0); c=doII(c,d,a,b,x[k+6], S43,0xA3014314); b=doII(b,c,d,a,x[k+13],S44,0x4E0811A1); a=doII(a,b,c,d,x[k+4], S41,0xF7537E82); d=doII(d,a,b,c,x[k+11],S42,0xBD3AF235); c=doII(c,d,a,b,x[k+2], S43,0x2AD7D2BB); b=doII(b,c,d,a,x[k+9], S44,0xEB86D391); a=addUnsigned(a,AA); b=addUnsigned(b,BB); c=addUnsigned(c,CC); d=addUnsigned(d,DD); } var temp = wordToHex(a)+wordToHex(b)+wordToHex(c)+wordToHex(d); return temp.toLowerCase(); }; Utils.closeMediaStream = function(stream) { if (!stream) { return; } // Latest spec states that MediaStream has no stop() method and instead must // call stop() on every MediaStreamTrack. try { var tracks, i, len; if (stream.getTracks) { tracks = stream.getTracks(); for (i = 0, len = tracks.length; i < len; i += 1) { tracks[i].stop(); } } else { tracks = stream.getAudioTracks(); for (i = 0, len = tracks.length; i < len; i += 1) { tracks[i].stop(); } tracks = stream.getVideoTracks(); for (i = 0, len = tracks.length; i < len; i += 1) { tracks[i].stop(); } } } catch (error) { // Deprecated by the spec, but still in use. // NOTE: In Temasys IE plugin stream.stop is a callable 'object'. if (typeof stream.stop === 'function' || typeof stream.stop === 'object') { stream.stop(); } } }; },{"./Constants":1,"./Grammar":6,"./URI":24}],26:[function(require,module,exports){ module.exports = WebSocketInterface; /** * Dependencies. */ var Grammar = require('./Grammar'); var debug = require('debug')('JsSIP:WebSocketInterface'); var debugerror = require('debug')('JsSIP:ERROR:WebSocketInterface'); debugerror.log = console.warn.bind(console); function WebSocketInterface(url) { debug('new() [url:"%s"]', url); var sip_uri = null; var via_transport = null; this.ws = null; // setting the 'scheme' alters the sip_uri too (used in SIP Route header field) Object.defineProperties(this, { via_transport: { get: function() { return via_transport; }, set: function(transport) { via_transport = transport.toUpperCase(); } }, sip_uri: { get: function() { return sip_uri; }}, url: { get: function() { return url; }} }); var parsed_url = Grammar.parse(url, 'absoluteURI'); if (parsed_url === -1) { debugerror('invalid WebSocket URI: ' + url); throw new TypeError('Invalid argument: ' + url); } else if(parsed_url.scheme !== 'wss' && parsed_url.scheme !== 'ws') { debugerror('invalid WebSocket URI scheme: ' + parsed_url.scheme); throw new TypeError('Invalid argument: ' + url); } else { sip_uri = 'sip:' + parsed_url.host + (parsed_url.port ? ':' + parsed_url.port : '') + ';transport=ws'; this.via_transport = parsed_url.scheme; } } WebSocketInterface.prototype.connect = function () { debug('connect()'); if (this.isConnected()) { debug('WebSocket ' + this.url + ' is already connected'); return; } else if (this.isConnecting()) { debug('WebSocket ' + this.url + ' is connecting'); return; } if (this.ws) { this.disconnect(); } debug('connecting to WebSocket ' + this.url); try { this.ws = new WebSocket(this.url, 'sip'); this.ws.binaryType = 'arraybuffer'; this.ws.onopen = onOpen.bind(this); this.ws.onclose = onClose.bind(this); this.ws.onmessage = onMessage.bind(this); this.ws.onerror = onError.bind(this); } catch(e) { onError.call(this, e); } }; WebSocketInterface.prototype.disconnect = function() { debug('disconnect()'); if (this.ws) { // unbind websocket event callbacks this.ws.onopen = function() {}; this.ws.onclose = function() {}; this.ws.onmessage = function() {}; this.ws.onerror = function() {}; this.ws.close(); this.ws = null; } }; WebSocketInterface.prototype.send = function(message) { debug('send()'); if (this.isConnected()) { this.ws.send(message); return true; } else { debugerror('unable to send message, WebSocket is not open'); return false; } }; WebSocketInterface.prototype.isConnected = function() { return this.ws && this.ws.readyState === this.ws.OPEN; }; WebSocketInterface.prototype.isConnecting = function() { return this.ws && this.ws.readyState === this.ws.CONNECTING; }; /** * WebSocket Event Handlers */ function onOpen() { debug('WebSocket ' + this.url + ' connected'); this.onconnect(); } function onClose(e) { debug('WebSocket ' + this.url + ' closed'); if (e.wasClean === false) { debug('WebSocket abrupt disconnection'); } this.ondisconnect(e.wasClean, e.code, e.reason); } function onMessage(e) { debug('received WebSocket message'); this.ondata(e.data); } function onError(e) { debugerror('WebSocket ' + this.url + ' error: '+ e); } },{"./Grammar":6,"debug":34}],27:[function(require,module,exports){ module.exports = sanityCheck; /** * Dependencies. */ var debug = require('debug')('JsSIP:sanityCheck'); var JsSIP_C = require('./Constants'); var SIPMessage = require('./SIPMessage'); var Utils = require('./Utils'); var message, ua, transport, requests = [], responses = [], all = []; requests.push(rfc3261_8_2_2_1); requests.push(rfc3261_16_3_4); requests.push(rfc3261_18_3_request); requests.push(rfc3261_8_2_2_2); responses.push(rfc3261_8_1_3_3); responses.push(rfc3261_18_3_response); all.push(minimumHeaders); function sanityCheck(m, u, t) { var len, pass; message = m; ua = u; transport = t; len = all.length; while(len--) { pass = all[len](message); if(pass === false) { return false; } } if(message instanceof SIPMessage.IncomingRequest) { len = requests.length; while(len--) { pass = requests[len](message); if(pass === false) { return false; } } } else if(message instanceof SIPMessage.IncomingResponse) { len = responses.length; while(len--) { pass = responses[len](message); if(pass === false) { return false; } } } //Everything is OK return true; } /* * Sanity Check for incoming Messages * * Requests: * - _rfc3261_8_2_2_1_ Receive a Request with a non supported URI scheme * - _rfc3261_16_3_4_ Receive a Request already sent by us * Does not look at via sent-by but at jssip_id, which is inserted as * a prefix in all initial requests generated by the ua * - _rfc3261_18_3_request_ Body Content-Length * - _rfc3261_8_2_2_2_ Merged Requests * * Responses: * - _rfc3261_8_1_3_3_ Multiple Via headers * - _rfc3261_18_3_response_ Body Content-Length * * All: * - Minimum headers in a SIP message */ // Sanity Check functions for requests function rfc3261_8_2_2_1() { if(message.s('to').uri.scheme !== 'sip') { reply(416); return false; } } function rfc3261_16_3_4() { if(!message.to_tag) { if(message.call_id.substr(0, 5) === ua.configuration.jssip_id) { reply(482); return false; } } } function rfc3261_18_3_request() { var len = Utils.str_utf8_length(message.body), contentLength = message.getHeader('content-length'); if(len < contentLength) { reply(400); return false; } } function rfc3261_8_2_2_2() { var tr, idx, fromTag = message.from_tag, call_id = message.call_id, cseq = message.cseq; // Accept any in-dialog request. if(message.to_tag) { return; } // INVITE request. if (message.method === JsSIP_C.INVITE) { // If the branch matches the key of any IST then assume it is a retransmission // and ignore the INVITE. // TODO: we should reply the last response. if (ua.transactions.ist[message.via_branch]) { return false; } // Otherwise check whether it is a merged request. else { for(idx in ua.transactions.ist) { tr = ua.transactions.ist[idx]; if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) { reply(482); return false; } } } } // Non INVITE request. else { // If the branch matches the key of any NIST then assume it is a retransmission // and ignore the request. // TODO: we should reply the last response. if (ua.transactions.nist[message.via_branch]) { return false; } // Otherwise check whether it is a merged request. else { for(idx in ua.transactions.nist) { tr = ua.transactions.nist[idx]; if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) { reply(482); return false; } } } } } // Sanity Check functions for responses function rfc3261_8_1_3_3() { if(message.getHeaders('via').length > 1) { debug('more than one Via header field present in the response, dropping the response'); return false; } } function rfc3261_18_3_response() { var len = Utils.str_utf8_length(message.body), contentLength = message.getHeader('content-length'); if(len < contentLength) { debug('message body length is lower than the value in Content-Length header field, dropping the response'); return false; } } // Sanity Check functions for requests and responses function minimumHeaders() { var mandatoryHeaders = ['from', 'to', 'call_id', 'cseq', 'via'], idx = mandatoryHeaders.length; while(idx--) { if(!message.hasHeader(mandatoryHeaders[idx])) { debug('missing mandatory header field : ' + mandatoryHeaders[idx] + ', dropping the response'); return false; } } } // Reply function reply(status_code) { var to, response = 'SIP/2.0 ' + status_code + ' ' + JsSIP_C.REASON_PHRASE[status_code] + '\r\n', vias = message.getHeaders('via'), length = vias.length, idx = 0; for(idx; idx < length; idx++) { response += 'Via: ' + vias[idx] + '\r\n'; } to = message.getHeader('To'); if(!message.to_tag) { to += ';tag=' + Utils.newTag(); } response += 'To: ' + to + '\r\n'; response += 'From: ' + message.getHeader('From') + '\r\n'; response += 'Call-ID: ' + message.call_id + '\r\n'; response += 'CSeq: ' + message.cseq + ' ' + message.method + '\r\n'; response += '\r\n'; transport.send(response); } },{"./Constants":1,"./SIPMessage":18,"./Utils":25,"debug":34}],28:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // 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 EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],29:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],30:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],31:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],32:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // 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. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":31,"_process":29,"inherits":30}],33:[function(require,module,exports){ /** * Helpers. */ var s = 1000 var m = s * 60 var h = m * 60 var d = h * 24 var y = d * 365.25 /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {} var type = typeof val if (type === 'string' && val.length > 0) { return parse(val) } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val) } throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) } /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str) if (str.length > 10000) { return } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) if (!match) { return } var n = parseFloat(match[1]) var type = (match[2] || 'ms').toLowerCase() switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y case 'days': case 'day': case 'd': return n * d case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n default: return undefined } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd' } if (ms >= h) { return Math.round(ms / h) + 'h' } if (ms >= m) { return Math.round(ms / m) + 'm' } if (ms >= s) { return Math.round(ms / s) + 's' } return ms + 'ms' } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms' } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name } return Math.ceil(ms / n) + ' ' + name + 's' } },{}],34:[function(require,module,exports){ (function (process){ /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = require('./debug'); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') { return true; } // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit') // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { try { return exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (typeof process !== 'undefined' && 'env' in process) { return process.env.DEBUG; } } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { return window.localStorage; } catch (e) {} } }).call(this,require('_process')) },{"./debug":35,"_process":29}],35:[function(require,module,exports){ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug.default = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = require('ms'); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %O args.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } return debug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } },{"ms":33}],36:[function(require,module,exports){ var grammar = module.exports = { v: [{ name: 'version', reg: /^(\d*)$/ }], o: [{ //o=- 20518 0 IN IP4 203.0.113.1 // NB: sessionId will be a String in most cases because it is huge name: 'origin', reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/, names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'], format: "%s %s %d %s IP%d %s" }], // default parsing of these only (though some of these feel outdated) s: [{ name: 'name' }], i: [{ name: 'description' }], u: [{ name: 'uri' }], e: [{ name: 'email' }], p: [{ name: 'phone' }], z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly.. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly //k: [{}], // outdated thing ignored t: [{ //t=0 0 name: 'timing', reg: /^(\d*) (\d*)/, names: ['start', 'stop'], format: "%d %d" }], c: [{ //c=IN IP4 10.47.197.26 name: 'connection', reg: /^IN IP(\d) (\S*)/, names: ['version', 'ip'], format: "IN IP%d %s" }], b: [{ //b=AS:4000 push: 'bandwidth', reg: /^(TIAS|AS|CT|RR|RS):(\d*)/, names: ['type', 'limit'], format: "%s:%s" }], m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31 // NB: special - pushes to session // TODO: rtp/fmtp should be filtered by the payloads found here? reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/, names: ['type', 'port', 'protocol', 'payloads'], format: "%s %d %s %s" }], a: [ { //a=rtpmap:110 opus/48000/2 push: 'rtp', reg: /^rtpmap:(\d*) ([\w\-\.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/, names: ['payload', 'codec', 'rate', 'encoding'], format: function (o) { return (o.encoding) ? "rtpmap:%d %s/%s/%s": o.rate ? "rtpmap:%d %s/%s": "rtpmap:%d %s"; } }, { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000 //a=fmtp:111 minptime=10; useinbandfec=1 push: 'fmtp', reg: /^fmtp:(\d*) ([\S| ]*)/, names: ['payload', 'config'], format: "fmtp:%d %s" }, { //a=control:streamid=0 name: 'control', reg: /^control:(.*)/, format: "control:%s" }, { //a=rtcp:65179 IN IP4 193.84.77.194 name: 'rtcp', reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/, names: ['port', 'netType', 'ipVer', 'address'], format: function (o) { return (o.address != null) ? "rtcp:%d %s IP%d %s": "rtcp:%d"; } }, { //a=rtcp-fb:98 trr-int 100 push: 'rtcpFbTrrInt', reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/, names: ['payload', 'value'], format: "rtcp-fb:%d trr-int %d" }, { //a=rtcp-fb:98 nack rpsi push: 'rtcpFb', reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/, names: ['payload', 'type', 'subtype'], format: function (o) { return (o.subtype != null) ? "rtcp-fb:%s %s %s": "rtcp-fb:%s %s"; } }, { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset //a=extmap:1/recvonly URI-gps-string push: 'ext', reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/, names: ['value', 'uri', 'config'], // value may include "/direction" suffix format: function (o) { return (o.config != null) ? "extmap:%s %s %s": "extmap:%s %s"; } }, { //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32 push: 'crypto', reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/, names: ['id', 'suite', 'config', 'sessionConfig'], format: function (o) { return (o.sessionConfig != null) ? "crypto:%d %s %s %s": "crypto:%d %s %s"; } }, { //a=setup:actpass name: 'setup', reg: /^setup:(\w*)/, format: "setup:%s" }, { //a=mid:1 name: 'mid', reg: /^mid:([^\s]*)/, format: "mid:%s" }, { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a name: 'msid', reg: /^msid:(.*)/, format: "msid:%s" }, { //a=ptime:20 name: 'ptime', reg: /^ptime:(\d*)/, format: "ptime:%d" }, { //a=maxptime:60 name: 'maxptime', reg: /^maxptime:(\d*)/, format: "maxptime:%d" }, { //a=sendrecv name: 'direction', reg: /^(sendrecv|recvonly|sendonly|inactive)/ }, { //a=ice-lite name: 'icelite', reg: /^(ice-lite)/ }, { //a=ice-ufrag:F7gI name: 'iceUfrag', reg: /^ice-ufrag:(\S*)/, format: "ice-ufrag:%s" }, { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g name: 'icePwd', reg: /^ice-pwd:(\S*)/, format: "ice-pwd:%s" }, { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33 name: 'fingerprint', reg: /^fingerprint:(\S*) (\S*)/, names: ['type', 'hash'], format: "fingerprint:%s %s" }, { //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0 //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0 //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0 //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0 push:'candidates', reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/, names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'], format: function (o) { var str = "candidate:%s %d %s %d %s %d typ %s"; str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v"; // NB: candidate has three optional chunks, so %void middles one if it's missing str += (o.tcptype != null) ? " tcptype %s" : "%v"; if (o.generation != null) { str += " generation %d"; } return str; } }, { //a=end-of-candidates (keep after the candidates line for readability) name: 'endOfCandidates', reg: /^(end-of-candidates)/ }, { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ... name: 'remoteCandidates', reg: /^remote-candidates:(.*)/, format: "remote-candidates:%s" }, { //a=ice-options:google-ice name: 'iceOptions', reg: /^ice-options:(\S*)/, format: "ice-options:%s" }, { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1 push: "ssrcs", reg: /^ssrc:(\d*) ([\w_]*):(.*)/, names: ['id', 'attribute', 'value'], format: "ssrc:%d %s:%s" }, { //a=ssrc-group:FEC 1 2 push: "ssrcGroups", reg: /^ssrc-group:(\w*) (.*)/, names: ['semantics', 'ssrcs'], format: "ssrc-group:%s %s" }, { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV name: "msidSemantic", reg: /^msid-semantic:\s?(\w*) (\S*)/, names: ['semantic', 'token'], format: "msid-semantic: %s %s" // space after ":" is not accidental }, { //a=group:BUNDLE audio video push: 'groups', reg: /^group:(\w*) (.*)/, names: ['type', 'mids'], format: "group:%s %s" }, { //a=rtcp-mux name: 'rtcpMux', reg: /^(rtcp-mux)/ }, { //a=rtcp-rsize name: 'rtcpRsize', reg: /^(rtcp-rsize)/ }, { //a=sctpmap:5000 webrtc-datachannel 1024 name: 'sctpmap', reg: /^sctpmap:([\w_\/]*) (\S*)(?: (\S*))?/, names: ['sctpmapNumber', 'app', 'maxMessageSize'], format: function (o) { return (o.maxMessageSize != null) ? "sctpmap:%s %s %s" : "sctpmap:%s %s"; } }, { // any a= that we don't understand is kepts verbatim on media.invalid push: 'invalid', names: ["value"] } ] }; // set sensible defaults to avoid polluting the grammar with boring details Object.keys(grammar).forEach(function (key) { var objs = grammar[key]; objs.forEach(function (obj) { if (!obj.reg) { obj.reg = /(.*)/; } if (!obj.format) { obj.format = "%s"; } }); }); },{}],37:[function(require,module,exports){ var parser = require('./parser'); var writer = require('./writer'); exports.write = writer; exports.parse = parser.parse; exports.parseFmtpConfig = parser.parseFmtpConfig; exports.parsePayloads = parser.parsePayloads; exports.parseRemoteCandidates = parser.parseRemoteCandidates; },{"./parser":38,"./writer":39}],38:[function(require,module,exports){ var toIntIfInt = function (v) { return String(Number(v)) === v ? Number(v) : v; }; var attachProperties = function (match, location, names, rawName) { if (rawName && !names) { location[rawName] = toIntIfInt(match[1]); } else { for (var i = 0; i < names.length; i += 1) { if (match[i+1] != null) { location[names[i]] = toIntIfInt(match[i+1]); } } } }; var parseReg = function (obj, location, content) { var needsBlank = obj.name && obj.names; if (obj.push && !location[obj.push]) { location[obj.push] = []; } else if (needsBlank && !location[obj.name]) { location[obj.name] = {}; } var keyLocation = obj.push ? {} : // blank object that will be pushed needsBlank ? location[obj.name] : location; // otherwise, named location or root attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name); if (obj.push) { location[obj.push].push(keyLocation); } }; var grammar = require('./grammar'); var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/); exports.parse = function (sdp) { var session = {} , media = [] , location = session; // points at where properties go under (one of the above) // parse lines we understand sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) { var type = l[0]; var content = l.slice(2); if (type === 'm') { media.push({rtp: [], fmtp: []}); location = media[media.length-1]; // point at latest media line } for (var j = 0; j < (grammar[type] || []).length; j += 1) { var obj = grammar[type][j]; if (obj.reg.test(content)) { return parseReg(obj, location, content); } } }); session.media = media; // link it up return session; }; var fmtpReducer = function (acc, expr) { var s = expr.split(/=(.+)/, 2); if (s.length === 2) { acc[s[0]] = toIntIfInt(s[1]); } return acc; }; exports.parseFmtpConfig = function (str) { return str.split(/\;\s?/).reduce(fmtpReducer, {}); }; exports.parsePayloads = function (str) { return str.split(' ').map(Number); }; exports.parseRemoteCandidates = function (str) { var candidates = []; var parts = str.split(' ').map(toIntIfInt); for (var i = 0; i < parts.length; i += 3) { candidates.push({ component: parts[i], ip: parts[i + 1], port: parts[i + 2] }); } return candidates; }; },{"./grammar":36}],39:[function(require,module,exports){ var grammar = require('./grammar'); // customized util.format - discards excess arguments and can void middle ones var formatRegExp = /%[sdv%]/g; var format = function (formatStr) { var i = 1; var args = arguments; var len = args.length; return formatStr.replace(formatRegExp, function (x) { if (i >= len) { return x; // missing argument } var arg = args[i]; i += 1; switch (x) { case '%%': return '%'; case '%s': return String(arg); case '%d': return Number(arg); case '%v': return ''; } }); // NB: we discard excess arguments - they are typically undefined from makeLine }; var makeLine = function (type, obj, location) { var str = obj.format instanceof Function ? (obj.format(obj.push ? location : location[obj.name])) : obj.format; var args = [type + '=' + str]; if (obj.names) { for (var i = 0; i < obj.names.length; i += 1) { var n = obj.names[i]; if (obj.name) { args.push(location[obj.name][n]); } else { // for mLine and push attributes args.push(location[obj.names[i]]); } } } else { args.push(location[obj.name]); } return format.apply(null, args); }; // RFC specified order // TODO: extend this with all the rest var defaultOuterOrder = [ 'v', 'o', 's', 'i', 'u', 'e', 'p', 'c', 'b', 't', 'r', 'z', 'a' ]; var defaultInnerOrder = ['i', 'c', 'b', 'a']; module.exports = function (session, opts) { opts = opts || {}; // ensure certain properties exist if (session.version == null) { session.version = 0; // "v=0" must be there (only defined version atm) } if (session.name == null) { session.name = " "; // "s= " must be there if no meaningful name set } session.media.forEach(function (mLine) { if (mLine.payloads == null) { mLine.payloads = ""; } }); var outerOrder = opts.outerOrder || defaultOuterOrder; var innerOrder = opts.innerOrder || defaultInnerOrder; var sdp = []; // loop through outerOrder for matching properties on session outerOrder.forEach(function (type) { grammar[type].forEach(function (obj) { if (obj.name in session && session[obj.name] != null) { sdp.push(makeLine(type, obj, session)); } else if (obj.push in session && session[obj.push] != null) { session[obj.push].forEach(function (el) { sdp.push(makeLine(type, obj, el)); }); } }); }); // then for each media line, follow the innerOrder session.media.forEach(function (mLine) { sdp.push(makeLine('m', grammar.m[0], mLine)); innerOrder.forEach(function (type) { grammar[type].forEach(function (obj) { if (obj.name in mLine && mLine[obj.name] != null) { sdp.push(makeLine(type, obj, mLine)); } else if (obj.push in mLine && mLine[obj.push] != null) { mLine[obj.push].forEach(function (el) { sdp.push(makeLine(type, obj, el)); }); } }); }); }); return sdp.join('\r\n') + '\r\n'; }; },{"./grammar":36}],40:[function(require,module,exports){ /* eslint-env node */ 'use strict'; // SDP helpers. var SDPUtils = {}; // Generate an alphanumeric identifier for cname or mids. // TODO: use UUIDs instead? https://gist.github.com/jed/982883 SDPUtils.generateIdentifier = function() { return Math.random().toString(36).substr(2, 10); }; // The RTCP CNAME used by all peerconnections from the same JS. SDPUtils.localCName = SDPUtils.generateIdentifier(); // Splits SDP into lines, dealing with both CRLF and LF. SDPUtils.splitLines = function(blob) { return blob.trim().split('\n').map(function(line) { return line.trim(); }); }; // Splits SDP into sessionpart and mediasections. Ensures CRLF. SDPUtils.splitSections = function(blob) { var parts = blob.split('\nm='); return parts.map(function(part, index) { return (index > 0 ? 'm=' + part : part).trim() + '\r\n'; }); }; // Returns lines that start with a certain prefix. SDPUtils.matchPrefix = function(blob, prefix) { return SDPUtils.splitLines(blob).filter(function(line) { return line.indexOf(prefix) === 0; }); }; // Parses an ICE candidate line. Sample input: // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8 // rport 55996" SDPUtils.parseCandidate = function(line) { var parts; // Parse both variants. if (line.indexOf('a=candidate:') === 0) { parts = line.substring(12).split(' '); } else { parts = line.substring(10).split(' '); } var candidate = { foundation: parts[0], component: parts[1], protocol: parts[2].toLowerCase(), priority: parseInt(parts[3], 10), ip: parts[4], port: parseInt(parts[5], 10), // skip parts[6] == 'typ' type: parts[7] }; for (var i = 8; i < parts.length; i += 2) { switch (parts[i]) { case 'raddr': candidate.relatedAddress = parts[i + 1]; break; case 'rport': candidate.relatedPort = parseInt(parts[i + 1], 10); break; case 'tcptype': candidate.tcpType = parts[i + 1]; break; default: // Unknown extensions are silently ignored. break; } } return candidate; }; // Translates a candidate object into SDP candidate attribute. SDPUtils.writeCandidate = function(candidate) { var sdp = []; sdp.push(candidate.foundation); sdp.push(candidate.component); sdp.push(candidate.protocol.toUpperCase()); sdp.push(candidate.priority); sdp.push(candidate.ip); sdp.push(candidate.port); var type = candidate.type; sdp.push('typ'); sdp.push(type); if (type !== 'host' && candidate.relatedAddress && candidate.relatedPort) { sdp.push('raddr'); sdp.push(candidate.relatedAddress); // was: relAddr sdp.push('rport'); sdp.push(candidate.relatedPort); // was: relPort } if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') { sdp.push('tcptype'); sdp.push(candidate.tcpType); } return 'candidate:' + sdp.join(' '); }; // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input: // a=rtpmap:111 opus/48000/2 SDPUtils.parseRtpMap = function(line) { var parts = line.substr(9).split(' '); var parsed = { payloadType: parseInt(parts.shift(), 10) // was: id }; parts = parts[0].split('/'); parsed.name = parts[0]; parsed.clockRate = parseInt(parts[1], 10); // was: clockrate // was: channels parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1; return parsed; }; // Generate an a=rtpmap line from RTCRtpCodecCapability or // RTCRtpCodecParameters. SDPUtils.writeRtpMap = function(codec) { var pt = codec.payloadType; if (codec.preferredPayloadType !== undefined) { pt = codec.preferredPayloadType; } return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate + (codec.numChannels !== 1 ? '/' + codec.numChannels : '') + '\r\n'; }; // Parses an a=extmap line (headerextension from RFC 5285). Sample input: // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset SDPUtils.parseExtmap = function(line) { var parts = line.substr(9).split(' '); return { id: parseInt(parts[0], 10), uri: parts[1] }; }; // Generates a=extmap line from RTCRtpHeaderExtensionParameters or // RTCRtpHeaderExtension. SDPUtils.writeExtmap = function(headerExtension) { return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) + ' ' + headerExtension.uri + '\r\n'; }; // Parses an ftmp line, returns dictionary. Sample input: // a=fmtp:96 vbr=on;cng=on // Also deals with vbr=on; cng=on SDPUtils.parseFmtp = function(line) { var parsed = {}; var kv; var parts = line.substr(line.indexOf(' ') + 1).split(';'); for (var j = 0; j < parts.length; j++) { kv = parts[j].trim().split('='); parsed[kv[0].trim()] = kv[1]; } return parsed; }; // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters. SDPUtils.writeFmtp = function(codec) { var line = ''; var pt = codec.payloadType; if (codec.preferredPayloadType !== undefined) { pt = codec.preferredPayloadType; } if (codec.parameters && Object.keys(codec.parameters).length) { var params = []; Object.keys(codec.parameters).forEach(function(param) { params.push(param + '=' + codec.parameters[param]); }); line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n'; } return line; }; // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input: // a=rtcp-fb:98 nack rpsi SDPUtils.parseRtcpFb = function(line) { var parts = line.substr(line.indexOf(' ') + 1).split(' '); return { type: parts.shift(), parameter: parts.join(' ') }; }; // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters. SDPUtils.writeRtcpFb = function(codec) { var lines = ''; var pt = codec.payloadType; if (codec.preferredPayloadType !== undefined) { pt = codec.preferredPayloadType; } if (codec.rtcpFeedback && codec.rtcpFeedback.length) { // FIXME: special handling for trr-int? codec.rtcpFeedback.forEach(function(fb) { lines += 'a=rtcp-fb:' + pt + ' ' + fb.type + (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') + '\r\n'; }); } return lines; }; // Parses an RFC 5576 ssrc media attribute. Sample input: // a=ssrc:3735928559 cname:something SDPUtils.parseSsrcMedia = function(line) { var sp = line.indexOf(' '); var parts = { ssrc: parseInt(line.substr(7, sp - 7), 10) }; var colon = line.indexOf(':', sp); if (colon > -1) { parts.attribute = line.substr(sp + 1, colon - sp - 1); parts.value = line.substr(colon + 1); } else { parts.attribute = line.substr(sp + 1); } return parts; }; // Extracts DTLS parameters from SDP media section or sessionpart. // FIXME: for consistency with other functions this should only // get the fingerprint line as input. See also getIceParameters. SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) { var lines = SDPUtils.splitLines(mediaSection); // Search in session part, too. lines = lines.concat(SDPUtils.splitLines(sessionpart)); var fpLine = lines.filter(function(line) { return line.indexOf('a=fingerprint:') === 0; })[0].substr(14); // Note: a=setup line is ignored since we use the 'auto' role. var dtlsParameters = { role: 'auto', fingerprints: [{ algorithm: fpLine.split(' ')[0], value: fpLine.split(' ')[1] }] }; return dtlsParameters; }; // Serializes DTLS parameters to SDP. SDPUtils.writeDtlsParameters = function(params, setupType) { var sdp = 'a=setup:' + setupType + '\r\n'; params.fingerprints.forEach(function(fp) { sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n'; }); return sdp; }; // Parses ICE information from SDP media section or sessionpart. // FIXME: for consistency with other functions this should only // get the ice-ufrag and ice-pwd lines as input. SDPUtils.getIceParameters = function(mediaSection, sessionpart) { var lines = SDPUtils.splitLines(mediaSection); // Search in session part, too. lines = lines.concat(SDPUtils.splitLines(sessionpart)); var iceParameters = { usernameFragment: lines.filter(function(line) { return line.indexOf('a=ice-ufrag:') === 0; })[0].substr(12), password: lines.filter(function(line) { return line.indexOf('a=ice-pwd:') === 0; })[0].substr(10) }; return iceParameters; }; // Serializes ICE parameters to SDP. SDPUtils.writeIceParameters = function(params) { return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' + 'a=ice-pwd:' + params.password + '\r\n'; }; // Parses the SDP media section and returns RTCRtpParameters. SDPUtils.parseRtpParameters = function(mediaSection) { var description = { codecs: [], headerExtensions: [], fecMechanisms: [], rtcp: [] }; var lines = SDPUtils.splitLines(mediaSection); var mline = lines[0].split(' '); for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..] var pt = mline[i]; var rtpmapline = SDPUtils.matchPrefix( mediaSection, 'a=rtpmap:' + pt + ' ')[0]; if (rtpmapline) { var codec = SDPUtils.parseRtpMap(rtpmapline); var fmtps = SDPUtils.matchPrefix( mediaSection, 'a=fmtp:' + pt + ' '); // Only the first a=fmtp:<pt> is considered. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {}; codec.rtcpFeedback = SDPUtils.matchPrefix( mediaSection, 'a=rtcp-fb:' + pt + ' ') .map(SDPUtils.parseRtcpFb); description.codecs.push(codec); // parse FEC mechanisms from rtpmap lines. switch (codec.name.toUpperCase()) { case 'RED': case 'ULPFEC': description.fecMechanisms.push(codec.name.toUpperCase()); break; default: // only RED and ULPFEC are recognized as FEC mechanisms. break; } } } SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) { description.headerExtensions.push(SDPUtils.parseExtmap(line)); }); // FIXME: parse rtcp. return description; }; // Generates parts of the SDP media section describing the capabilities / // parameters. SDPUtils.writeRtpDescription = function(kind, caps) { var sdp = ''; // Build the mline. sdp += 'm=' + kind + ' '; sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs. sdp += ' UDP/TLS/RTP/SAVPF '; sdp += caps.codecs.map(function(codec) { if (codec.preferredPayloadType !== undefined) { return codec.preferredPayloadType; } return codec.payloadType; }).join(' ') + '\r\n'; sdp += 'c=IN IP4 0.0.0.0\r\n'; sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n'; // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb. caps.codecs.forEach(function(codec) { sdp += SDPUtils.writeRtpMap(codec); sdp += SDPUtils.writeFmtp(codec); sdp += SDPUtils.writeRtcpFb(codec); }); sdp += 'a=rtcp-mux\r\n'; caps.headerExtensions.forEach(function(extension) { sdp += SDPUtils.writeExtmap(extension); }); // FIXME: write fecMechanisms. return sdp; }; // Parses the SDP media section and returns an array of // RTCRtpEncodingParameters. SDPUtils.parseRtpEncodingParameters = function(mediaSection) { var encodingParameters = []; var description = SDPUtils.parseRtpParameters(mediaSection); var hasRed = description.fecMechanisms.indexOf('RED') !== -1; var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1; // filter a=ssrc:... cname:, ignore PlanB-msid var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:') .map(function(line) { return SDPUtils.parseSsrcMedia(line); }) .filter(function(parts) { return parts.attribute === 'cname'; }); var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc; var secondarySsrc; var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID') .map(function(line) { var parts = line.split(' '); parts.shift(); return parts.map(function(part) { return parseInt(part, 10); }); }); if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) { secondarySsrc = flows[0][1]; } description.codecs.forEach(function(codec) { if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) { var encParam = { ssrc: primarySsrc, codecPayloadType: parseInt(codec.parameters.apt, 10), rtx: { payloadType: codec.payloadType, ssrc: secondarySsrc } }; encodingParameters.push(encParam); if (hasRed) { encParam = JSON.parse(JSON.stringify(encParam)); encParam.fec = { ssrc: secondarySsrc, mechanism: hasUlpfec ? 'red+ulpfec' : 'red' }; encodingParameters.push(encParam); } } }); if (encodingParameters.length === 0 && primarySsrc) { encodingParameters.push({ ssrc: primarySsrc }); } // we support both b=AS and b=TIAS but interpret AS as TIAS. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b='); if (bandwidth.length) { if (bandwidth[0].indexOf('b=TIAS:') === 0) { bandwidth = parseInt(bandwidth[0].substr(7), 10); } else if (bandwidth[0].indexOf('b=AS:') === 0) { bandwidth = parseInt(bandwidth[0].substr(5), 10); } encodingParameters.forEach(function(params) { params.maxBitrate = bandwidth; }); } return encodingParameters; }; SDPUtils.writeSessionBoilerplate = function() { // FIXME: sess-id should be an NTP timestamp. return 'v=0\r\n' + 'o=thisisadapterortc 8169639915646943137 2 IN IP4 127.0.0.1\r\n' + 's=-\r\n' + 't=0 0\r\n'; }; SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) { var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps); // Map ICE parameters (ufrag, pwd) to SDP. sdp += SDPUtils.writeIceParameters( transceiver.iceGatherer.getLocalParameters()); // Map DTLS parameters to SDP. sdp += SDPUtils.writeDtlsParameters( transceiver.dtlsTransport.getLocalParameters(), type === 'offer' ? 'actpass' : 'active'); sdp += 'a=mid:' + transceiver.mid + '\r\n'; if (transceiver.rtpSender && transceiver.rtpReceiver) { sdp += 'a=sendrecv\r\n'; } else if (transceiver.rtpSender) { sdp += 'a=sendonly\r\n'; } else if (transceiver.rtpReceiver) { sdp += 'a=recvonly\r\n'; } else { sdp += 'a=inactive\r\n'; } // FIXME: for RTX there might be multiple SSRCs. Not implemented in Edge yet. if (transceiver.rtpSender) { var msid = 'msid:' + stream.id + ' ' + transceiver.rtpSender.track.id + '\r\n'; sdp += 'a=' + msid; sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc + ' ' + msid; } // FIXME: this should be written by writeRtpDescription. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc + ' cname:' + SDPUtils.localCName + '\r\n'; return sdp; }; // Gets the direction from the mediaSection or the sessionpart. SDPUtils.getDirection = function(mediaSection, sessionpart) { // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv. var lines = SDPUtils.splitLines(mediaSection); for (var i = 0; i < lines.length; i++) { switch (lines[i]) { case 'a=sendrecv': case 'a=sendonly': case 'a=recvonly': case 'a=inactive': return lines[i].substr(2); default: // FIXME: What should happen here? } } if (sessionpart) { return SDPUtils.getDirection(sessionpart); } return 'sendrecv'; }; // Expose public methods. module.exports = SDPUtils; },{}],41:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; // Shimming starts here. (function() { // Utils. var logging = require('./utils').log; var browserDetails = require('./utils').browserDetails; // Export to the adapter global object visible in the browser. module.exports.browserDetails = browserDetails; module.exports.extractVersion = require('./utils').extractVersion; module.exports.disableLog = require('./utils').disableLog; // Uncomment the line below if you want logging to occur, including logging // for the switch statement below. Can also be turned on in the browser via // adapter.disableLog(false), but then logging from the switch statement below // will not appear. // require('./utils').disableLog(false); // Browser shims. var chromeShim = require('./chrome/chrome_shim') || null; var edgeShim = require('./edge/edge_shim') || null; var firefoxShim = require('./firefox/firefox_shim') || null; var safariShim = require('./safari/safari_shim') || null; // Shim browser if found. switch (browserDetails.browser) { case 'opera': // fallthrough as it uses chrome shims case 'chrome': if (!chromeShim || !chromeShim.shimPeerConnection) { logging('Chrome shim is not included in this adapter release.'); return; } logging('adapter.js shimming chrome.'); // Export to the adapter global object visible in the browser. module.exports.browserShim = chromeShim; chromeShim.shimGetUserMedia(); chromeShim.shimMediaStream(); chromeShim.shimSourceObject(); chromeShim.shimPeerConnection(); chromeShim.shimOnTrack(); break; case 'firefox': if (!firefoxShim || !firefoxShim.shimPeerConnection) { logging('Firefox shim is not included in this adapter release.'); return; } logging('adapter.js shimming firefox.'); // Export to the adapter global object visible in the browser. module.exports.browserShim = firefoxShim; firefoxShim.shimGetUserMedia(); firefoxShim.shimSourceObject(); firefoxShim.shimPeerConnection(); firefoxShim.shimOnTrack(); break; case 'edge': if (!edgeShim || !edgeShim.shimPeerConnection) { logging('MS edge shim is not included in this adapter release.'); return; } logging('adapter.js shimming edge.'); // Export to the adapter global object visible in the browser. module.exports.browserShim = edgeShim; edgeShim.shimGetUserMedia(); edgeShim.shimPeerConnection(); break; case 'safari': if (!safariShim) { logging('Safari shim is not included in this adapter release.'); return; } logging('adapter.js shimming safari.'); // Export to the adapter global object visible in the browser. module.exports.browserShim = safariShim; safariShim.shimGetUserMedia(); break; default: logging('Unsupported browser!'); } })(); },{"./chrome/chrome_shim":42,"./edge/edge_shim":44,"./firefox/firefox_shim":46,"./safari/safari_shim":48,"./utils":49}],42:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logging = require('../utils.js').log; var browserDetails = require('../utils.js').browserDetails; var chromeShim = { shimMediaStream: function() { window.MediaStream = window.MediaStream || window.webkitMediaStream; }, shimOnTrack: function() { if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) { Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', { get: function() { return this._ontrack; }, set: function(f) { var self = this; if (this._ontrack) { this.removeEventListener('track', this._ontrack); this.removeEventListener('addstream', this._ontrackpoly); } this.addEventListener('track', this._ontrack = f); this.addEventListener('addstream', this._ontrackpoly = function(e) { // onaddstream does not fire when a track is added to an existing // stream. But stream.onaddtrack is implemented so we use that. e.stream.addEventListener('addtrack', function(te) { var event = new Event('track'); event.track = te.track; event.receiver = {track: te.track}; event.streams = [e.stream]; self.dispatchEvent(event); }); e.stream.getTracks().forEach(function(track) { var event = new Event('track'); event.track = track; event.receiver = {track: track}; event.streams = [e.stream]; this.dispatchEvent(event); }.bind(this)); }.bind(this)); } }); } }, shimSourceObject: function() { if (typeof window === 'object') { if (window.HTMLMediaElement && !('srcObject' in window.HTMLMediaElement.prototype)) { // Shim the srcObject property, once, when HTMLMediaElement is found. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { get: function() { return this._srcObject; }, set: function(stream) { var self = this; // Use _srcObject as a private property for this shim this._srcObject = stream; if (this.src) { URL.revokeObjectURL(this.src); } if (!stream) { this.src = ''; return; } this.src = URL.createObjectURL(stream); // We need to recreate the blob url when a track is added or // removed. Doing it manually since we want to avoid a recursion. stream.addEventListener('addtrack', function() { if (self.src) { URL.revokeObjectURL(self.src); } self.src = URL.createObjectURL(stream); }); stream.addEventListener('removetrack', function() { if (self.src) { URL.revokeObjectURL(self.src); } self.src = URL.createObjectURL(stream); }); } }); } } }, shimPeerConnection: function() { // The RTCPeerConnection object. window.RTCPeerConnection = function(pcConfig, pcConstraints) { // Translate iceTransportPolicy to iceTransports, // see https://code.google.com/p/webrtc/issues/detail?id=4869 logging('PeerConnection'); if (pcConfig && pcConfig.iceTransportPolicy) { pcConfig.iceTransports = pcConfig.iceTransportPolicy; } var pc = new webkitRTCPeerConnection(pcConfig, pcConstraints); var origGetStats = pc.getStats.bind(pc); pc.getStats = function(selector, successCallback, errorCallback) { var self = this; var args = arguments; // If selector is a function then we are in the old style stats so just // pass back the original getStats format to avoid breaking old users. if (arguments.length > 0 && typeof selector === 'function') { return origGetStats(selector, successCallback); } var fixChromeStats_ = function(response) { var standardReport = {}; var reports = response.result(); reports.forEach(function(report) { var standardStats = { id: report.id, timestamp: report.timestamp, type: report.type }; report.names().forEach(function(name) { standardStats[name] = report.stat(name); }); standardReport[standardStats.id] = standardStats; }); return standardReport; }; // shim getStats with maplike support var makeMapStats = function(stats, legacyStats) { var map = new Map(Object.keys(stats).map(function(key) { return[key, stats[key]]; })); legacyStats = legacyStats || stats; Object.keys(legacyStats).forEach(function(key) { map[key] = legacyStats[key]; }); return map; }; if (arguments.length >= 2) { var successCallbackWrapper_ = function(response) { args[1](makeMapStats(fixChromeStats_(response))); }; return origGetStats.apply(this, [successCallbackWrapper_, arguments[0]]); } // promise-support return new Promise(function(resolve, reject) { if (args.length === 1 && typeof selector === 'object') { origGetStats.apply(self, [ function(response) { resolve(makeMapStats(fixChromeStats_(response))); }, reject]); } else { // Preserve legacy chrome stats only on legacy access of stats obj origGetStats.apply(self, [ function(response) { resolve(makeMapStats(fixChromeStats_(response), response.result())); }, reject]); } }).then(successCallback, errorCallback); }; return pc; }; window.RTCPeerConnection.prototype = webkitRTCPeerConnection.prototype; // wrap static methods. Currently just generateCertificate. if (webkitRTCPeerConnection.generateCertificate) { Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', { get: function() { return webkitRTCPeerConnection.generateCertificate; } }); } ['createOffer', 'createAnswer'].forEach(function(method) { var nativeMethod = webkitRTCPeerConnection.prototype[method]; webkitRTCPeerConnection.prototype[method] = function() { var self = this; if (arguments.length < 1 || (arguments.length === 1 && typeof arguments[0] === 'object')) { var opts = arguments.length === 1 ? arguments[0] : undefined; return new Promise(function(resolve, reject) { nativeMethod.apply(self, [resolve, reject, opts]); }); } return nativeMethod.apply(this, arguments); }; }); // add promise support -- natively available in Chrome 51 if (browserDetails.version < 51) { ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] .forEach(function(method) { var nativeMethod = webkitRTCPeerConnection.prototype[method]; webkitRTCPeerConnection.prototype[method] = function() { var args = arguments; var self = this; var promise = new Promise(function(resolve, reject) { nativeMethod.apply(self, [args[0], resolve, reject]); }); if (args.length < 2) { return promise; } return promise.then(function() { args[1].apply(null, []); }, function(err) { if (args.length >= 3) { args[2].apply(null, [err]); } }); }; }); } // shim implicit creation of RTCSessionDescription/RTCIceCandidate ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] .forEach(function(method) { var nativeMethod = webkitRTCPeerConnection.prototype[method]; webkitRTCPeerConnection.prototype[method] = function() { arguments[0] = new ((method === 'addIceCandidate') ? RTCIceCandidate : RTCSessionDescription)(arguments[0]); return nativeMethod.apply(this, arguments); }; }); // support for addIceCandidate(null or undefined) var nativeAddIceCandidate = RTCPeerConnection.prototype.addIceCandidate; RTCPeerConnection.prototype.addIceCandidate = function() { if (!arguments[0]) { if (arguments[1]) { arguments[1].apply(null); } return Promise.resolve(); } return nativeAddIceCandidate.apply(this, arguments); }; } }; // Expose public methods. module.exports = { shimMediaStream: chromeShim.shimMediaStream, shimOnTrack: chromeShim.shimOnTrack, shimSourceObject: chromeShim.shimSourceObject, shimPeerConnection: chromeShim.shimPeerConnection, shimGetUserMedia: require('./getusermedia') }; },{"../utils.js":49,"./getusermedia":43}],43:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logging = require('../utils.js').log; // Expose public methods. module.exports = function() { var constraintsToChrome_ = function(c) { if (typeof c !== 'object' || c.mandatory || c.optional) { return c; } var cc = {}; Object.keys(c).forEach(function(key) { if (key === 'require' || key === 'advanced' || key === 'mediaSource') { return; } var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; if (r.exact !== undefined && typeof r.exact === 'number') { r.min = r.max = r.exact; } var oldname_ = function(prefix, name) { if (prefix) { return prefix + name.charAt(0).toUpperCase() + name.slice(1); } return (name === 'deviceId') ? 'sourceId' : name; }; if (r.ideal !== undefined) { cc.optional = cc.optional || []; var oc = {}; if (typeof r.ideal === 'number') { oc[oldname_('min', key)] = r.ideal; cc.optional.push(oc); oc = {}; oc[oldname_('max', key)] = r.ideal; cc.optional.push(oc); } else { oc[oldname_('', key)] = r.ideal; cc.optional.push(oc); } } if (r.exact !== undefined && typeof r.exact !== 'number') { cc.mandatory = cc.mandatory || {}; cc.mandatory[oldname_('', key)] = r.exact; } else { ['min', 'max'].forEach(function(mix) { if (r[mix] !== undefined) { cc.mandatory = cc.mandatory || {}; cc.mandatory[oldname_(mix, key)] = r[mix]; } }); } }); if (c.advanced) { cc.optional = (cc.optional || []).concat(c.advanced); } return cc; }; var shimConstraints_ = function(constraints, func) { constraints = JSON.parse(JSON.stringify(constraints)); if (constraints && constraints.audio) { constraints.audio = constraintsToChrome_(constraints.audio); } if (constraints && typeof constraints.video === 'object') { // Shim facingMode for mobile, where it defaults to "user". var face = constraints.video.facingMode; face = face && ((typeof face === 'object') ? face : {ideal: face}); if ((face && (face.exact === 'user' || face.exact === 'environment' || face.ideal === 'user' || face.ideal === 'environment')) && !(navigator.mediaDevices.getSupportedConstraints && navigator.mediaDevices.getSupportedConstraints().facingMode)) { delete constraints.video.facingMode; if (face.exact === 'environment' || face.ideal === 'environment') { // Look for "back" in label, or use last cam (typically back cam). return navigator.mediaDevices.enumerateDevices() .then(function(devices) { devices = devices.filter(function(d) { return d.kind === 'videoinput'; }); var back = devices.find(function(d) { return d.label.toLowerCase().indexOf('back') !== -1; }) || (devices.length && devices[devices.length - 1]); if (back) { constraints.video.deviceId = face.exact ? {exact: back.deviceId} : {ideal: back.deviceId}; } constraints.video = constraintsToChrome_(constraints.video); logging('chrome: ' + JSON.stringify(constraints)); return func(constraints); }); } } constraints.video = constraintsToChrome_(constraints.video); } logging('chrome: ' + JSON.stringify(constraints)); return func(constraints); }; var shimError_ = function(e) { return { name: { PermissionDeniedError: 'NotAllowedError', ConstraintNotSatisfiedError: 'OverconstrainedError' }[e.name] || e.name, message: e.message, constraint: e.constraintName, toString: function() { return this.name + (this.message && ': ') + this.message; } }; }; var getUserMedia_ = function(constraints, onSuccess, onError) { shimConstraints_(constraints, function(c) { navigator.webkitGetUserMedia(c, onSuccess, function(e) { onError(shimError_(e)); }); }); }; navigator.getUserMedia = getUserMedia_; // Returns the result of getUserMedia as a Promise. var getUserMediaPromise_ = function(constraints) { return new Promise(function(resolve, reject) { navigator.getUserMedia(constraints, resolve, reject); }); }; if (!navigator.mediaDevices) { navigator.mediaDevices = { getUserMedia: getUserMediaPromise_, enumerateDevices: function() { return new Promise(function(resolve) { var kinds = {audio: 'audioinput', video: 'videoinput'}; return MediaStreamTrack.getSources(function(devices) { resolve(devices.map(function(device) { return {label: device.label, kind: kinds[device.kind], deviceId: device.id, groupId: ''}; })); }); }); } }; } // A shim for getUserMedia method on the mediaDevices object. // TODO(KaptenJansson) remove once implemented in Chrome stable. if (!navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia = function(constraints) { return getUserMediaPromise_(constraints); }; } else { // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia // function which returns a Promise, it does not accept spec-style // constraints. var origGetUserMedia = navigator.mediaDevices.getUserMedia. bind(navigator.mediaDevices); navigator.mediaDevices.getUserMedia = function(cs) { return shimConstraints_(cs, function(c) { return origGetUserMedia(c).then(function(stream) { if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) { stream.getTracks().forEach(function(track) { track.stop(); }); throw new DOMException('', 'NotFoundError'); } return stream; }, function(e) { return Promise.reject(shimError_(e)); }); }); }; } // Dummy devicechange event methods. // TODO(KaptenJansson) remove once implemented in Chrome stable. if (typeof navigator.mediaDevices.addEventListener === 'undefined') { navigator.mediaDevices.addEventListener = function() { logging('Dummy mediaDevices.addEventListener called.'); }; } if (typeof navigator.mediaDevices.removeEventListener === 'undefined') { navigator.mediaDevices.removeEventListener = function() { logging('Dummy mediaDevices.removeEventListener called.'); }; } }; },{"../utils.js":49}],44:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var SDPUtils = require('sdp'); var browserDetails = require('../utils').browserDetails; var edgeShim = { shimPeerConnection: function() { if (window.RTCIceGatherer) { // ORTC defines an RTCIceCandidate object but no constructor. // Not implemented in Edge. if (!window.RTCIceCandidate) { window.RTCIceCandidate = function(args) { return args; }; } // ORTC does not have a session description object but // other browsers (i.e. Chrome) that will support both PC and ORTC // in the future might have this defined already. if (!window.RTCSessionDescription) { window.RTCSessionDescription = function(args) { return args; }; } // this adds an additional event listener to MediaStrackTrack that signals // when a tracks enabled property was changed. var origMSTEnabled = Object.getOwnPropertyDescriptor( MediaStreamTrack.prototype, 'enabled'); Object.defineProperty(MediaStreamTrack.prototype, 'enabled', { set: function(value) { origMSTEnabled.set.call(this, value); var ev = new Event('enabled'); ev.enabled = value; this.dispatchEvent(ev); } }); } window.RTCPeerConnection = function(config) { var self = this; var _eventTarget = document.createDocumentFragment(); ['addEventListener', 'removeEventListener', 'dispatchEvent'] .forEach(function(method) { self[method] = _eventTarget[method].bind(_eventTarget); }); this.onicecandidate = null; this.onaddstream = null; this.ontrack = null; this.onremovestream = null; this.onsignalingstatechange = null; this.oniceconnectionstatechange = null; this.onnegotiationneeded = null; this.ondatachannel = null; this.localStreams = []; this.remoteStreams = []; this.getLocalStreams = function() { return self.localStreams; }; this.getRemoteStreams = function() { return self.remoteStreams; }; this.localDescription = new RTCSessionDescription({ type: '', sdp: '' }); this.remoteDescription = new RTCSessionDescription({ type: '', sdp: '' }); this.signalingState = 'stable'; this.iceConnectionState = 'new'; this.iceGatheringState = 'new'; this.iceOptions = { gatherPolicy: 'all', iceServers: [] }; if (config && config.iceTransportPolicy) { switch (config.iceTransportPolicy) { case 'all': case 'relay': this.iceOptions.gatherPolicy = config.iceTransportPolicy; break; case 'none': // FIXME: remove once implementation and spec have added this. throw new TypeError('iceTransportPolicy "none" not supported'); default: // don't set iceTransportPolicy. break; } } this.usingBundle = config && config.bundlePolicy === 'max-bundle'; if (config && config.iceServers) { // Edge does not like // 1) stun: // 2) turn: that does not have all of turn:host:port?transport=udp // 3) turn: with ipv6 addresses var iceServers = JSON.parse(JSON.stringify(config.iceServers)); this.iceOptions.iceServers = iceServers.filter(function(server) { if (server && server.urls) { var urls = server.urls; if (typeof urls === 'string') { urls = [urls]; } urls = urls.filter(function(url) { return (url.indexOf('turn:') === 0 && url.indexOf('transport=udp') !== -1 && url.indexOf('turn:[') === -1) || (url.indexOf('stun:') === 0 && browserDetails.version >= 14393); })[0]; return !!urls; } return false; }); } this._config = config; // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ... // everything that is needed to describe a SDP m-line. this.transceivers = []; // since the iceGatherer is currently created in createOffer but we // must not emit candidates until after setLocalDescription we buffer // them in this array. this._localIceCandidatesBuffer = []; }; window.RTCPeerConnection.prototype._emitBufferedCandidates = function() { var self = this; var sections = SDPUtils.splitSections(self.localDescription.sdp); // FIXME: need to apply ice candidates in a way which is async but // in-order this._localIceCandidatesBuffer.forEach(function(event) { var end = !event.candidate || Object.keys(event.candidate).length === 0; if (end) { for (var j = 1; j < sections.length; j++) { if (sections[j].indexOf('\r\na=end-of-candidates\r\n') === -1) { sections[j] += 'a=end-of-candidates\r\n'; } } } else if (event.candidate.candidate.indexOf('typ endOfCandidates') === -1) { sections[event.candidate.sdpMLineIndex + 1] += 'a=' + event.candidate.candidate + '\r\n'; } self.localDescription.sdp = sections.join(''); self.dispatchEvent(event); if (self.onicecandidate !== null) { self.onicecandidate(event); } if (!event.candidate && self.iceGatheringState !== 'complete') { var complete = self.transceivers.every(function(transceiver) { return transceiver.iceGatherer && transceiver.iceGatherer.state === 'completed'; }); if (complete) { self.iceGatheringState = 'complete'; } } }); this._localIceCandidatesBuffer = []; }; window.RTCPeerConnection.prototype.getConfiguration = function() { return this._config; }; window.RTCPeerConnection.prototype.addStream = function(stream) { // Clone is necessary for local demos mostly, attaching directly // to two different senders does not work (build 10547). var clonedStream = stream.clone(); stream.getTracks().forEach(function(track, idx) { var clonedTrack = clonedStream.getTracks()[idx]; track.addEventListener('enabled', function(event) { clonedTrack.enabled = event.enabled; }); }); this.localStreams.push(clonedStream); this._maybeFireNegotiationNeeded(); }; window.RTCPeerConnection.prototype.removeStream = function(stream) { var idx = this.localStreams.indexOf(stream); if (idx > -1) { this.localStreams.splice(idx, 1); this._maybeFireNegotiationNeeded(); } }; window.RTCPeerConnection.prototype.getSenders = function() { return this.transceivers.filter(function(transceiver) { return !!transceiver.rtpSender; }) .map(function(transceiver) { return transceiver.rtpSender; }); }; window.RTCPeerConnection.prototype.getReceivers = function() { return this.transceivers.filter(function(transceiver) { return !!transceiver.rtpReceiver; }) .map(function(transceiver) { return transceiver.rtpReceiver; }); }; // Determines the intersection of local and remote capabilities. window.RTCPeerConnection.prototype._getCommonCapabilities = function(localCapabilities, remoteCapabilities) { var commonCapabilities = { codecs: [], headerExtensions: [], fecMechanisms: [] }; localCapabilities.codecs.forEach(function(lCodec) { for (var i = 0; i < remoteCapabilities.codecs.length; i++) { var rCodec = remoteCapabilities.codecs[i]; if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() && lCodec.clockRate === rCodec.clockRate) { // number of channels is the highest common number of channels rCodec.numChannels = Math.min(lCodec.numChannels, rCodec.numChannels); // push rCodec so we reply with offerer payload type commonCapabilities.codecs.push(rCodec); // determine common feedback mechanisms rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) { for (var j = 0; j < lCodec.rtcpFeedback.length; j++) { if (lCodec.rtcpFeedback[j].type === fb.type && lCodec.rtcpFeedback[j].parameter === fb.parameter) { return true; } } return false; }); // FIXME: also need to determine .parameters // see https://github.com/openpeer/ortc/issues/569 break; } } }); localCapabilities.headerExtensions .forEach(function(lHeaderExtension) { for (var i = 0; i < remoteCapabilities.headerExtensions.length; i++) { var rHeaderExtension = remoteCapabilities.headerExtensions[i]; if (lHeaderExtension.uri === rHeaderExtension.uri) { commonCapabilities.headerExtensions.push(rHeaderExtension); break; } } }); // FIXME: fecMechanisms return commonCapabilities; }; // Create ICE gatherer, ICE transport and DTLS transport. window.RTCPeerConnection.prototype._createIceAndDtlsTransports = function(mid, sdpMLineIndex) { var self = this; var iceGatherer = new RTCIceGatherer(self.iceOptions); var iceTransport = new RTCIceTransport(iceGatherer); iceGatherer.onlocalcandidate = function(evt) { var event = new Event('icecandidate'); event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex}; var cand = evt.candidate; var end = !cand || Object.keys(cand).length === 0; // Edge emits an empty object for RTCIceCandidateComplete‥ if (end) { // polyfill since RTCIceGatherer.state is not implemented in // Edge 10547 yet. if (iceGatherer.state === undefined) { iceGatherer.state = 'completed'; } // Emit a candidate with type endOfCandidates to make the samples // work. Edge requires addIceCandidate with this empty candidate // to start checking. The real solution is to signal // end-of-candidates to the other side when getting the null // candidate but some apps (like the samples) don't do that. event.candidate.candidate = 'candidate:1 1 udp 1 0.0.0.0 9 typ endOfCandidates'; } else { // RTCIceCandidate doesn't have a component, needs to be added cand.component = iceTransport.component === 'RTCP' ? 2 : 1; event.candidate.candidate = SDPUtils.writeCandidate(cand); } // update local description. var sections = SDPUtils.splitSections(self.localDescription.sdp); if (event.candidate.candidate.indexOf('typ endOfCandidates') === -1) { sections[event.candidate.sdpMLineIndex + 1] += 'a=' + event.candidate.candidate + '\r\n'; } else { sections[event.candidate.sdpMLineIndex + 1] += 'a=end-of-candidates\r\n'; } self.localDescription.sdp = sections.join(''); var complete = self.transceivers.every(function(transceiver) { return transceiver.iceGatherer && transceiver.iceGatherer.state === 'completed'; }); // Emit candidate if localDescription is set. // Also emits null candidate when all gatherers are complete. switch (self.iceGatheringState) { case 'new': self._localIceCandidatesBuffer.push(event); if (end && complete) { self._localIceCandidatesBuffer.push( new Event('icecandidate')); } break; case 'gathering': self._emitBufferedCandidates(); self.dispatchEvent(event); if (self.onicecandidate !== null) { self.onicecandidate(event); } if (complete) { self.dispatchEvent(new Event('icecandidate')); if (self.onicecandidate !== null) { self.onicecandidate(new Event('icecandidate')); } self.iceGatheringState = 'complete'; } break; case 'complete': // should not happen... currently! break; default: // no-op. break; } }; iceTransport.onicestatechange = function() { self._updateConnectionState(); }; var dtlsTransport = new RTCDtlsTransport(iceTransport); dtlsTransport.ondtlsstatechange = function() { self._updateConnectionState(); }; dtlsTransport.onerror = function() { // onerror does not set state to failed by itself. dtlsTransport.state = 'failed'; self._updateConnectionState(); }; return { iceGatherer: iceGatherer, iceTransport: iceTransport, dtlsTransport: dtlsTransport }; }; // Start the RTP Sender and Receiver for a transceiver. window.RTCPeerConnection.prototype._transceive = function(transceiver, send, recv) { var params = this._getCommonCapabilities(transceiver.localCapabilities, transceiver.remoteCapabilities); if (send && transceiver.rtpSender) { params.encodings = transceiver.sendEncodingParameters; params.rtcp = { cname: SDPUtils.localCName }; if (transceiver.recvEncodingParameters.length) { params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc; } transceiver.rtpSender.send(params); } if (recv && transceiver.rtpReceiver) { // remove RTX field in Edge 14942 if (transceiver.kind === 'video' && transceiver.recvEncodingParameters) { transceiver.recvEncodingParameters.forEach(function(p) { delete p.rtx; }); } params.encodings = transceiver.recvEncodingParameters; params.rtcp = { cname: transceiver.cname }; if (transceiver.sendEncodingParameters.length) { params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc; } transceiver.rtpReceiver.receive(params); } }; window.RTCPeerConnection.prototype.setLocalDescription = function(description) { var self = this; var sections; var sessionpart; if (description.type === 'offer') { // FIXME: What was the purpose of this empty if statement? // if (!this._pendingOffer) { // } else { if (this._pendingOffer) { // VERY limited support for SDP munging. Limited to: // * changing the order of codecs sections = SDPUtils.splitSections(description.sdp); sessionpart = sections.shift(); sections.forEach(function(mediaSection, sdpMLineIndex) { var caps = SDPUtils.parseRtpParameters(mediaSection); self._pendingOffer[sdpMLineIndex].localCapabilities = caps; }); this.transceivers = this._pendingOffer; delete this._pendingOffer; } } else if (description.type === 'answer') { sections = SDPUtils.splitSections(self.remoteDescription.sdp); sessionpart = sections.shift(); var isIceLite = SDPUtils.matchPrefix(sessionpart, 'a=ice-lite').length > 0; sections.forEach(function(mediaSection, sdpMLineIndex) { var transceiver = self.transceivers[sdpMLineIndex]; var iceGatherer = transceiver.iceGatherer; var iceTransport = transceiver.iceTransport; var dtlsTransport = transceiver.dtlsTransport; var localCapabilities = transceiver.localCapabilities; var remoteCapabilities = transceiver.remoteCapabilities; var rejected = mediaSection.split('\n', 1)[0] .split(' ', 2)[1] === '0'; if (!rejected && !transceiver.isDatachannel) { var remoteIceParameters = SDPUtils.getIceParameters( mediaSection, sessionpart); if (isIceLite) { var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:') .map(function(cand) { return SDPUtils.parseCandidate(cand); }) .filter(function(cand) { return cand.component === '1'; }); // ice-lite only includes host candidates in the SDP so we can // use setRemoteCandidates (which implies an // RTCIceCandidateComplete) if (cands.length) { iceTransport.setRemoteCandidates(cands); } } var remoteDtlsParameters = SDPUtils.getDtlsParameters( mediaSection, sessionpart); if (isIceLite) { remoteDtlsParameters.role = 'server'; } if (!self.usingBundle || sdpMLineIndex === 0) { iceTransport.start(iceGatherer, remoteIceParameters, isIceLite ? 'controlling' : 'controlled'); dtlsTransport.start(remoteDtlsParameters); } // Calculate intersection of capabilities. var params = self._getCommonCapabilities(localCapabilities, remoteCapabilities); // Start the RTCRtpSender. The RTCRtpReceiver for this // transceiver has already been started in setRemoteDescription. self._transceive(transceiver, params.codecs.length > 0, false); } }); } this.localDescription = { type: description.type, sdp: description.sdp }; switch (description.type) { case 'offer': this._updateSignalingState('have-local-offer'); break; case 'answer': this._updateSignalingState('stable'); break; default: throw new TypeError('unsupported type "' + description.type + '"'); } // If a success callback was provided, emit ICE candidates after it // has been executed. Otherwise, emit callback after the Promise is // resolved. var hasCallback = arguments.length > 1 && typeof arguments[1] === 'function'; if (hasCallback) { var cb = arguments[1]; window.setTimeout(function() { cb(); if (self.iceGatheringState === 'new') { self.iceGatheringState = 'gathering'; } self._emitBufferedCandidates(); }, 0); } var p = Promise.resolve(); p.then(function() { if (!hasCallback) { if (self.iceGatheringState === 'new') { self.iceGatheringState = 'gathering'; } // Usually candidates will be emitted earlier. window.setTimeout(self._emitBufferedCandidates.bind(self), 500); } }); return p; }; window.RTCPeerConnection.prototype.setRemoteDescription = function(description) { var self = this; var stream = new MediaStream(); var receiverList = []; var sections = SDPUtils.splitSections(description.sdp); var sessionpart = sections.shift(); var isIceLite = SDPUtils.matchPrefix(sessionpart, 'a=ice-lite').length > 0; this.usingBundle = SDPUtils.matchPrefix(sessionpart, 'a=group:BUNDLE ').length > 0; sections.forEach(function(mediaSection, sdpMLineIndex) { var lines = SDPUtils.splitLines(mediaSection); var mline = lines[0].substr(2).split(' '); var kind = mline[0]; var rejected = mline[1] === '0'; var direction = SDPUtils.getDirection(mediaSection, sessionpart); var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:'); if (mid.length) { mid = mid[0].substr(6); } else { mid = SDPUtils.generateIdentifier(); } // Reject datachannels which are not implemented yet. if (kind === 'application' && mline[2] === 'DTLS/SCTP') { self.transceivers[sdpMLineIndex] = { mid: mid, isDatachannel: true }; return; } var transceiver; var iceGatherer; var iceTransport; var dtlsTransport; var rtpSender; var rtpReceiver; var sendEncodingParameters; var recvEncodingParameters; var localCapabilities; var track; // FIXME: ensure the mediaSection has rtcp-mux set. var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection); var remoteIceParameters; var remoteDtlsParameters; if (!rejected) { remoteIceParameters = SDPUtils.getIceParameters(mediaSection, sessionpart); remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection, sessionpart); remoteDtlsParameters.role = 'client'; } recvEncodingParameters = SDPUtils.parseRtpEncodingParameters(mediaSection); var cname; // Gets the first SSRC. Note that with RTX there might be multiple // SSRCs. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:') .map(function(line) { return SDPUtils.parseSsrcMedia(line); }) .filter(function(obj) { return obj.attribute === 'cname'; })[0]; if (remoteSsrc) { cname = remoteSsrc.value; } var isComplete = SDPUtils.matchPrefix(mediaSection, 'a=end-of-candidates', sessionpart).length > 0; var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:') .map(function(cand) { return SDPUtils.parseCandidate(cand); }) .filter(function(cand) { return cand.component === '1'; }); if (description.type === 'offer' && !rejected) { var transports = self.usingBundle && sdpMLineIndex > 0 ? { iceGatherer: self.transceivers[0].iceGatherer, iceTransport: self.transceivers[0].iceTransport, dtlsTransport: self.transceivers[0].dtlsTransport } : self._createIceAndDtlsTransports(mid, sdpMLineIndex); if (isComplete) { transports.iceTransport.setRemoteCandidates(cands); } localCapabilities = RTCRtpReceiver.getCapabilities(kind); // filter RTX until additional stuff needed for RTX is implemented // in adapter.js localCapabilities.codecs = localCapabilities.codecs.filter( function(codec) { return codec.name !== 'rtx'; }); sendEncodingParameters = [{ ssrc: (2 * sdpMLineIndex + 2) * 1001 }]; rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind); track = rtpReceiver.track; receiverList.push([track, rtpReceiver]); // FIXME: not correct when there are multiple streams but that is // not currently supported in this shim. stream.addTrack(track); // FIXME: look at direction. if (self.localStreams.length > 0 && self.localStreams[0].getTracks().length >= sdpMLineIndex) { var localTrack; if (kind === 'audio') { localTrack = self.localStreams[0].getAudioTracks()[0]; } else if (kind === 'video') { localTrack = self.localStreams[0].getVideoTracks()[0]; } if (localTrack) { rtpSender = new RTCRtpSender(localTrack, transports.dtlsTransport); } } self.transceivers[sdpMLineIndex] = { iceGatherer: transports.iceGatherer, iceTransport: transports.iceTransport, dtlsTransport: transports.dtlsTransport, localCapabilities: localCapabilities, remoteCapabilities: remoteCapabilities, rtpSender: rtpSender, rtpReceiver: rtpReceiver, kind: kind, mid: mid, cname: cname, sendEncodingParameters: sendEncodingParameters, recvEncodingParameters: recvEncodingParameters }; // Start the RTCRtpReceiver now. The RTPSender is started in // setLocalDescription. self._transceive(self.transceivers[sdpMLineIndex], false, direction === 'sendrecv' || direction === 'sendonly'); } else if (description.type === 'answer' && !rejected) { transceiver = self.transceivers[sdpMLineIndex]; iceGatherer = transceiver.iceGatherer; iceTransport = transceiver.iceTransport; dtlsTransport = transceiver.dtlsTransport; rtpSender = transceiver.rtpSender; rtpReceiver = transceiver.rtpReceiver; sendEncodingParameters = transceiver.sendEncodingParameters; localCapabilities = transceiver.localCapabilities; self.transceivers[sdpMLineIndex].recvEncodingParameters = recvEncodingParameters; self.transceivers[sdpMLineIndex].remoteCapabilities = remoteCapabilities; self.transceivers[sdpMLineIndex].cname = cname; if ((isIceLite || isComplete) && cands.length) { iceTransport.setRemoteCandidates(cands); } if (!self.usingBundle || sdpMLineIndex === 0) { iceTransport.start(iceGatherer, remoteIceParameters, 'controlling'); dtlsTransport.start(remoteDtlsParameters); } self._transceive(transceiver, direction === 'sendrecv' || direction === 'recvonly', direction === 'sendrecv' || direction === 'sendonly'); if (rtpReceiver && (direction === 'sendrecv' || direction === 'sendonly')) { track = rtpReceiver.track; receiverList.push([track, rtpReceiver]); stream.addTrack(track); } else { // FIXME: actually the receiver should be created later. delete transceiver.rtpReceiver; } } }); this.remoteDescription = { type: description.type, sdp: description.sdp }; switch (description.type) { case 'offer': this._updateSignalingState('have-remote-offer'); break; case 'answer': this._updateSignalingState('stable'); break; default: throw new TypeError('unsupported type "' + description.type + '"'); } if (stream.getTracks().length) { self.remoteStreams.push(stream); window.setTimeout(function() { var event = new Event('addstream'); event.stream = stream; self.dispatchEvent(event); if (self.onaddstream !== null) { window.setTimeout(function() { self.onaddstream(event); }, 0); } receiverList.forEach(function(item) { var track = item[0]; var receiver = item[1]; var trackEvent = new Event('track'); trackEvent.track = track; trackEvent.receiver = receiver; trackEvent.streams = [stream]; self.dispatchEvent(event); if (self.ontrack !== null) { window.setTimeout(function() { self.ontrack(trackEvent); }, 0); } }); }, 0); } if (arguments.length > 1 && typeof arguments[1] === 'function') { window.setTimeout(arguments[1], 0); } return Promise.resolve(); }; window.RTCPeerConnection.prototype.close = function() { this.transceivers.forEach(function(transceiver) { /* not yet if (transceiver.iceGatherer) { transceiver.iceGatherer.close(); } */ if (transceiver.iceTransport) { transceiver.iceTransport.stop(); } if (transceiver.dtlsTransport) { transceiver.dtlsTransport.stop(); } if (transceiver.rtpSender) { transceiver.rtpSender.stop(); } if (transceiver.rtpReceiver) { transceiver.rtpReceiver.stop(); } }); // FIXME: clean up tracks, local streams, remote streams, etc this._updateSignalingState('closed'); }; // Update the signaling state. window.RTCPeerConnection.prototype._updateSignalingState = function(newState) { this.signalingState = newState; var event = new Event('signalingstatechange'); this.dispatchEvent(event); if (this.onsignalingstatechange !== null) { this.onsignalingstatechange(event); } }; // Determine whether to fire the negotiationneeded event. window.RTCPeerConnection.prototype._maybeFireNegotiationNeeded = function() { // Fire away (for now). var event = new Event('negotiationneeded'); this.dispatchEvent(event); if (this.onnegotiationneeded !== null) { this.onnegotiationneeded(event); } }; // Update the connection state. window.RTCPeerConnection.prototype._updateConnectionState = function() { var self = this; var newState; var states = { 'new': 0, closed: 0, connecting: 0, checking: 0, connected: 0, completed: 0, failed: 0 }; this.transceivers.forEach(function(transceiver) { states[transceiver.iceTransport.state]++; states[transceiver.dtlsTransport.state]++; }); // ICETransport.completed and connected are the same for this purpose. states.connected += states.completed; newState = 'new'; if (states.failed > 0) { newState = 'failed'; } else if (states.connecting > 0 || states.checking > 0) { newState = 'connecting'; } else if (states.disconnected > 0) { newState = 'disconnected'; } else if (states.new > 0) { newState = 'new'; } else if (states.connected > 0 || states.completed > 0) { newState = 'connected'; } if (newState !== self.iceConnectionState) { self.iceConnectionState = newState; var event = new Event('iceconnectionstatechange'); this.dispatchEvent(event); if (this.oniceconnectionstatechange !== null) { this.oniceconnectionstatechange(event); } } }; window.RTCPeerConnection.prototype.createOffer = function() { var self = this; if (this._pendingOffer) { throw new Error('createOffer called while there is a pending offer.'); } var offerOptions; if (arguments.length === 1 && typeof arguments[0] !== 'function') { offerOptions = arguments[0]; } else if (arguments.length === 3) { offerOptions = arguments[2]; } var tracks = []; var numAudioTracks = 0; var numVideoTracks = 0; // Default to sendrecv. if (this.localStreams.length) { numAudioTracks = this.localStreams[0].getAudioTracks().length; numVideoTracks = this.localStreams[0].getVideoTracks().length; } // Determine number of audio and video tracks we need to send/recv. if (offerOptions) { // Reject Chrome legacy constraints. if (offerOptions.mandatory || offerOptions.optional) { throw new TypeError( 'Legacy mandatory/optional constraints not supported.'); } if (offerOptions.offerToReceiveAudio !== undefined) { numAudioTracks = offerOptions.offerToReceiveAudio; } if (offerOptions.offerToReceiveVideo !== undefined) { numVideoTracks = offerOptions.offerToReceiveVideo; } } if (this.localStreams.length) { // Push local streams. this.localStreams[0].getTracks().forEach(function(track) { tracks.push({ kind: track.kind, track: track, wantReceive: track.kind === 'audio' ? numAudioTracks > 0 : numVideoTracks > 0 }); if (track.kind === 'audio') { numAudioTracks--; } else if (track.kind === 'video') { numVideoTracks--; } }); } // Create M-lines for recvonly streams. while (numAudioTracks > 0 || numVideoTracks > 0) { if (numAudioTracks > 0) { tracks.push({ kind: 'audio', wantReceive: true }); numAudioTracks--; } if (numVideoTracks > 0) { tracks.push({ kind: 'video', wantReceive: true }); numVideoTracks--; } } var sdp = SDPUtils.writeSessionBoilerplate(); var transceivers = []; tracks.forEach(function(mline, sdpMLineIndex) { // For each track, create an ice gatherer, ice transport, // dtls transport, potentially rtpsender and rtpreceiver. var track = mline.track; var kind = mline.kind; var mid = SDPUtils.generateIdentifier(); var transports = self.usingBundle && sdpMLineIndex > 0 ? { iceGatherer: transceivers[0].iceGatherer, iceTransport: transceivers[0].iceTransport, dtlsTransport: transceivers[0].dtlsTransport } : self._createIceAndDtlsTransports(mid, sdpMLineIndex); var localCapabilities = RTCRtpSender.getCapabilities(kind); // filter RTX until additional stuff needed for RTX is implemented // in adapter.js localCapabilities.codecs = localCapabilities.codecs.filter( function(codec) { return codec.name !== 'rtx'; }); localCapabilities.codecs.forEach(function(codec) { // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552 // by adding level-asymmetry-allowed=1 if (codec.name === 'H264' && codec.parameters['level-asymmetry-allowed'] === undefined) { codec.parameters['level-asymmetry-allowed'] = '1'; } }); var rtpSender; var rtpReceiver; // generate an ssrc now, to be used later in rtpSender.send var sendEncodingParameters = [{ ssrc: (2 * sdpMLineIndex + 1) * 1001 }]; if (track) { rtpSender = new RTCRtpSender(track, transports.dtlsTransport); } if (mline.wantReceive) { rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind); } transceivers[sdpMLineIndex] = { iceGatherer: transports.iceGatherer, iceTransport: transports.iceTransport, dtlsTransport: transports.dtlsTransport, localCapabilities: localCapabilities, remoteCapabilities: null, rtpSender: rtpSender, rtpReceiver: rtpReceiver, kind: kind, mid: mid, sendEncodingParameters: sendEncodingParameters, recvEncodingParameters: null }; }); if (this.usingBundle) { sdp += 'a=group:BUNDLE ' + transceivers.map(function(t) { return t.mid; }).join(' ') + '\r\n'; } tracks.forEach(function(mline, sdpMLineIndex) { var transceiver = transceivers[sdpMLineIndex]; sdp += SDPUtils.writeMediaSection(transceiver, transceiver.localCapabilities, 'offer', self.localStreams[0]); }); this._pendingOffer = transceivers; var desc = new RTCSessionDescription({ type: 'offer', sdp: sdp }); if (arguments.length && typeof arguments[0] === 'function') { window.setTimeout(arguments[0], 0, desc); } return Promise.resolve(desc); }; window.RTCPeerConnection.prototype.createAnswer = function() { var self = this; var sdp = SDPUtils.writeSessionBoilerplate(); if (this.usingBundle) { sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) { return t.mid; }).join(' ') + '\r\n'; } this.transceivers.forEach(function(transceiver) { if (transceiver.isDatachannel) { sdp += 'm=application 0 DTLS/SCTP 5000\r\n' + 'c=IN IP4 0.0.0.0\r\n' + 'a=mid:' + transceiver.mid + '\r\n'; return; } // Calculate intersection of capabilities. var commonCapabilities = self._getCommonCapabilities( transceiver.localCapabilities, transceiver.remoteCapabilities); sdp += SDPUtils.writeMediaSection(transceiver, commonCapabilities, 'answer', self.localStreams[0]); }); var desc = new RTCSessionDescription({ type: 'answer', sdp: sdp }); if (arguments.length && typeof arguments[0] === 'function') { window.setTimeout(arguments[0], 0, desc); } return Promise.resolve(desc); }; window.RTCPeerConnection.prototype.addIceCandidate = function(candidate) { if (!candidate) { this.transceivers.forEach(function(transceiver) { transceiver.iceTransport.addRemoteCandidate({}); }); } else { var mLineIndex = candidate.sdpMLineIndex; if (candidate.sdpMid) { for (var i = 0; i < this.transceivers.length; i++) { if (this.transceivers[i].mid === candidate.sdpMid) { mLineIndex = i; break; } } } var transceiver = this.transceivers[mLineIndex]; if (transceiver) { var cand = Object.keys(candidate.candidate).length > 0 ? SDPUtils.parseCandidate(candidate.candidate) : {}; // Ignore Chrome's invalid candidates since Edge does not like them. if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) { return; } // Ignore RTCP candidates, we assume RTCP-MUX. if (cand.component !== '1') { return; } // A dirty hack to make samples work. if (cand.type === 'endOfCandidates') { cand = {}; } transceiver.iceTransport.addRemoteCandidate(cand); // update the remoteDescription. var sections = SDPUtils.splitSections(this.remoteDescription.sdp); sections[mLineIndex + 1] += (cand.type ? candidate.candidate.trim() : 'a=end-of-candidates') + '\r\n'; this.remoteDescription.sdp = sections.join(''); } } if (arguments.length > 1 && typeof arguments[1] === 'function') { window.setTimeout(arguments[1], 0); } return Promise.resolve(); }; window.RTCPeerConnection.prototype.getStats = function() { var promises = []; this.transceivers.forEach(function(transceiver) { ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport', 'dtlsTransport'].forEach(function(method) { if (transceiver[method]) { promises.push(transceiver[method].getStats()); } }); }); var cb = arguments.length > 1 && typeof arguments[1] === 'function' && arguments[1]; return new Promise(function(resolve) { // shim getStats with maplike support var results = new Map(); Promise.all(promises).then(function(res) { res.forEach(function(result) { Object.keys(result).forEach(function(id) { results.set(id, result[id]); results[id] = result[id]; }); }); if (cb) { window.setTimeout(cb, 0, results); } resolve(results); }); }); }; } }; // Expose public methods. module.exports = { shimPeerConnection: edgeShim.shimPeerConnection, shimGetUserMedia: require('./getusermedia') }; },{"../utils":49,"./getusermedia":45,"sdp":40}],45:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; // Expose public methods. module.exports = function() { var shimError_ = function(e) { return { name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name, message: e.message, constraint: e.constraint, toString: function() { return this.name; } }; }; // getUserMedia error shim. var origGetUserMedia = navigator.mediaDevices.getUserMedia. bind(navigator.mediaDevices); navigator.mediaDevices.getUserMedia = function(c) { return origGetUserMedia(c).catch(function(e) { return Promise.reject(shimError_(e)); }); }; }; },{}],46:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var browserDetails = require('../utils').browserDetails; var firefoxShim = { shimOnTrack: function() { if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) { Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', { get: function() { return this._ontrack; }, set: function(f) { if (this._ontrack) { this.removeEventListener('track', this._ontrack); this.removeEventListener('addstream', this._ontrackpoly); } this.addEventListener('track', this._ontrack = f); this.addEventListener('addstream', this._ontrackpoly = function(e) { e.stream.getTracks().forEach(function(track) { var event = new Event('track'); event.track = track; event.receiver = {track: track}; event.streams = [e.stream]; this.dispatchEvent(event); }.bind(this)); }.bind(this)); } }); } }, shimSourceObject: function() { // Firefox has supported mozSrcObject since FF22, unprefixed in 42. if (typeof window === 'object') { if (window.HTMLMediaElement && !('srcObject' in window.HTMLMediaElement.prototype)) { // Shim the srcObject property, once, when HTMLMediaElement is found. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { get: function() { return this.mozSrcObject; }, set: function(stream) { this.mozSrcObject = stream; } }); } } }, shimPeerConnection: function() { if (typeof window !== 'object' || !(window.RTCPeerConnection || window.mozRTCPeerConnection)) { return; // probably media.peerconnection.enabled=false in about:config } // The RTCPeerConnection object. if (!window.RTCPeerConnection) { window.RTCPeerConnection = function(pcConfig, pcConstraints) { if (browserDetails.version < 38) { // .urls is not supported in FF < 38. // create RTCIceServers with a single url. if (pcConfig && pcConfig.iceServers) { var newIceServers = []; for (var i = 0; i < pcConfig.iceServers.length; i++) { var server = pcConfig.iceServers[i]; if (server.hasOwnProperty('urls')) { for (var j = 0; j < server.urls.length; j++) { var newServer = { url: server.urls[j] }; if (server.urls[j].indexOf('turn') === 0) { newServer.username = server.username; newServer.credential = server.credential; } newIceServers.push(newServer); } } else { newIceServers.push(pcConfig.iceServers[i]); } } pcConfig.iceServers = newIceServers; } } return new mozRTCPeerConnection(pcConfig, pcConstraints); }; window.RTCPeerConnection.prototype = mozRTCPeerConnection.prototype; // wrap static methods. Currently just generateCertificate. if (mozRTCPeerConnection.generateCertificate) { Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', { get: function() { return mozRTCPeerConnection.generateCertificate; } }); } window.RTCSessionDescription = mozRTCSessionDescription; window.RTCIceCandidate = mozRTCIceCandidate; } // shim away need for obsolete RTCIceCandidate/RTCSessionDescription. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] .forEach(function(method) { var nativeMethod = RTCPeerConnection.prototype[method]; RTCPeerConnection.prototype[method] = function() { arguments[0] = new ((method === 'addIceCandidate') ? RTCIceCandidate : RTCSessionDescription)(arguments[0]); return nativeMethod.apply(this, arguments); }; }); // support for addIceCandidate(null or undefined) var nativeAddIceCandidate = RTCPeerConnection.prototype.addIceCandidate; RTCPeerConnection.prototype.addIceCandidate = function() { if (!arguments[0]) { if (arguments[1]) { arguments[1].apply(null); } return Promise.resolve(); } return nativeAddIceCandidate.apply(this, arguments); }; if (browserDetails.version < 48) { // shim getStats with maplike support var makeMapStats = function(stats) { var map = new Map(); Object.keys(stats).forEach(function(key) { map.set(key, stats[key]); map[key] = stats[key]; }); return map; }; var nativeGetStats = RTCPeerConnection.prototype.getStats; RTCPeerConnection.prototype.getStats = function(selector, onSucc, onErr) { return nativeGetStats.apply(this, [selector || null]) .then(function(stats) { return makeMapStats(stats); }) .then(onSucc, onErr); }; } } }; // Expose public methods. module.exports = { shimOnTrack: firefoxShim.shimOnTrack, shimSourceObject: firefoxShim.shimSourceObject, shimPeerConnection: firefoxShim.shimPeerConnection, shimGetUserMedia: require('./getusermedia') }; },{"../utils":49,"./getusermedia":47}],47:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logging = require('../utils').log; var browserDetails = require('../utils').browserDetails; // Expose public methods. module.exports = function() { var shimError_ = function(e) { return { name: { SecurityError: 'NotAllowedError', PermissionDeniedError: 'NotAllowedError' }[e.name] || e.name, message: { 'The operation is insecure.': 'The request is not allowed by the ' + 'user agent or the platform in the current context.' }[e.message] || e.message, constraint: e.constraint, toString: function() { return this.name + (this.message && ': ') + this.message; } }; }; // getUserMedia constraints shim. var getUserMedia_ = function(constraints, onSuccess, onError) { var constraintsToFF37_ = function(c) { if (typeof c !== 'object' || c.require) { return c; } var require = []; Object.keys(c).forEach(function(key) { if (key === 'require' || key === 'advanced' || key === 'mediaSource') { return; } var r = c[key] = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; if (r.min !== undefined || r.max !== undefined || r.exact !== undefined) { require.push(key); } if (r.exact !== undefined) { if (typeof r.exact === 'number') { r. min = r.max = r.exact; } else { c[key] = r.exact; } delete r.exact; } if (r.ideal !== undefined) { c.advanced = c.advanced || []; var oc = {}; if (typeof r.ideal === 'number') { oc[key] = {min: r.ideal, max: r.ideal}; } else { oc[key] = r.ideal; } c.advanced.push(oc); delete r.ideal; if (!Object.keys(r).length) { delete c[key]; } } }); if (require.length) { c.require = require; } return c; }; constraints = JSON.parse(JSON.stringify(constraints)); if (browserDetails.version < 38) { logging('spec: ' + JSON.stringify(constraints)); if (constraints.audio) { constraints.audio = constraintsToFF37_(constraints.audio); } if (constraints.video) { constraints.video = constraintsToFF37_(constraints.video); } logging('ff37: ' + JSON.stringify(constraints)); } return navigator.mozGetUserMedia(constraints, onSuccess, function(e) { onError(shimError_(e)); }); }; // Returns the result of getUserMedia as a Promise. var getUserMediaPromise_ = function(constraints) { return new Promise(function(resolve, reject) { getUserMedia_(constraints, resolve, reject); }); }; // Shim for mediaDevices on older versions. if (!navigator.mediaDevices) { navigator.mediaDevices = {getUserMedia: getUserMediaPromise_, addEventListener: function() { }, removeEventListener: function() { } }; } navigator.mediaDevices.enumerateDevices = navigator.mediaDevices.enumerateDevices || function() { return new Promise(function(resolve) { var infos = [ {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''}, {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''} ]; resolve(infos); }); }; if (browserDetails.version < 41) { // Work around http://bugzil.la/1169665 var orgEnumerateDevices = navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices); navigator.mediaDevices.enumerateDevices = function() { return orgEnumerateDevices().then(undefined, function(e) { if (e.name === 'NotFoundError') { return []; } throw e; }); }; } if (browserDetails.version < 49) { var origGetUserMedia = navigator.mediaDevices.getUserMedia. bind(navigator.mediaDevices); navigator.mediaDevices.getUserMedia = function(c) { return origGetUserMedia(c).then(function(stream) { // Work around https://bugzil.la/802326 if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) { stream.getTracks().forEach(function(track) { track.stop(); }); throw new DOMException('The object can not be found here.', 'NotFoundError'); } return stream; }, function(e) { return Promise.reject(shimError_(e)); }); }; } navigator.getUserMedia = function(constraints, onSuccess, onError) { if (browserDetails.version < 44) { return getUserMedia_(constraints, onSuccess, onError); } // Replace Firefox 44+'s deprecation warning with unprefixed version. console.warn('navigator.getUserMedia has been replaced by ' + 'navigator.mediaDevices.getUserMedia'); navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError); }; }; },{"../utils":49}],48:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ 'use strict'; var safariShim = { // TODO: DrAlex, should be here, double check against LayoutTests // shimOnTrack: function() { }, // TODO: once the back-end for the mac port is done, add. // TODO: check for webkitGTK+ // shimPeerConnection: function() { }, shimGetUserMedia: function() { navigator.getUserMedia = navigator.webkitGetUserMedia; } }; // Expose public methods. module.exports = { shimGetUserMedia: safariShim.shimGetUserMedia // TODO // shimOnTrack: safariShim.shimOnTrack, // shimPeerConnection: safariShim.shimPeerConnection }; },{}],49:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logDisabled_ = true; // Utility methods. var utils = { disableLog: function(bool) { if (typeof bool !== 'boolean') { return new Error('Argument type: ' + typeof bool + '. Please use a boolean.'); } logDisabled_ = bool; return (bool) ? 'adapter.js logging disabled' : 'adapter.js logging enabled'; }, log: function() { if (typeof window === 'object') { if (logDisabled_) { return; } if (typeof console !== 'undefined' && typeof console.log === 'function') { console.log.apply(console, arguments); } } }, /** * Extract browser version out of the provided user agent string. * * @param {!string} uastring userAgent string. * @param {!string} expr Regular expression used as match criteria. * @param {!number} pos position in the version string to be returned. * @return {!number} browser version. */ extractVersion: function(uastring, expr, pos) { var match = uastring.match(expr); return match && match.length >= pos && parseInt(match[pos], 10); }, /** * Browser detector. * * @return {object} result containing browser and version * properties. */ detectBrowser: function() { // Returned result object. var result = {}; result.browser = null; result.version = null; // Fail early if it's not a browser if (typeof window === 'undefined' || !window.navigator) { result.browser = 'Not a browser.'; return result; } // Firefox. if (navigator.mozGetUserMedia) { result.browser = 'firefox'; result.version = this.extractVersion(navigator.userAgent, /Firefox\/([0-9]+)\./, 1); // all webkit-based browsers } else if (navigator.webkitGetUserMedia) { // Chrome, Chromium, Webview, Opera, all use the chrome shim for now if (window.webkitRTCPeerConnection) { result.browser = 'chrome'; result.version = this.extractVersion(navigator.userAgent, /Chrom(e|ium)\/([0-9]+)\./, 2); // Safari or unknown webkit-based // for the time being Safari has support for MediaStreams but not webRTC } else { // Safari UA substrings of interest for reference: // - webkit version: AppleWebKit/602.1.25 (also used in Op,Cr) // - safari UI version: Version/9.0.3 (unique to Safari) // - safari UI webkit version: Safari/601.4.4 (also used in Op,Cr) // // if the webkit version and safari UI webkit versions are equals, // ... this is a stable version. // // only the internal webkit version is important today to know if // media streams are supported // if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) { result.browser = 'safari'; result.version = this.extractVersion(navigator.userAgent, /AppleWebKit\/([0-9]+)\./, 1); // unknown webkit-based browser } else { result.browser = 'Unsupported webkit-based browser ' + 'with GUM support but no WebRTC support.'; return result; } } // Edge. } else if (navigator.mediaDevices && navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { result.browser = 'edge'; result.version = this.extractVersion(navigator.userAgent, /Edge\/(\d+).(\d+)$/, 2); // Default fallthrough: not supported. } else { result.browser = 'Not a supported browser.'; return result; } return result; } }; // Export. module.exports = { log: utils.log, disableLog: utils.disableLog, browserDetails: utils.detectBrowser(), extractVersion: utils.extractVersion }; },{}],50:[function(require,module,exports){ module.exports={ "name": "jssip", "title": "JsSIP", "description": "the Javascript SIP library", "version": "3.0.2", "homepage": "http://jssip.net", "author": "José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)", "contributors": [ "Iñaki Baz Castillo <ibc@aliax.net> (https://github.com/ibc)", "Saúl Ibarra Corretgé <saghul@gmail.com> (https://github.com/saghul)" ], "main": "lib/JsSIP.js", "keywords": [ "sip", "websocket", "webrtc", "node", "browser", "library" ], "license": "MIT", "repository": { "type": "git", "url": "https://github.com/versatica/JsSIP.git" }, "bugs": { "url": "https://github.com/versatica/JsSIP/issues" }, "dependencies": { "debug": "^2.3.3", "sdp-transform": "^1.6.2", "webrtc-adapter": "^2.0.8" }, "devDependencies": { "browserify": "^13.1.1", "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", "gulp-expect-file": "0.0.7", "gulp-header": "1.8.8", "gulp-jshint": "^2.0.4", "gulp-nodeunit-runner": "^0.2.2", "gulp-rename": "^1.2.2", "gulp-uglify": "^2.0.0", "gulp-util": "^3.0.7", "jshint": "^2.9.4", "jshint-stylish": "^2.2.1", "pegjs": "0.7.0", "vinyl-buffer": "^1.0.0", "vinyl-source-stream": "^1.1.0" }, "scripts": { "test": "gulp test" } } },{}]},{},[7])(7) });
tonytomov/cdnjs
ajax/libs/jssip/3.0.3/jssip.js
JavaScript
mit
798,200
var five = require("../lib/johnny-five.js"); var board = new five.Board(); board.on("ready", function() { var temperature = new five.Temperature({ controller: "MPL115A2" }); temperature.on("data", function() { console.log("temperature"); console.log(" celsius : ", this.celsius); console.log(" fahrenheit : ", this.fahrenheit); console.log(" kelvin : ", this.kelvin); console.log("--------------------------------------"); }); }); // @markdown // - [MPL115A2 - I2C Barometric Pressure/Temperature Sensor](https://www.adafruit.com/product/992) // @markdown
manorius/printing_with_node
node_modules/johnny-five/eg/temperature-mpl115a2.js
JavaScript
mit
607
<?php /** * @package Joomla.Site * @subpackage com_content * * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; JHtml::addIncludePath(JPATH_COMPONENT.'/helpers'); ?> <section class="category-list <?php echo strtolower($this->pageclass_sfx);?>"> <?php if ($this->params->get('show_page_heading')) : ?> <h1> <?php echo $this->escape($this->params->get('page_heading')); ?> </h1> <?php endif; ?> <?php if ($this->params->get('show_category_title', 1) or $this->params->get('page_subheading')) : ?> <h2> <?php echo $this->escape($this->params->get('page_subheading')); ?> <?php if ($this->params->get('show_category_title')) : ?> <span class="subheading-category"><?php echo $this->category->title;?></span> <?php endif; ?> </h2> <?php endif; ?> <?php if ($this->params->get('show_description', 1) || $this->params->def('show_description_image', 1)) : ?> <section class="category-desc"> <?php if ($this->params->get('show_description_image') && $this->category->getParams()->get('image')) : ?> <img src="<?php echo $this->category->getParams()->get('image'); ?>" alt="<?php echo $this->category->title;?>" /> <?php endif; ?> <?php if ($this->params->get('show_description') && $this->category->description) : ?> <?php echo JHtml::_('content.prepare', $this->category->description); ?> <?php endif; ?> </section> <?php endif; ?> <section class="cat-items"> <?php echo $this->loadTemplate('articles'); ?> </section> <?php if (!empty($this->children[$this->category->id])&& $this->maxLevel != 0) : ?> <?php echo $this->loadTemplate('children'); ?> <?php endif; ?> </section>
baxri/cvote
tmp/install_54bd2998c811f/plugins/system/helix/html/com_content/category/default.php
PHP
gpl-2.0
1,779
<?php /* ---------------------------------------------------------------------- * views/administrate/setup/list_item_editor_delete_html.php : * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2008-2011 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * ---------------------------------------------------------------------- */ $t_item = $this->getVar('t_subject'); $vn_type_id = $this->getVar('subject_id'); ?> <div class="sectionBox"> <?php if (!$this->getVar('confirmed')) { // show delete confirmation notice print caDeleteWarningBox($this->request, $t_item, $this->getVar('subject_name'), 'administrate/setup/relationship_type_editor', 'RelationshipTypeEditor', 'Edit/'.$this->request->getActionExtra(), array('type_id' => $vn_type_id)); } ?> </div>
leigh-moulder/providence-theme-dunes
views/administrate/setup/relationship_type_editor/delete_html.php
PHP
gpl-2.0
1,649
<?php /* * Fields and groups functions * * $HeadURL: http://plugins.svn.wordpress.org/types/tags/1.6.4/includes/fields.php $ * $LastChangedDate: 2014-11-18 06:47:25 +0000 (Tue, 18 Nov 2014) $ * $LastChangedRevision: 1027712 $ * $LastChangedBy: iworks $ * */ require_once WPCF_EMBEDDED_INC_ABSPATH . '/fields.php'; /** * Gets post_types supported by specific group. * * @global type $wpdb * @param type $group_id * @return type */ function wpcf_admin_get_post_types_by_group( $group_id ) { $post_types = get_post_meta( $group_id, '_wp_types_group_post_types', true ); if ( $post_types == 'all' ) { return array(); } $post_types = explode( ',', trim( $post_types, ',' ) ); return $post_types; } /** * Gets taxonomies supported by specific group. * * @global type $wpdb * @param type $group_id * @return type */ function wpcf_admin_get_taxonomies_by_group( $group_id ) { global $wpdb; $terms = get_post_meta( $group_id, '_wp_types_group_terms', true ); if ( $terms == 'all' ) { return array(); } $terms = explode( ',', trim( $terms, ',' ) ); $taxonomies = array(); if ( !empty( $terms ) ) { foreach ( $terms as $term ) { $term = $wpdb->get_row( "SELECT tt.term_taxonomy_id, tt.taxonomy, t.term_id, t.slug, t.name FROM {$wpdb->prefix}term_taxonomy tt JOIN {$wpdb->prefix}terms t WHERE t.term_id = tt.term_id AND tt.term_taxonomy_id=" . intval( $term ), ARRAY_A ); if ( !empty( $term ) ) { $taxonomies[$term['taxonomy']][$term['term_taxonomy_id']] = $term; } } } else { return array(); } return $taxonomies; } /** * Gets templates supported by specific group. * * @global type $wpdb * @param type $group_id * @return type */ function wpcf_admin_get_templates_by_group( $group_id ) { global $wpdb; $data = get_post_meta( $group_id, '_wp_types_group_templates', true ); if ( $data == 'all' ) { return array(); } $data = explode( ',', trim( $data, ',' ) ); $templates = get_page_templates(); $templates[] = 'default'; $templates_views = get_posts( 'post_type=view-template&numberposts=-1&status=publish' ); foreach ( $templates_views as $template_view ) { $templates[] = $template_view->ID; } $result = array(); if ( !empty( $data ) ) { foreach ( $templates as $template ) { if ( in_array( $template, $data ) ) { $result[] = $template; } } } return $result; } /** * Activates group. * Modified by Gen, 13.02.2013 * * @global type $wpdb * @param type $group_id * @return type */ function wpcf_admin_fields_activate_group( $group_id, $post_type = 'wp-types-group' ) { global $wpdb; return $wpdb->update( $wpdb->posts, array('post_status' => 'publish'), array('ID' => intval( $group_id ), 'post_type' => $post_type), array('%s'), array('%d', '%s') ); } /** * Deactivates group. * Modified by Gen, 13.02.2013 * * @global type $wpdb * @param type $group_id * @return type */ function wpcf_admin_fields_deactivate_group( $group_id, $post_type = 'wp-types-group' ) { global $wpdb; return $wpdb->update( $wpdb->posts, array('post_status' => 'draft'), array('ID' => intval( $group_id ), 'post_type' => $post_type), array('%s'), array('%d', '%s') ); } /** * Removes specific field from group. * * @global type $wpdb * @global type $wpdb * @param type $group_id * @param type $field_id * @return type */ function wpcf_admin_fields_remove_field_from_group( $group_id, $field_id ) { $group_fields = get_post_meta( $group_id, '_wp_types_group_fields', true ); if ( empty( $group_fields ) ) { return false; } $group_fields = str_replace( ',' . $field_id . ',', ',', $group_fields ); update_post_meta( $group_id, '_wp_types_group_fields', $group_fields ); } /** * Bulk removal * * @param type $group_id * @param type $fields * @return type */ function wpcf_admin_fields_remove_field_from_group_bulk( $group_id, $fields ) { foreach ( $fields as $field_id ) { wpcf_admin_fields_remove_field_from_group( $group_id, $field_id ); } } /** * Deletes field. * Modified by Gen, 13.02.2013 * * @param type $field_id */ function wpcf_admin_fields_delete_field( $field_id, $post_type = 'wp-types-group', $meta_name = 'wpcf-fields' ) { global $wpdb; $fields = get_option( $meta_name, array() ); if ( isset( $fields[$field_id] ) ) { // Remove from groups $groups = wpcf_admin_fields_get_groups( $post_type ); foreach ( $groups as $key => $group ) { wpcf_admin_fields_remove_field_from_group( $group['id'], $field_id ); } // Remove from posts if ( !wpcf_types_cf_under_control( 'check_outsider', $field_id, $post_type, $meta_name ) ) { $results = $wpdb->get_results( "SELECT post_id, meta_key FROM $wpdb->postmeta WHERE meta_key = '" . wpcf_types_get_meta_prefix( $fields[$field_id] ) . strval( $field_id ) . "'" ); foreach ( $results as $result ) { delete_post_meta( $result->post_id, $result->meta_key ); } } unset( $fields[$field_id] ); wpcf_admin_fields_save_fields( $fields, true, $meta_name ); return true; } else { return false; } } /** * Deletes group by ID. * Modified by Gen, 13.02.2013 * * @global type $wpdb * @param type $group_id * @return type */ function wpcf_admin_fields_delete_group( $group_id, $post_type = 'wp-types-group' ) { $group = get_post( $group_id ); if ( empty( $group ) || $group->post_type != $post_type ) { return false; } wp_delete_post( $group_id, true ); } /** * Saves group. * Modified by Gen, 13.02.2013 * * @param type $group * @return type */ function wpcf_admin_fields_save_group( $group, $post_type = 'wp-types-group' ) { if ( !isset( $group['name'] ) ) { return false; } $post = array( 'post_status' => 'publish', 'post_type' => $post_type, 'post_title' => $group['name'], 'post_name' => $group['name'], 'post_content' => !empty( $group['description'] ) ? $group['description'] : '', ); $update = false; if ( isset( $group['id'] ) ) { $update = true; $post_to_update = get_post( $group['id'] ); if ( empty( $post_to_update ) || $post_to_update->post_type != $post_type ) { return false; } $post['ID'] = $post_to_update->ID; $post['post_status'] = $post_to_update->post_status; } if ( $update ) { $group_id = wp_update_post( $post ); if ( !$group_id ) { return false; } } else { $group_id = wp_insert_post( $post, true ); if ( is_wp_error( $group_id ) ) { return false; } } if ( !empty( $group['filters_association'] ) ) { update_post_meta( $group_id, '_wp_types_group_filters_association', $group['filters_association'] ); } else { delete_post_meta( $group_id, '_wp_types_group_filters_association' ); } // WPML register strings if ( function_exists( 'icl_register_string' ) ) { wpcf_translate_register_string( 'plugin Types', 'group ' . $group_id . ' name', $group['name'] ); wpcf_translate_register_string( 'plugin Types', 'group ' . $group_id . ' description', $group['description'] ); } return $group_id; } /** * Saves all fields. * Modified by Gen, 13.02.2013 * * @param type $fields */ function wpcf_admin_fields_save_fields( $fields, $forced = false, $option_name = 'wpcf-fields' ) { $original = get_option( $option_name, array() ); if ( !$forced ) { $fields = array_merge( $original, $fields ); } update_option( $option_name, $fields ); } /** * Saves field. * Modified by Gen, 13.02.2013 * * @param type $field * @return type */ function wpcf_admin_fields_save_field( $field, $post_type = 'wp-types-group', $meta_name = 'wpcf-fields' ) { if ( !isset( $field['name'] ) || !isset( $field['type'] ) ) { return new WP_Error( 'wpcf_save_field_no_name_or_type', __( "Error saving field", 'wpcf' ) ); } $field = wpcf_sanitize_field( $field ); if ( empty( $field['name'] ) || empty( $field['slug'] ) ) { return new WP_Error( 'wpcf_save_field_no_name', __( "Please set name for field", 'wpcf' ) ); } $field['id'] = $field['slug']; // Set field specific data // NOTE: This was $field['data'] = $field and seemed to work on most systems. // I changed it to asign via a temporary variable to fix on one system. $temp_field = $field; $field['data'] = $temp_field; // Unset default fields unset( $field['data']['type'], $field['data']['slug'], $field['data']['name'], $field['data']['description'], $field['data']['user_id'], $field['data']['id'], $field['data']['data'] ); // Merge previous data (added because of outside fields) // @TODO Remember why if ( wpcf_types_cf_under_control( 'check_outsider', $field['id'], $post_type, $meta_name ) ) { $field_previous_data = wpcf_admin_fields_get_field( $field['id'], false, true, false, $meta_name ); if ( !empty( $field_previous_data['data'] ) ) { $field['data'] = array_merge( $field_previous_data['data'], $field['data'] ); } } $field['data'] = apply_filters( 'wpcf_fields_' . $field['type'] . '_meta_data', $field['data'], $field ); // Check validation if ( isset( $field['data']['validate'] ) ) { foreach ( $field['data']['validate'] as $method => $data ) { if ( !isset( $data['active'] ) ) { unset( $field['data']['validate'][$method] ); } } if ( empty( $field['data']['validate'] ) ) { unset( $field['data']['validate'] ); } } $save_data = array(); $save_data['id'] = $field['id']; $save_data['slug'] = $field['slug']; $save_data['type'] = $field['type']; $save_data['name'] = $field['name']; $save_data['description'] = $field['description']; $save_data['data'] = $field['data']; $save_data['data']['disabled_by_type'] = 0; // For radios or select if ( !empty( $field['data']['options'] ) ) { foreach ( $field['data']['options'] as $name => $option ) { if ( isset( $option['title'] ) ) { $option['title'] = $field['data']['options'][$name]['title'] = htmlspecialchars_decode( $option['title'] ); } if ( isset( $option['value'] ) ) { $option['value'] = $field['data']['options'][$name]['value'] = htmlspecialchars_decode( $option['value'] ); } if ( isset( $option['display_value'] ) ) { $option['display_value'] = $field['data']['options'][$name]['display_value'] = htmlspecialchars_decode( $option['display_value'] ); } // For checkboxes if ( $field['type'] == 'checkboxes' && isset( $option['set_value'] ) && $option['set_value'] != '1' ) { $option['set_value'] = $field['data']['options'][$name]['set_value'] = htmlspecialchars_decode( $option['set_value'] ); } if ( $field['type'] == 'checkboxes' && !empty( $option['display_value_selected'] ) ) { $option['display_value_selected'] = $field['data']['options'][$name]['display_value_selected'] = htmlspecialchars_decode( $option['display_value_selected'] ); } if ( $field['type'] == 'checkboxes' && !empty( $option['display_value_not_selected'] ) ) { $option['display_value_not_selected'] = $field['data']['options'][$name]['display_value_not_selected'] = htmlspecialchars_decode( $option['display_value_not_selected'] ); } } } // For checkboxes if ( $field['type'] == 'checkbox' && $field['set_value'] != '1' ) { $field['set_value'] = htmlspecialchars_decode( $field['set_value'] ); } if ( $field['type'] == 'checkbox' && !empty( $field['display_value_selected'] ) ) { $field['display_value_selected'] = htmlspecialchars_decode( $field['display_value_selected'] ); } if ( $field['type'] == 'checkbox' && !empty( $field['display_value_not_selected'] ) ) { $field['display_value_not_selected'] = htmlspecialchars_decode( $field['display_value_not_selected'] ); } // Save field $fields = get_option( $meta_name, array() ); $fields[$field['slug']] = $save_data; update_option( $meta_name, $fields ); $field_id = $field['slug']; // WPML register strings if ( function_exists( 'icl_register_string' ) ) { if ( isset($_POST['wpml_cf_translation_preferences'][$field_id] ) ) { $__wpml_action = intval( $_POST['wpml_cf_translation_preferences'][$field_id] ); } else { $__wpml_action = wpcf_wpml_get_action_by_type( $field['type'] ); } wpcf_translate_register_string( 'plugin Types', 'field ' . $field_id . ' name', $field['name'] ); wpcf_translate_register_string( 'plugin Types', 'field ' . $field_id . ' description', $field['description'] ); // For radios or select if ( !empty( $field['data']['options'] ) ) { foreach ( $field['data']['options'] as $name => $option ) { if ( $name == 'default' ) { continue; } if ( isset( $option['title'] ) ) { wpcf_translate_register_string( 'plugin Types', 'field ' . $field_id . ' option ' . $name . ' title', $option['title'] ); } if ($__wpml_action === 2) { if ( isset( $option['value'] ) ) { wpcf_translate_register_string( 'plugin Types', 'field ' . $field_id . ' option ' . $name . ' value', $option['value'] ); } } if ( isset( $option['display_value'] ) ) { wpcf_translate_register_string( 'plugin Types', 'field ' . $field_id . ' option ' . $name . ' display value', $option['display_value'] ); } // For checkboxes if ( isset( $option['set_value'] ) && $option['set_value'] != '1' ) { wpcf_translate_register_string( 'plugin Types', 'field ' . $field_id . ' option ' . $name . ' value', $option['set_value'] ); } if ( !empty( $option['display_value_selected'] ) ) { wpcf_translate_register_string( 'plugin Types', 'field ' . $field_id . ' option ' . $name . ' display value selected', $option['display_value_selected'] ); } if ( !empty( $option['display_value_not_selected'] ) ) { wpcf_translate_register_string( 'plugin Types', 'field ' . $field_id . ' option ' . $name . ' display value not selected', $option['display_value_not_selected'] ); } } } if ( $field['type'] == 'checkbox' && $field['set_value'] != '1' ) { // we need to translate the check box value to store wpcf_translate_register_string( 'plugin Types', 'field ' . $field_id . ' checkbox value', $field['set_value'] ); } if ( $field['type'] == 'checkbox' && !empty( $field['display_value_selected'] ) ) { // we need to translate the check box value to store wpcf_translate_register_string( 'plugin Types', 'field ' . $field_id . ' checkbox value selected', $field['display_value_selected'] ); } if ( $field['type'] == 'checkbox' && !empty( $field['display_value_not_selected'] ) ) { // we need to translate the check box value to store wpcf_translate_register_string( 'plugin Types', 'field ' . $field_id . ' checkbox value not selected', $field['display_value_not_selected'] ); } // Validation message if ( !empty( $field['data']['validate'] ) ) { foreach ( $field['data']['validate'] as $method => $validation ) { if ( !empty( $validation['message'] ) ) { // Skip if it's same as default $default_message = wpcf_admin_validation_messages( $method ); if ( $validation['message'] != $default_message ) { wpcf_translate_register_string( 'plugin Types', 'field ' . $field_id . ' validation message ' . $method, $validation['message'] ); } } } } } return $field_id; } /** * Changes field type. * Modified by Gen, 13.02.2013 * * @param type $fields * @param type $type */ function wpcf_admin_custom_fields_change_type( $fields, $type, $post_type = 'wp-types-group', $meta_name = 'wpcf-fields' ) { if ( !is_array( $fields ) ) { $fields = array(strval( $fields )); } $fields = wpcf_types_cf_under_control( 'add', array('fields' => $fields, 'type' => $type), $post_type, $meta_name ); $allowed = array( 'audio' => array('wysiwyg', 'url', 'textarea', 'textfield', 'email', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'textfield' => array('wysiwyg', 'textfield', 'textarea', 'email', 'url', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'textarea' => array('wysiwyg', 'textfield', 'textarea', 'email', 'url', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'date' => array('wysiwyg', 'date', 'textarea', 'textfield', 'email', 'url', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'email' => array('wysiwyg', 'email', 'textarea', 'textfield', 'date', 'url', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'embed' => array('wysiwyg', 'url', 'textarea', 'textfield', 'email', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'file' => array('wysiwyg', 'file', 'textarea', 'textfield', 'email', 'url', 'phone', 'fdate', 'image', 'numeric', 'audio', 'video', 'embed'), 'image' => array('wysiwyg', 'image', 'textarea', 'textfield', 'email', 'url', 'phone', 'file', 'idate', 'numeric', 'audio', 'video', 'embed'), 'numeric' => array('wysiwyg', 'numeric', 'textarea', 'textfield', 'email', 'url', 'phone', 'file', 'image', 'date', 'audio', 'video', 'embed'), 'phone' => array('wysiwyg', 'phone', 'textarea', 'textfield', 'email', 'url', 'date', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'select' => array('wysiwyg', 'select', 'textarea', 'textfield', 'date', 'email', 'url', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'skype' => array('wysiwyg', 'skype', 'textarea', 'textfield', 'date', 'email', 'url', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'url' => array('wysiwyg', 'url', 'textarea', 'textfield', 'email', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'checkbox' => array('wysiwyg', 'checkbox', 'textarea', 'textfield', 'email', 'url', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'radio' => array('wysiwyg', 'radio', 'textarea', 'textfield', 'email', 'url', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'video' => array('wysiwyg', 'url', 'textarea', 'textfield', 'email', 'date', 'phone', 'file', 'image', 'numeric', 'audio', 'video', 'embed'), 'wysiwyg' => array('wysiwyg', 'textarea'), ); $all_fields = wpcf_admin_fields_get_fields( false, false, false, $meta_name ); foreach ( $fields as $field_id ) { if ( !isset( $all_fields[$field_id] ) ) { continue; } $field = $all_fields[$field_id]; if ( !in_array( $type, $allowed[$field['type']] ) ) { wpcf_admin_message_store( sprintf( __( 'Field "%s" type was converted from %s to %s. You need to set some further settings in the group editor.', 'wpcf' ), $field['name'], $field['type'], $type ) ); $all_fields[$field_id]['data']['disabled_by_type'] = 1; } else { $all_fields[$field_id]['data']['disabled'] = 0; $all_fields[$field_id]['data']['disabled_by_type'] = 0; } if ( $field['type'] == 'numeric' && isset( $all_fields[$field_id]['data']['validate']['number'] ) ) { unset( $all_fields[$field_id]['data']['validate']['number'] ); } else if ( $type == 'numeric' ) { $all_fields[$field_id]['data']['validate'] = array('number' => array( 'active' => true, 'message' => __('Please enter numeric data', 'wpcf'))); } $all_fields[$field_id]['type'] = $type; } update_option( $meta_name, $all_fields ); } /** * Saves group's fields. * Modified by Gen, 13.02.2013 * * @global type $wpdb * @param type $group_id * @param type $fields */ function wpcf_admin_fields_save_group_fields( $group_id, $fields, $add = false, $post_type = 'wp-types-group' ) { $meta_name = ($post_type == 'wp-types-group' ? 'wpcf-fields' : 'wpcf-usermeta'); $fields = wpcf_types_cf_under_control( 'add', array('fields' => $fields), $post_type, $meta_name ); if ( $add ) { $existing_fields = wpcf_admin_fields_get_fields_by_group( $group_id, 'slug', false, true, false, $post_type, $meta_name ); $order = array(); if ( !empty( $existing_fields ) ) { foreach ( $existing_fields as $field_id => $field ) { if ( in_array( $field['id'], $fields ) ) { continue; } $order[] = $field['id']; } foreach ( $fields as $field ) { $order[] = $field; } $fields = $order; } } if ( empty( $fields ) ) { delete_post_meta( $group_id, '_wp_types_group_fields' ); return false; } $fields = ',' . implode( ',', (array) $fields ) . ','; update_post_meta( $group_id, '_wp_types_group_fields', $fields ); } /** * Saves group's post types. * * @global type $wpdb * @param type $group_id * @param type $post_types */ function wpcf_admin_fields_save_group_post_types( $group_id, $post_types ) { if ( empty( $post_types ) ) { update_post_meta( $group_id, '_wp_types_group_post_types', 'all' ); return true; } $post_types = ',' . implode( ',', (array) $post_types ) . ','; update_post_meta( $group_id, '_wp_types_group_post_types', $post_types ); } /** * Saves group's terms. * * @global type $wpdb * @param type $group_id * @param type $terms */ function wpcf_admin_fields_save_group_terms( $group_id, $terms ) { if ( empty( $terms ) ) { update_post_meta( $group_id, '_wp_types_group_terms', 'all' ); return true; } $terms = ',' . implode( ',', (array) $terms ) . ','; update_post_meta( $group_id, '_wp_types_group_terms', $terms ); } /** * Saves group's templates. * * @global type $wpdb * @param type $group_id * @param type $terms */ function wpcf_admin_fields_save_group_templates( $group_id, $templates ) { if ( empty( $templates ) ) { update_post_meta( $group_id, '_wp_types_group_templates', 'all' ); return true; } $templates = ',' . implode( ',', (array) $templates ) . ','; update_post_meta( $group_id, '_wp_types_group_templates', $templates ); } /** * Returns HTML formatted AJAX activation link. * * @param type $group_id * @return type */ function wpcf_admin_fields_get_ajax_activation_link( $group_id ) { return '<a href="' . admin_url( 'admin-ajax.php?action=wpcf_ajax&amp;' . 'wpcf_action=activate_group&amp;group_id=' . $group_id . '&amp;wpcf_ajax_update=wpcf_list_ajax_response_' . $group_id ) . '&amp;_wpnonce=' . wp_create_nonce( 'activate_group' ) . '" class="wpcf-ajax-link" id="wpcf-list-activate-' . $group_id . '">' . __( 'Activate', 'wpcf' ) . '</a>'; } /** * Returns HTML formatted AJAX deactivation link. * @param type $group_id * @return type */ function wpcf_admin_fields_get_ajax_deactivation_link( $group_id ) { return '<a href="' . admin_url( 'admin-ajax.php?action=wpcf_ajax&amp;' . 'wpcf_action=deactivate_group&amp;group_id=' . $group_id . '&amp;wpcf_ajax_update=wpcf_list_ajax_response_' . $group_id ) . '&amp;_wpnonce=' . wp_create_nonce( 'deactivate_group' ) . '" class="wpcf-ajax-link" id="wpcf-list-activate-' . $group_id . '">' . __( 'Deactivate', 'wpcf' ) . '</a>'; } /** * Check how many posts needs checkbox update. * * @param type $field * @param type $action * @return boolean|int */ function wpcf_admin_fields_checkbox_migrate_empty_check( $field, $action ) { if ( $field['type'] != 'checkbox' ) { return false; } if ($field['meta_type'] == 'postmeta') { $filter = wpcf_admin_fields_get_filter_by_field( $field['id'] ); if ( !empty( $filter ) ) { $posts = array(); $meta_key = wpcf_types_get_meta_prefix( $field ) . $field['id']; $meta_query = ''; if ( $action == 'do_not_save_check' ) { $meta_query = "(m.meta_key = '$meta_key' AND m.meta_value = '0')"; $posts = wpcf_admin_fields_get_posts_by_filter( $filter, $meta_query ); } else if ( $action == 'save_check' ) { $posts = wpcf_admin_fields_get_posts_by_filter_missing_meta( $filter, $meta_key ); } $option = get_option( 'wpcf_checkbox_migration', array() ); $cache_key = $action == 'do_not_save_check' ? 'do_not_save' : 'save'; $option[$cache_key] = $posts; update_option( 'wpcf_checkbox_migration', $option ); return $posts; } } else if ($field['meta_type'] == 'usermeta') { $option = get_option( 'wpcf_checkbox_migration_usermeta', array() ); $cache_key = $action == 'do_not_save_check' ? 'do_not_save' : 'save'; if ( $action == 'do_not_save_check' ) { $user_query = new WP_User_Query( array('meta_key' => $field['meta_key'], 'meta_value' => '0', 'meta_compare' => '=', 'fields' => 'ID') ); $r = $user_query->results; } else if ( $action == 'save_check' ) { global $wpdb; $_query = "SELECT u.ID FROM {$wpdb->users} u WHERE NOT EXISTS (SELECT um.user_id FROM {$wpdb->usermeta} um WHERE u.ID = um.user_id AND um.meta_key = '%s')"; $r = $wpdb->get_col($wpdb->prepare( $_query, $field['meta_key']) ); } $option[$field['meta_key']][$cache_key] = $r; update_option( 'wpcf_checkbox_migration_usermeta', $option ); return $r; } return false; } /** * Update posts checkboxes fields. * * @param type $field * @param type $action * @return boolean|int */ function wpcf_admin_fields_checkbox_migrate_empty( $field, $action ) { if ( $field['type'] != 'checkbox' ) { return false; } if ( $field['meta_type'] == 'usermeta' ) { $option = get_option( 'wpcf_checkbox_migration_usermeta', array() ); if ( empty( $option[$field['meta_key']][$action] ) ) { $users = wpcf_admin_fields_checkbox_migrate_empty_check( $field, $action . '_check' ); } else { $users = $option[$field['meta_key']][$action]; } if ( !empty( $users ) ) { if ( $action == 'do_not_save' ) { $count = 0; foreach ( $users as $temp_key => $user_id ) { if ( $count == 1000 ) { $option[$field['meta_key']][$action] = $users; update_option( 'wpcf_checkbox_migration', $option ); $data = array('offset' => $temp_key); return $data; } delete_user_meta( $user_id, $field['meta_key'], 0 ); unset( $users[$temp_key] ); $count++; } unset( $option[$field['meta_key']][$action] ); update_option( 'wpcf_checkbox_migration_usermeta', $option ); return $users; } else if ( $action == 'save' ) { $count = 0; foreach ( $users as $temp_key => $user_id ) { if ( $count == 1000 ) { $option[$field['meta_key']][$action] = $users; update_option( 'wpcf_checkbox_migration_usermeta', $option ); $data = array('offset' => $temp_key); return $data; } update_user_meta( $user_id, $field['meta_key'], 0 ); unset( $users[$temp_key] ); $count++; } unset( $option[$field['meta_key']][$action] ); update_option( 'wpcf_checkbox_migration_usermeta', $option ); return $users; } } return false; } $option = get_option( 'wpcf_checkbox_migration', array() ); $meta_key = wpcf_types_get_meta_prefix( $field ) . $field['id']; if ( empty( $option[$action] ) ) { $posts = wpcf_admin_fields_checkbox_migrate_empty_check( $field, $action . '_check' ); } else { $posts = $option[$action]; } if ( !empty( $posts ) ) { if ( $action == 'do_not_save' ) { $count = 0; foreach ( $posts as $temp_key => $post_id ) { if ( $count == 1000 ) { $option[$action] = $posts; update_option( 'wpcf_checkbox_migration', $option ); $data = array('offset' => $temp_key); return $data; } delete_post_meta( $post_id, $meta_key, 0 ); unset( $posts[$temp_key] ); $count++; } unset( $option[$action] ); update_option( 'wpcf_checkbox_migration', $option ); return $posts; } else if ( $action == 'save' ) { $count = 0; foreach ( $posts as $temp_key => $post_id ) { if ( $count == 1000 ) { $option[$action] = $posts; update_option( 'wpcf_checkbox_migration', $option ); $data = array('offset' => $temp_key); return $data; } update_post_meta( $post_id, $meta_key, 0 ); unset( $posts[$temp_key] ); $count++; } unset( $option[$action] ); update_option( 'wpcf_checkbox_migration', $option ); return $posts; } } return false; } /** * Gets all filters required for field to be used. * * @param type $field * @return boolean|string */ function wpcf_admin_fields_get_filter_by_field( $field ) { $field = wpcf_admin_fields_get_field( $field ); if ( empty( $field ) ) { return false; } $filter = array(); $filter['types'] = array(); $filter['terms'] = array(); $filter['templates'] = array(); $groups = wpcf_admin_fields_get_groups_by_field( $field['id'] ); foreach ( $groups as $group_id => $group_data ) { // Get filters $filter['types'] = array_merge( $filter['types'], explode( ',', trim( get_post_meta( $group_id, '_wp_types_group_post_types', true ), ',' ) ) ); $filter['terms'] = array_merge( $filter['terms'], explode( ',', trim( get_post_meta( $group_id, '_wp_types_group_terms', true ), ',' ) ) ); $filter['templates'] = array_merge( $filter['templates'], explode( ',', trim( get_post_meta( $group_id, '_wp_types_group_templates', true ), ',' ) ) ); $filter['association'] = isset( $group_data['filters_association'] ) && $group_data['filters_association'] == 'any' ? 'OR' : 'AND'; } if ( in_array( 'all', $filter['types'] ) ) { $filter['types'] = 'all'; } if ( in_array( 'all', $filter['terms'] ) ) { $filter['terms'] = 'all'; } if ( in_array( 'all', $filter['templates'] ) ) { $filter['templates'] = 'all'; } return $filter; } /** * Gets posts by filter fetched with wpcf_admin_fields_get_filter_by_field(). * * @global type $wpdb * @param type $filter * @return type */ function wpcf_admin_fields_get_posts_by_filter( $filter, $meta_query = '' ) { global $wpdb, $wpcf; $query = array(); $join = array(); if ( $filter['types'] != 'all' && !empty( $filter['types'] ) ) { $query[] = 'p.post_type IN (\'' . implode( '\',\'', $filter['types'] ) . '\')'; } else { $post_types = get_post_types( array('show_ui' => true), 'names' ); foreach ( $post_types as $post_type_slug => $post_type ) { if ( in_array( $post_type_slug, $wpcf->excluded_post_types ) ) { unset( $post_types[$post_type_slug] ); } } $query[] = 'p.post_type IN (\'' . implode( '\',\'', $post_types ) . '\')'; } if ( $filter['terms'] != 'all' && !empty( $filter['terms'] ) ) { $ttid = array(); foreach ( $filter['terms'] as $term_id ) { $term_taxonomy_id = $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE term_id=%d", $term_id ) ); if ( !empty( $term_taxonomy_id ) ) { $ttid[] = $term_taxonomy_id; } } $query[] = 't.term_taxonomy_id IN (\'' . implode( '\',\'', $ttid ) . '\')'; $join[] = "LEFT JOIN $wpdb->term_relationships t ON p.ID = t.object_id "; } if ( $filter['templates'] != 'all' && !empty( $filter['templates'] ) ) { $query[] = '(m.meta_key = \'_wp_page_template\' AND m.meta_value IN (\'' . implode( '\',\'', $filter['templates'] ) . '\'))'; } if ( !empty( $meta_query ) || ($filter['templates'] != 'all' && !empty( $filter['templates'] )) ) { $join[] = "LEFT JOIN $wpdb->postmeta m ON p.ID = m.post_id "; } $_query = "SELECT p.ID FROM $wpdb->posts p " . implode( '', $join ); if ( !empty( $query ) ) { $_query .= "WHERE " . implode( ' ' . $filter['association'] . ' ', $query ) . ' '; if ( !empty( $meta_query ) ) { $_query .= ' AND ' . $meta_query . ' '; } } else if ( !empty( $meta_query ) ) { $_query .= "WHERE " . $meta_query . ' '; } $_query .= "GROUP BY p.ID"; $posts = $wpdb->get_col( $_query ); return $posts; } /** * Gets posts by filter with missing meta fetched * with wpcf_admin_fields_get_filter_by_field(). * * @global type $wpdb * @param type $filter * @return type */ function wpcf_admin_fields_get_posts_by_filter_missing_meta( $filter, $meta_key = '' ) { global $wpdb, $wpcf; $query = array(); $join = array(); if ( $filter['types'] != 'all' && !empty( $filter['types'] ) ) { $query[] = 'p.post_type IN (\'' . implode( '\',\'', $filter['types'] ) . '\')'; } else { $post_types = get_post_types( array('show_ui' => true), 'names' ); foreach ( $post_types as $post_type_slug => $post_type ) { if ( in_array( $post_type_slug, $wpcf->excluded_post_types ) ) { unset( $post_types[$post_type_slug] ); } } $query[] = 'p.post_type IN (\'' . implode( '\',\'', $post_types ) . '\')'; } if ( $filter['terms'] != 'all' && !empty( $filter['terms'] ) ) { $ttid = array(); foreach ( $filter['terms'] as $term_id ) { $term_taxonomy_id = $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE term_id=%d", $term_id ) ); if ( !empty( $term_taxonomy_id ) ) { $ttid[] = $term_taxonomy_id; } } $query[] = 't.term_taxonomy_id IN (\'' . implode( '\',\'', $ttid ) . '\')'; $join[] = "LEFT JOIN $wpdb->term_relationships t ON p.ID = t.object_id "; } if ( $filter['templates'] != 'all' && !empty( $filter['templates'] ) ) { $query[] = '(m.meta_key = \'_wp_page_template\' AND m.meta_value IN (\'' . implode( '\',\'', $filter['templates'] ) . '\'))'; $join[] = "LEFT JOIN $wpdb->postmeta m ON p.ID = m.post_id "; } $_query = "SELECT DISTINCT p.ID FROM $wpdb->posts p " . implode( '', $join ); $_query .= "WHERE NOT EXISTS (SELECT * FROM $wpdb->postmeta mm WHERE p.ID = mm.post_id AND mm.meta_key = '$meta_key')"; if ( !empty( $query ) ) { $_query .= "AND (" . implode( ' ' . $filter['association'] . ' ', $query ) . ') '; } $_query .= "GROUP BY p.ID"; $posts = $wpdb->get_col( $_query ); return $posts; } /** * Check how many posts needs checkboxes update. * * @param type $field * @param type $action * @return boolean|int */ function wpcf_admin_fields_checkboxes_migrate_empty_check( $field, $action ) { if ( $field['type'] != 'checkboxes' || empty( $field['data']['options'] ) ) { return false; } if ( $field['meta_type'] == 'usermeta' ) { global $wpdb; if ( $action == 'do_not_save_check' ) { $query = array(); foreach ( $field['data']['options'] as $option_id => $option_data ) { // $query[] = '\"' . $option_id . '\";s:1:\"0\";'; $query[] = '\"' . $option_id . '\";i:0;'; } $meta_query = "SELECT u.ID FROM {$wpdb->users} u LEFT JOIN {$wpdb->usermeta} um ON u.ID = um.user_id WHERE (um.meta_key = '%s' AND (um.meta_value LIKE '%%" . implode( "%%' OR um.meta_value LIKE '%%", $query ) . "%%'))"; } else if ( $action == 'save_check' ) { $query = array(); foreach ( $field['data']['options'] as $option_id => $option_data ) { // $query[] = '\"' . $option_id . '\";s:1:\"0\";'; // Check only if missing $query[] = '\"' . $option_id . '\"'; } $meta_query = "SELECT u.ID FROM {$wpdb->users} u LEFT JOIN {$wpdb->usermeta} um ON u.ID = um.user_id WHERE (um.meta_key = '%s' AND (um.meta_value NOT LIKE '%%" . implode( "%%' OR um.meta_value NOT LIKE '%%", $query ) . "%%'))"; } $users = $wpdb->get_col( $wpdb->prepare( $meta_query, $field['meta_key'] ) ); $option = get_option( 'wpcf_checkboxes_migration_usermeta', array() ); $cache_key = $action == 'do_not_save_check' ? 'do_not_save' : 'save'; $option[$field['meta_key']][$cache_key] = $users; update_option( 'wpcf_checkboxes_migration_usermeta', $option ); return $users; } $filter = wpcf_admin_fields_get_filter_by_field( $field['id'] ); if ( !empty( $filter ) ) { $posts = array(); $meta_key = wpcf_types_get_meta_prefix( $field ) . $field['id']; $meta_query = ''; // "wpcf-fields-checkboxes-option-1873650245";s:1:"1"; if ( $action == 'do_not_save_check' ) { $query = array(); foreach ( $field['data']['options'] as $option_id => $option_data ) { $query[] = '\"' . $option_id . '\";i:0;'; } $meta_query = "(m.meta_key = '$meta_key' AND (m.meta_value LIKE '%%" . implode( "%%' OR m.meta_value LIKE '%%", $query ) . "%%'))"; $posts = wpcf_admin_fields_get_posts_by_filter( $filter, $meta_query ); } else if ( $action == 'save_check' ) { $query = array(); foreach ( $field['data']['options'] as $option_id => $option_data ) { // Check only if missing $query[] = '\"' . $option_id . '\"'; } $meta_query = "(m.meta_key = '$meta_key' AND (m.meta_value NOT LIKE '%%" . implode( "%%' OR m.meta_value NOT LIKE '%%", $query ) . "%%'))"; $posts = wpcf_admin_fields_get_posts_by_filter( $filter, $meta_query ); } $option = get_option( 'wpcf_checkboxes_migration', array() ); $cache_key = $action == 'do_not_save_check' ? 'do_not_save' : 'save'; $option[$cache_key] = $posts; update_option( 'wpcf_checkboxes_migration', $option ); return $posts; } return false; } /** * Update posts checkboxes fields. * * @param type $field * @param type $action * @return boolean|int */ function wpcf_admin_fields_checkboxes_migrate_empty( $field, $action ) { if ( $field['type'] != 'checkboxes' || empty( $field['data']['options'] ) ) { return false; } if ( $field['meta_type'] == 'usermeta' ) { $option = get_option( 'wpcf_checkboxes_migration_usermeta', array() ); if ( empty( $option[$field['meta_key']][$action] ) ) { $users = wpcf_admin_fields_checkboxes_migrate_empty_check( $field, $action . '_check' ); } else { $users = $option[$field['meta_key']][$action]; } if ( !empty( $users ) ) { if ( $action == 'do_not_save' ) { $count = 0; foreach ( $users as $temp_key => $user_id ) { if ( $count == 1000 ) { $option[$field['meta_key']][$action] = $users; update_option( 'wpcf_checkboxes_migration_usermeta', $option ); $data = array('offset' => $temp_key); return $data; } $meta_saved = get_user_meta( $user_id, $field['meta_key'] ); if ( !empty( $meta_saved ) ) { foreach ( $meta_saved as $key => $value ) { if ( !is_array( $value ) ) { $value_check = array(); } else { $value_check = $value; } foreach ( $field['data']['options'] as $option_id => $option_data ) { if ( isset( $value_check[$option_id] ) && $value_check[$option_id] == '0' ) { unset( $value_check[$option_id] ); } } update_user_meta( $user_id, $field['meta_key'], $value_check, $value ); } } unset( $users[$temp_key] ); $count++; } unset( $option[$field['meta_key']][$action] ); update_option( 'wpcf_checkboxes_migration_usermeta', $option ); return $users; } else if ( $action == 'save' ) { $count = 0; foreach ( $users as $temp_key => $user_id ) { if ( $count == 1000 ) { $option[$field['meta_key']][$action] = $users; update_option( 'wpcf_checkboxes_migration_usermeta', $option ); $data = array('offset' => $temp_key); return $data; } $meta_saved = get_user_meta( $user_id, $field['meta_key'] ); if ( !empty( $meta_saved ) ) { foreach ( $meta_saved as $key => $value ) { if ( !is_array( $value ) ) { $value_check = array(); } else { $value_check = $value; } $set_value = array(); foreach ( $field['data']['options'] as $option_id => $option_data ) { if ( !isset( $value_check[$option_id] ) ) { $set_value[$option_id] = 0; } } $updated_value = $value_check + $set_value; update_user_meta( $user_id, $field['meta_key'], $updated_value, $value ); } } unset( $users[$temp_key] ); $count++; } unset( $option[$field['meta_key']][$action] ); update_option( 'wpcf_checkboxes_migration_usermeta', $option ); return $users; } } return false; } $option = get_option( 'wpcf_checkboxes_migration', array() ); $meta_key = wpcf_types_get_meta_prefix( $field ) . $field['id']; if ( empty( $option[$action] ) ) { $posts = wpcf_admin_fields_checkboxes_migrate_empty_check( $field, $action . '_check' ); } else { $posts = $option[$action]; } if ( !empty( $posts ) ) { if ( $action == 'do_not_save' ) { $count = 0; foreach ( $posts as $temp_key => $post_id ) { if ( $count == 1000 ) { $option[$action] = $posts; update_option( 'wpcf_checkboxes_migration', $option ); $data = array('offset' => $temp_key); return $data; } $meta_saved = get_post_meta( $post_id, $meta_key ); if ( !empty( $meta_saved ) ) { foreach ( $meta_saved as $key => $value ) { if ( !is_array( $value ) ) { $value_check = array(); } else { $value_check = $value; } foreach ( $field['data']['options'] as $option_id => $option_data ) { if ( isset( $value_check[$option_id] ) && $value_check[$option_id] == '0' ) { unset( $value_check[$option_id] ); } } update_post_meta( $post_id, $meta_key, $value_check, $value ); } } unset( $posts[$temp_key] ); $count++; } unset( $option[$action] ); update_option( 'wpcf_checkboxes_migration', $option ); return $posts; } else if ( $action == 'save' ) { $count = 0; foreach ( $posts as $temp_key => $post_id ) { if ( $count == 1000 ) { $option[$action] = $posts; update_option( 'wpcf_checkboxes_migration', $option ); $data = array('offset' => $temp_key); return $data; } $meta_saved = get_post_meta( $post_id, $meta_key ); if ( !empty( $meta_saved ) ) { foreach ( $meta_saved as $key => $value ) { if ( !is_array( $value ) ) { $value_check = array(); } else { $value_check = $value; } $set_value = array(); foreach ( $field['data']['options'] as $option_id => $option_data ) { if ( !isset( $value_check[$option_id] ) ) { $set_value[$option_id] = 0; } } $updated_value = $value_check + $set_value; update_post_meta( $post_id, $meta_key, $updated_value, $value ); } } unset( $posts[$temp_key] ); $count++; } unset( $option[$action] ); update_option( 'wpcf_checkboxes_migration', $option ); return $posts; } } return false; } function wpcf_admin_fields_form_fix_styles() { $suffix = SCRIPT_DEBUG ? '' : '.min'; wp_enqueue_style( 'wpcf-dashicons', site_url( "/wp-includes/css/dashicons$suffix.css" ) ); }
vperezma/h2osite
wp-content/plugins/types/includes/fields.php
PHP
gpl-2.0
51,409
/* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef OS_SOLARIS_VM_OS_SOLARIS_INLINE_HPP #define OS_SOLARIS_VM_OS_SOLARIS_INLINE_HPP #include "runtime/atomic.inline.hpp" #include "runtime/os.hpp" #ifdef TARGET_OS_ARCH_solaris_x86 # include "orderAccess_solaris_x86.inline.hpp" #endif #ifdef TARGET_OS_ARCH_solaris_sparc # include "orderAccess_solaris_sparc.inline.hpp" #endif // System includes #include <sys/param.h> #include <dlfcn.h> #include <sys/socket.h> #include <sys/poll.h> #include <sys/filio.h> #include <unistd.h> #include <netdb.h> #include <setjmp.h> inline const char* os::file_separator() { return "/"; } inline const char* os::line_separator() { return "\n"; } inline const char* os::path_separator() { return ":"; } // File names are case-sensitive on windows only inline int os::file_name_strcmp(const char* s1, const char* s2) { return strcmp(s1, s2); } inline bool os::uses_stack_guard_pages() { return true; } inline bool os::allocate_stack_guard_pages() { assert(uses_stack_guard_pages(), "sanity check"); int r = thr_main() ; guarantee (r == 0 || r == 1, "CR6501650 or CR6493689") ; return r; } // On Solaris, reservations are made on a page by page basis, nothing to do. inline void os::pd_split_reserved_memory(char *base, size_t size, size_t split, bool realloc) { } // Bang the shadow pages if they need to be touched to be mapped. inline void os::bang_stack_shadow_pages() { } inline void os::dll_unload(void *lib) { ::dlclose(lib); } inline DIR* os::opendir(const char* dirname) { assert(dirname != NULL, "just checking"); return ::opendir(dirname); } inline int os::readdir_buf_size(const char *path) { int size = pathconf(path, _PC_NAME_MAX); return (size < 0 ? MAXPATHLEN : size) + sizeof(dirent) + 1; } inline struct dirent* os::readdir(DIR* dirp, dirent* dbuf) { assert(dirp != NULL, "just checking"); #if defined(_LP64) || defined(_GNU_SOURCE) || _FILE_OFFSET_BITS==64 dirent* p; int status; if((status = ::readdir_r(dirp, dbuf, &p)) != 0) { errno = status; return NULL; } else return p; #else // defined(_LP64) || defined(_GNU_SOURCE) || _FILE_OFFSET_BITS==64 return ::readdir_r(dirp, dbuf); #endif // defined(_LP64) || defined(_GNU_SOURCE) || _FILE_OFFSET_BITS==64 } inline int os::closedir(DIR *dirp) { assert(dirp != NULL, "argument is NULL"); return ::closedir(dirp); } ////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // macros for interruptible io and system calls and system call restarting #define _INTERRUPTIBLE(_setup, _cmd, _result, _thread, _clear, _before, _after, _int_enable) \ do { \ _setup; \ _before; \ OSThread* _osthread = _thread->osthread(); \ if (_int_enable && _thread->has_last_Java_frame()) { \ /* this is java interruptible io stuff */ \ if (os::is_interrupted(_thread, _clear)) { \ os::Solaris::bump_interrupted_before_count(); \ _result = OS_INTRPT; \ } else { \ /* _cmd always expands to an assignment to _result */ \ if ((_cmd) < 0 && errno == EINTR \ && os::is_interrupted(_thread, _clear)) { \ os::Solaris::bump_interrupted_during_count(); \ _result = OS_INTRPT; \ } \ } \ } else { \ /* this is normal blocking io stuff */ \ _cmd; \ } \ _after; \ } while(false) // Interruptible io support + restarting of interrupted system calls #ifndef ASSERT #define INTERRUPTIBLE(_cmd, _result, _clear) do { \ _INTERRUPTIBLE( JavaThread* _thread = (JavaThread*)ThreadLocalStorage::thread(),_result = _cmd, _result, _thread, _clear, , , UseVMInterruptibleIO); \ } while((_result == OS_ERR) && (errno == EINTR)) #else // This adds an assertion that it is only called from thread_in_native // The call overhead is skipped for performance in product mode #define INTERRUPTIBLE(_cmd, _result, _clear) do { \ _INTERRUPTIBLE(JavaThread* _thread = os::Solaris::setup_interruptible_native(), _result = _cmd, _result, _thread, _clear, , os::Solaris::cleanup_interruptible_native(_thread), UseVMInterruptibleIO ); \ } while((_result == OS_ERR) && (errno == EINTR)) #endif // Used for calls from _thread_in_vm, not from _thread_in_native #define INTERRUPTIBLE_VM(_cmd, _result, _clear) do { \ _INTERRUPTIBLE(JavaThread* _thread = os::Solaris::setup_interruptible(), _result = _cmd, _result, _thread, _clear, , os::Solaris::cleanup_interruptible(_thread), UseVMInterruptibleIO ); \ } while((_result == OS_ERR) && (errno == EINTR)) /* Use NORESTART when the system call cannot return EINTR, when something other than a system call is being invoked, or when the caller must do EINTR handling. */ #ifndef ASSERT #define INTERRUPTIBLE_NORESTART(_cmd, _result, _clear) \ _INTERRUPTIBLE( JavaThread* _thread = (JavaThread*)ThreadLocalStorage::thread(),_result = _cmd, _result, _thread, _clear, , , UseVMInterruptibleIO) #else // This adds an assertion that it is only called from thread_in_native // The call overhead is skipped for performance in product mode #define INTERRUPTIBLE_NORESTART(_cmd, _result, _clear) \ _INTERRUPTIBLE(JavaThread* _thread = os::Solaris::setup_interruptible_native(), _result = _cmd, _result, _thread, _clear, , os::Solaris::cleanup_interruptible_native(_thread), UseVMInterruptibleIO ) #endif // Don't attend to UseVMInterruptibleIO. Always allow interruption. // Also assumes that it is called from the _thread_blocked state. // Used by os_sleep(). #define INTERRUPTIBLE_NORESTART_VM_ALWAYS(_cmd, _result, _thread, _clear) \ _INTERRUPTIBLE(os::Solaris::setup_interruptible_already_blocked(_thread), _result = _cmd, _result, _thread, _clear, , , true ) #define INTERRUPTIBLE_RETURN_INT(_cmd, _clear) do { \ int _result; \ do { \ INTERRUPTIBLE(_cmd, _result, _clear); \ } while((_result == OS_ERR) && (errno == EINTR)); \ return _result; \ } while(false) #define INTERRUPTIBLE_RETURN_INT_VM(_cmd, _clear) do { \ int _result; \ do { \ INTERRUPTIBLE_VM(_cmd, _result, _clear); \ } while((_result == OS_ERR) && (errno == EINTR)); \ return _result; \ } while(false) #define INTERRUPTIBLE_RETURN_INT_NORESTART(_cmd, _clear) do { \ int _result; \ INTERRUPTIBLE_NORESTART(_cmd, _result, _clear); \ return _result; \ } while(false) /* Use the RESTARTABLE macros when interruptible io is not needed */ #define RESTARTABLE(_cmd, _result) do { \ do { \ _result = _cmd; \ } while((_result == OS_ERR) && (errno == EINTR)); \ } while(false) #define RESTARTABLE_RETURN_INT(_cmd) do { \ int _result; \ RESTARTABLE(_cmd, _result); \ return _result; \ } while(false) inline bool os::numa_has_static_binding() { return false; } inline bool os::numa_has_group_homing() { return true; } inline int os::socket(int domain, int type, int protocol) { return ::socket(domain, type, protocol); } inline int os::listen(int fd, int count) { if (fd < 0) return OS_ERR; return ::listen(fd, count); } inline int os::socket_shutdown(int fd, int howto){ return ::shutdown(fd, howto); } inline int os::get_sock_name(int fd, struct sockaddr* him, socklen_t* len){ return ::getsockname(fd, him, len); } inline int os::get_host_name(char* name, int namelen){ return ::gethostname(name, namelen); } inline struct hostent* os::get_host_by_name(char* name) { return ::gethostbyname(name); } inline int os::get_sock_opt(int fd, int level, int optname, char* optval, socklen_t* optlen) { return ::getsockopt(fd, level, optname, optval, optlen); } inline int os::set_sock_opt(int fd, int level, int optname, const char *optval, socklen_t optlen) { return ::setsockopt(fd, level, optname, optval, optlen); } #endif // OS_SOLARIS_VM_OS_SOLARIS_INLINE_HPP
lewurm/graal
src/os/solaris/vm/os_solaris.inline.hpp
C++
gpl-2.0
8,884
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2013 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # translate is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. from pytest import mark from translate.misc import wStringIO from translate.storage import dtd, test_monolingual def test_roundtrip_quoting(): specials = [ 'Fish & chips', 'five < six', 'six > five', 'Use &nbsp;', 'Use &amp;nbsp;A "solution"', "skop 'n bal", '"""', "'''", '\n', '\t', '\r', 'Escape at end \\', '', '\\n', '\\t', '\\r', '\\"', '\r\n', '\\r\\n', '\\', "Completed %S", "&blockAttackSites;", "&#x00A0;", "&intro-point2-a;", "&basePBMenu.label;", #"Don't buy", #"Don't \"buy\"", "A \"thing\"", "<a href=\"http" ] for special in specials: quoted_special = dtd.quotefordtd(special) unquoted_special = dtd.unquotefromdtd(quoted_special) print("special: %r\nquoted: %r\nunquoted: %r\n" % (special, quoted_special, unquoted_special)) assert special == unquoted_special @mark.xfail(reason="Not Implemented") def test_quotefordtd_unimplemented_cases(): """Test unimplemented quoting DTD cases.""" assert dtd.quotefordtd("Between <p> and </p>") == ('"Between &lt;p&gt; and' ' &lt;/p&gt;"') def test_quotefordtd(): """Test quoting DTD definitions""" assert dtd.quotefordtd('') == '""' assert dtd.quotefordtd("") == '""' assert dtd.quotefordtd("Completed %S") == '"Completed &#037;S"' assert dtd.quotefordtd("&blockAttackSites;") == '"&blockAttackSites;"' assert dtd.quotefordtd("&#x00A0;") == '"&#x00A0;"' assert dtd.quotefordtd("&intro-point2-a;") == '"&intro-point2-a;"' assert dtd.quotefordtd("&basePBMenu.label;") == '"&basePBMenu.label;"' # The ' character isn't escaped as &apos; since the " char isn't present. assert dtd.quotefordtd("Don't buy") == '"Don\'t buy"' # The ' character is escaped as &apos; because the " character is present. assert dtd.quotefordtd("Don't \"buy\"") == '"Don&apos;t &quot;buy&quot;"' assert dtd.quotefordtd("A \"thing\"") == '"A &quot;thing&quot;"' # The " character is not escaped when it indicates an attribute value. assert dtd.quotefordtd("<a href=\"http") == "'<a href=\"http'" # &amp; assert dtd.quotefordtd("Color & Light") == '"Color &amp; Light"' assert dtd.quotefordtd("Color & &block;") == '"Color &amp; &block;"' assert dtd.quotefordtd("Color&Light &red;") == '"Color&amp;Light &red;"' assert dtd.quotefordtd("Color & Light; Yes") == '"Color &amp; Light; Yes"' @mark.xfail(reason="Not Implemented") def test_unquotefromdtd_unimplemented_cases(): """Test unimplemented unquoting DTD cases.""" assert dtd.unquotefromdtd('"&lt;p&gt; and &lt;/p&gt;"') == "<p> and </p>" def test_unquotefromdtd(): """Test unquoting DTD definitions""" # % assert dtd.unquotefromdtd('"Completed &#037;S"') == "Completed %S" assert dtd.unquotefromdtd('"Completed &#37;S"') == "Completed %S" assert dtd.unquotefromdtd('"Completed &#x25;S"') == "Completed %S" # &entity; assert dtd.unquotefromdtd('"Color&light &block;"') == "Color&light &block;" assert dtd.unquotefromdtd('"Color & Light; Red"') == "Color & Light; Red" assert dtd.unquotefromdtd('"&blockAttackSites;"') == "&blockAttackSites;" assert dtd.unquotefromdtd('"&intro-point2-a;"') == "&intro-point2-a;" assert dtd.unquotefromdtd('"&basePBMenu.label"') == "&basePBMenu.label" # &amp; assert dtd.unquotefromdtd('"Color &amp; Light"') == "Color & Light" assert dtd.unquotefromdtd('"Color &amp; &block;"') == "Color & &block;" # nbsp assert dtd.unquotefromdtd('"&#x00A0;"') == "&#x00A0;" # ' assert dtd.unquotefromdtd("'Don&apos;t buy'") == "Don't buy" # " assert dtd.unquotefromdtd("'Don&apos;t &quot;buy&quot;'") == 'Don\'t "buy"' assert dtd.unquotefromdtd('"A &quot;thing&quot;"') == "A \"thing\"" assert dtd.unquotefromdtd('"A &#x0022;thing&#x0022;"') == "A \"thing\"" assert dtd.unquotefromdtd("'<a href=\"http'") == "<a href=\"http" # other chars assert dtd.unquotefromdtd('"&#187;"') == u"»" def test_android_roundtrip_quoting(): specials = [ "don't", 'the "thing"' ] for special in specials: quoted_special = dtd.quoteforandroid(special) unquoted_special = dtd.unquotefromandroid(quoted_special) print("special: %r\nquoted: %r\nunquoted: %r\n" % (special, quoted_special, unquoted_special)) assert special == unquoted_special def test_quoteforandroid(): """Test quoting Android DTD definitions.""" assert dtd.quoteforandroid("don't") == r'"don\u0027t"' assert dtd.quoteforandroid('the "thing"') == r'"the \&quot;thing\&quot;"' def test_unquotefromandroid(): """Test unquoting Android DTD definitions.""" assert dtd.unquotefromandroid('"Don\\&apos;t show"') == "Don't show" assert dtd.unquotefromandroid('"Don\\\'t show"') == "Don't show" assert dtd.unquotefromandroid('"Don\\u0027t show"') == "Don't show" assert dtd.unquotefromandroid('"A \\&quot;thing\\&quot;"') == "A \"thing\"" def test_removeinvalidamp(recwarn): """tests the the removeinvalidamps function""" def tester(actual, expected=None): if expected is None: expected = actual assert dtd.removeinvalidamps("test.name", actual) == expected # No errors tester("Valid &entity; included") tester("Valid &entity.name; included") tester("Valid &#1234; included") tester("Valid &entity_name;") # Errors that require & removal tester("This &amp is broken", "This amp is broken") tester("Mad & &amp &amp;", "Mad amp &amp;") dtd.removeinvalidamps("simple.warningtest", "Dimpled &Ring") assert recwarn.pop(UserWarning) class TestDTDUnit(test_monolingual.TestMonolingualUnit): UnitClass = dtd.dtdunit def test_rich_get(self): pass def test_rich_set(self): pass class TestDTD(test_monolingual.TestMonolingualStore): StoreClass = dtd.dtdfile def dtdparse(self, dtdsource): """helper that parses dtd source without requiring files""" dummyfile = wStringIO.StringIO(dtdsource) dtdfile = dtd.dtdfile(dummyfile) return dtdfile def dtdregen(self, dtdsource): """helper that converts dtd source to dtdfile object and back""" return str(self.dtdparse(dtdsource)) def test_simpleentity(self): """checks that a simple dtd entity definition is parsed correctly""" dtdsource = '<!ENTITY test.me "bananas for sale">\n' dtdfile = self.dtdparse(dtdsource) assert len(dtdfile.units) == 1 dtdunit = dtdfile.units[0] assert dtdunit.entity == "test.me" assert dtdunit.definition == '"bananas for sale"' def test_blanklines(self): """checks that blank lines don't break the parsing or regeneration""" dtdsource = '<!ENTITY test.me "bananas for sale">\n\n' dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen def test_simpleentity_source(self): """checks that a simple dtd entity definition can be regenerated as source""" dtdsource = '<!ENTITY test.me "">\n' dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen dtdsource = '<!ENTITY test.me "bananas for sale">\n' dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen def test_hashcomment_source(self): """checks that a #expand comment is retained in the source""" dtdsource = '#expand <!ENTITY lang.version "__MOZILLA_LOCALE_VERSION__">\n' dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen def test_commentclosing(self): """tests that comment closes with trailing space aren't duplicated""" dtdsource = '<!-- little comment --> \n<!ENTITY pane.title "Notifications">\n' dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen def test_commententity(self): """check that we don't process messages in <!-- comments -->: bug 102""" dtdsource = '''<!-- commenting out until bug 38906 is fixed <!ENTITY messagesHeader.label "Messages"> -->''' dtdfile = self.dtdparse(dtdsource) assert len(dtdfile.units) == 1 dtdunit = dtdfile.units[0] print(dtdunit) assert dtdunit.isnull() def test_newlines_in_entity(self): """tests that we can handle newlines in the entity itself""" dtdsource = '''<!ENTITY fileNotFound.longDesc " <ul> <li>Check the file name for capitalisation or other typing errors.</li> <li>Check to see if the file was moved, renamed or deleted.</li> </ul> "> ''' dtdregen = self.dtdregen(dtdsource) print(dtdregen) print(dtdsource) assert dtdsource == dtdregen def test_conflate_comments(self): """Tests that comments don't run onto the same line""" dtdsource = '<!-- test comments -->\n<!-- getting conflated -->\n<!ENTITY sample.txt "hello">\n' dtdregen = self.dtdregen(dtdsource) print(dtdsource) print(dtdregen) assert dtdsource == dtdregen def test_localisation_notes(self): """test to ensure that we retain the localisation note correctly""" dtdsource = '''<!--LOCALIZATION NOTE (publishFtp.label): Edit box appears beside this label --> <!ENTITY publishFtp.label "If publishing to a FTP site, enter the HTTP address to browse to:"> ''' dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen def test_entitityreference_in_source(self): """checks that an &entity; in the source is retained""" dtdsource = '<!ENTITY % realBrandDTD SYSTEM "chrome://branding/locale/brand.dtd">\n%realBrandDTD;\n' dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen #test for bug #610 def test_entitityreference_order_in_source(self): """checks that an &entity; in the source is retained""" dtdsource = '<!ENTITY % realBrandDTD SYSTEM "chrome://branding/locale/brand.dtd">\n%realBrandDTD;\n<!-- some comment -->\n' dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen # The following test is identical to the one above, except that the entity is split over two lines. # This is to ensure that a recent bug fixed in dtdunit.parse() is at least partly documented. # The essence of the bug was that after it had read "realBrandDTD", the line index is not reset # before starting to parse the next line. It would then read the next available word (sequence of # alphanum characters) in stead of SYSTEM and then get very confused by not finding an opening ' or # " in the entity, borking the parsing for threst of the file. dtdsource = '<!ENTITY % realBrandDTD\n SYSTEM "chrome://branding/locale/brand.dtd">\n%realBrandDTD;\n' # FIXME: The following line is necessary, because of dtdfile's inability to remember the spacing of # the source DTD file when converting back to DTD. dtdregen = self.dtdregen(dtdsource).replace('realBrandDTD SYSTEM', 'realBrandDTD\n SYSTEM') print(dtdsource) print(dtdregen) assert dtdsource == dtdregen @mark.xfail(reason="Not Implemented") def test_comment_following(self): """check that comments that appear after and entity are not pushed onto another line""" dtdsource = '<!ENTITY textZoomEnlargeCmd.commandkey2 "="> <!-- + is above this key on many keyboards -->' dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen def test_comment_newline_space_closing(self): """check that comments that are closed by a newline then space then --> don't break the following entries""" dtdsource = '<!-- Comment\n -->\n<!ENTITY searchFocus.commandkey "k">\n' dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen @mark.xfail(reason="Not Implemented") def test_invalid_quoting(self): """checks that invalid quoting doesn't work - quotes can't be reopened""" # TODO: we should rather raise an error dtdsource = '<!ENTITY test.me "bananas for sale""room">\n' assert dtd.unquotefromdtd(dtdsource[dtdsource.find('"'):]) == 'bananas for sale' dtdfile = self.dtdparse(dtdsource) assert len(dtdfile.units) == 1 dtdunit = dtdfile.units[0] assert dtdunit.definition == '"bananas for sale"' assert str(dtdfile) == '<!ENTITY test.me "bananas for sale">\n' def test_missing_quotes(self, recwarn): """test that we fail graacefully when a message without quotes is found (bug #161)""" dtdsource = '<!ENTITY bad no quotes">\n<!ENTITY good "correct quotes">\n' dtdfile = self.dtdparse(dtdsource) assert len(dtdfile.units) == 1 assert recwarn.pop(Warning) # Test for bug #68 def test_entity_escaping(self): """Test entities escaping (&amp; &quot; &lt; &gt; &apos;) (bug #68)""" dtdsource = ('<!ENTITY securityView.privacy.header "Privacy &amp; ' 'History">\n<!ENTITY rights.safebrowsing-term3 "Uncheck ' 'the options to &quot;&blockAttackSites.label;&quot; and ' '&quot;&blockWebForgeries.label;&quot;">\n<!ENTITY ' 'translate.test1 \'XML encodings don&apos;t work\'>\n' '<!ENTITY translate.test2 "In HTML the text paragraphs ' 'are enclosed between &lt;p&gt; and &lt;/p&gt; tags.">\n') dtdfile = self.dtdparse(dtdsource) assert len(dtdfile.units) == 4 #dtdunit = dtdfile.units[0] #assert dtdunit.definition == '"Privacy &amp; History"' #assert dtdunit.target == "Privacy & History" #assert dtdunit.source == "Privacy & History" dtdunit = dtdfile.units[1] assert dtdunit.definition == ('"Uncheck the options to &quot;' '&blockAttackSites.label;&quot; and ' '&quot;&blockWebForgeries.label;&quot;"') assert dtdunit.target == ("Uncheck the options to \"" "&blockAttackSites.label;\" and \"" "&blockWebForgeries.label;\"") assert dtdunit.source == ("Uncheck the options to \"" "&blockAttackSites.label;\" and \"" "&blockWebForgeries.label;\"") dtdunit = dtdfile.units[2] assert dtdunit.definition == "'XML encodings don&apos;t work'" assert dtdunit.target == "XML encodings don\'t work" assert dtdunit.source == "XML encodings don\'t work" #dtdunit = dtdfile.units[3] #assert dtdunit.definition == ('"In HTML the text paragraphs are ' # 'enclosed between &lt;p&gt; and &lt;/p' # '&gt; tags."') #assert dtdunit.target == ("In HTML the text paragraphs are enclosed " # "between <p> and </p> tags.") #assert dtdunit.source == ("In HTML the text paragraphs are enclosed " # "between <p> and </p> tags.") # Test for bug #68 def test_entity_escaping_roundtrip(self): """Test entities escaping roundtrip (&amp; &quot; ...) (bug #68)""" dtdsource = ('<!ENTITY securityView.privacy.header "Privacy &amp; ' 'History">\n<!ENTITY rights.safebrowsing-term3 "Uncheck ' 'the options to &quot;&blockAttackSites.label;&quot; and ' '&quot;&blockWebForgeries.label;&quot;">\n<!ENTITY ' 'translate.test1 \'XML encodings don&apos;t work\'>\n' '<!ENTITY translate.test2 "In HTML the text paragraphs ' 'are enclosed between &lt;p&gt; and &lt;/p&gt; tags.">\n') dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen class TestAndroidDTD(test_monolingual.TestMonolingualStore): StoreClass = dtd.dtdfile def dtdparse(self, dtdsource): """Parses an Android DTD source string and returns a DTD store. This allows to simulate reading from Android DTD files without really having real Android DTD files. """ dummyfile = wStringIO.StringIO(dtdsource) dtdfile = dtd.dtdfile(dummyfile, android=True) return dtdfile def dtdregen(self, dtdsource): """Parses an Android DTD string to DTD store and then converts it back. This allows to simulate reading from an Android DTD file to an in-memory store and writing back to an Android DTD file without really having a real file. """ return str(self.dtdparse(dtdsource)) # Test for bug #2480 def test_android_single_quote_escape(self): """Checks several single quote unescaping cases in Android DTD. See bug #2480. """ dtdsource = ('<!ENTITY pref_char_encoding_off "Don\\\'t show menu">\n' '<!ENTITY sync.nodevice.label \'Don\\&apos;t show\'>\n' '<!ENTITY sync.nodevice.label "Don\\u0027t show">\n') dtdfile = self.dtdparse(dtdsource) assert len(dtdfile.units) == 3 dtdunit = dtdfile.units[0] assert dtdunit.definition == '"Don\\\'t show menu"' assert dtdunit.target == "Don't show menu" assert dtdunit.source == "Don't show menu" dtdunit = dtdfile.units[1] assert dtdunit.definition == "'Don\\&apos;t show'" assert dtdunit.target == "Don't show" assert dtdunit.source == "Don't show" dtdunit = dtdfile.units[2] assert dtdunit.definition == '"Don\\u0027t show"' assert dtdunit.target == "Don't show" assert dtdunit.source == "Don't show" # Test for bug #2480 def test_android_single_quote_escape_parse_and_convert_back(self): """Checks that Android DTD don't change after parse and convert back. An Android DTD source string with several single quote escapes is used instead of real files. See bug #2480. """ dtdsource = ('<!ENTITY pref_char_encoding_off "Don\\\'t show menu">\n' '<!ENTITY sync.nodevice.label \'Don\\&apos;t show\'>\n' '<!ENTITY sync.nodevice.label "Don\\u0027t show">\n') dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen def test_android_double_quote_escape(self): """Checks double quote unescaping in Android DTD.""" dtdsource = '<!ENTITY translate.test "A \\&quot;thing\\&quot;">\n' dtdfile = self.dtdparse(dtdsource) assert len(dtdfile.units) == 1 dtdunit = dtdfile.units[0] assert dtdunit.definition == '"A \\&quot;thing\\&quot;"' assert dtdunit.target == "A \"thing\"" assert dtdunit.source == "A \"thing\"" def test_android_double_quote_escape_parse_and_convert_back(self): """Checks that Android DTD don't change after parse and convert back. An Android DTD source string with double quote escapes is used instead of real files. """ dtdsource = '<!ENTITY translate.test "A \\&quot;thing\\&quot;">\n' dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen
bluemini/kuma
vendor/packages/translate/storage/test_dtd.py
Python
mpl-2.0
20,624
class AddLastVoteAtToMotions < ActiveRecord::Migration def up add_column :motions, :last_vote_at, :datetime remove_column :motions, :activity end def down remove_column :motions, :last_vote_at add_column :motions, :activity, :integer, :default => 0 end end
juliagra/loomio
db/migrate/20121008002211_add_last_vote_at_to_motions.rb
Ruby
agpl-3.0
281
require 'rails_helper' describe 'Cache flow' do describe 'Tag destroy' do it 'invalidates Debate cache keys' do debate = create(:debate, tag_list: "Good, Bad") tag = ActsAsTaggableOn::Tag.find_by(name: "Bad") expect{tag.destroy}.to change {debate.reload.cache_key} end end end
AjuntamentdeBarcelona/decidim.barcelona-legacy
spec/lib/cache_spec.rb
Ruby
agpl-3.0
311
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: google/protobuf/field_mask.proto package types import ( bytes "bytes" fmt "fmt" proto "github.com/gogo/protobuf/proto" io "io" math "math" reflect "reflect" strings "strings" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package // `FieldMask` represents a set of symbolic field paths, for example: // // paths: "f.a" // paths: "f.b.d" // // Here `f` represents a field in some root message, `a` and `b` // fields in the message found in `f`, and `d` a field found in the // message in `f.b`. // // Field masks are used to specify a subset of fields that should be // returned by a get operation or modified by an update operation. // Field masks also have a custom JSON encoding (see below). // // # Field Masks in Projections // // When used in the context of a projection, a response message or // sub-message is filtered by the API to only contain those fields as // specified in the mask. For example, if the mask in the previous // example is applied to a response message as follows: // // f { // a : 22 // b { // d : 1 // x : 2 // } // y : 13 // } // z: 8 // // The result will not contain specific values for fields x,y and z // (their value will be set to the default, and omitted in proto text // output): // // // f { // a : 22 // b { // d : 1 // } // } // // A repeated field is not allowed except at the last position of a // paths string. // // If a FieldMask object is not present in a get operation, the // operation applies to all fields (as if a FieldMask of all fields // had been specified). // // Note that a field mask does not necessarily apply to the // top-level response message. In case of a REST get operation, the // field mask applies directly to the response, but in case of a REST // list operation, the mask instead applies to each individual message // in the returned resource list. In case of a REST custom method, // other definitions may be used. Where the mask applies will be // clearly documented together with its declaration in the API. In // any case, the effect on the returned resource/resources is required // behavior for APIs. // // # Field Masks in Update Operations // // A field mask in update operations specifies which fields of the // targeted resource are going to be updated. The API is required // to only change the values of the fields as specified in the mask // and leave the others untouched. If a resource is passed in to // describe the updated values, the API ignores the values of all // fields not covered by the mask. // // If a repeated field is specified for an update operation, new values will // be appended to the existing repeated field in the target resource. Note that // a repeated field is only allowed in the last position of a `paths` string. // // If a sub-message is specified in the last position of the field mask for an // update operation, then new value will be merged into the existing sub-message // in the target resource. // // For example, given the target message: // // f { // b { // d: 1 // x: 2 // } // c: [1] // } // // And an update message: // // f { // b { // d: 10 // } // c: [2] // } // // then if the field mask is: // // paths: ["f.b", "f.c"] // // then the result will be: // // f { // b { // d: 10 // x: 2 // } // c: [1, 2] // } // // An implementation may provide options to override this default behavior for // repeated and message fields. // // In order to reset a field's value to the default, the field must // be in the mask and set to the default value in the provided resource. // Hence, in order to reset all fields of a resource, provide a default // instance of the resource and set all fields in the mask, or do // not provide a mask as described below. // // If a field mask is not present on update, the operation applies to // all fields (as if a field mask of all fields has been specified). // Note that in the presence of schema evolution, this may mean that // fields the client does not know and has therefore not filled into // the request will be reset to their default. If this is unwanted // behavior, a specific service may require a client to always specify // a field mask, producing an error if not. // // As with get operations, the location of the resource which // describes the updated values in the request message depends on the // operation kind. In any case, the effect of the field mask is // required to be honored by the API. // // ## Considerations for HTTP REST // // The HTTP kind of an update operation which uses a field mask must // be set to PATCH instead of PUT in order to satisfy HTTP semantics // (PUT must only be used for full updates). // // # JSON Encoding of Field Masks // // In JSON, a field mask is encoded as a single string where paths are // separated by a comma. Fields name in each path are converted // to/from lower-camel naming conventions. // // As an example, consider the following message declarations: // // message Profile { // User user = 1; // Photo photo = 2; // } // message User { // string display_name = 1; // string address = 2; // } // // In proto a field mask for `Profile` may look as such: // // mask { // paths: "user.display_name" // paths: "photo" // } // // In JSON, the same mask is represented as below: // // { // mask: "user.displayName,photo" // } // // # Field Masks and Oneof Fields // // Field masks treat fields in oneofs just as regular fields. Consider the // following message: // // message SampleMessage { // oneof test_oneof { // string name = 4; // SubMessage sub_message = 9; // } // } // // The field mask can be: // // mask { // paths: "name" // } // // Or: // // mask { // paths: "sub_message" // } // // Note that oneof type names ("test_oneof" in this case) cannot be used in // paths. // // ## Field Mask Verification // // The implementation of any API method which has a FieldMask type field in the // request should verify the included field paths, and return an // `INVALID_ARGUMENT` error if any path is duplicated or unmappable. type FieldMask struct { // The set of field mask paths. Paths []string `protobuf:"bytes,1,rep,name=paths,proto3" json:"paths,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *FieldMask) Reset() { *m = FieldMask{} } func (*FieldMask) ProtoMessage() {} func (*FieldMask) Descriptor() ([]byte, []int) { return fileDescriptor_5158202634f0da48, []int{0} } func (m *FieldMask) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } func (m *FieldMask) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_FieldMask.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalTo(b) if err != nil { return nil, err } return b[:n], nil } } func (m *FieldMask) XXX_Merge(src proto.Message) { xxx_messageInfo_FieldMask.Merge(m, src) } func (m *FieldMask) XXX_Size() int { return m.Size() } func (m *FieldMask) XXX_DiscardUnknown() { xxx_messageInfo_FieldMask.DiscardUnknown(m) } var xxx_messageInfo_FieldMask proto.InternalMessageInfo func (m *FieldMask) GetPaths() []string { if m != nil { return m.Paths } return nil } func (*FieldMask) XXX_MessageName() string { return "google.protobuf.FieldMask" } func init() { proto.RegisterType((*FieldMask)(nil), "google.protobuf.FieldMask") } func init() { proto.RegisterFile("google/protobuf/field_mask.proto", fileDescriptor_5158202634f0da48) } var fileDescriptor_5158202634f0da48 = []byte{ // 203 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcb, 0x4c, 0xcd, 0x49, 0x89, 0xcf, 0x4d, 0x2c, 0xce, 0xd6, 0x03, 0x8b, 0x09, 0xf1, 0x43, 0x54, 0xe8, 0xc1, 0x54, 0x28, 0x29, 0x72, 0x71, 0xba, 0x81, 0x14, 0xf9, 0x26, 0x16, 0x67, 0x0b, 0x89, 0x70, 0xb1, 0x16, 0x24, 0x96, 0x64, 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6b, 0x70, 0x06, 0x41, 0x38, 0x4e, 0x1d, 0x8c, 0x37, 0x1e, 0xca, 0x31, 0x7c, 0x78, 0x28, 0xc7, 0xf8, 0xe3, 0xa1, 0x1c, 0x63, 0xc3, 0x23, 0x39, 0xc6, 0x15, 0x8f, 0xe4, 0x18, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x17, 0x8f, 0xe4, 0x18, 0x3e, 0x80, 0xc4, 0x1f, 0xcb, 0x31, 0x9e, 0x78, 0x2c, 0xc7, 0xc8, 0x25, 0x9c, 0x9c, 0x9f, 0xab, 0x87, 0x66, 0x95, 0x13, 0x1f, 0xdc, 0xa2, 0x00, 0x90, 0x50, 0x00, 0x63, 0x14, 0x6b, 0x49, 0x65, 0x41, 0x6a, 0xf1, 0x0f, 0x46, 0xc6, 0x45, 0x4c, 0xcc, 0xee, 0x01, 0x4e, 0xab, 0x98, 0xe4, 0xdc, 0x21, 0x7a, 0x02, 0xa0, 0x7a, 0xf4, 0xc2, 0x53, 0x73, 0x72, 0xbc, 0xf3, 0xf2, 0xcb, 0xf3, 0x42, 0x40, 0x2a, 0x93, 0xd8, 0xc0, 0x86, 0x19, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x43, 0xa0, 0x83, 0xd0, 0xe9, 0x00, 0x00, 0x00, } func (this *FieldMask) Compare(that interface{}) int { if that == nil { if this == nil { return 0 } return 1 } that1, ok := that.(*FieldMask) if !ok { that2, ok := that.(FieldMask) if ok { that1 = &that2 } else { return 1 } } if that1 == nil { if this == nil { return 0 } return 1 } else if this == nil { return -1 } if len(this.Paths) != len(that1.Paths) { if len(this.Paths) < len(that1.Paths) { return -1 } return 1 } for i := range this.Paths { if this.Paths[i] != that1.Paths[i] { if this.Paths[i] < that1.Paths[i] { return -1 } return 1 } } if c := bytes.Compare(this.XXX_unrecognized, that1.XXX_unrecognized); c != 0 { return c } return 0 } func (this *FieldMask) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*FieldMask) if !ok { that2, ok := that.(FieldMask) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if len(this.Paths) != len(that1.Paths) { return false } for i := range this.Paths { if this.Paths[i] != that1.Paths[i] { return false } } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return false } return true } func (this *FieldMask) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 5) s = append(s, "&types.FieldMask{") s = append(s, "Paths: "+fmt.Sprintf("%#v", this.Paths)+",\n") if this.XXX_unrecognized != nil { s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") } s = append(s, "}") return strings.Join(s, "") } func valueToGoStringFieldMask(v interface{}, typ string) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) } func (m *FieldMask) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *FieldMask) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if len(m.Paths) > 0 { for _, s := range m.Paths { dAtA[i] = 0xa i++ l = len(s) for l >= 1<<7 { dAtA[i] = uint8(uint64(l)&0x7f | 0x80) l >>= 7 i++ } dAtA[i] = uint8(l) i++ i += copy(dAtA[i:], s) } } if m.XXX_unrecognized != nil { i += copy(dAtA[i:], m.XXX_unrecognized) } return i, nil } func encodeVarintFieldMask(dAtA []byte, offset int, v uint64) int { for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return offset + 1 } func NewPopulatedFieldMask(r randyFieldMask, easy bool) *FieldMask { this := &FieldMask{} v1 := r.Intn(10) this.Paths = make([]string, v1) for i := 0; i < v1; i++ { this.Paths[i] = string(randStringFieldMask(r)) } if !easy && r.Intn(10) != 0 { this.XXX_unrecognized = randUnrecognizedFieldMask(r, 2) } return this } type randyFieldMask interface { Float32() float32 Float64() float64 Int63() int64 Int31() int32 Uint32() uint32 Intn(n int) int } func randUTF8RuneFieldMask(r randyFieldMask) rune { ru := r.Intn(62) if ru < 10 { return rune(ru + 48) } else if ru < 36 { return rune(ru + 55) } return rune(ru + 61) } func randStringFieldMask(r randyFieldMask) string { v2 := r.Intn(100) tmps := make([]rune, v2) for i := 0; i < v2; i++ { tmps[i] = randUTF8RuneFieldMask(r) } return string(tmps) } func randUnrecognizedFieldMask(r randyFieldMask, maxFieldNumber int) (dAtA []byte) { l := r.Intn(5) for i := 0; i < l; i++ { wire := r.Intn(4) if wire == 3 { wire = 5 } fieldNumber := maxFieldNumber + r.Intn(100) dAtA = randFieldFieldMask(dAtA, r, fieldNumber, wire) } return dAtA } func randFieldFieldMask(dAtA []byte, r randyFieldMask, fieldNumber int, wire int) []byte { key := uint32(fieldNumber)<<3 | uint32(wire) switch wire { case 0: dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(key)) v3 := r.Int63() if r.Intn(2) == 0 { v3 *= -1 } dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(v3)) case 1: dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(key)) dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) case 2: dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(key)) ll := r.Intn(100) dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(ll)) for j := 0; j < ll; j++ { dAtA = append(dAtA, byte(r.Intn(256))) } default: dAtA = encodeVarintPopulateFieldMask(dAtA, uint64(key)) dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) } return dAtA } func encodeVarintPopulateFieldMask(dAtA []byte, v uint64) []byte { for v >= 1<<7 { dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80)) v >>= 7 } dAtA = append(dAtA, uint8(v)) return dAtA } func (m *FieldMask) Size() (n int) { if m == nil { return 0 } var l int _ = l if len(m.Paths) > 0 { for _, s := range m.Paths { l = len(s) n += 1 + l + sovFieldMask(uint64(l)) } } if m.XXX_unrecognized != nil { n += len(m.XXX_unrecognized) } return n } func sovFieldMask(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozFieldMask(x uint64) (n int) { return sovFieldMask(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (this *FieldMask) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&FieldMask{`, `Paths:` + fmt.Sprintf("%v", this.Paths) + `,`, `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, `}`, }, "") return s } func valueToStringFieldMask(v interface{}) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("*%v", pv) } func (m *FieldMask) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowFieldMask } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= uint64(b&0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: FieldMask: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: FieldMask: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Paths", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowFieldMask } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthFieldMask } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthFieldMask } if postIndex > l { return io.ErrUnexpectedEOF } m.Paths = append(m.Paths, string(dAtA[iNdEx:postIndex])) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipFieldMask(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthFieldMask } if (iNdEx + skippy) < 0 { return ErrInvalidLengthFieldMask } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipFieldMask(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowFieldMask } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowFieldMask } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } return iNdEx, nil case 1: iNdEx += 8 return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowFieldMask } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if length < 0 { return 0, ErrInvalidLengthFieldMask } iNdEx += length if iNdEx < 0 { return 0, ErrInvalidLengthFieldMask } return iNdEx, nil case 3: for { var innerWire uint64 var start int = iNdEx for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowFieldMask } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ innerWire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } innerWireType := int(innerWire & 0x7) if innerWireType == 4 { break } next, err := skipFieldMask(dAtA[start:]) if err != nil { return 0, err } iNdEx = start + next if iNdEx < 0 { return 0, ErrInvalidLengthFieldMask } } return iNdEx, nil case 4: return iNdEx, nil case 5: iNdEx += 4 return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } } panic("unreachable") } var ( ErrInvalidLengthFieldMask = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowFieldMask = fmt.Errorf("proto: integer overflow") )
kolyshkin/moby
vendor/github.com/gogo/protobuf/types/field_mask.pb.go
GO
apache-2.0
19,725
import org.junit.*; import play.mvc.*; import play.test.*; import static play.test.Helpers.*; import static org.junit.Assert.*; import static org.fluentlenium.core.filter.FilterConstructor.*; public class IntegrationTest { /** * add your integration test here * in this example we just check if the welcome page is being shown */ @Test public void test() { running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, browser -> { browser.goTo("http://localhost:3333"); assertTrue(browser.pageSource().contains("Your new application is ready.")); }); } }
saivarunr/zemoso-training
whatsapp_project/whatsapp/test/IntegrationTest.java
Java
apache-2.0
644
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.common.errors; public class ReplicaNotAvailableException extends ApiException { private static final long serialVersionUID = 1L; public ReplicaNotAvailableException(String message) { super(message); } public ReplicaNotAvailableException(String message, Throwable cause) { super(message, cause); } public ReplicaNotAvailableException(Throwable cause) { super(cause); } }
wangcy6/storm_app
frame/kafka-0.11.0/kafka-0.11.0.1-src/clients/src/main/java/org/apache/kafka/common/errors/ReplicaNotAvailableException.java
Java
apache-2.0
1,252
<?php /* * This file is part of Respect/Validation. * * (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net> * * For the full copyright and license information, please view the "LICENSE.md" * file that was distributed with this source code. */ namespace Respect\Validation\Rules\SubdivisionCode; use Respect\Validation\Rules\AbstractSearcher; /** * Validator for Serbia subdivision code. * * ISO 3166-1 alpha-2: RS * * @link http://www.geonames.org/RS/administrative-division-serbia.html */ class RsSubdivisionCode extends AbstractSearcher { public $haystack = [ 'KM', // Kosovo 'VO', // Vojvodina '00', // Beograd '01', // Severnobački okrug '02', // Srednjebanatski okrug '03', // Severnobanatski okrug '04', // Južnobanatski okrug '05', // Zapadno-Bački Okrug '06', // Južnobački okrug '07', // Srem '08', // Mačvanski okrug '09', // Kolubarski okrug '10', // Podunavski okrug '11', // Braničevski okrug '12', // Šumadija '13', // Pomoravski okrug '14', // Borski okrug '15', // Zaječar '16', // Zlatibor '17', // Moravički okrug '18', // Raški okrug '19', // Rasinski okrug '20', // Nišavski okrug '21', // Toplica '22', // Pirotski okrug '23', // Jablanički okrug '24', // Pčinjski okrug '25', // Kosovski okrug '26', // Pećki okrug '27', // Prizrenski okrug '28', // Kosovsko-Mitrovački okrug '29', // Kosovsko-Pomoravski okrug ]; public $compareIdentical = true; }
torzuoliH/instabab
vendor/respect/validation/library/Rules/SubdivisionCode/RsSubdivisionCode.php
PHP
mit
1,675
ej.addCulture( "az-Latn-AZ", { name: "az-Latn-AZ", englishName: "Azerbaijani (Latin, Azerbaijan)", nativeName: "Azərbaycan dili (Azərbaycan)", language: "az-Latn", numberFormat: { ",": " ", ".": ",", percent: { pattern: ["-n%","n%"], ",": " ", ".": "," }, currency: { pattern: ["-n $","n $"], ",": " ", ".": ",", symbol: "manat" } }, calendars: { standard: { "/": ".", firstDay: 1, days: { names: ["bazar","Bazar ertəsi","çərşənbə axşamı","çərşənbə","Cümə axşamı","Cümə","şənbə"], namesAbbr: ["B","Be","Ça","Ç","Ca","C","Ş"], namesShort: ["B","Be","Ça","Ç","Ca","C","Ş"] }, months: { names: ["yanvar","fevral","mart","aprel","may","iyun","iyul","avgust","sentyabr","oktyabr","noyabr","dekabr",""], namesAbbr: ["Yan","Fev","Mar","Apr","May","İyun","İyul","Avg","Sen","Okt","Noy","Dek",""] }, AM: null, PM: null, patterns: { d: "dd.MM.yyyy", D: "dd MMMM yyyy'-cü il'", t: "HH:mm", T: "HH:mm:ss", f: "dd MMMM yyyy'-cü il' HH:mm", F: "dd MMMM yyyy'-cü il' HH:mm:ss", M: "d MMMM" } }, Hijri: { name: "Hijri", "/": ".", firstDay: 1, days: { names: ["Bazar","Bazar ertəsi","Çərşənbə axşamı","Çərşənbə","Cümə axşamı","Cümə","Şənbə"], namesAbbr: ["B","Be","Ça","Ç","Ca","C","Ş"], namesShort: ["B","Be","Ça","Ç","Ca","C","Ş"] }, months: { names: ["Məhərrəm","Səfər","Rəbiüləvvəl","Rəbiülaxır","Cəmadiyələvvəl","Cəmadiyəlaxır","Rəcəb","Şaban","Ramazan","Şəvval","Zilqədə","Zilhiccə",""], namesAbbr: ["Məhərrəm","Səfər","Rəbiüləvvəl","Rəbiülaxır","Cəmadiyələvvəl","Cəmadiyəlaxır","Rəcəb","Şaban","Ramazan","Şəvval","Zilqədə","Zilhiccə",""] }, AM: null, PM: null, twoDigitYearMax: 1451, patterns: { d: "dd.MM.yyyy", D: "d MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "d MMMM yyyy HH:mm", F: "d MMMM yyyy HH:mm:ss", M: "d MMMM" }, convert: { // Adapted to Script from System.Globalization.HijriCalendar ticks1970: 62135596800000, // number of days leading up to each month monthDays: [0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355], minDate: -42521673600000, maxDate: 253402300799999, // The number of days to add or subtract from the calendar to accommodate the variances // in the start and the end of Ramadan and to accommodate the date difference between // countries/regions. May be dynamically adjusted based on user preference, but should // remain in the range of -2 to 2, inclusive. hijriAdjustment: 0, toGregorian: function(hyear, hmonth, hday) { var daysSinceJan0101 = this.daysToYear(hyear) + this.monthDays[hmonth] + hday - 1 - this.hijriAdjustment; // 86400000 = ticks per day var gdate = new Date(daysSinceJan0101 * 86400000 - this.ticks1970); // adjust for timezone, because we are interested in the gregorian date for the same timezone // but ticks in javascript is always from GMT, unlike the server were ticks counts from the base // date in the current timezone. gdate.setMinutes(gdate.getMinutes() + gdate.getTimezoneOffset()); return gdate; }, fromGregorian: function(gdate) { if ((gdate < this.minDate) || (gdate > this.maxDate)) return null; var ticks = this.ticks1970 + (gdate-0) - gdate.getTimezoneOffset() * 60000, daysSinceJan0101 = Math.floor(ticks / 86400000) + 1 + this.hijriAdjustment; // very particular formula determined by someone smart, adapted from the server-side implementation. // it approximates the hijri year. var hday, hmonth, hyear = Math.floor(((daysSinceJan0101 - 227013) * 30) / 10631) + 1, absDays = this.daysToYear(hyear), daysInYear = this.isLeapYear(hyear) ? 355 : 354; // hyear is just approximate, it may need adjustment up or down by 1. if (daysSinceJan0101 < absDays) { hyear--; absDays -= daysInYear; } else if (daysSinceJan0101 === absDays) { hyear--; absDays = this.daysToYear(hyear); } else { if (daysSinceJan0101 > (absDays + daysInYear)) { absDays += daysInYear; hyear++; } } // determine month by looking at how many days into the hyear we are // monthDays contains the number of days up to each month. hmonth = 0; var daysIntoYear = daysSinceJan0101 - absDays; while (hmonth <= 11 && daysIntoYear > this.monthDays[hmonth]) { hmonth++; } hmonth--; hday = daysIntoYear - this.monthDays[hmonth]; return [hyear, hmonth, hday]; }, daysToYear: function(year) { // calculates how many days since Jan 1, 0001 var yearsToYear30 = Math.floor((year - 1) / 30) * 30, yearsInto30 = year - yearsToYear30 - 1, days = Math.floor((yearsToYear30 * 10631) / 30) + 227013; while (yearsInto30 > 0) { days += (this.isLeapYear(yearsInto30) ? 355 : 354); yearsInto30--; } return days; }, isLeapYear: function(year) { return ((((year * 11) + 14) % 30) < 11); } } } } });
Asaf-S/jsdelivr
files/syncfusion-ej-global/15.1.41/i18n/ej.culture.az-Latn-AZ.js
JavaScript
mit
6,524
/* Norwegian initialisation for the jQuery UI date picker plugin. */ /* Written by Naimdjon Takhirov (naimdjon@gmail.com). */ jQuery(function($){ $.datepicker.regional['no'] = { closeText: 'Lukk', prevText: '&laquo;Forrige', nextText: 'Neste&raquo;', currentText: 'I dag', monthNames: ['januar','februar','mars','april','mai','juni','juli','august','september','oktober','november','desember'], monthNamesShort: ['jan','feb','mar','apr','mai','jun','jul','aug','sep','okt','nov','des'], dayNamesShort: ['søn','man','tir','ons','tor','fre','lør'], dayNames: ['søndag','mandag','tirsdag','onsdag','torsdag','fredag','lørdag'], dayNamesMin: ['sø','ma','ti','on','to','fr','lø'], weekHeader: 'Uke', dateFormat: 'dd.mm.yy', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: '' }; $.datepicker.setDefaults($.datepicker.regional['no']); });
olek1984/dremboard
wp-content/plugins/wp-maintenance-mode/js/i18n/jquery.ui.datepicker-no.js
JavaScript
gpl-2.0
946