text
stringlengths
3
1.05M
from typing import Optional, Union import time import numbers from xnmt import batchers, events, logger, losses, sent, utils from xnmt.eval import metrics class AccumTimeTracker(object): def __init__(self) -> None: self.start_time = None self.accum_time = 0.0 def __enter__(self): self.start_time = time.time() def __exit__(self, *args): self.accum_time += time.time() - self.start_time def get_and_reset(self) -> numbers.Real: ret = self.accum_time self.accum_time = 0.0 return ret class TrainLossTracker(object): REPORT_TEMPLATE_SPEED = 'Epoch {epoch:.4f}: {data_name}_loss/word={loss:.6f} (words={words}, words/sec={words_per_sec:.2f}, time={time})' REPORT_TEMPLATE = 'Epoch {epoch:.4f}: {data_name}_loss/word={loss:.6f} (words={words}, words/sec={words_per_sec}, time={time})' REPORT_TEMPLATE_ADDITIONAL = '- {loss_name} {loss:5.6f}' REPORT_EVERY = 1000 @events.register_xnmt_handler def __init__(self, training_task: 'xnmt.train.tasks.TrainingTask') -> None: self.training_task = training_task self.epoch_loss = losses.FactoredLossVal() self.epoch_words = 0 self.last_report_sents_into_epoch = 0 self.last_report_sents_since_start = 0 self.last_report_words = 0 self.time_tracker = AccumTimeTracker() self.start_time = time.time() self.name = self.training_task.name @events.handle_xnmt_event def on_new_epoch(self, training_task, num_sents): if training_task is self.training_task: self.epoch_loss.clear() self.epoch_words = 0 self.last_report_sents_since_start = 0 self.last_report_words = 0 def report(self, trg: Union[sent.Sequence, batchers.Batch], loss: losses.FactoredLossVal) -> None: """ Accumulate training loss and report every REPORT_EVERY sentences. """ self.epoch_words += self.count_trg_words(trg) self.epoch_loss += loss sent_num_not_report = self.training_task.training_state.sents_since_start - self.last_report_sents_since_start should_report = sent_num_not_report >= TrainLossTracker.REPORT_EVERY \ or self.training_task.training_state.sents_into_epoch == self.training_task.cur_num_sentences() if should_report: fractional_epoch = (self.training_task.training_state.epoch_num - 1) \ + self.training_task.training_state.sents_into_epoch / self.training_task.cur_num_sentences() accum_time = self.time_tracker.get_and_reset() rep_train_loss = self.epoch_loss.sum_factors() / self.epoch_words utils.log_readable_and_tensorboard( template = TrainLossTracker.REPORT_TEMPLATE_SPEED if accum_time else TrainLossTracker.REPORT_TEMPLATE, args = {"loss": rep_train_loss}, n_iter = fractional_epoch, time = utils.format_time(time.time() - self.start_time), words = self.epoch_words, data_name = "train", task_name = self.name, words_per_sec = (self.epoch_words - self.last_report_words) / accum_time if accum_time else None ) if len(self.epoch_loss) > 1: for loss_name, loss_values in self.epoch_loss.items(): utils.log_readable_and_tensorboard(template=TrainLossTracker.REPORT_TEMPLATE_ADDITIONAL, args={loss_name: loss_values / self.epoch_words}, n_iter=fractional_epoch, data_name="train", task_name=self.name, loss_name=loss_name, loss=loss_values / self.epoch_words, ) self.last_report_words = self.epoch_words self.last_report_sents_since_start = self.training_task.training_state.sents_since_start def count_trg_words(self, trg_words: Union[sent.Sentence, batchers.Batch]) -> int: if isinstance(trg_words, batchers.Batch): return sum(inp.len_unpadded() for inp in trg_words) else: return trg_words.len_unpadded() class DevLossTracker(object): REPORT_TEMPLATE_DEV = 'Epoch {epoch:.4f} dev {score} (time={time})' REPORT_TEMPLATE_DEV_AUX = ' dev auxiliary {score}' REPORT_TEMPLATE_TIME_NEEDED = ' checkpoint took {time_needed}' def __init__(self, training_task: 'xnmt.train.tasks.TrainingTask', eval_every: numbers.Integral, name: Optional[str]=None) -> None: self.training_task = training_task self.eval_dev_every = eval_every self.last_report_sents_since_start = 0 self.fractional_epoch = 0 self.dev_score = None self.aux_scores = [] self.start_time = time.time() self.name = name self.time_tracker = AccumTimeTracker() def set_dev_score(self, dev_score: metrics.EvalScore) -> None: self.dev_score = dev_score def add_aux_score(self, score: metrics.EvalScore) -> None: self.aux_scores.append(score) def should_report_dev(self) -> bool: sent_num_not_report = self.training_task.training_state.sents_since_start - self.last_report_sents_since_start if self.eval_dev_every > 0: return sent_num_not_report >= self.eval_dev_every else: return sent_num_not_report >= self.training_task.cur_num_sentences() def report(self) -> None: this_report_time = time.time() self.last_report_sents_since_start = self.training_task.training_state.sents_since_start self.fractional_epoch = (self.training_task.training_state.epoch_num - 1) \ + self.training_task.training_state.sents_into_epoch / self.training_task.cur_num_sentences() dev_time = self.time_tracker.get_and_reset() utils.log_readable_and_tensorboard(template=DevLossTracker.REPORT_TEMPLATE_DEV, args={self.dev_score.metric_name(): self.dev_score.value()}, n_iter=self.fractional_epoch, data_name="dev", task_name=self.name, score=self.dev_score, time=utils.format_time(this_report_time - self.start_time)) for score in self.aux_scores: utils.log_readable_and_tensorboard(template=DevLossTracker.REPORT_TEMPLATE_DEV_AUX, args={score.metric_name(): score.value()}, n_iter=self.fractional_epoch, data_name="dev", task_name=self.name, score=score) logger.info(DevLossTracker.REPORT_TEMPLATE_TIME_NEEDED.format(time_needed= utils.format_time(dev_time), extra={"task_name" : self.name})) self.aux_scores = []
describe('filter', function() { beforeEach(module('spBlogger.admin.filters')); describe('Permalink Filter Test\n', function() { it('Should Replace all spaces with hyphens and convert to lowercase', inject(function(permalinkFilter) { expect(permalinkFilter('I had 3 spaces')).toEqual('i-had-3-spaces'); })); }); describe('Wordcount Filter Test\n', function() { it('Should count the number of words as 3', inject(function(wordcountFilter) { expect(wordcountFilter('Three words here')).toEqual(3); })); }); });
import asyncio import pytest from hat import util from hat import aio from hat.drivers import tcp @pytest.fixture def addr(): return tcp.Address('127.0.0.1', util.get_unused_tcp_port()) async def test_connect_listen(addr): with pytest.raises(ConnectionError): await tcp.connect(addr) conn_queue = aio.Queue() srv = await tcp.listen(conn_queue.put_nowait, addr) conn1 = await tcp.connect(addr) conn2 = await conn_queue.get() assert srv.is_open assert conn1.is_open assert conn2.is_open assert srv.addresses == [addr] assert conn1.info.local_addr == conn2.info.remote_addr assert conn1.info.remote_addr == conn2.info.local_addr await conn1.async_close() await conn2.async_close() await srv.async_close() async def test_read(addr): conn_queue = aio.Queue() srv = await tcp.listen(conn_queue.put_nowait, addr) conn1 = await tcp.connect(addr) conn2 = await conn_queue.get() data = b'123' result = await conn1.read(0) assert result == b'' conn1.write(data) await conn1.drain() result = await conn2.read(len(data)) assert result == data conn2.write(data) result = await conn1.read(len(data) - 1) assert result == data[:-1] result = await conn1.read(1) assert result == data[-1:] conn2.write(data) result = await conn1.read(len(data) + 1) assert result == data conn2.write(data) await conn2.async_close() result = await conn1.read() assert result == data with pytest.raises(ConnectionError): await conn1.read() with pytest.raises(ConnectionError): await conn2.read() await conn1.async_close() await srv.async_close() async def test_readexactly(addr): conn_queue = aio.Queue() srv = await tcp.listen(conn_queue.put_nowait, addr) conn1 = await tcp.connect(addr) conn2 = await conn_queue.get() data = b'123' result = await conn1.readexactly(0) assert result == b'' conn1.write(data) result = await conn2.readexactly(len(data)) assert result == data conn2.write(data) result = await conn1.readexactly(len(data) - 1) assert result == data[:-1] result = await conn1.readexactly(1) assert result == data[-1:] conn2.write(data) await conn2.async_close() with pytest.raises(ConnectionError): await conn1.readexactly(len(data) + 1) with pytest.raises(ConnectionError): await conn1.readexactly(1) await conn1.async_close() await srv.async_close() @pytest.mark.parametrize("bind_connections", [True, False]) @pytest.mark.parametrize("conn_count", [1, 2, 5]) async def test_bind_connections(addr, bind_connections, conn_count): conn_queue = aio.Queue() srv = await tcp.listen(conn_queue.put_nowait, addr, bind_connections=bind_connections) conns = [] for _ in range(conn_count): conn1 = await tcp.connect(addr) conn2 = await conn_queue.get() conns.append((conn1, conn2)) for conn1, conn2 in conns: assert conn1.is_open assert conn2.is_open await srv.async_close() for conn1, conn2 in conns: if bind_connections: with pytest.raises(ConnectionError): await conn1.read() assert not conn1.is_open assert not conn2.is_open else: assert conn1.is_open assert conn2.is_open await conn1.async_close() await conn2.async_close() async def test_example_docs(): addr = tcp.Address('127.0.0.1', util.get_unused_tcp_port()) conn2_future = asyncio.Future() srv = await tcp.listen(conn2_future.set_result, addr) conn1 = await tcp.connect(addr) conn2 = await conn2_future # send from conn1 to conn2 data = b'123' conn1.write(data) result = await conn2.readexactly(len(data)) assert result == data # send from conn2 to conn1 data = b'321' conn2.write(data) result = await conn1.readexactly(len(data)) assert result == data await conn1.async_close() await conn2.async_close() await srv.async_close()
from manimlib.imports import * NEW_BLUE = "#68a8e1" class Thumbnail(GraphScene): CONFIG = { "y_max": 8, "y_axis_height": 5, } def construct(self): self.show_function_graph() def show_function_graph(self): self.setup_axes(animate=False) def func(x): return 0.1 * (x + 3-5) * (x - 3-5) * (x-5) + 5 def rect(x): return 2.775*(x-1.5)+3.862 recta = self.get_graph(rect, x_min=-1, x_max=5) graph = self.get_graph(func, x_min=0.2, x_max=9) graph.set_color(NEW_BLUE) input_tracker_p1 = ValueTracker(1.5) input_tracker_p2 = ValueTracker(3.5) def get_x_value(input_tracker): return input_tracker.get_value() def get_y_value(input_tracker): return graph.underlying_function(get_x_value(input_tracker)) def get_x_point(input_tracker): return self.coords_to_point(get_x_value(input_tracker), 0) def get_y_point(input_tracker): return self.coords_to_point(0, get_y_value(input_tracker)) def get_graph_point(input_tracker): return self.coords_to_point(get_x_value(input_tracker), get_y_value(input_tracker)) def get_v_line(input_tracker): return DashedLine(get_x_point(input_tracker), get_graph_point(input_tracker), stroke_width=2) def get_h_line(input_tracker): return DashedLine(get_graph_point(input_tracker), get_y_point(input_tracker), stroke_width=2) # input_triangle_p1 = RegularPolygon(n=3, start_angle=TAU / 4) output_triangle_p1 = RegularPolygon(n=3, start_angle=0) for triangle in input_triangle_p1, output_triangle_p1: triangle.set_fill(WHITE, 1) triangle.set_stroke(width=0) triangle.scale(0.1) # input_triangle_p2 = RegularPolygon(n=3, start_angle=TAU / 4) output_triangle_p2 = RegularPolygon(n=3, start_angle=0) for triangle in input_triangle_p2, output_triangle_p2: triangle.set_fill(WHITE, 1) triangle.set_stroke(width=0) triangle.scale(0.1) # x_label_p1 = TexMobject("a") output_label_p1 = TexMobject("f(a)") x_label_p2 = TexMobject("b") output_label_p2 = TexMobject("f(b)") v_line_p1 = get_v_line(input_tracker_p1) v_line_p2 = get_v_line(input_tracker_p2) h_line_p1 = get_h_line(input_tracker_p1) h_line_p2 = get_h_line(input_tracker_p2) graph_dot_p1 = Dot(color=WHITE) graph_dot_p2 = Dot(color=WHITE) # reposition mobjects x_label_p1.next_to(v_line_p1, DOWN) x_label_p2.next_to(v_line_p2, DOWN) output_label_p1.next_to(h_line_p1, LEFT) output_label_p2.next_to(h_line_p2, LEFT) input_triangle_p1.next_to(v_line_p1, DOWN, buff=0) input_triangle_p2.next_to(v_line_p2, DOWN, buff=0) output_triangle_p1.next_to(h_line_p1, LEFT, buff=0) output_triangle_p2.next_to(h_line_p2, LEFT, buff=0) graph_dot_p1.move_to(get_graph_point(input_tracker_p1)) graph_dot_p2.move_to(get_graph_point(input_tracker_p2)) # self.play( ShowCreation(graph), ) # Animacion del punto a self.add_foreground_mobject(graph_dot_p1) self.add_foreground_mobject(graph_dot_p2) self.play( DrawBorderThenFill(input_triangle_p1), Write(x_label_p1), ShowCreation(v_line_p1), GrowFromCenter(graph_dot_p1), ShowCreation(h_line_p1), Write(output_label_p1), DrawBorderThenFill(output_triangle_p1), DrawBorderThenFill(input_triangle_p2), Write(x_label_p2), ShowCreation(v_line_p2), GrowFromCenter(graph_dot_p2), ShowCreation(h_line_p2), Write(output_label_p2), DrawBorderThenFill(output_triangle_p2), run_time=0.5 ) self.add( input_triangle_p2, x_label_p2, graph_dot_p2, v_line_p2, h_line_p2, output_triangle_p2, output_label_p2, ) ################### pendiente_recta = self.get_secant_slope_group( 1.9, recta, dx=1.4, df_label=None, dx_label=None, dx_line_color=PURPLE, df_line_color=ORANGE, ) grupo_secante = self.get_secant_slope_group( 1.5, graph, dx=2, df_label=None, dx_label=None, dx_line_color="#942357", df_line_color="#3f7d5c", secant_line_color=RED, ) self.add( input_triangle_p2, graph_dot_p2, v_line_p2, h_line_p2, output_triangle_p2, ) self.play(FadeIn(grupo_secante)) kwargs = { "x_min": 4, "x_max": 9, "fill_opacity": 0.75, "stroke_width": 0.25, } self.graph = graph iteraciones = 6 self.rect_list = self.get_riemann_rectangles_list( graph, iteraciones, start_color=PURPLE, end_color=ORANGE, **kwargs ) flat_rects = self.get_riemann_rectangles( self.get_graph(lambda x: 0), dx=0.5, start_color=invert_color(PURPLE), end_color=invert_color(ORANGE), **kwargs ) rects = self.rect_list[0] self.transform_between_riemann_rects( flat_rects, rects, replace_mobject_with_target_in_scene=True, run_time=0.9 ) # adding manim picture = Group(*self.mobjects) picture.scale(0.6).to_edge(LEFT, buff=SMALL_BUFF) manim = TextMobject("Manim").set_height(1.5) \ .next_to(picture, RIGHT) \ .shift(DOWN * 0.7) self.add(manim)
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime import re from collections import OrderedDict from future.backports.urllib.parse import quote_plus from saml2_tophat.config import Config from saml2_tophat.mdstore import MetadataStore, MetaDataExtern from saml2_tophat.mdstore import MetaDataMDX from saml2_tophat.mdstore import SAML_METADATA_CONTENT_TYPE from saml2_tophat.mdstore import destinations from saml2_tophat.mdstore import name from saml2_tophat import sigver from saml2_tophat.httpbase import HTTPBase from saml2_tophat import BINDING_SOAP from saml2_tophat import BINDING_HTTP_REDIRECT from saml2_tophat import BINDING_HTTP_POST from saml2_tophat import BINDING_HTTP_ARTIFACT from saml2_tophat import config from saml2_tophat.attribute_converter import ac_factory from saml2_tophat.attribute_converter import d_to_local_name from saml2_tophat.s_utils import UnknownPrincipal from pathutils import full_path import responses sec_config = config.Config() # sec_config.xmlsec_binary = sigver.get_xmlsec_binary(["/opt/local/bin"]) TEST_CERT = """MIICsDCCAhmgAwIBAgIJAJrzqSSwmDY9MA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMDkxMDA2MTk0OTQxWhcNMDkxMTA1MTk0OTQxWjBF MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQDJg2cms7MqjniT8Fi/XkNHZNPbNVQyMUMXE9tXOdqwYCA1cc8vQdzkihscQMXy 3iPw2cMggBu6gjMTOSOxECkuvX5ZCclKr8pXAJM5cY6gVOaVO2PdTZcvDBKGbiaN efiEw5hnoZomqZGp8wHNLAUkwtH9vjqqvxyS/vclc6k2ewIDAQABo4GnMIGkMB0G A1UdDgQWBBRePsKHKYJsiojE78ZWXccK9K4aJTB1BgNVHSMEbjBsgBRePsKHKYJs iojE78ZWXccK9K4aJaFJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUt U3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAJrzqSSw mDY9MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAJSrKOEzHO7TL5cy6 h3qh+3+JAk8HbGBW+cbX6KBCAw/mzU8flK25vnWwXS3dv2FF3Aod0/S7AWNfKib5 U/SA9nJaz/mWeF9S0farz9AQFc8/NSzAzaVq7YbM4F6f6N2FRl7GikdXRCed45j6 mrPzGzk3ECbupFnqyREH3+ZPSdk=""" TEST_METADATA_STRING = """ <EntitiesDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:shibmeta="urn:mace:shibboleth:metadata:1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Name="urn:mace:example.com:test-1.0"> <EntityDescriptor entityID="http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php" xml:base="swamid-1.0/idp.umu.se-saml2_tophat.xml"> <IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"> <KeyDescriptor> <ds:KeyInfo> <ds:X509Data> <ds:X509Certificate> {cert_data} </ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> </KeyDescriptor> <NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</NameIDFormat> <SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php"/> </IDPSSODescriptor> <Organization> <OrganizationName xml:lang="en">Catalogix</OrganizationName> <OrganizationDisplayName xml:lang="en">Catalogix</OrganizationDisplayName> <OrganizationURL xml:lang="en">http://www.catalogix.se</OrganizationURL> </Organization> <ContactPerson contactType="technical"> <SurName>Hedberg</SurName> <EmailAddress>[email protected]</EmailAddress> </ContactPerson> </EntityDescriptor> </EntitiesDescriptor> """.format(cert_data=TEST_CERT) ATTRCONV = ac_factory(full_path("attributemaps")) METADATACONF = { "1": [{ "class": "saml2_tophat.mdstore.MetaDataFile", "metadata": [(full_path("swamid-1.0.xml"),)], }], "2": [{ "class": "saml2_tophat.mdstore.MetaDataFile", "metadata": [(full_path("InCommon-metadata.xml"),)], }], "3": [{ "class": "saml2_tophat.mdstore.MetaDataFile", "metadata": [(full_path("extended.xml"),)], }], # "7": [{ # "class": "saml2_tophat.mdstore.MetaDataFile", # "metadata": [(full_path("metadata_sp_1.xml"), ), # (full_path("InCommon-metadata.xml"), )], }, # { # "class": "saml2_tophat.mdstore.MetaDataExtern", # "metadata": [ # ("https://kalmar2.org/simplesaml/module.php/aggregator/?id # =kalmarcentral2&set=saml2_tophat", # full_path("kalmar2.pem")), ], # }], "4": [{ "class": "saml2_tophat.mdstore.MetaDataFile", "metadata": [(full_path("metadata_example.xml"),)], }], "5": [{ "class": "saml2_tophat.mdstore.MetaDataFile", "metadata": [(full_path("metadata.aaitest.xml"),)], }], "8": [{ "class": "saml2_tophat.mdstore.MetaDataMD", "metadata": [(full_path("swamid.md"),)], }], "9": [{ "class": "saml2_tophat.mdstore.MetaDataFile", "metadata": [(full_path("metadata"),)] }], "10": [{ "class": "saml2_tophat.mdstore.MetaDataExtern", "metadata": [ ("http://md.incommon.org/InCommon/InCommon-metadata-export.xml", full_path("inc-md-cert.pem"))] }], "11": [{ "class": "saml2_tophat.mdstore.InMemoryMetaData", "metadata": [(TEST_METADATA_STRING,)] }], "12": [{ "class": "saml2_tophat.mdstore.MetaDataFile", "metadata": [(full_path("uu.xml"),)], }], } def _eq(l1, l2): return set(l1) == set(l2) def _fix_valid_until(xmlstring): new_date = datetime.datetime.now() + datetime.timedelta(days=1) new_date = new_date.strftime("%Y-%m-%dT%H:%M:%SZ") return re.sub(r' validUntil=".*?"', ' validUntil="%s"' % new_date, xmlstring) def test_swami_1(): UMU_IDP = 'https://idp.umu.se/saml2/idp/metadata.php' mds = MetadataStore(ATTRCONV, sec_config, disable_ssl_certificate_validation=True) mds.imp(METADATACONF["1"]) assert len(mds) == 1 # One source idps = mds.with_descriptor("idpsso") assert idps.keys() idpsso = mds.single_sign_on_service(UMU_IDP) assert len(idpsso) == 1 assert destinations(idpsso) == [ 'https://idp.umu.se/saml2/idp/SSOService.php'] _name = name(mds[UMU_IDP]) assert _name == u'Umeå University (SAML2)' certs = mds.certs(UMU_IDP, "idpsso", "signing") assert len(certs) == 1 sps = mds.with_descriptor("spsso") assert len(sps) == 108 wants = mds.attribute_requirement('https://connect8.sunet.se/shibboleth') lnamn = [d_to_local_name(mds.attrc, attr) for attr in wants["optional"]] assert _eq(lnamn, ['eduPersonPrincipalName', 'mail', 'givenName', 'sn', 'eduPersonScopedAffiliation']) wants = mds.attribute_requirement('https://beta.lobber.se/shibboleth') assert wants["required"] == [] lnamn = [d_to_local_name(mds.attrc, attr) for attr in wants["optional"]] assert _eq(lnamn, ['eduPersonPrincipalName', 'mail', 'givenName', 'sn', 'eduPersonScopedAffiliation', 'eduPersonEntitlement']) def test_incommon_1(): mds = MetadataStore(ATTRCONV, sec_config, disable_ssl_certificate_validation=True) mds.imp(METADATACONF["2"]) print(mds.entities()) assert mds.entities() > 1700 idps = mds.with_descriptor("idpsso") print(idps.keys()) assert len(idps) > 300 # ~ 18% try: _ = mds.single_sign_on_service('urn:mace:incommon:uiuc.edu') except UnknownPrincipal: pass idpsso = mds.single_sign_on_service('urn:mace:incommon:alaska.edu') assert len(idpsso) == 1 print(idpsso) assert destinations(idpsso) == [ 'https://idp.alaska.edu/idp/profile/SAML2/Redirect/SSO'] sps = mds.with_descriptor("spsso") acs_sp = [] for nam, desc in sps.items(): if "attribute_consuming_service" in desc: acs_sp.append(nam) assert len(acs_sp) == 0 # Look for attribute authorities aas = mds.with_descriptor("attribute_authority") print(aas.keys()) assert len(aas) == 180 def test_ext_2(): mds = MetadataStore(ATTRCONV, sec_config, disable_ssl_certificate_validation=True) mds.imp(METADATACONF["3"]) # No specific binding defined ents = mds.with_descriptor("spsso") for binding in [BINDING_SOAP, BINDING_HTTP_POST, BINDING_HTTP_ARTIFACT, BINDING_HTTP_REDIRECT]: assert mds.single_logout_service(list(ents.keys())[0], binding, "spsso") def test_example(): mds = MetadataStore(ATTRCONV, sec_config, disable_ssl_certificate_validation=True) mds.imp(METADATACONF["4"]) assert len(mds.keys()) == 1 idps = mds.with_descriptor("idpsso") assert list(idps.keys()) == [ 'http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php'] certs = mds.certs( 'http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php', "idpsso", "signing") assert len(certs) == 1 def test_switch_1(): mds = MetadataStore(ATTRCONV, sec_config, disable_ssl_certificate_validation=True) mds.imp(METADATACONF["5"]) assert len(mds.keys()) > 160 idps = mds.with_descriptor("idpsso") print(idps.keys()) idpsso = mds.single_sign_on_service( 'https://aai-demo-idp.switch.ch/idp/shibboleth') assert len(idpsso) == 1 print(idpsso) assert destinations(idpsso) == [ 'https://aai-demo-idp.switch.ch/idp/profile/SAML2/Redirect/SSO'] assert len(idps) > 30 aas = mds.with_descriptor("attribute_authority") print(aas.keys()) aad = aas['https://aai-demo-idp.switch.ch/idp/shibboleth'] print(aad.keys()) assert len(aad["attribute_authority_descriptor"]) == 1 assert len(aad["idpsso_descriptor"]) == 1 sps = mds.with_descriptor("spsso") dual = [eid for eid, ent in idps.items() if eid in sps] print(len(dual)) assert len(dual) == 0 def test_metadata_file(): sec_config.xmlsec_binary = sigver.get_xmlsec_binary(["/opt/local/bin"]) mds = MetadataStore(ATTRCONV, sec_config, disable_ssl_certificate_validation=True) mds.imp(METADATACONF["8"]) print(len(mds.keys())) assert len(mds.keys()) == 560 @responses.activate def test_mdx_service(): entity_id = "http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php" url = "http://mdx.example.com/entities/{}".format( quote_plus(MetaDataMDX.sha1_entity_transform(entity_id))) responses.add(responses.GET, url, body=TEST_METADATA_STRING, status=200, content_type=SAML_METADATA_CONTENT_TYPE) mdx = MetaDataMDX("http://mdx.example.com") sso_loc = mdx.service(entity_id, "idpsso_descriptor", "single_sign_on_service") assert sso_loc[BINDING_HTTP_REDIRECT][0]["location"] == "http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php" certs = mdx.certs(entity_id, "idpsso") assert len(certs) == 1 @responses.activate def test_mdx_single_sign_on_service(): entity_id = "http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php" url = "http://mdx.example.com/entities/{}".format( quote_plus(MetaDataMDX.sha1_entity_transform(entity_id))) responses.add(responses.GET, url, body=TEST_METADATA_STRING, status=200, content_type=SAML_METADATA_CONTENT_TYPE) mdx = MetaDataMDX("http://mdx.example.com") sso_loc = mdx.single_sign_on_service(entity_id, BINDING_HTTP_REDIRECT) assert sso_loc[0]["location"] == "http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php" # pyff-test not available # def test_mdx_service(): # sec_config.xmlsec_binary = sigver.get_xmlsec_binary(["/opt/local/bin"]) # http = HTTPBase(verify=False, ca_bundle=None) # # mdx = MetaDataMDX(quote_plus, ATTRCONV, # "http://pyff-test.nordu.net", # sec_config, None, http) # foo = mdx.service("https://idp.umu.se/saml2/idp/metadata.php", # "idpsso_descriptor", "single_sign_on_service") # # assert len(foo) == 1 # assert foo.keys()[0] == BINDING_HTTP_REDIRECT # # # def test_mdx_certs(): # sec_config.xmlsec_binary = sigver.get_xmlsec_binary(["/opt/local/bin"]) # http = HTTPBase(verify=False, ca_bundle=None) # # mdx = MetaDataMDX(quote_plus, ATTRCONV, # "http://pyff-test.nordu.net", # sec_config, None, http) # foo = mdx.certs("https://idp.umu.se/saml2/idp/metadata.php", "idpsso") # # assert len(foo) == 1 def test_load_local_dir(): sec_config.xmlsec_binary = sigver.get_xmlsec_binary(["/opt/local/bin"]) mds = MetadataStore(ATTRCONV, sec_config, disable_ssl_certificate_validation=True) mds.imp(METADATACONF["9"]) print(mds) assert len(mds) == 3 # Three sources assert len(mds.keys()) == 4 # number of idps def test_load_extern_incommon(): sec_config.xmlsec_binary = sigver.get_xmlsec_binary(["/opt/local/bin"]) mds = MetadataStore(ATTRCONV, sec_config, disable_ssl_certificate_validation=True) mds.imp(METADATACONF["10"]) print(mds) assert mds assert len(mds.keys()) def test_load_local(): # string representation of XML idp definition with open(full_path("metadata.xml")) as fp: idp_metadata = fp.read() saml_config = Config() config_dict = { "metadata": {"inline": [idp_metadata]} } cfg = saml_config.load(config_dict) assert cfg def test_load_remote_encoding(): crypto = sigver._get_xmlsec_cryptobackend() sc = sigver.SecurityContext(crypto, key_type="", cert_type="") httpc = HTTPBase() mds = MetaDataExtern(ATTRCONV, 'http://metadata.aai.switch.ch/metadata.aaitest.xml', sc, full_path('SWITCHaaiRootCA.crt.pem'), httpc) mds.load() def test_load_string(): sec_config.xmlsec_binary = sigver.get_xmlsec_binary(["/opt/local/bin"]) mds = MetadataStore(ATTRCONV, sec_config, disable_ssl_certificate_validation=True) mds.imp(METADATACONF["11"]) # print(mds) assert len(mds.keys()) == 1 idps = mds.with_descriptor("idpsso") assert list(idps.keys()) == [ 'http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php'] certs = mds.certs( 'http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php', "idpsso", "signing") assert len(certs) == 1 def test_get_certs_from_metadata(): mds = MetadataStore(ATTRCONV, None) mds.imp(METADATACONF["11"]) certs1 = mds.certs("http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php", "any") certs2 = mds.certs("http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php", "idpsso") assert certs1[0] == certs2[0] == TEST_CERT def test_get_certs_from_metadata_without_keydescriptor(): mds = MetadataStore(ATTRCONV, None) mds.imp([{ "class": "saml2_tophat.mdstore.InMemoryMetaData", "metadata": [(""" <EntitiesDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:shibmeta="urn:mace:shibboleth:metadata:1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Name="urn:mace:example.com:test-1.0"> <EntityDescriptor entityID="http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php" xml:base="swamid-1.0/idp.umu.se-saml2_tophat.xml"> <IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"> <NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</NameIDFormat> <SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php"/> </IDPSSODescriptor> <Organization> <OrganizationName xml:lang="en">Catalogix</OrganizationName> <OrganizationDisplayName xml:lang="en">Catalogix</OrganizationDisplayName> <OrganizationURL xml:lang="en">http://www.catalogix.se</OrganizationURL> </Organization> <ContactPerson contactType="technical"> <SurName>Hedberg</SurName> <EmailAddress>[email protected]</EmailAddress> </ContactPerson> </EntityDescriptor> </EntitiesDescriptor>""",)] }]) certs = mds.certs("http://xenosmilus.umdc.umu.se/simplesaml/saml2/idp/metadata.php", "idpsso") assert len(certs) == 0 def test_metadata_extension_algsupport(): mds = MetadataStore(ATTRCONV, None) mds.imp(METADATACONF["12"]) mdf = mds.metadata[full_path("uu.xml")] assert mds def test_extension(): mds = MetadataStore(ATTRCONV, None) # use ordered dict to force expected entity to be last metadata = OrderedDict() metadata["1"] = {"entity1": {}} metadata["2"] = {"entity2": {"idpsso_descriptor": [{"extensions": {"extension_elements": [{"__class__": "test"}]}}]}} mds.metadata = metadata assert mds.extension("entity2", "idpsso_descriptor", "test") if __name__ == "__main__": test_metadata_extension_algsupport()
from setuptools import setup, find_packages # Always prefer setuptools over distutils from codecs import open # To use a consistent encoding from os import path here = path.abspath(path.dirname(__file__)) setup( name='common_etl', version='0.0.2', description='A sample Python project', # The project's main homepage. url='https://github.com/OpenAddressesUK/common-ETL', # Author details author='John Murray', # Choose your license license='MIT', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['contrib', 'docs', 'tests*']), # List run-time dependencies here. These will be installed by pip when your # project is installed. For an analysis of "install_requires" vs pip's # requirements files see: # https://packaging.python.org/en/latest/technical.html#install-requires-vs-requirements-files # install_requires=['peppercorn'], # List additional groups of dependencies here (e.g. development dependencies). # You can install these using the following syntax, for example: # $ pip install -e .[dev,test] # extras_require = { # 'dev': ['check-manifest'], # 'test': ['coverage'], # }, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. # package_data={ # 'sample': ['package_data.dat'], # }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. # see http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' # data_files=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. # entry_points={ # 'console_scripts': [ # 'sample=sample:main', # ], # }, )
const sequelize = require('../config/connection'); const { Employee, Project, Task, ProjectEmployee } = require('../models'); const employeeData = require('./employeeData.json'); const projectData = require('./projectData.json'); const taskData = require('./taskData.json'); const seedDatabase = async () => { await sequelize.sync({ force: true }); const employees = await Employee.bulkCreate(employeeData, { individualHooks: true, returning: true, }); const projects = await Project.bulkCreate(projectData, { returning: true }) for (const i in projects) { for (let j = 0; j < employees.length; j++) { await ProjectEmployee.create({ project_id: projects[i].id, employee_id: employees[j].id }) } } for (const task of taskData) { let randomNumber = employees[Math.floor(Math.random() * employees.length)].id; const employeeData = await Employee.findByPk(randomNumber); await Task.create({ ...task, project_id: projects[Math.floor(Math.random() * projects.length)].id, employee_id: randomNumber, task_user: employeeData.dataValues.username }); } process.exit(0); }; seedDatabase();
export default function Modal () { const modalWrapper = document.querySelector('.modal-wrapper') const cancelButton = document.querySelector('.button.cancel') cancelButton.addEventListener('click', close) function open() { //funcionalidade de atribuir a classe active para a modal modalWrapper.classList.add('active') } function close() { //funcionalidade de remover a classe active para a modal modalWrapper.classList.remove('active') } return { open, close } }
const nbayes = require('./lib/io-naivebayes'); nbayes.train('positif', 'budi alhamdulillah'); nbayes.train('negatif', 'budi suka bom'); console.log(nbayes.classify('alhamdulillah baik baik saja')); console.log(nbayes.classifyplus('bom itu meledak'));
const { Game, InvItem, Capability } = require("../../classes"); import { COMM_INTERRUP_SELECTED } from "../../../client/src/redux/actions/actionTypes"; import { SOCKET_SERVER_REDIRECT, SOCKET_SERVER_SENDING_ACTION } from "../../../client/src/constants/otherConstants"; import { GAME_INACTIVE_TAG, GAME_DOES_NOT_EXIST } from "../../pages/errorTypes"; import { COMMUNICATIONS_INTERRUPTION_TYPE_ID, COMBAT_PHASE_ID, SLICE_PLANNING_ID, TYPE_MAIN } from "../../../client/src/constants/gameConstants"; const sendUserFeedback = require("../sendUserFeedback"); const commInterruptConfirm = async (socket, payload) => { const { gameId, gameTeam, gameControllers } = socket.handshake.session.ir3; if (payload == null || payload.selectedPositionId == null) { sendUserFeedback(socket, "Server Error: Malformed Payload (missing selectedPositionId)"); return; } const { selectedPositionId, invItem } = payload; const thisGame = await new Game({ gameId }).init(); if (!thisGame) { socket.emit(SOCKET_SERVER_REDIRECT, GAME_DOES_NOT_EXIST); return; } const { gameActive, gamePhase, gameSlice, game0Points, game1Points } = thisGame; if (!gameActive) { socket.emit(SOCKET_SERVER_REDIRECT, GAME_INACTIVE_TAG); return; } //gamePhase 2 is only phase for comm interrupt if (gamePhase != COMBAT_PHASE_ID) { sendUserFeedback(socket, "Not the right phase..."); return; } //gameSlice 0 is only slice for comm interrupt if (gameSlice != SLICE_PLANNING_ID) { sendUserFeedback(socket, "Not the right slice (must be planning)..."); return; } //Only the main controller (0) can use comm interrupt if (!gameControllers.includes(TYPE_MAIN)) { sendUserFeedback(socket, "Not the main controller (0)..."); return; } const { invItemId } = invItem; //Does the invItem exist for it? const thisInvItem = await new InvItem(invItemId).init(); if (!thisInvItem) { sendUserFeedback(socket, "Did not have the invItem to complete this request."); return; } //verify correct type of inv item const { invItemTypeId } = thisInvItem; if (invItemTypeId != COMMUNICATIONS_INTERRUPTION_TYPE_ID) { sendUserFeedback(socket, "Inv Item was not a comm interrupt type."); return; } //does the position make sense? if (selectedPositionId < 0) { sendUserFeedback(socket, "got a negative position for comm interrupt."); return; } //insert the 'plan' for comm interrupt into the db for later use if (!(await Capability.insertCommInterrupt(gameId, gameTeam, selectedPositionId))) { sendUserFeedback(socket, "db failed to insert comm interrupt, likely already an entry for that position."); return; } await thisInvItem.delete(); const confirmedCommInterrupt = await Capability.getCommInterrupt(gameId, gameTeam); // let the client(team) know that this plan was accepted const serverAction = { type: COMM_INTERRUP_SELECTED, payload: { invItem: thisInvItem, confirmedCommInterrupt } }; socket.emit(SOCKET_SERVER_SENDING_ACTION, serverAction); }; module.exports = commInterruptConfirm;
// A GIFBuilder based on the gifshot module import {assert} from './lib/utils/assert'; import gifshot from './libs/gifshot'; // TODO - load dynamically to avoid bloating // These are gifshot module options const GIF_BUILDER_OPTIONS = { source: 'images', width: 200, // Desired width of the image height: 200, // Desired height of the image crossOrigin: 'Anonymous', // Options are 'Anonymous', 'use-credentials', or a falsy value to not set a CORS attribute. // CALLBACKS progressCallback: (captureProgress) => {}, // Callback that provides the current progress of the current image completeCallback: () => {}, // Callback function that is called when the current image is completed // QUALITY SETTINGS numWorkers: 2, // how many web workers to use to process the animated GIF frames. Default is 2. sampleInterval: 10, // pixels to skip when creating the palette. Default is 10. Less is better, but slower. interval: 0.1, // The amount of time (in seconds) to wait between each frame capture offset: null, // The amount of time (in seconds) to start capturing the GIF (only for HTML5 videos) numFrames: 10, // The number of frames to use to create the animated GIF. Note: Each frame is captured every 100 milliseconds of a video and every ms for existing images frameDuration: 1, // The amount of time (10 = 1s) to stay on each frame // CSS FILTER OPTIONS filter: '', // CSS filter that will be applied to the image (eg. blur(5px)) // WATERMARK OPTIONS waterMark: null, // If an image is given here, it will be stamped on top of the GIF frames waterMarkHeight: null, // Height of the waterMark waterMarkWidth: null, // Height of the waterMark waterMarkXCoordinate: 1, // The X (horizontal) Coordinate of the watermark image waterMarkYCoordinate: 1, // The Y (vertical) Coordinate of the watermark image // TEXT OPTIONS text: '', // The text that covers the animated GIF showFrameText: true, // If frame-specific text is supplied with the image array, you can force to not be displayed fontWeight: 'normal', // The font weight of the text that covers the animated GIF fontSize: '16px', // The font size of the text that covers the animated GIF minFontSize: '10px', // The minimum font size of the text that covers the animated GIF resizeFont: false, // Whether or not the animated GIF text will be resized to fit within the GIF container fontFamily: 'sans-serif', // The font family of the text that covers the animated GIF fontColor: '#ffffff', // The font color of the text that covers the animated GIF textAlign: 'center', // The horizontal text alignment of the text that covers the animated GIF textBaseline: 'bottom', // The vertical text alignment of the text that covers the animated GIF textXCoordinate: null, // The X (horizontal) Coordinate of the text that covers the animated GIF textYCoordinate: null, // The Y (vertical) Coordinate of the text that covers the animated GIF // ADVANCED OPTIONS // WEBCAM CAPTURE OPTIONS webcamVideoElement: null, // You can pass an existing video element to use for the webcam GIF creation process, keepCameraOn: false, // Whether or not you would like the user's camera to stay on after the GIF is created cameraStream: null, // Expects a cameraStream Media object // CANVAS OPTIMIZATION OPTIONS saveRenderingContexts: false, // Whether or not you would like to save all of the canvas image binary data savedRenderingContexts: [] // Array of canvas image data }; export default class GIFBuilder { static get properties() { return { id: 'gif', name: 'GIF', extensions: ['gif'], mimeTypes: ['image/gif'], builder: GIFBuilder, options: GIF_BUILDER_OPTIONS }; } constructor(options) { this.options = {...options}; this.source = options.source; delete options.source; // Allow files to be added this.files = []; // Expose the gifshot module so that the full gifshot API is available to apps (Experimental) this.gifshot = gifshot; } async initialize(options) { // Expose the gifshot module so that the full gifshot API is available to apps (Experimental) // this.gifshot = await loadGifshotModule(options); } async add(file) { await this.initialize(); this.files.push(file); } async build() { await this.initialize(); this._cleanOptions(this.options); switch (this.source) { case 'images': this.options.images = this.files; break; case 'video': this.options.video = this.files; break; case 'webcam': assert(this.files.length === 0); break; default: throw new Error('GIFBuilder: invalid source'); } return await this._createGIF(); } // PRIVATE async _createGIF() { return new Promise((resolve, reject) => { this.gifshot.createGIF(this.options, (result) => { // callback object properties // -------------------------- // image - Base 64 image // cameraStream - The webRTC MediaStream object // error - Boolean that determines if an error occurred // errorCode - Helpful error label // errorMsg - Helpful error message // savedRenderingContexts - An array of canvas image data (will only be set if the saveRenderingContexts option was used) if (result.error) { reject(result.errorMsg); return; } // image - Base 64 image resolve(result.image); // var image = obj.image, // animatedImage = document.createElement('img'); // animatedImage.src = image; // document.body.appendChild(animatedImage); }); }); } // Remove some gifshot options _cleanOptions(options) { if (options.video || options.images || options.gifWidth || options.gifHeight) { console.warn('GIFBuilder: ignoring options'); // eslint-disable-line } // We control these through options.source instead delete options.video; delete options.images; // Use width/height props (to standardize across builders) options.gifWidth = options.width; options.gifHeight = options.height; delete options.width; delete options.height; } }
/** * @fileoverview Main function src. */ // HTML5 Shiv. Must be in <head> to support older browsers. document.createElement('video'); document.createElement('audio'); document.createElement('track'); /** * Doubles as the main function for users to create a player instance and also * the main library object. * * **ALIASES** videojs, _V_ (deprecated) * * The `vjs` function can be used to initialize or retrieve a player. * * var myPlayer = vjs('my_video_id'); * * @param {String|Element} id Video element or video element ID * @param {Object=} options Optional options object for config/settings * @param {Function=} ready Optional ready callback * @return {vjs.Player} A player instance * @namespace */ var vjs = function(id, options, ready){ var tag; // Element of ID // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (vjs.players[id]) { // If options or ready funtion are passed, warn if (options) { vjs.log.warn ('Player "' + id + '" is already initialised. Options will not be applied.'); } if (ready) { vjs.players[id].ready(ready); } return vjs.players[id]; // Otherwise get element for ID } else { tag = vjs.el(id); } // ID is a media element } else { tag = id; } // Check for a useable element if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns } // Element may have a player attr referring to an already created player instance. // If not, set up a new player and return the instance. return tag['player'] || new vjs.Player(tag, options, ready); }; // Extended name, also available externally, window.videojs var videojs = window['videojs'] = vjs; // CDN Version. Used to target right flash swf. vjs.CDN_VERSION = '4.12'; vjs.ACCESS_PROTOCOL = ('https:' == document.location.protocol ? 'https://' : 'http://'); /** * Full player version * @type {string} */ vjs['VERSION'] = '4.12.11'; /** * Global Player instance options, surfaced from vjs.Player.prototype.options_ * vjs.options = vjs.Player.prototype.options_ * All options should use string keys so they avoid * renaming by closure compiler * @type {Object} */ vjs.options = { // Default order of fallback technology 'techOrder': ['html5','flash'], // techOrder: ['flash','html5'], 'html5': {}, 'flash': {}, // Default of web browser is 300x150. Should rely on source width/height. 'width': 300, 'height': 150, // defaultVolume: 0.85, 'defaultVolume': 0.00, // The freakin seaguls are driving me crazy! // default playback rates 'playbackRates': [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // default inactivity timeout 'inactivityTimeout': 2000, // Included control sets 'children': { 'mediaLoader': {}, 'posterImage': {}, 'loadingSpinner': {}, 'textTrackDisplay': {}, 'bigPlayButton': {}, 'controlBar': {}, 'errorDisplay': {}, 'textTrackSettings': {} }, 'language': document.getElementsByTagName('html')[0].getAttribute('lang') || navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language || 'en', // locales and their language translations 'languages': {}, // Default message to show when a video cannot be played. 'notSupportedMessage': 'No compatible source was found for this video.' }; // Set CDN Version of swf // The added (+) blocks the replace from changing this 4.12 string if (vjs.CDN_VERSION !== 'GENERATED'+'_CDN_VSN') { videojs.options['flash']['swf'] = vjs.ACCESS_PROTOCOL + 'vjs.zencdn.net/'+vjs.CDN_VERSION+'/video-js.swf'; } /** * Utility function for adding languages to the default options. Useful for * amending multiple language support at runtime. * * Example: vjs.addLanguage('es', {'Hello':'Hola'}); * * @param {String} code The language code or dictionary property * @param {Object} data The data values to be translated * @return {Object} The resulting global languages dictionary object */ vjs.addLanguage = function(code, data){ if(vjs.options['languages'][code] !== undefined) { vjs.options['languages'][code] = vjs.util.mergeOptions(vjs.options['languages'][code], data); } else { vjs.options['languages'][code] = data; } return vjs.options['languages']; }; /** * Global player list * @type {Object} */ vjs.players = {}; /*! * Custom Universal Module Definition (UMD) * * Video.js will never be a non-browser lib so we can simplify UMD a bunch and * still support requirejs and browserify. This also needs to be closure * compiler compatible, so string keys are used. */ if (typeof define === 'function' && define['amd']) { define('videojs', [], function(){ return videojs; }); // checking that module is an object too because of umdjs/umd#35 } else if (typeof exports === 'object' && typeof module === 'object') { module['exports'] = videojs; } /** * Core Object/Class for objects that use inheritance + constructors * * To create a class that can be subclassed itself, extend the CoreObject class. * * var Animal = CoreObject.extend(); * var Horse = Animal.extend(); * * The constructor can be defined through the init property of an object argument. * * var Animal = CoreObject.extend({ * init: function(name, sound){ * this.name = name; * } * }); * * Other methods and properties can be added the same way, or directly to the * prototype. * * var Animal = CoreObject.extend({ * init: function(name){ * this.name = name; * }, * getName: function(){ * return this.name; * }, * sound: '...' * }); * * Animal.prototype.makeSound = function(){ * alert(this.sound); * }; * * To create an instance of a class, use the create method. * * var fluffy = Animal.create('Fluffy'); * fluffy.getName(); // -> Fluffy * * Methods and properties can be overridden in subclasses. * * var Horse = Animal.extend({ * sound: 'Neighhhhh!' * }); * * var horsey = Horse.create('Horsey'); * horsey.getName(); // -> Horsey * horsey.makeSound(); // -> Alert: Neighhhhh! * * @class * @constructor */ vjs.CoreObject = vjs['CoreObject'] = function(){}; // Manually exporting vjs['CoreObject'] here for Closure Compiler // because of the use of the extend/create class methods // If we didn't do this, those functions would get flattened to something like // `a = ...` and `this.prototype` would refer to the global object instead of // CoreObject /** * Create a new object that inherits from this Object * * var Animal = CoreObject.extend(); * var Horse = Animal.extend(); * * @param {Object} props Functions and properties to be applied to the * new object's prototype * @return {vjs.CoreObject} An object that inherits from CoreObject * @this {*} */ vjs.CoreObject.extend = function(props){ var init, subObj; props = props || {}; // Set up the constructor using the supplied init method // or using the init of the parent object // Make sure to check the unobfuscated version for external libs init = props['init'] || props.init || this.prototype['init'] || this.prototype.init || function(){}; // In Resig's simple class inheritance (previously used) the constructor // is a function that calls `this.init.apply(arguments)` // However that would prevent us from using `ParentObject.call(this);` // in a Child constructor because the `this` in `this.init` // would still refer to the Child and cause an infinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, arguments);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. subObj = function(){ init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = vjs.obj.create(this.prototype); // Reset the constructor property for subObj otherwise // instances of subObj would have the constructor of the parent Object subObj.prototype.constructor = subObj; // Make the class extendable subObj.extend = vjs.CoreObject.extend; // Make a function for creating instances subObj.create = vjs.CoreObject.create; // Extend subObj's prototype with functions and other properties from props for (var name in props) { if (props.hasOwnProperty(name)) { subObj.prototype[name] = props[name]; } } return subObj; }; /** * Create a new instance of this Object class * * var myAnimal = Animal.create(); * * @return {vjs.CoreObject} An instance of a CoreObject subclass * @this {*} */ vjs.CoreObject.create = function(){ // Create a new object that inherits from this object's prototype var inst = vjs.obj.create(this.prototype); // Apply this constructor function to the new object this.apply(inst, arguments); // Return the new object return inst; }; /** * @fileoverview Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. */ /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @private */ vjs.on = function(elem, type, fn){ if (vjs.obj.isArray(type)) { return _handleMultipleEvents(vjs.on, elem, type, fn); } var data = vjs.getData(elem); // We need a place to store all our handler data if (!data.handlers) data.handlers = {}; if (!data.handlers[type]) data.handlers[type] = []; if (!fn.guid) fn.guid = vjs.guid++; data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event){ if (data.disabled) return; event = vjs.fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { handlersCopy[m].call(elem, event); } } } }; } if (data.handlers[type].length == 1) { if (elem.addEventListener) { elem.addEventListener(type, data.dispatcher, false); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } }; /** * Removes event listeners from an element * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @private */ vjs.off = function(elem, type, fn) { // Don't want to add a cache object through getData if not needed if (!vjs.hasData(elem)) return; var data = vjs.getData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (vjs.obj.isArray(type)) { return _handleMultipleEvents(vjs.off, elem, type, fn); } // Utility function var removeType = function(t){ data.handlers[t] = []; vjs.cleanUpEvents(elem,t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) removeType(t); return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) return; // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } vjs.cleanUpEvents(elem, type); }; /** * Clean up the listener cache and dispatchers * @param {Element|Object} elem Element to clean up * @param {String} type Type of event to clean up * @private */ vjs.cleanUpEvents = function(elem, type) { var data = vjs.getData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (vjs.isEmpty(data.handlers)) { delete data.handlers; delete data.dispatcher; delete data.disabled; // data.handlers = null; // data.dispatcher = null; // data.disabled = null; } // Finally remove the expando if there is no data left if (vjs.isEmpty(data)) { vjs.removeData(elem); } }; /** * Fix a native event to have standard property values * @param {Object} event Event object to fix * @return {Object} * @private */ vjs.fixEvent = function(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || window.event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key == 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || document; } // Handle which other element the event is related to event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; event.isDefaultPrevented = returnTrue; event.defaultPrevented = true; }; event.isDefaultPrevented = returnFalse; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX != null) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button != null) { event.button = (event.button & 1 ? 0 : (event.button & 4 ? 1 : (event.button & 2 ? 2 : 0))); } } // Returns fixed-up instance return event; }; /** * Trigger an event for an element * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @private */ vjs.trigger = function(elem, event) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasData first. var elemData = (vjs.hasData(elem)) ? vjs.getData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type:event, target:elem }; } // Normalizes the event properties. event = vjs.fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles !== false) { vjs.trigger(parent, event); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = vjs.getData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; /* Original version of js ninja events wasn't complete. * We've since updated to the latest version, but keeping this around * for now just in case. */ // // Added in addition to book. Book code was broke. // event = typeof event === 'object' ? // event[vjs.expando] ? // event : // new vjs.Event(type, event) : // new vjs.Event(type); // event.type = type; // if (handler) { // handler.call(elem, event); // } // // Clean up the event in case it is being reused // event.result = undefined; // event.target = elem; }; /** * Trigger a listener only once for an event * @param {Element|Object} elem Element or object to * @param {String|Array} type * @param {Function} fn * @private */ vjs.one = function(elem, type, fn) { if (vjs.obj.isArray(type)) { return _handleMultipleEvents(vjs.one, elem, type, fn); } var func = function(){ vjs.off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || vjs.guid++; vjs.on(elem, type, func); }; /** * Loops through an array of event types and calls the requested method for each type. * @param {Function} fn The event method we want to use. * @param {Element|Object} elem Element or object to bind listeners to * @param {String} type Type of event to bind to. * @param {Function} callback Event listener. * @private */ function _handleMultipleEvents(fn, elem, type, callback) { vjs.arr.forEach(type, function(type) { fn(elem, type, callback); //Call the event method for each one of the types }); } var hasOwnProp = Object.prototype.hasOwnProperty; /** * Creates an element and applies properties. * @param {String=} tagName Name of tag to be created. * @param {Object=} properties Element properties to be applied. * @return {Element} * @private */ vjs.createEl = function(tagName, properties){ var el; tagName = tagName || 'div'; properties = properties || {}; el = document.createElement(tagName); vjs.obj.each(properties, function(propName, val){ // Not remembering why we were checking for dash // but using setAttribute means you have to use getAttribute // The check for dash checks for the aria-* attributes, like aria-label, aria-valuemin. // The additional check for "role" is because the default method for adding attributes does not // add the attribute "role". My guess is because it's not a valid attribute in some namespaces, although // browsers handle the attribute just fine. The W3C allows for aria-* attributes to be used in pre-HTML5 docs. // http://www.w3.org/TR/wai-aria-primer/#ariahtml. Using setAttribute gets around this problem. if (propName.indexOf('aria-') !== -1 || propName == 'role') { el.setAttribute(propName, val); } else { el[propName] = val; } }); return el; }; /** * Uppercase the first letter of a string * @param {String} string String to be uppercased * @return {String} * @private */ vjs.capitalize = function(string){ return string.charAt(0).toUpperCase() + string.slice(1); }; /** * Object functions container * @type {Object} * @private */ vjs.obj = {}; /** * Object.create shim for prototypal inheritance * * https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create * * @function * @param {Object} obj Object to use as prototype * @private */ vjs.obj.create = Object.create || function(obj){ //Create a new function called 'F' which is just an empty object. function F() {} //the prototype of the 'F' function should point to the //parameter of the anonymous function. F.prototype = obj; //create a new constructor function based off of the 'F' function. return new F(); }; /** * Loop through each property in an object and call a function * whose arguments are (key,value) * @param {Object} obj Object of properties * @param {Function} fn Function to be called on each property. * @this {*} * @private */ vjs.obj.each = function(obj, fn, context){ for (var key in obj) { if (hasOwnProp.call(obj, key)) { fn.call(context || this, key, obj[key]); } } }; /** * Merge two objects together and return the original. * @param {Object} obj1 * @param {Object} obj2 * @return {Object} * @private */ vjs.obj.merge = function(obj1, obj2){ if (!obj2) { return obj1; } for (var key in obj2){ if (hasOwnProp.call(obj2, key)) { obj1[key] = obj2[key]; } } return obj1; }; /** * Merge two objects, and merge any properties that are objects * instead of just overwriting one. Uses to merge options hashes * where deeper default settings are important. * @param {Object} obj1 Object to override * @param {Object} obj2 Overriding object * @return {Object} New object. Obj1 and Obj2 will be untouched. * @private */ vjs.obj.deepMerge = function(obj1, obj2){ var key, val1, val2; // make a copy of obj1 so we're not overwriting original values. // like prototype.options_ and all sub options objects obj1 = vjs.obj.copy(obj1); for (key in obj2){ if (hasOwnProp.call(obj2, key)) { val1 = obj1[key]; val2 = obj2[key]; // Check if both properties are pure objects and do a deep merge if so if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) { obj1[key] = vjs.obj.deepMerge(val1, val2); } else { obj1[key] = obj2[key]; } } } return obj1; }; /** * Make a copy of the supplied object * @param {Object} obj Object to copy * @return {Object} Copy of object * @private */ vjs.obj.copy = function(obj){ return vjs.obj.merge({}, obj); }; /** * Check if an object is plain, and not a dom node or any object sub-instance * @param {Object} obj Object to check * @return {Boolean} True if plain, false otherwise * @private */ vjs.obj.isPlain = function(obj){ return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object; }; /** * Check if an object is Array * Since instanceof Array will not work on arrays created in another frame we need to use Array.isArray, but since IE8 does not support Array.isArray we need this shim * @param {Object} obj Object to check * @return {Boolean} True if plain, false otherwise * @private */ vjs.obj.isArray = Array.isArray || function(arr) { return Object.prototype.toString.call(arr) === '[object Array]'; }; /** * Check to see whether the input is NaN or not. * NaN is the only JavaScript construct that isn't equal to itself * @param {Number} num Number to check * @return {Boolean} True if NaN, false otherwise * @private */ vjs.isNaN = function(num) { return num !== num; }; /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function It also stores a unique id on the function so it can be easily removed from events * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} * @private */ vjs.bind = function(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = vjs.guid++; } // Create the new function that changes the context var ret = function() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks ret.guid = (uid) ? uid + '_' + fn.guid : fn.guid; return ret; }; /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * @type {Object} * @private */ vjs.cache = {}; /** * Unique ID for an element or function * @type {Number} * @private */ vjs.guid = 1; /** * Unique attribute name to store an element's guid in * @type {String} * @constant * @private */ vjs.expando = 'vdata' + (new Date()).getTime(); /** * Returns the cache object where data for an element is stored * @param {Element} el Element to store data for. * @return {Object} * @private */ vjs.getData = function(el){ var id = el[vjs.expando]; if (!id) { id = el[vjs.expando] = vjs.guid++; } if (!vjs.cache[id]) { vjs.cache[id] = {}; } return vjs.cache[id]; }; /** * Returns the cache object where data for an element is stored * @param {Element} el Element to store data for. * @return {Object} * @private */ vjs.hasData = function(el){ var id = el[vjs.expando]; return !(!id || vjs.isEmpty(vjs.cache[id])); }; /** * Delete data for the element from the cache and the guid attr from getElementById * @param {Element} el Remove data for an element * @private */ vjs.removeData = function(el){ var id = el[vjs.expando]; if (!id) { return; } // Remove all stored data // Changed to = null // http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/ // vjs.cache[id] = null; delete vjs.cache[id]; // Remove the expando property from the DOM node try { delete el[vjs.expando]; } catch(e) { if (el.removeAttribute) { el.removeAttribute(vjs.expando); } else { // IE doesn't appear to support removeAttribute on the document element el[vjs.expando] = null; } } }; /** * Check if an object is empty * @param {Object} obj The object to check for emptiness * @return {Boolean} * @private */ vjs.isEmpty = function(obj) { for (var prop in obj) { // Inlude null properties as empty. if (obj[prop] !== null) { return false; } } return true; }; /** * Check if an element has a CSS class * @param {Element} element Element to check * @param {String} classToCheck Classname to check * @private */ vjs.hasClass = function(element, classToCheck){ return ((' ' + element.className + ' ').indexOf(' ' + classToCheck + ' ') !== -1); }; /** * Add a CSS class name to an element * @param {Element} element Element to add class name to * @param {String} classToAdd Classname to add * @private */ vjs.addClass = function(element, classToAdd){ if (!vjs.hasClass(element, classToAdd)) { element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd; } }; /** * Remove a CSS class name from an element * @param {Element} element Element to remove from class name * @param {String} classToAdd Classname to remove * @private */ vjs.removeClass = function(element, classToRemove){ var classNames, i; if (!vjs.hasClass(element, classToRemove)) {return;} classNames = element.className.split(' '); // no arr.indexOf in ie8, and we don't want to add a big shim for (i = classNames.length - 1; i >= 0; i--) { if (classNames[i] === classToRemove) { classNames.splice(i,1); } } element.className = classNames.join(' '); }; /** * Element for testing browser HTML5 video capabilities * @type {Element} * @constant * @private */ vjs.TEST_VID = vjs.createEl('video'); (function() { var track = document.createElement('track'); track.kind = 'captions'; track.srclang = 'en'; track.label = 'English'; vjs.TEST_VID.appendChild(track); })(); /** * Useragent for browser testing. * @type {String} * @constant * @private */ vjs.USER_AGENT = navigator.userAgent; /** * Device is an iPhone * @type {Boolean} * @constant * @private */ vjs.IS_IPHONE = (/iPhone/i).test(vjs.USER_AGENT); vjs.IS_IPAD = (/iPad/i).test(vjs.USER_AGENT); vjs.IS_IPOD = (/iPod/i).test(vjs.USER_AGENT); vjs.IS_IOS = vjs.IS_IPHONE || vjs.IS_IPAD || vjs.IS_IPOD; vjs.IOS_VERSION = (function(){ var match = vjs.USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } })(); vjs.IS_ANDROID = (/Android/i).test(vjs.USER_AGENT); vjs.ANDROID_VERSION = (function() { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = vjs.USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i), major, minor; if (!match) { return null; } major = match[1] && parseFloat(match[1]); minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } else { return null; } })(); // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser vjs.IS_OLD_ANDROID = vjs.IS_ANDROID && (/webkit/i).test(vjs.USER_AGENT) && vjs.ANDROID_VERSION < 2.3; vjs.IS_FIREFOX = (/Firefox/i).test(vjs.USER_AGENT); vjs.IS_CHROME = (/Chrome/i).test(vjs.USER_AGENT); vjs.IS_IE8 = (/MSIE\s8\.0/).test(vjs.USER_AGENT); vjs.TOUCH_ENABLED = !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch); vjs.BACKGROUND_SIZE_SUPPORTED = 'backgroundSize' in vjs.TEST_VID.style; /** * Apply attributes to an HTML element. * @param {Element} el Target element. * @param {Object=} attributes Element attributes to be applied. * @private */ vjs.setElementAttributes = function(el, attributes){ vjs.obj.each(attributes, function(attrName, attrValue) { if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, (attrValue === true ? '' : attrValue)); } }); }; /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * @param {Element} tag Element from which to get tag attributes * @return {Object} * @private */ vjs.getElementAttributes = function(tag){ var obj, knownBooleans, attrs, attrName, attrVal; obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from knownBooleans = ','+'autoplay,controls,loop,muted,default'+','; if (tag && tag.attributes && tag.attributes.length > 0) { attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { attrName = attrs[i].name; attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(','+attrName+',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = (attrVal !== null) ? true : false; } obj[attrName] = attrVal; } } return obj; }; /** * Get the computed style value for an element * From http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ * @param {Element} el Element to get style value for * @param {String} strCssRule Style name * @return {String} Style value * @private */ vjs.getComputedDimension = function(el, strCssRule){ var strValue = ''; if(document.defaultView && document.defaultView.getComputedStyle){ strValue = document.defaultView.getComputedStyle(el, '').getPropertyValue(strCssRule); } else if(el.currentStyle){ // IE8 Width/Height support strValue = el['client'+strCssRule.substr(0,1).toUpperCase() + strCssRule.substr(1)] + 'px'; } return strValue; }; /** * Insert an element as the first child node of another * @param {Element} child Element to insert * @param {[type]} parent Element to insert child into * @private */ vjs.insertFirst = function(child, parent){ if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } }; /** * Object to hold browser support information * @type {Object} * @private */ vjs.browser = {}; /** * Shorthand for document.getElementById() * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs. * @param {String} id Element ID * @return {Element} Element with supplied ID * @private */ vjs.el = function(id){ if (id.indexOf('#') === 0) { id = id.slice(1); } return document.getElementById(id); }; /** * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @private */ vjs.formatTime = function(seconds, guide) { // Default to using seconds as guide guide = guide || seconds; var s = Math.floor(seconds % 60), m = Math.floor(seconds / 60 % 60), h = Math.floor(seconds / 3600), gm = Math.floor(guide / 60 % 60), gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = (h > 0 || gh > 0) ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = (((h || gm >= 10) && m < 10) ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = (s < 10) ? '0' + s : s; return h + m + s; }; // Attempt to block the ability to select text while dragging controls vjs.blockTextSelection = function(){ document.body.focus(); document.onselectstart = function () { return false; }; }; // Turn off text selection blocking vjs.unblockTextSelection = function(){ document.onselectstart = function () { return true; }; }; /** * Trim whitespace from the ends of a string. * @param {String} string String to trim * @return {String} Trimmed string * @private */ vjs.trim = function(str){ return (str+'').replace(/^\s+|\s+$/g, ''); }; /** * Should round off a number to a decimal place * @param {Number} num Number to round * @param {Number} dec Number of decimal places to round to * @return {Number} Rounded number * @private */ vjs.round = function(num, dec) { if (!dec) { dec = 0; } return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); }; /** * Should create a fake TimeRange object * Mimics an HTML5 time range instance, which has functions that * return the start and end times for a range * TimeRanges are returned by the buffered() method * @param {Number} start Start time in seconds * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @private */ vjs.createTimeRange = function(start, end){ if (start === undefined && end === undefined) { return { length: 0, start: function() { throw new Error('This TimeRanges object is empty'); }, end: function() { throw new Error('This TimeRanges object is empty'); } }; } return { length: 1, start: function() { return start; }, end: function() { return end; } }; }; /** * Add to local storage (may removable) * @private */ vjs.setLocalStorage = function(key, value){ try { // IE was throwing errors referencing the var anywhere without this var localStorage = window.localStorage || false; if (!localStorage) { return; } localStorage[key] = value; } catch(e) { if (e.code == 22 || e.code == 1014) { // Webkit == 22 / Firefox == 1014 vjs.log('LocalStorage Full (VideoJS)', e); } else { if (e.code == 18) { vjs.log('LocalStorage not allowed (VideoJS)', e); } else { vjs.log('LocalStorage Error (VideoJS)', e); } } } }; /** * Get absolute version of relative URL. Used to tell flash correct URL. * http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue * @param {String} url URL to make absolute * @return {String} Absolute URL * @private */ vjs.getAbsoluteURL = function(url){ // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. url = vjs.createEl('div', { innerHTML: '<a href="'+url+'">x</a>' }).firstChild.href; } return url; }; /** * Resolve and parse the elements of a URL * @param {String} url The url to parse * @return {Object} An object of url details */ vjs.parseUrl = function(url) { var div, a, addToBody, props, details; props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL a = vjs.createEl('a', { href: url }); // IE8 (and 9?) Fix // ie8 doesn't parse the URL correctly until the anchor is actually // added to the body, and an innerHTML is needed to trigger the parsing addToBody = (a.host === '' && a.protocol !== 'file:'); if (addToBody) { div = vjs.createEl('div'); div.innerHTML = '<a href="'+url+'"></a>'; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); document.body.appendChild(div); } // Copy the specific URL properties to a new object // This is also needed for IE8 because the anchor loses its // properties when it's removed from the dom details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } // IE9 adds the port to the host property unlike everyone else. If // a port identifier is added for standard ports, strip it. if (details.protocol === 'http:') { details.host = details.host.replace(/:80$/, ''); } if (details.protocol === 'https:') { details.host = details.host.replace(/:443$/, ''); } if (addToBody) { document.body.removeChild(div); } return details; }; /** * Log messages to the console and history based on the type of message * * @param {String} type The type of message, or `null` for `log` * @param {[type]} args The args to be passed to the log * @private */ function _logType(type, args){ var argsArray, noop, console; // convert args to an array to get array functions argsArray = Array.prototype.slice.call(args); // if there's no console then don't try to output messages // they will still be stored in vjs.log.history // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist noop = function(){}; console = window['console'] || { 'log': noop, 'warn': noop, 'error': noop }; if (type) { // add the type to the front of the message argsArray.unshift(type.toUpperCase()+':'); } else { // default to log with no prefix type = 'log'; } // add to history vjs.log.history.push(argsArray); // add console prefix after adding to history argsArray.unshift('VIDEOJS:'); // call appropriate log function if (console[type].apply) { console[type].apply(console, argsArray); } else { // ie8 doesn't allow error.apply, but it will just join() the array anyway console[type](argsArray.join(' ')); } } /** * Log plain debug messages */ vjs.log = function(){ _logType(null, arguments); }; /** * Keep a history of log messages * @type {Array} */ vjs.log.history = []; /** * Log error messages */ vjs.log.error = function(){ _logType('error', arguments); }; /** * Log warning messages */ vjs.log.warn = function(){ _logType('warn', arguments); }; // Offset Left // getBoundingClientRect technique from John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/ vjs.findPosition = function(el) { var box, docEl, body, clientLeft, scrollLeft, left, clientTop, scrollTop, top; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } docEl = document.documentElement; body = document.body; clientLeft = docEl.clientLeft || body.clientLeft || 0; scrollLeft = window.pageXOffset || body.scrollLeft; left = box.left + scrollLeft - clientLeft; clientTop = docEl.clientTop || body.clientTop || 0; scrollTop = window.pageYOffset || body.scrollTop; top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: vjs.round(left), top: vjs.round(top) }; }; /** * Array functions container * @type {Object} * @private */ vjs.arr = {}; /* * Loops through an array and runs a function for each item inside it. * @param {Array} array The array * @param {Function} callback The function to be run for each item * @param {*} thisArg The `this` binding of callback * @returns {Array} The array * @private */ vjs.arr.forEach = function(array, callback, thisArg) { if (vjs.obj.isArray(array) && callback instanceof Function) { for (var i = 0, len = array.length; i < len; ++i) { callback.call(thisArg || vjs, array[i], i, array); } } return array; }; /** * Simple http request for retrieving external files (e.g. text tracks) * * ##### Example * * // using url string * videojs.xhr('http://example.com/myfile.vtt', function(error, response, responseBody){}); * * // or options block * videojs.xhr({ * uri: 'http://example.com/myfile.vtt', * method: 'GET', * responseType: 'text' * }, function(error, response, responseBody){ * if (error) { * // log the error * } else { * // successful, do something with the response * } * }); * * * API is modeled after the Raynos/xhr, which we hope to use after * getting browserify implemented. * https://github.com/Raynos/xhr/blob/master/index.js * * @param {Object|String} options Options block or URL string * @param {Function} callback The callback function * @returns {Object} The request */ vjs.xhr = function(options, callback){ var XHR, request, urlInfo, winLoc, fileUrl, crossOrigin, abortTimeout, successHandler, errorHandler; // If options is a string it's the url if (typeof options === 'string') { options = { uri: options }; } // Merge with default options videojs.util.mergeOptions({ method: 'GET', timeout: 45 * 1000 }, options); callback = callback || function(){}; successHandler = function(){ window.clearTimeout(abortTimeout); callback(null, request, request.response || request.responseText); }; errorHandler = function(err){ window.clearTimeout(abortTimeout); if (!err || typeof err === 'string') { err = new Error(err); } callback(err, request); }; XHR = window.XMLHttpRequest; if (typeof XHR === 'undefined') { // Shim XMLHttpRequest for older IEs XHR = function () { try { return new window.ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {} try { return new window.ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (f) {} try { return new window.ActiveXObject('Msxml2.XMLHTTP'); } catch (g) {} throw new Error('This browser does not support XMLHttpRequest.'); }; } request = new XHR(); // Store a reference to the url on the request instance request.uri = options.uri; urlInfo = vjs.parseUrl(options.uri); winLoc = window.location; // Check if url is for another domain/origin // IE8 doesn't know location.origin, so we won't rely on it here crossOrigin = (urlInfo.protocol + urlInfo.host) !== (winLoc.protocol + winLoc.host); // XDomainRequest -- Use for IE if XMLHTTPRequest2 isn't available // 'withCredentials' is only available in XMLHTTPRequest2 // Also XDomainRequest has a lot of gotchas, so only use if cross domain if (crossOrigin && window.XDomainRequest && !('withCredentials' in request)) { request = new window.XDomainRequest(); request.onload = successHandler; request.onerror = errorHandler; // These blank handlers need to be set to fix ie9 // http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/ request.onprogress = function(){}; request.ontimeout = function(){}; // XMLHTTPRequest } else { fileUrl = (urlInfo.protocol == 'file:' || winLoc.protocol == 'file:'); request.onreadystatechange = function() { if (request.readyState === 4) { if (request.timedout) { return errorHandler('timeout'); } if (request.status === 200 || fileUrl && request.status === 0) { successHandler(); } else { errorHandler(); } } }; if (options.timeout) { abortTimeout = window.setTimeout(function() { if (request.readyState !== 4) { request.timedout = true; request.abort(); } }, options.timeout); } } // open the connection try { // Third arg is async, or ignored by XDomainRequest request.open(options.method || 'GET', options.uri, true); } catch(err) { return errorHandler(err); } // withCredentials only supported by XMLHttpRequest2 if(options.withCredentials) { request.withCredentials = true; } if (options.responseType) { request.responseType = options.responseType; } // send the request try { request.send(); } catch(err) { return errorHandler(err); } return request; }; /** * Utility functions namespace * @namespace * @type {Object} */ vjs.util = {}; /** * Merge two options objects, recursively merging any plain object properties as * well. Previously `deepMerge` * * @param {Object} obj1 Object to override values in * @param {Object} obj2 Overriding object * @return {Object} New object -- obj1 and obj2 will be untouched */ vjs.util.mergeOptions = function(obj1, obj2){ var key, val1, val2; // make a copy of obj1 so we're not overwriting original values. // like prototype.options_ and all sub options objects obj1 = vjs.obj.copy(obj1); for (key in obj2){ if (obj2.hasOwnProperty(key)) { val1 = obj1[key]; val2 = obj2[key]; // Check if both properties are pure objects and do a deep merge if so if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) { obj1[key] = vjs.util.mergeOptions(val1, val2); } else { obj1[key] = obj2[key]; } } } return obj1; };vjs.EventEmitter = function() { }; vjs.EventEmitter.prototype.allowedEvents_ = { }; vjs.EventEmitter.prototype.on = function(type, fn) { // Remove the addEventListener alias before calling vjs.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = Function.prototype; vjs.on(this, type, fn); this.addEventListener = ael; }; vjs.EventEmitter.prototype.addEventListener = vjs.EventEmitter.prototype.on; vjs.EventEmitter.prototype.off = function(type, fn) { vjs.off(this, type, fn); }; vjs.EventEmitter.prototype.removeEventListener = vjs.EventEmitter.prototype.off; vjs.EventEmitter.prototype.one = function(type, fn) { vjs.one(this, type, fn); }; vjs.EventEmitter.prototype.trigger = function(event) { var type = event.type || event; if (typeof event === 'string') { event = { type: type }; } event = vjs.fixEvent(event); if (this.allowedEvents_[type] && this['on' + type]) { this['on' + type](event); } vjs.trigger(this, event); }; // The standard DOM EventTarget.dispatchEvent() is aliased to trigger() vjs.EventEmitter.prototype.dispatchEvent = vjs.EventEmitter.prototype.trigger; /** * @fileoverview Player Component - Base class for all UI objects * */ /** * Base UI Component class * * Components are embeddable UI objects that are represented by both a * javascript object and an element in the DOM. They can be children of other * components, and can have many children themselves. * * // adding a button to the player * var button = player.addChild('button'); * button.el(); // -> button element * * <div class="video-js"> * <div class="vjs-button">Button</div> * </div> * * Components are also event emitters. * * button.on('click', function(){ * console.log('Button Clicked!'); * }); * * button.trigger('customevent'); * * @param {Object} player Main Player * @param {Object=} options * @class * @constructor * @extends vjs.CoreObject */ vjs.Component = vjs.CoreObject.extend({ /** * the constructor function for the class * * @constructor */ init: function(player, options, ready){ this.player_ = player; // Make a copy of prototype.options_ to protect against overriding global defaults this.options_ = vjs.obj.copy(this.options_); // Updated options with supplied options options = this.options(options); // Get ID from options or options element if one is supplied this.id_ = options['id'] || (options['el'] && options['el']['id']); // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players this.id_ = ((player.id && player.id()) || 'no_player') + '_component_' + vjs.guid++; } this.name_ = options['name'] || null; // Create element if one wasn't provided in options this.el_ = options['el'] || this.createEl(); this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options this.initChildren(); this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } }); /** * Dispose of the component and all child components */ vjs.Component.prototype.dispose = function(){ this.trigger({ type: 'dispose', 'bubbles': false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove all event listeners. this.off(); // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } vjs.removeData(this.el_); this.el_ = null; }; /** * Reference to main player instance * * @type {vjs.Player} * @private */ vjs.Component.prototype.player_ = true; /** * Return the component's player * * @return {vjs.Player} */ vjs.Component.prototype.player = function(){ return this.player_; }; /** * The component's options object * * @type {Object} * @private */ vjs.Component.prototype.options_; /** * Deep merge of options objects * * Whenever a property is an object on both options objects * the two properties will be merged using vjs.obj.deepMerge. * * This is used for merging options for child components. We * want it to be easy to override individual options on a child * component without having to rewrite all the other default options. * * Parent.prototype.options_ = { * children: { * 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' }, * 'childTwo': {}, * 'childThree': {} * } * } * newOptions = { * children: { * 'childOne': { 'foo': 'baz', 'abc': '123' } * 'childTwo': null, * 'childFour': {} * } * } * * this.options(newOptions); * * RESULT * * { * children: { * 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, * 'childTwo': null, // Disabled. Won't be initialized. * 'childThree': {}, * 'childFour': {} * } * } * * @param {Object} obj Object of new option values * @return {Object} A NEW object of this.options_ and obj merged */ vjs.Component.prototype.options = function(obj){ if (obj === undefined) return this.options_; return this.options_ = vjs.util.mergeOptions(this.options_, obj); }; /** * The DOM element for the component * * @type {Element} * @private */ vjs.Component.prototype.el_; /** * Create the component's DOM element * * @param {String=} tagName Element's node type. e.g. 'div' * @param {Object=} attributes An object of element attributes that should be set on the element * @return {Element} */ vjs.Component.prototype.createEl = function(tagName, attributes){ return vjs.createEl(tagName, attributes); }; vjs.Component.prototype.localize = function(string){ var lang = this.player_.language(), languages = this.player_.languages(); if (languages && languages[lang] && languages[lang][string]) { return languages[lang][string]; } return string; }; /** * Get the component's DOM element * * var domEl = myComponent.el(); * * @return {Element} */ vjs.Component.prototype.el = function(){ return this.el_; }; /** * An optional element where, if defined, children will be inserted instead of * directly in `el_` * * @type {Element} * @private */ vjs.Component.prototype.contentEl_; /** * Return the component's DOM element for embedding content. * Will either be el_ or a new element defined in createEl. * * @return {Element} */ vjs.Component.prototype.contentEl = function(){ return this.contentEl_ || this.el_; }; /** * The ID for the component * * @type {String} * @private */ vjs.Component.prototype.id_; /** * Get the component's ID * * var id = myComponent.id(); * * @return {String} */ vjs.Component.prototype.id = function(){ return this.id_; }; /** * The name for the component. Often used to reference the component. * * @type {String} * @private */ vjs.Component.prototype.name_; /** * Get the component's name. The name is often used to reference the component. * * var name = myComponent.name(); * * @return {String} */ vjs.Component.prototype.name = function(){ return this.name_; }; /** * Array of child components * * @type {Array} * @private */ vjs.Component.prototype.children_; /** * Get an array of all child components * * var kids = myComponent.children(); * * @return {Array} The children */ vjs.Component.prototype.children = function(){ return this.children_; }; /** * Object of child components by ID * * @type {Object} * @private */ vjs.Component.prototype.childIndex_; /** * Returns a child component with the provided ID * * @return {vjs.Component} */ vjs.Component.prototype.getChildById = function(id){ return this.childIndex_[id]; }; /** * Object of child components by name * * @type {Object} * @private */ vjs.Component.prototype.childNameIndex_; /** * Returns a child component with the provided name * * @return {vjs.Component} */ vjs.Component.prototype.getChild = function(name){ return this.childNameIndex_[name]; }; /** * Adds a child component inside this component * * myComponent.el(); * // -> <div class='my-component'></div> * myComonent.children(); * // [empty array] * * var myButton = myComponent.addChild('MyButton'); * // -> <div class='my-component'><div class="my-button">myButton<div></div> * // -> myButton === myComonent.children()[0]; * * Pass in options for child constructors and options for children of the child * * var myButton = myComponent.addChild('MyButton', { * text: 'Press Me', * children: { * buttonChildExample: { * buttonChildOption: true * } * } * }); * * @param {String|vjs.Component} child The class name or instance of a child to add * @param {Object=} options Options, including options to be passed to children of the child. * @return {vjs.Component} The child component (created by this process if a string was used) * @suppress {accessControls|checkRegExp|checkTypes|checkVars|const|constantProperty|deprecated|duplicate|es5Strict|fileoverviewTags|globalThis|invalidCasts|missingProperties|nonStandardJsDocs|strictModuleDepCheck|undefinedNames|undefinedVars|unknownDefines|uselessCode|visibility} */ vjs.Component.prototype.addChild = function(child, options){ var component, componentClass, componentName; // If child is a string, create new component with options if (typeof child === 'string') { componentName = child; // Make sure options is at least an empty object to protect against errors options = options || {}; // If no componentClass in options, assume componentClass is the name lowercased // (e.g. playButton) componentClass = options['componentClass'] || vjs.capitalize(componentName); // Set name through options options['name'] = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player // Closure Compiler throws an 'incomplete alias' warning if we use the vjs variable directly. // Every class should be exported, so this should never be a problem here. component = new window['videojs'][componentClass](this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.push(component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || (component.name && component.name()); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component['el'] === 'function' && component['el']()) { this.contentEl().appendChild(component['el']()); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child component from this component's list of children, and the * child component's element from this component's element * * @param {vjs.Component} component Component to remove */ vjs.Component.prototype.removeChild = function(component){ if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) return; var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i,1); break; } } if (!childFound) return; this.childIndex_[component.id()] = null; this.childNameIndex_[component.name()] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child components from options * * // when an instance of MyComponent is created, all children in options * // will be added to the instance by their name strings and options * MyComponent.prototype.options_.children = { * myChildComponent: { * myChildOption: true * } * } * * // Or when creating the component * var myComp = new MyComponent(player, { * children: { * myChildComponent: { * myChildOption: true * } * } * }); * * The children option can also be an Array of child names or * child options objects (that also include a 'name' key). * * var myComp = new MyComponent(player, { * children: [ * 'button', * { * name: 'button', * someOtherOption: true * } * ] * }); * */ vjs.Component.prototype.initChildren = function(){ var parent, parentOptions, children, child, name, opts, handleAdd; parent = this; parentOptions = parent.options(); children = parentOptions['children']; if (children) { handleAdd = function(name, opts){ // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. vjs.options['children']['posterImage'] = false if (opts === false) return; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each parent[name] = parent.addChild(name, opts); }; // Allow for an array of children details to passed in the options if (vjs.obj.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; if (typeof child == 'string') { // ['myComponent'] name = child; opts = {}; } else { // [{ name: 'myComponent', otherOption: true }] name = child.name; opts = child; } handleAdd(name, opts); } } else { vjs.obj.each(children, handleAdd); } } }; /** * Allows sub components to stack CSS class names * * @return {String} The constructed class name */ vjs.Component.prototype.buildCSSClass = function(){ // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /* Events ============================================================================= */ /** * Add an event listener to this component's element * * var myFunc = function(){ * var myComponent = this; * // Do something when the event is fired * }; * * myComponent.on('eventType', myFunc); * * The context of myFunc will be myComponent unless previously bound. * * Alternatively, you can add a listener to another element or component. * * myComponent.on(otherElement, 'eventName', myFunc); * myComponent.on(otherComponent, 'eventName', myFunc); * * The benefit of using this over `vjs.on(otherElement, 'eventName', myFunc)` * and `otherComponent.on('eventName', myFunc)` is that this way the listeners * will be automatically cleaned up when either component is disposed. * It will also bind myComponent as the context of myFunc. * * **NOTE**: When using this on elements in the page other than window * and document (both permanent), if you remove the element from the DOM * you need to call `vjs.trigger(el, 'dispose')` on it to clean up * references to it and allow the browser to garbage collect it. * * @param {String|vjs.Component} first The event type or other component * @param {Function|String} second The event handler or event type * @param {Function} third The event handler * @return {vjs.Component} self */ vjs.Component.prototype.on = function(first, second, third){ var target, type, fn, removeOnDispose, cleanRemover, thisComponent; if (typeof first === 'string' || vjs.obj.isArray(first)) { vjs.on(this.el_, first, vjs.bind(this, second)); // Targeting another component or element } else { target = first; type = second; fn = vjs.bind(this, third); thisComponent = this; // When this component is disposed, remove the listener from the other component removeOnDispose = function(){ thisComponent.off(target, type, fn); }; // Use the same function ID so we can remove it later it using the ID // of the original listener removeOnDispose.guid = fn.guid; this.on('dispose', removeOnDispose); // If the other component is disposed first we need to clean the reference // to the other component in this component's removeOnDispose listener // Otherwise we create a memory leak. cleanRemover = function(){ thisComponent.off('dispose', removeOnDispose); }; // Add the same function ID so we can easily remove it later cleanRemover.guid = fn.guid; // Check if this is a DOM node if (first.nodeName) { // Add the listener to the other element vjs.on(target, type, fn); vjs.on(target, 'dispose', cleanRemover); // Should be a component // Not using `instanceof vjs.Component` because it makes mock players difficult } else if (typeof first.on === 'function') { // Add the listener to the other component target.on(type, fn); target.on('dispose', cleanRemover); } } return this; }; /** * Remove an event listener from this component's element * * myComponent.off('eventType', myFunc); * * If myFunc is excluded, ALL listeners for the event type will be removed. * If eventType is excluded, ALL listeners will be removed from the component. * * Alternatively you can use `off` to remove listeners that were added to other * elements or components using `myComponent.on(otherComponent...`. * In this case both the event type and listener function are REQUIRED. * * myComponent.off(otherElement, 'eventType', myFunc); * myComponent.off(otherComponent, 'eventType', myFunc); * * @param {String=|vjs.Component} first The event type or other component * @param {Function=|String} second The listener function or event type * @param {Function=} third The listener for other component * @return {vjs.Component} */ vjs.Component.prototype.off = function(first, second, third){ var target, otherComponent, type, fn, otherEl; if (!first || typeof first === 'string' || vjs.obj.isArray(first)) { vjs.off(this.el_, first, second); } else { target = first; type = second; // Ensure there's at least a guid, even if the function hasn't been used fn = vjs.bind(this, third); // Remove the dispose listener on this component, // which was given the same guid as the event listener this.off('dispose', fn); if (first.nodeName) { // Remove the listener vjs.off(target, type, fn); // Remove the listener for cleaning the dispose listener vjs.off(target, 'dispose', fn); } else { target.off(type, fn); target.off('dispose', fn); } } return this; }; /** * Add an event listener to be triggered only once and then removed * * myComponent.one('eventName', myFunc); * * Alternatively you can add a listener to another element or component * that will be triggered only once. * * myComponent.one(otherElement, 'eventName', myFunc); * myComponent.one(otherComponent, 'eventName', myFunc); * * @param {String|vjs.Component} first The event type or other component * @param {Function|String} second The listener function or event type * @param {Function=} third The listener function for other component * @return {vjs.Component} */ vjs.Component.prototype.one = function(first, second, third) { var target, type, fn, thisComponent, newFunc; if (typeof first === 'string' || vjs.obj.isArray(first)) { vjs.one(this.el_, first, vjs.bind(this, second)); } else { target = first; type = second; fn = vjs.bind(this, third); thisComponent = this; newFunc = function(){ thisComponent.off(target, type, newFunc); fn.apply(this, arguments); }; // Keep the same function ID so we can remove it later newFunc.guid = fn.guid; this.on(target, type, newFunc); } return this; }; /** * Trigger an event on an element * * myComponent.trigger('eventName'); * myComponent.trigger({'type':'eventName'}); * * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @return {vjs.Component} self */ vjs.Component.prototype.trigger = function(event){ vjs.trigger(this.el_, event); return this; }; /* Ready ================================================================================ */ /** * Is the component loaded * This can mean different things depending on the component. * * @private * @type {Boolean} */ vjs.Component.prototype.isReady_; /** * Trigger ready as soon as initialization is finished * * Allows for delaying ready. Override on a sub class prototype. * If you set this.isReadyOnInitFinish_ it will affect all components. * Specially used when waiting for the Flash player to asynchronously load. * * @type {Boolean} * @private */ vjs.Component.prototype.isReadyOnInitFinish_ = true; /** * List of ready listeners * * @type {Array} * @private */ vjs.Component.prototype.readyQueue_; /** * Bind a listener to the component's ready state * * Different from event listeners in that if the ready event has already happened * it will trigger the function immediately. * * @param {Function} fn Ready listener * @return {vjs.Component} */ vjs.Component.prototype.ready = function(fn){ if (fn) { if (this.isReady_) { fn.call(this); } else { if (this.readyQueue_ === undefined) { this.readyQueue_ = []; } this.readyQueue_.push(fn); } } return this; }; /** * Trigger the ready listeners * * @return {vjs.Component} */ vjs.Component.prototype.triggerReady = function(){ this.isReady_ = true; var readyQueue = this.readyQueue_; if (readyQueue && readyQueue.length > 0) { for (var i = 0, j = readyQueue.length; i < j; i++) { readyQueue[i].call(this); } // Reset Ready Queue this.readyQueue_ = []; // Allow for using event listeners also, in case you want to do something everytime a source is ready. this.trigger('ready'); } }; /* Display ============================================================================= */ /** * Check if a component's element has a CSS class name * * @param {String} classToCheck Classname to check * @return {vjs.Component} */ vjs.Component.prototype.hasClass = function(classToCheck){ return vjs.hasClass(this.el_, classToCheck); }; /** * Add a CSS class name to the component's element * * @param {String} classToAdd Classname to add * @return {vjs.Component} */ vjs.Component.prototype.addClass = function(classToAdd){ vjs.addClass(this.el_, classToAdd); return this; }; /** * Remove a CSS class name from the component's element * * @param {String} classToRemove Classname to remove * @return {vjs.Component} */ vjs.Component.prototype.removeClass = function(classToRemove){ vjs.removeClass(this.el_, classToRemove); return this; }; /** * Show the component element if hidden * * @return {vjs.Component} */ vjs.Component.prototype.show = function(){ this.removeClass('vjs-hidden'); return this; }; /** * Hide the component element if currently showing * * @return {vjs.Component} */ vjs.Component.prototype.hide = function(){ this.addClass('vjs-hidden'); return this; }; /** * Lock an item in its visible state * To be used with fadeIn/fadeOut. * * @return {vjs.Component} * @private */ vjs.Component.prototype.lockShowing = function(){ this.addClass('vjs-lock-showing'); return this; }; /** * Unlock an item to be hidden * To be used with fadeIn/fadeOut. * * @return {vjs.Component} * @private */ vjs.Component.prototype.unlockShowing = function(){ this.removeClass('vjs-lock-showing'); return this; }; /** * Disable component by making it unshowable * * Currently private because we're moving towards more css-based states. * @private */ vjs.Component.prototype.disable = function(){ this.hide(); this.show = function(){}; }; /** * Set or get the width of the component (CSS values) * * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num Optional width number * @param {Boolean} skipListeners Skip the 'resize' event trigger * @return {vjs.Component} This component, when setting the width * @return {Number|String} The width, when getting */ vjs.Component.prototype.width = function(num, skipListeners){ return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component (CSS values) * * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num New component height * @param {Boolean=} skipListeners Skip the resize event trigger * @return {vjs.Component} This component, when setting the height * @return {Number|String} The height, when getting */ vjs.Component.prototype.height = function(num, skipListeners){ return this.dimension('height', num, skipListeners); }; /** * Set both width and height at the same time * * @param {Number|String} width * @param {Number|String} height * @return {vjs.Component} The component */ vjs.Component.prototype.dimensions = function(width, height){ // Skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * Get or set width or height * * This is the shared code for the width() and height() methods. * All for an integer, integer + 'px' or integer + '%'; * * Known issue: Hidden elements officially have a width of 0. We're defaulting * to the style.width value and falling back to computedStyle which has the * hidden element issue. Info, but probably not an efficient fix: * http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/ * * @param {String} widthOrHeight 'width' or 'height' * @param {Number|String=} num New dimension * @param {Boolean=} skipListeners Skip resize event trigger * @return {vjs.Component} The component if a dimension was set * @return {Number|String} The dimension if nothing was set * @private */ vjs.Component.prototype.dimension = function(widthOrHeight, num, skipListeners){ if (num !== undefined) { if (num === null || vjs.isNaN(num)) { num = 0; } // Check if using css width/height (% or px) and adjust if ((''+num).indexOf('%') !== -1 || (''+num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num+'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { this.trigger('resize'); } // Return component return this; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) return 0; // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0,pxIndex), 10); // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px } else { return parseInt(this.el_['offset'+vjs.capitalize(widthOrHeight)], 10); // ComputedStyle version. // Only difference is if the element is hidden it will return // the percent value (e.g. '100%'') // instead of zero like offsetWidth returns. // var val = vjs.getComputedStyleValue(this.el_, widthOrHeight); // var pxIndex = val.indexOf('px'); // if (pxIndex !== -1) { // return val.slice(0, pxIndex); // } else { // return val; // } } }; /** * Fired when the width and/or height of the component changes * @event resize */ vjs.Component.prototype.onResize; /** * Emit 'tap' events when touch events are supported * * This is used to support toggling the controls through a tap on the video. * * We're requiring them to be enabled because otherwise every component would * have this extra overhead unnecessarily, on mobile devices where extra * overhead is especially bad. * @private */ vjs.Component.prototype.emitTapEvents = function(){ var touchStart, firstTouch, touchTime, couldBeTap, noTap, xdiff, ydiff, touchDistance, tapMovementThreshold, touchTimeThreshold; // Track the start time so we can determine how long the touch lasted touchStart = 0; firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap // Other popular libs use anywhere from 2 (hammer.js) to 15, so 10 seems like a nice, round number. tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap touchTimeThreshold = 200; this.on('touchstart', function(event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { firstTouch = vjs.obj.copy(event.touches[0]); // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function(event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap xdiff = event.touches[0].pageX - firstTouch.pageX; ydiff = event.touches[0].pageY - firstTouch.pageY; touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); noTap = function(){ couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function(event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted touchTime = new Date().getTime() - touchStart; // Make sure the touch was less than the threshold to be considered a tap if (touchTime < touchTimeThreshold) { event.preventDefault(); // Don't let browser turn this into a click this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // vjs.fixEvent runs (e.g. event.target) } } }); }; /** * Report user touch activity when touch events occur * * User activity is used to determine when controls should show/hide. It's * relatively simple when it comes to mouse events, because any mouse event * should show the controls. So we capture mouse events that bubble up to the * player and report activity when that happens. * * With touch events it isn't as easy. We can't rely on touch events at the * player level, because a tap (touchstart + touchend) on the video itself on * mobile devices is meant to turn controls off (and on). User activity is * checked asynchronously, so what could happen is a tap event on the video * turns the controls off, then the touchend event bubbles up to the player, * which if it reported user activity, would turn the controls right back on. * (We also don't want to completely block touch events from bubbling up) * * Also a touchmove, touch+hold, and anything other than a tap is not supposed * to turn the controls back on on a mobile device. * * Here we're setting the default component behavior to report user activity * whenever touch events happen, and this can be turned off by components that * want touch events to act differently. */ vjs.Component.prototype.enableTouchActivity = function() { var report, touchHolding, touchEnd; // Don't continue if the root player doesn't support reporting user activity if (!this.player().reportUserActivity) { return; } // listener for reporting that the user is active report = vjs.bind(this.player(), this.player().reportUserActivity); this.on('touchstart', function() { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); touchEnd = function(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /** * Creates timeout and sets up disposal automatically. * @param {Function} fn The function to run after the timeout. * @param {Number} timeout Number of ms to delay before executing specified function. * @return {Number} Returns the timeout ID */ vjs.Component.prototype.setTimeout = function(fn, timeout) { fn = vjs.bind(this, fn); // window.setTimeout would be preferable here, but due to some bizarre issue with Sinon and/or Phantomjs, we can't. var timeoutId = setTimeout(fn, timeout); var disposeFn = function() { this.clearTimeout(timeoutId); }; disposeFn.guid = 'vjs-timeout-'+ timeoutId; this.on('dispose', disposeFn); return timeoutId; }; /** * Clears a timeout and removes the associated dispose listener * @param {Number} timeoutId The id of the timeout to clear * @return {Number} Returns the timeout ID */ vjs.Component.prototype.clearTimeout = function(timeoutId) { clearTimeout(timeoutId); var disposeFn = function(){}; disposeFn.guid = 'vjs-timeout-'+ timeoutId; this.off('dispose', disposeFn); return timeoutId; }; /** * Creates an interval and sets up disposal automatically. * @param {Function} fn The function to run every N seconds. * @param {Number} interval Number of ms to delay before executing specified function. * @return {Number} Returns the interval ID */ vjs.Component.prototype.setInterval = function(fn, interval) { fn = vjs.bind(this, fn); var intervalId = setInterval(fn, interval); var disposeFn = function() { this.clearInterval(intervalId); }; disposeFn.guid = 'vjs-interval-'+ intervalId; this.on('dispose', disposeFn); return intervalId; }; /** * Clears an interval and removes the associated dispose listener * @param {Number} intervalId The id of the interval to clear * @return {Number} Returns the interval ID */ vjs.Component.prototype.clearInterval = function(intervalId) { clearInterval(intervalId); var disposeFn = function(){}; disposeFn.guid = 'vjs-interval-'+ intervalId; this.off('dispose', disposeFn); return intervalId; }; /* Button - Base class for all buttons ================================================================================ */ /** * Base class for all buttons * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.Button = vjs.Component.extend({ /** * @constructor * @inheritDoc */ init: function(player, options){ vjs.Component.call(this, player, options); this.emitTapEvents(); this.on('tap', this.onClick); this.on('click', this.onClick); this.on('focus', this.onFocus); this.on('blur', this.onBlur); } }); vjs.Button.prototype.createEl = function(type, props){ var el; // Add standard Aria and Tabindex info props = vjs.obj.merge({ className: this.buildCSSClass(), 'role': 'button', 'aria-live': 'polite', // let the screen reader user know that the text of the button may change tabIndex: 0 }, props); el = vjs.Component.prototype.createEl.call(this, type, props); // if innerHTML hasn't been overridden (bigPlayButton), add content elements if (!props.innerHTML) { this.contentEl_ = vjs.createEl('div', { className: 'vjs-control-content' }); this.controlText_ = vjs.createEl('span', { className: 'vjs-control-text', innerHTML: this.localize(this.buttonText) || 'Need Text' }); this.contentEl_.appendChild(this.controlText_); el.appendChild(this.contentEl_); } return el; }; vjs.Button.prototype.buildCSSClass = function(){ // TODO: Change vjs-control to vjs-button? return 'vjs-control ' + vjs.Component.prototype.buildCSSClass.call(this); }; // Click - Override with specific functionality for button vjs.Button.prototype.onClick = function(){}; // Focus - Add keyboard functionality to element vjs.Button.prototype.onFocus = function(){ vjs.on(document, 'keydown', vjs.bind(this, this.onKeyPress)); }; // KeyPress (document level) - Trigger click when keys are pressed vjs.Button.prototype.onKeyPress = function(event){ // Check for space bar (32) or enter (13) keys if (event.which == 32 || event.which == 13) { event.preventDefault(); this.onClick(); } }; // Blur - Remove keyboard triggers vjs.Button.prototype.onBlur = function(){ vjs.off(document, 'keydown', vjs.bind(this, this.onKeyPress)); }; /* Slider ================================================================================ */ /** * The base functionality for sliders like the volume bar and seek bar * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.Slider = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // Set property names to bar and handle to match with the child Slider class is looking for this.bar = this.getChild(this.options_['barName']); this.handle = this.getChild(this.options_['handleName']); this.on('mousedown', this.onMouseDown); this.on('touchstart', this.onMouseDown); this.on('focus', this.onFocus); this.on('blur', this.onBlur); this.on('click', this.onClick); this.on(player, 'controlsvisible', this.update); this.on(player, this.playerEvent, this.update); } }); vjs.Slider.prototype.createEl = function(type, props) { props = props || {}; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = vjs.obj.merge({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabIndex: 0 }, props); return vjs.Component.prototype.createEl.call(this, type, props); }; vjs.Slider.prototype.onMouseDown = function(event){ event.preventDefault(); vjs.blockTextSelection(); this.addClass('vjs-sliding'); this.on(document, 'mousemove', this.onMouseMove); this.on(document, 'mouseup', this.onMouseUp); this.on(document, 'touchmove', this.onMouseMove); this.on(document, 'touchend', this.onMouseUp); this.onMouseMove(event); }; // To be overridden by a subclass vjs.Slider.prototype.onMouseMove = function(){}; vjs.Slider.prototype.onMouseUp = function() { vjs.unblockTextSelection(); this.removeClass('vjs-sliding'); this.off(document, 'mousemove', this.onMouseMove); this.off(document, 'mouseup', this.onMouseUp); this.off(document, 'touchmove', this.onMouseMove); this.off(document, 'touchend', this.onMouseUp); this.update(); }; vjs.Slider.prototype.update = function(){ // In VolumeBar init we have a setTimeout for update that pops and update to the end of the // execution stack. The player is destroyed before then update will cause an error if (!this.el_) return; // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse. // On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var barProgress, progress = this.getPercent(), handle = this.handle, bar = this.bar; // Protect against no duration and other division issues if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) { progress = 0; } barProgress = progress; // If there is a handle, we need to account for the handle in our calculation for progress bar // so that it doesn't fall short of or extend past the handle. if (handle) { var box = this.el_, boxWidth = box.offsetWidth, handleWidth = handle.el().offsetWidth, // The width of the handle in percent of the containing box // In IE, widths may not be ready yet causing NaN handlePercent = (handleWidth) ? handleWidth / boxWidth : 0, // Get the adjusted size of the box, considering that the handle's center never touches the left or right side. // There is a margin of half the handle's width on both sides. boxAdjustedPercent = 1 - handlePercent, // Adjust the progress that we'll use to set widths to the new adjusted box width adjustedProgress = progress * boxAdjustedPercent; // The bar does reach the left side, so we need to account for this in the bar's width barProgress = adjustedProgress + (handlePercent / 2); // Move the handle from the left based on the adjected progress handle.el().style.left = vjs.round(adjustedProgress * 100, 2) + '%'; } // Set the new bar width if (bar) { bar.el().style.width = vjs.round(barProgress * 100, 2) + '%'; } }; vjs.Slider.prototype.calculateDistance = function(event){ var el, box, boxX, boxY, boxW, boxH, handle, pageX, pageY; el = this.el_; box = vjs.findPosition(el); boxW = boxH = el.offsetWidth; handle = this.handle; if (this.options()['vertical']) { boxY = box.top; if (event.changedTouches) { pageY = event.changedTouches[0].pageY; } else { pageY = event.pageY; } if (handle) { var handleH = handle.el().offsetHeight; // Adjusted X and Width, so handle doesn't go outside the bar boxY = boxY + (handleH / 2); boxH = boxH - handleH; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, ((boxY - pageY) + boxH) / boxH)); } else { boxX = box.left; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; } else { pageX = event.pageX; } if (handle) { var handleW = handle.el().offsetWidth; // Adjusted X and Width, so handle doesn't go outside the bar boxX = boxX + (handleW / 2); boxW = boxW - handleW; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (pageX - boxX) / boxW)); } }; vjs.Slider.prototype.onFocus = function(){ this.on(document, 'keydown', this.onKeyPress); }; vjs.Slider.prototype.onKeyPress = function(event){ if (event.which == 37 || event.which == 40) { // Left and Down Arrows event.preventDefault(); this.stepBack(); } else if (event.which == 38 || event.which == 39) { // Up and Right Arrows event.preventDefault(); this.stepForward(); } }; vjs.Slider.prototype.onBlur = function(){ this.off(document, 'keydown', this.onKeyPress); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * @param {Object} event Event object */ vjs.Slider.prototype.onClick = function(event){ event.stopImmediatePropagation(); event.preventDefault(); }; /** * SeekBar Behavior includes play progress bar, and seek handle * Needed so it can determine seek position based on handle position/size * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SliderHandle = vjs.Component.extend(); /** * Default value of the slider * * @type {Number} * @private */ vjs.SliderHandle.prototype.defaultValue = 0; /** @inheritDoc */ vjs.SliderHandle.prototype.createEl = function(type, props) { props = props || {}; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider-handle'; props = vjs.obj.merge({ innerHTML: '<span class="vjs-control-text">'+this.defaultValue+'</span>' }, props); return vjs.Component.prototype.createEl.call(this, 'div', props); }; /* Menu ================================================================================ */ /** * The Menu component is used to build pop up menus, including subtitle and * captions selection menus. * * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.Menu = vjs.Component.extend(); /** * Add a menu item to the menu * @param {Object|String} component Component or component type to add */ vjs.Menu.prototype.addItem = function(component){ this.addChild(component); component.on('click', vjs.bind(this, function(){ this.unlockShowing(); })); }; /** @inheritDoc */ vjs.Menu.prototype.createEl = function(){ var contentElType = this.options().contentElType || 'ul'; this.contentEl_ = vjs.createEl(contentElType, { className: 'vjs-menu-content' }); var el = vjs.Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant vjs.on(el, 'click', function(event){ event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; /** * The component for a menu item. `<li>` * * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.MenuItem = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.selected(options['selected']); } }); /** @inheritDoc */ vjs.MenuItem.prototype.createEl = function(type, props){ return vjs.Button.prototype.createEl.call(this, 'li', vjs.obj.merge({ className: 'vjs-menu-item', innerHTML: this.localize(this.options_['label']) }, props)); }; /** * Handle a click on the menu item, and set it to selected */ vjs.MenuItem.prototype.onClick = function(){ this.selected(true); }; /** * Set this menu item as selected or not * @param {Boolean} selected */ vjs.MenuItem.prototype.selected = function(selected){ if (selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-selected',true); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-selected',false); } }; /** * A button class with a popup menu * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.MenuButton = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.update(); this.on('keydown', this.onKeyPress); this.el_.setAttribute('aria-haspopup', true); this.el_.setAttribute('role', 'button'); } }); vjs.MenuButton.prototype.update = function() { var menu = this.createMenu(); if (this.menu) { this.removeChild(this.menu); } this.menu = menu; this.addChild(menu); if (this.items && this.items.length === 0) { this.hide(); } else if (this.items && this.items.length > 1) { this.show(); } }; /** * Track the state of the menu button * @type {Boolean} * @private */ vjs.MenuButton.prototype.buttonPressed_ = false; vjs.MenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player_); // Add a title list item to the top if (this.options().title) { menu.contentEl().appendChild(vjs.createEl('li', { className: 'vjs-menu-title', innerHTML: vjs.capitalize(this.options().title), tabindex: -1 })); } this.items = this['createItems'](); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; }; /** * Create the list of menu items. Specific to each subclass. */ vjs.MenuButton.prototype.createItems = function(){}; /** @inheritDoc */ vjs.MenuButton.prototype.buildCSSClass = function(){ return this.className + ' vjs-menu-button ' + vjs.Button.prototype.buildCSSClass.call(this); }; // Focus - Add keyboard functionality to element // This function is not needed anymore. Instead, the keyboard functionality is handled by // treating the button as triggering a submenu. When the button is pressed, the submenu // appears. Pressing the button again makes the submenu disappear. vjs.MenuButton.prototype.onFocus = function(){}; // Can't turn off list display that we turned on with focus, because list would go away. vjs.MenuButton.prototype.onBlur = function(){}; vjs.MenuButton.prototype.onClick = function(){ // When you click the button it adds focus, which will show the menu indefinitely. // So we'll remove focus when the mouse leaves the button. // Focus is needed for tab navigation. this.one('mouseout', vjs.bind(this, function(){ this.menu.unlockShowing(); this.el_.blur(); })); if (this.buttonPressed_){ this.unpressButton(); } else { this.pressButton(); } }; vjs.MenuButton.prototype.onKeyPress = function(event){ // Check for space bar (32) or enter (13) keys if (event.which == 32 || event.which == 13) { if (this.buttonPressed_){ this.unpressButton(); } else { this.pressButton(); } event.preventDefault(); // Check for escape (27) key } else if (event.which == 27){ if (this.buttonPressed_){ this.unpressButton(); } event.preventDefault(); } }; vjs.MenuButton.prototype.pressButton = function(){ this.buttonPressed_ = true; this.menu.lockShowing(); this.el_.setAttribute('aria-pressed', true); if (this.items && this.items.length > 0) { this.items[0].el().focus(); // set the focus to the title of the submenu } }; vjs.MenuButton.prototype.unpressButton = function(){ this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-pressed', false); }; /** * Custom MediaError to mimic the HTML5 MediaError * @param {Number} code The media error code */ vjs.MediaError = function(code){ if (typeof code === 'number') { this.code = code; } else if (typeof code === 'string') { // default code is zero, so this is a custom error this.message = code; } else if (typeof code === 'object') { // object vjs.obj.merge(this, code); } if (!this.message) { this.message = vjs.MediaError.defaultMessages[this.code] || ''; } }; /** * The error code that refers two one of the defined * MediaError types * @type {Number} */ vjs.MediaError.prototype.code = 0; /** * An optional message to be shown with the error. * Message is not part of the HTML5 video spec * but allows for more informative custom errors. * @type {String} */ vjs.MediaError.prototype.message = ''; /** * An optional status code that can be set by plugins * to allow even more detail about the error. * For example the HLS plugin might provide the specific * HTTP status code that was returned when the error * occurred, then allowing a custom error overlay * to display more information. * @type {[type]} */ vjs.MediaError.prototype.status = null; vjs.MediaError.errorTypes = [ 'MEDIA_ERR_CUSTOM', // = 0 'MEDIA_ERR_ABORTED', // = 1 'MEDIA_ERR_NETWORK', // = 2 'MEDIA_ERR_DECODE', // = 3 'MEDIA_ERR_SRC_NOT_SUPPORTED', // = 4 'MEDIA_ERR_ENCRYPTED' // = 5 ]; vjs.MediaError.defaultMessages = { 1: 'You aborted the video playback', 2: 'A network error caused the video download to fail part-way.', 3: 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support.', 4: 'The video could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The video is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < vjs.MediaError.errorTypes.length; errNum++) { vjs.MediaError[vjs.MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance vjs.MediaError.prototype[vjs.MediaError.errorTypes[errNum]] = errNum; } (function(){ var apiMap, specApi, browserApi, i; /** * Store the browser-specific methods for the fullscreen API * @type {Object|undefined} * @private */ vjs.browser.fullscreenAPI; // browser API methods // map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js apiMap = [ // Spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html [ 'requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror' ], // WebKit [ 'webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror' ], // Old WebKit (Safari 5.1) [ 'webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror' ], // Mozilla [ 'mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror' ], // Microsoft [ 'msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError' ] ]; specApi = apiMap[0]; // determine the supported set of functions for (i=0; i<apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in document) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names // or leave vjs.browser.fullscreenAPI undefined if (browserApi) { vjs.browser.fullscreenAPI = {}; for (i=0; i<browserApi.length; i++) { vjs.browser.fullscreenAPI[specApi[i]] = browserApi[i]; } } })(); /** * An instance of the `vjs.Player` class is created when any of the Video.js setup methods are used to initialize a video. * * ```js * var myPlayer = videojs('example_video_1'); * ``` * * In the following example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready. * * ```html * <video id="example_video_1" data-setup='{}' controls> * <source src="my-source.mp4" type="video/mp4"> * </video> * ``` * * After an instance has been created it can be accessed globally using `Video('example_video_1')`. * * @class * @extends vjs.Component */ vjs.Player = vjs.Component.extend({ /** * player's constructor function * * @constructs * @method init * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Player options * @param {Function=} ready Ready callback function */ init: function(tag, options, ready){ this.tag = tag; // Store the original tag used to set options // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + vjs.guid++; // Store the tag attributes used to restore html5 element this.tagAttributes = tag && vjs.getElementAttributes(tag); // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = vjs.obj.merge(this.getTagSettings(tag), options); // Update Current Language this.language_ = options['language'] || vjs.options['language']; // Update Supported Languages this.languages_ = options['languages'] || vjs.options['languages']; // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options['poster'] || ''; // Set controls this.controls_ = !!options['controls']; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Set isAudio based on whether or not an audio tag was used this.isAudio(this.tag.nodeName.toLowerCase() === 'audio'); // Run base component initializing with new options. // Builds the element through createEl() // Inits and embeds any child components in opts vjs.Component.call(this, this, options, ready); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } if (this.isAudio()) { this.addClass('vjs-audio'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (vjs.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Make player easily findable by ID vjs.players[this.id_] = this; if (options['plugins']) { vjs.obj.each(options['plugins'], function(key, val){ this[key](val); }, this); } this.listenForUserActivity(); } }); /** * The player's stored language code * * @type {String} * @private */ vjs.Player.prototype.language_; /** * The player's language code * @param {String} languageCode The locale string * @return {String} The locale string when getting * @return {vjs.Player} self, when setting */ vjs.Player.prototype.language = function (languageCode) { if (languageCode === undefined) { return this.language_; } this.language_ = languageCode; return this; }; /** * The player's stored language dictionary * * @type {Object} * @private */ vjs.Player.prototype.languages_; vjs.Player.prototype.languages = function(){ return this.languages_; }; /** * Player instance options, surfaced using vjs.options * vjs.options = vjs.Player.prototype.options_ * Make changes in vjs.options, not here. * All options should use string keys so they avoid * renaming by closure compiler * @type {Object} * @private */ vjs.Player.prototype.options_ = vjs.options; /** * Destroys the video player and does any necessary cleanup * * myPlayer.dispose(); * * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. */ vjs.Player.prototype.dispose = function(){ this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); // Kill reference to this player vjs.players[this.id_] = null; if (this.tag && this.tag['player']) { this.tag['player'] = null; } if (this.el_ && this.el_['player']) { this.el_['player'] = null; } if (this.tech) { this.tech.dispose(); } // Component dispose vjs.Component.prototype.dispose.call(this); }; vjs.Player.prototype.getTagSettings = function(tag){ var tagOptions, dataSetup, options = { 'sources': [], 'tracks': [] }; tagOptions = vjs.getElementAttributes(tag); dataSetup = tagOptions['data-setup']; // Check if data-setup attr exists. if (dataSetup !== null){ // Parse options JSON // If empty string, make it a parsable json object. vjs.obj.merge(tagOptions, vjs.JSON.parse(dataSetup || '{}')); } vjs.obj.merge(options, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children, child, childName, i, j; children = tag.childNodes; for (i=0,j=children.length; i<j; i++) { child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ childName = child.nodeName.toLowerCase(); if (childName === 'source') { options['sources'].push(vjs.getElementAttributes(child)); } else if (childName === 'track') { options['tracks'].push(vjs.getElementAttributes(child)); } } } return options; }; vjs.Player.prototype.createEl = function(){ var el = this.el_ = vjs.Component.prototype.createEl.call(this, 'div'), tag = this.tag, attrs; // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag attrs = vjs.getElementAttributes(tag); vjs.obj.each(attrs, function(attr) { // workaround so we don't totally break IE7 // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 if (attr == 'class') { el.className = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } }); // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag['player'] = el['player'] = this; // Default state of video is paused this.addClass('vjs-paused'); // Make box use width/height of tag, or rely on default implementation // Enforce with CSS since width/height attrs don't work on divs this.width(this.options_['width'], true); // (true) Skip resize listener on load this.height(this.options_['height'], true); // vjs.insertFirst seems to cause the networkState to flicker from 3 to 2, so // keep track of the original for later so we can know if the source originally failed tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container if (tag.parentNode) { tag.parentNode.insertBefore(el, tag); } vjs.insertFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup. // The event listeners need to be added before the children are added // in the component init because the tech (loaded with mediaLoader) may // fire events, like loadstart, that these events need to capture. // Long term it might be better to expose a way to do this in component.init // like component.initEventListeners() that runs between el creation and // adding children this.el_ = el; this.on('loadstart', this.onLoadStart); this.on('waiting', this.onWaiting); this.on(['canplay', 'canplaythrough', 'playing', 'ended'], this.onWaitEnd); this.on('seeking', this.onSeeking); this.on('seeked', this.onSeeked); this.on('ended', this.onEnded); this.on('play', this.onPlay); this.on('firstplay', this.onFirstPlay); this.on('pause', this.onPause); this.on('progress', this.onProgress); this.on('durationchange', this.onDurationChange); this.on('fullscreenchange', this.onFullscreenChange); return el; }; // /* Media Technology (tech) // ================================================================================ */ // Load/Create an instance of playback technology including element and API methods // And append playback element in player div. vjs.Player.prototype.loadTech = function(techName, source){ // Pause and remove current playback technology if (this.tech) { this.unloadTech(); } // get rid of the HTML5 video tag as soon as we are using another tech if (techName !== 'Html5' && this.tag) { vjs.Html5.disposeMediaElement(this.tag); this.tag = null; } this.techName = techName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; var techReady = function(){ this.player_.triggerReady(); }; // Grab tech-specific options from player options and add source and parent element to use. var techOptions = vjs.obj.merge({ 'source': source, 'parentEl': this.el_ }, this.options_[techName.toLowerCase()]); if (source) { this.currentType_ = source.type; if (source.src == this.cache_.src && this.cache_.currentTime > 0) { techOptions['startTime'] = this.cache_.currentTime; } this.cache_.src = source.src; } // Initialize tech instance this.tech = new window['videojs'][techName](this, techOptions); this.tech.ready(techReady); }; vjs.Player.prototype.unloadTech = function(){ this.isReady_ = false; this.tech.dispose(); this.tech = false; }; // There's many issues around changing the size of a Flash (or other plugin) object. // First is a plugin reload issue in Firefox that has been around for 11 years: https://bugzilla.mozilla.org/show_bug.cgi?id=90268 // Then with the new fullscreen API, Mozilla and webkit browsers will reload the flash object after going to fullscreen. // To get around this, we're unloading the tech, caching source and currentTime values, and reloading the tech once the plugin is resized. // reloadTech: function(betweenFn){ // vjs.log('unloadingTech') // this.unloadTech(); // vjs.log('unloadedTech') // if (betweenFn) { betweenFn.call(); } // vjs.log('LoadingTech') // this.loadTech(this.techName, { src: this.cache_.src }) // vjs.log('loadedTech') // }, // /* Player event handlers (how the player reacts to certain events) // ================================================================================ */ /** * Fired when the user agent begins looking for media data * @event loadstart */ vjs.Player.prototype.onLoadStart = function() { // TODO: Update to use `emptied` event instead. See #1277. this.removeClass('vjs-ended'); // reset the error state this.error(null); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); } }; vjs.Player.prototype.hasStarted_ = false; vjs.Player.prototype.hasStarted = function(hasStarted){ if (hasStarted !== undefined) { // only update if this is a new value if (this.hasStarted_ !== hasStarted) { this.hasStarted_ = hasStarted; if (hasStarted) { this.addClass('vjs-has-started'); // trigger the firstplay event if this newly has played this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } return this; } return this.hasStarted_; }; /** * Fired when the player has initial duration and dimension information * @event loadedmetadata */ vjs.Player.prototype.onLoadedMetaData; /** * Fired when the player has downloaded data at the current playback position * @event loadeddata */ vjs.Player.prototype.onLoadedData; /** * Fired when the player has finished downloading the source data * @event loadedalldata */ vjs.Player.prototype.onLoadedAllData; /** * Fired whenever the media begins or resumes playback * @event play */ vjs.Player.prototype.onPlay = function(){ this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // hide the poster when the user hits play // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play this.hasStarted(true); }; /** * Fired whenever the media begins waiting * @event waiting */ vjs.Player.prototype.onWaiting = function(){ this.addClass('vjs-waiting'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * @private */ vjs.Player.prototype.onWaitEnd = function(){ this.removeClass('vjs-waiting'); }; /** * Fired whenever the player is jumping to a new time * @event seeking */ vjs.Player.prototype.onSeeking = function(){ this.addClass('vjs-seeking'); }; /** * Fired when the player has finished jumping to a new time * @event seeked */ vjs.Player.prototype.onSeeked = function(){ this.removeClass('vjs-seeking'); }; /** * Fired the first time a video is played * * Not part of the HLS spec, and we're not sure if this is the best * implementation yet, so use sparingly. If you don't have a reason to * prevent playback, use `myPlayer.one('play');` instead. * * @event firstplay */ vjs.Player.prototype.onFirstPlay = function(){ //If the first starttime attribute is specified //then we will start at the given offset in seconds if(this.options_['starttime']){ this.currentTime(this.options_['starttime']); } this.addClass('vjs-has-started'); }; /** * Fired whenever the media has been paused * @event pause */ vjs.Player.prototype.onPause = function(){ this.removeClass('vjs-playing'); this.addClass('vjs-paused'); }; /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * @event timeupdate */ vjs.Player.prototype.onTimeUpdate; /** * Fired while the user agent is downloading media data * @event progress */ vjs.Player.prototype.onProgress = function(){ // Add custom event for when source is finished downloading. if (this.bufferedPercent() == 1) { this.trigger('loadedalldata'); } }; /** * Fired when the end of the media resource is reached (currentTime == duration) * @event ended */ vjs.Player.prototype.onEnded = function(){ this.addClass('vjs-ended'); if (this.options_['loop']) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } }; /** * Fired when the duration of the media resource is first known or changed * @event durationchange */ vjs.Player.prototype.onDurationChange = function(){ // Allows for caching value instead of asking player each time. // We need to get the techGet response and check for a value so we don't // accidentally cause the stack to blow up. var duration = this.techGet('duration'); if (duration) { if (duration < 0) { duration = Infinity; } this.duration(duration); // Determine if the stream is live and propagate styles down to UI. if (duration === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } } }; /** * Fired when the volume changes * @event volumechange */ vjs.Player.prototype.onVolumeChange; /** * Fired when the player switches in or out of fullscreen mode * @event fullscreenchange */ vjs.Player.prototype.onFullscreenChange = function() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; /** * Fired when an error occurs * @event error */ vjs.Player.prototype.onError; // /* Player API // ================================================================================ */ /** * Object for cached values. * @private */ vjs.Player.prototype.cache_; vjs.Player.prototype.getCache = function(){ return this.cache_; }; // Pass values to the playback tech vjs.Player.prototype.techCall = function(method, arg){ // If it's not ready yet, call method when it is if (this.tech && !this.tech.isReady_) { this.tech.ready(function(){ this[method](arg); }); // Otherwise call method now } else { try { this.tech[method](arg); } catch(e) { vjs.log(e); throw e; } } }; // Get calls can't wait for the tech, and sometimes don't need to. vjs.Player.prototype.techGet = function(method){ if (this.tech && this.tech.isReady_) { // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech[method](); } catch(e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech[method] === undefined) { vjs.log('Video.js: ' + method + ' method not defined for '+this.techName+' playback technology.', e); } else { // When a method isn't available on the object it throws a TypeError if (e.name == 'TypeError') { vjs.log('Video.js: ' + method + ' unavailable on '+this.techName+' playback technology element.', e); this.tech.isReady_ = false; } else { vjs.log(e); } } throw e; } } return; }; /** * start media playback * * myPlayer.play(); * * @return {vjs.Player} self */ vjs.Player.prototype.play = function(){ this.techCall('play'); return this; }; /** * Pause the video playback * * myPlayer.pause(); * * @return {vjs.Player} self */ vjs.Player.prototype.pause = function(){ this.techCall('pause'); return this; }; /** * Check if the player is paused * * var isPaused = myPlayer.paused(); * var isPlaying = !myPlayer.paused(); * * @return {Boolean} false if the media is currently playing, or true otherwise */ vjs.Player.prototype.paused = function(){ // The initial state of paused should be true (in Safari it's actually false) return (this.techGet('paused') === false) ? false : true; }; /** * Get or set the current time (in seconds) * * // get * var whereYouAt = myPlayer.currentTime(); * * // set * myPlayer.currentTime(120); // 2 minutes into the video * * @param {Number|String=} seconds The time to seek to * @return {Number} The time in seconds, when not setting * @return {vjs.Player} self, when the current time is set */ vjs.Player.prototype.currentTime = function(seconds){ if (seconds !== undefined) { this.techCall('setCurrentTime', seconds); return this; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. return this.cache_.currentTime = (this.techGet('currentTime') || 0); }; /** * Get the length in time of the video in seconds * * var lengthOfVideo = myPlayer.duration(); * * **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @return {Number} The duration of the video in seconds */ vjs.Player.prototype.duration = function(seconds){ if (seconds !== undefined) { // cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = parseFloat(seconds); return this; } if (this.cache_.duration === undefined) { this.onDurationChange(); } return this.cache_.duration || 0; }; /** * Calculates how much time is left. * * var timeLeft = myPlayer.remainingTime(); * * Not a native video element function, but useful * @return {Number} The time remaining in seconds */ vjs.Player.prototype.remainingTime = function(){ return this.duration() - this.currentTime(); }; // http://dev.w3.org/html5/spec/video.html#dom-media-buffered // Buffered returns a timerange object. // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with the times of the video that have been downloaded * * If you just want the percent of the video that's been downloaded, * use bufferedPercent. * * // Number of different ranges of time have been buffered. Usually 1. * numberOfRanges = bufferedTimeRange.length, * * // Time in seconds when the first range starts. Usually 0. * firstRangeStart = bufferedTimeRange.start(0), * * // Time in seconds when the first range ends * firstRangeEnd = bufferedTimeRange.end(0), * * // Length in seconds of the first time range * firstRangeLength = firstRangeEnd - firstRangeStart; * * @return {Object} A mock TimeRange object (following HTML spec) */ vjs.Player.prototype.buffered = function(){ var buffered = this.techGet('buffered'); if (!buffered || !buffered.length) { buffered = vjs.createTimeRange(0,0); } return buffered; }; /** * Get the percent (as a decimal) of the video that's been downloaded * * var howMuchIsDownloaded = myPlayer.bufferedPercent(); * * 0 means none, 1 means all. * (This method isn't in the HTML5 spec, but it's very convenient) * * @return {Number} A decimal between 0 and 1 representing the percent */ vjs.Player.prototype.bufferedPercent = function(){ var duration = this.duration(), buffered = this.buffered(), bufferedDuration = 0, start, end; if (!duration) { return 0; } for (var i=0; i<buffered.length; i++){ start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; }; /** * Get the ending time of the last buffered time range * * This is used in the progress bar to encapsulate all time ranges. * @return {Number} The end of the last buffered time range */ vjs.Player.prototype.bufferedEnd = function(){ var buffered = this.buffered(), duration = this.duration(), end = buffered.end(buffered.length-1); if (end > duration) { end = duration; } return end; }; /** * Get or set the current volume of the media * * // get * var howLoudIsIt = myPlayer.volume(); * * // set * myPlayer.volume(0.5); // Set volume to half * * 0 is off (muted), 1.0 is all the way up, 0.5 is half way. * * @param {Number} percentAsDecimal The new volume as a decimal percent * @return {Number} The current volume, when getting * @return {vjs.Player} self, when setting */ vjs.Player.prototype.volume = function(percentAsDecimal){ var vol; if (percentAsDecimal !== undefined) { vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1 this.cache_.volume = vol; this.techCall('setVolume', vol); vjs.setLocalStorage('volume', vol); return this; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet('volume')); return (isNaN(vol)) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * * // get * var isVolumeMuted = myPlayer.muted(); * * // set * myPlayer.muted(true); // mute the volume * * @param {Boolean=} muted True to mute, false to unmute * @return {Boolean} True if mute is on, false if not, when getting * @return {vjs.Player} self, when setting mute */ vjs.Player.prototype.muted = function(muted){ if (muted !== undefined) { this.techCall('setMuted', muted); return this; } return this.techGet('muted') || false; // Default to false }; // Check if current tech can support native fullscreen // (e.g. with built in controls like iOS, so not our flash swf) vjs.Player.prototype.supportsFullScreen = function(){ return this.techGet('supportsFullScreen') || false; }; /** * is the player in fullscreen * @type {Boolean} * @private */ vjs.Player.prototype.isFullscreen_ = false; /** * Check if the player is in fullscreen mode * * // get * var fullscreenOrNot = myPlayer.isFullscreen(); * * // set * myPlayer.isFullscreen(true); // tell the player it's in fullscreen * * NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {Boolean=} isFS Update the player's fullscreen state * @return {Boolean} true if fullscreen, false if not * @return {vjs.Player} self, when setting */ vjs.Player.prototype.isFullscreen = function(isFS){ if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return this; } return this.isFullscreen_; }; /** * Old naming for isFullscreen() * @deprecated for lowercase 's' version */ vjs.Player.prototype.isFullScreen = function(isFS){ vjs.log.warn('player.isFullScreen() has been deprecated, use player.isFullscreen() with a lowercase "s")'); return this.isFullscreen(isFS); }; /** * Increase the size of the video to full screen * * myPlayer.requestFullscreen(); * * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @return {vjs.Player} self */ vjs.Player.prototype.requestFullscreen = function(){ var fsApi = vjs.browser.fullscreenAPI; this.isFullscreen(true); if (fsApi) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events vjs.on(document, fsApi['fullscreenchange'], vjs.bind(this, function(e){ this.isFullscreen(document[fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { vjs.off(document, fsApi['fullscreenchange'], arguments.callee); } this.trigger('fullscreenchange'); })); this.el_[fsApi.requestFullscreen](); } else if (this.tech.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Old naming for requestFullscreen * @deprecated for lower case 's' version */ vjs.Player.prototype.requestFullScreen = function(){ vjs.log.warn('player.requestFullScreen() has been deprecated, use player.requestFullscreen() with a lowercase "s")'); return this.requestFullscreen(); }; /** * Return the video to its normal size after having been in full screen mode * * myPlayer.exitFullscreen(); * * @return {vjs.Player} self */ vjs.Player.prototype.exitFullscreen = function(){ var fsApi = vjs.browser.fullscreenAPI; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi) { document[fsApi.exitFullscreen](); } else if (this.tech.supportsFullScreen()) { this.techCall('exitFullScreen'); } else { this.exitFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Old naming for exitFullscreen * @deprecated for exitFullscreen */ vjs.Player.prototype.cancelFullScreen = function(){ vjs.log.warn('player.cancelFullScreen() has been deprecated, use player.exitFullscreen()'); return this.exitFullscreen(); }; // When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us. vjs.Player.prototype.enterFullWindow = function(){ this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = document.documentElement.style.overflow; // Add listener for esc key to exit fullscreen vjs.on(document, 'keydown', vjs.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars document.documentElement.style.overflow = 'hidden'; // Apply fullscreen styles vjs.addClass(document.body, 'vjs-full-window'); this.trigger('enterFullWindow'); }; vjs.Player.prototype.fullWindowOnEscKey = function(event){ if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; vjs.Player.prototype.exitFullWindow = function(){ this.isFullWindow = false; vjs.off(document, 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. document.documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles vjs.removeClass(document.body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); this.trigger('exitFullWindow'); }; vjs.Player.prototype.selectSource = function(sources){ // Loop through each playback technology in the options order for (var i=0,j=this.options_['techOrder'];i<j.length;i++) { var techName = vjs.capitalize(j[i]), tech = window['videojs'][techName]; // Check if the current tech is defined before continuing if (!tech) { vjs.log.error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); continue; } // Check if the browser supports this technology if (tech.isSupported()) { // Loop through each source object for (var a=0,b=sources;a<b.length;a++) { var source = b[a]; // Check if source can be played with this technology if (tech['canPlaySource'](source)) { return { source: source, tech: techName }; } } } } return false; }; /** * The source function updates the video source * * There are three types of variables you can pass as the argument. * * **URL String**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * * myPlayer.src("http://www.example.com/path/to/video.mp4"); * * **Source Object (or element):** A javascript object containing information * about the source file. Use this method if you want the player to determine if * it can support the file using the type information. * * myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); * * **Array of Source Objects:** To provide multiple versions of the source so * that it can be played using HTML5 across browsers you can use an array of * source objects. Video.js will detect which version is supported and load that * file. * * myPlayer.src([ * { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }, * { type: "video/webm", src: "http://www.example.com/path/to/video.webm" }, * { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } * ]); * * @param {String|Object|Array=} source The source URL, object, or array of sources * @return {String} The current video source when getting * @return {String} The player when setting */ vjs.Player.prototype.src = function(source){ if (source === undefined) { return this.techGet('src'); } // case: Array of source objects to choose from and pick the best to play if (vjs.obj.isArray(source)) { this.sourceList_(source); // case: URL String (http://myvideo...) } else if (typeof source === 'string') { // create a source object from the string this.src({ src: source }); // case: Source object { src: '', type: '' ... } } else if (source instanceof Object) { // check if the source has a type and the loaded tech cannot play the source // if there's no type we'll just try the current tech if (source.type && !window['videojs'][this.techName]['canPlaySource'](source)) { // create a source list with the current source and send through // the tech loop to check for a compatible technology this.sourceList_([source]); } else { this.cache_.src = source.src; this.currentType_ = source.type || ''; // wait until the tech is ready to set the source this.ready(function(){ // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (window['videojs'][this.techName].prototype.hasOwnProperty('setSource')) { this.techCall('setSource', source); } else { this.techCall('src', source.src); } if (this.options_['preload'] == 'auto') { this.load(); } if (this.options_['autoplay']) { this.play(); } }); } } return this; }; /** * Handle an array of source objects * @param {[type]} sources Array of source objects * @private */ vjs.Player.prototype.sourceList_ = function(sources){ var sourceTech = this.selectSource(sources); if (sourceTech) { if (sourceTech.tech === this.techName) { // if this technology is already loaded, set the source this.src(sourceTech.source); } else { // load this technology with the chosen source this.loadTech(sourceTech.tech, sourceTech.source); } } else { // We need to wrap this in a timeout to give folks a chance to add error event handlers this.setTimeout( function() { this.error({ code: 4, message: this.localize(this.options()['notSupportedMessage']) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed this.triggerReady(); } }; /** * Begin loading the src data. * @return {vjs.Player} Returns the player */ vjs.Player.prototype.load = function(){ this.techCall('load'); return this; }; /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. * @return {String} The current source */ vjs.Player.prototype.currentSrc = function(){ return this.techGet('currentSrc') || this.cache_.src || ''; }; /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * @return {String} The source MIME type */ vjs.Player.prototype.currentType = function(){ return this.currentType_ || ''; }; /** * Get or set the preload attribute. * @return {String} The preload attribute value when getting * @return {vjs.Player} Returns the player when setting */ vjs.Player.prototype.preload = function(value){ if (value !== undefined) { this.techCall('setPreload', value); this.options_['preload'] = value; return this; } return this.techGet('preload'); }; /** * Get or set the autoplay attribute. * @return {String} The autoplay attribute value when getting * @return {vjs.Player} Returns the player when setting */ vjs.Player.prototype.autoplay = function(value){ if (value !== undefined) { this.techCall('setAutoplay', value); this.options_['autoplay'] = value; return this; } return this.techGet('autoplay', value); }; /** * Get or set the loop attribute on the video element. * @return {String} The loop attribute value when getting * @return {vjs.Player} Returns the player when setting */ vjs.Player.prototype.loop = function(value){ if (value !== undefined) { this.techCall('setLoop', value); this.options_['loop'] = value; return this; } return this.techGet('loop'); }; /** * the url of the poster image source * @type {String} * @private */ vjs.Player.prototype.poster_; /** * get or set the poster image source url * * ##### EXAMPLE: * * // getting * var currentPoster = myPlayer.poster(); * * // setting * myPlayer.poster('http://example.com/myImage.jpg'); * * @param {String=} [src] Poster image source URL * @return {String} poster URL when getting * @return {vjs.Player} self when setting */ vjs.Player.prototype.poster = function(src){ if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall('setPoster', src); // alert components that the poster has been set this.trigger('posterchange'); return this; }; /** * Whether or not the controls are showing * @type {Boolean} * @private */ vjs.Player.prototype.controls_; /** * Get or set whether or not the controls are showing. * @param {Boolean} controls Set controls to showing or not * @return {Boolean} Controls are showing */ vjs.Player.prototype.controls = function(bool){ if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); this.trigger('controlsenabled'); } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); this.trigger('controlsdisabled'); } } return this; } return this.controls_; }; vjs.Player.prototype.usingNativeControls_; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @param {Boolean} bool True signals that native controls are on * @return {vjs.Player} Returns the player * @private */ vjs.Player.prototype.usingNativeControls = function(bool){ if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event usingnativecontrols * @memberof vjs.Player * @instance * @private */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event usingcustomcontrols * @memberof vjs.Player * @instance * @private */ this.trigger('usingcustomcontrols'); } } return this; } return this.usingNativeControls_; }; /** * Store the current media error * @type {Object} * @private */ vjs.Player.prototype.error_ = null; /** * Set or get the current MediaError * @param {*} err A MediaError or a String/Number to be turned into a MediaError * @return {vjs.MediaError|null} when getting * @return {vjs.Player} when setting */ vjs.Player.prototype.error = function(err){ if (err === undefined) { return this.error_; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); return this; } // error instance if (err instanceof vjs.MediaError) { this.error_ = err; } else { this.error_ = new vjs.MediaError(err); } // fire an error event on the player this.trigger('error'); // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // ie8 just logs "[object object]" if you just log the error object vjs.log.error('(CODE:'+this.error_.code+' '+vjs.MediaError.errorTypes[this.error_.code]+')', this.error_.message, this.error_); return this; }; /** * Returns whether or not the player is in the "ended" state. * @return {Boolean} True if the player is in the ended state, false if not. */ vjs.Player.prototype.ended = function(){ return this.techGet('ended'); }; /** * Returns whether or not the player is in the "seeking" state. * @return {Boolean} True if the player is in the seeking state, false if not. */ vjs.Player.prototype.seeking = function(){ return this.techGet('seeking'); }; /** * Returns the TimeRanges of the media that are currently available * for seeking to. * @return {TimeRanges} the seekable intervals of the media timeline */ vjs.Player.prototype.seekable = function(){ return this.techGet('seekable'); }; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed vjs.Player.prototype.userActivity_ = true; vjs.Player.prototype.reportUserActivity = function(event){ this.userActivity_ = true; }; vjs.Player.prototype.userActive_ = true; vjs.Player.prototype.userActive = function(bool){ if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if(this.tech) { this.tech.one('mousemove', function(e){ e.stopPropagation(); e.preventDefault(); }); } this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); this.trigger('userinactive'); } } return this; } return this.userActive_; }; vjs.Player.prototype.listenForUserActivity = function(){ var onActivity, onMouseMove, onMouseDown, mouseInProgress, onMouseUp, activityCheck, inactivityTimeout, lastMoveX, lastMoveY; onActivity = vjs.bind(this, this.reportUserActivity); onMouseMove = function(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if(e.screenX != lastMoveX || e.screenY != lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; onActivity(); } }; onMouseDown = function() { onActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(onActivity, 250); }; onMouseUp = function(event) { onActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', onMouseDown); this.on('mousemove', onMouseMove); this.on('mouseup', onMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', onActivity); this.on('keyup', onActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ activityCheck = this.setInterval(function() { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options()['inactivityTimeout']; if (timeout > 0) { // In <timeout> milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activityCheck loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); } } }, 250); }; /** * Gets or sets the current playback rate. * @param {Boolean} rate New playback rate to set. * @return {Number} Returns the new playback rate when setting * @return {Number} Returns the current playback rate when getting */ vjs.Player.prototype.playbackRate = function(rate) { if (rate !== undefined) { this.techCall('setPlaybackRate', rate); return this; } if (this.tech && this.tech['featuresPlaybackRate']) { return this.techGet('playbackRate'); } else { return 1.0; } }; /** * Store the current audio state * @type {Boolean} * @private */ vjs.Player.prototype.isAudio_ = false; /** * Gets or sets the audio flag * * @param {Boolean} bool True signals that this is an audio player. * @return {Boolean} Returns true if player is audio, false if not when getting * @return {vjs.Player} Returns the player if setting * @private */ vjs.Player.prototype.isAudio = function(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return this; } return this.isAudio_; }; /** * Returns the current state of network activity for the element, from * the codes in the list below. * - NETWORK_EMPTY (numeric value 0) * The element has not yet been initialised. All attributes are in * their initial states. * - NETWORK_IDLE (numeric value 1) * The element's resource selection algorithm is active and has * selected a resource, but it is not actually using the network at * this time. * - NETWORK_LOADING (numeric value 2) * The user agent is actively trying to download data. * - NETWORK_NO_SOURCE (numeric value 3) * The element's resource selection algorithm is active, but it has * not yet found a resource to use. * @return {Number} the current network activity state * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states */ vjs.Player.prototype.networkState = function(){ return this.techGet('networkState'); }; /** * Returns a value that expresses the current state of the element * with respect to rendering the current playback position, from the * codes in the list below. * - HAVE_NOTHING (numeric value 0) * No information regarding the media resource is available. * - HAVE_METADATA (numeric value 1) * Enough of the resource has been obtained that the duration of the * resource is available. * - HAVE_CURRENT_DATA (numeric value 2) * Data for the immediate current playback position is available. * - HAVE_FUTURE_DATA (numeric value 3) * Data for the immediate current playback position is available, as * well as enough data for the user agent to advance the current * playback position in the direction of playback. * - HAVE_ENOUGH_DATA (numeric value 4) * The user agent estimates that enough data is available for * playback to proceed uninterrupted. * @return {Number} the current playback rendering state * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate */ vjs.Player.prototype.readyState = function(){ return this.techGet('readyState'); }; /** * Text tracks are tracks of timed text events. * Captions - text displayed over the video for the hearing impaired * Subtitles - text displayed over the video for those who don't understand language in the video * Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video * Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device */ /** * Get an array of associated text tracks. captions, subtitles, chapters, descriptions * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * @return {Array} Array of track objects */ vjs.Player.prototype.textTracks = function(){ // cannot use techGet directly because it checks to see whether the tech is ready. // Flash is unlikely to be ready in time but textTracks should still work. return this.tech && this.tech['textTracks'](); }; vjs.Player.prototype.remoteTextTracks = function() { return this.tech && this.tech['remoteTextTracks'](); }; /** * Add a text track * In addition to the W3C settings we allow adding additional info through options. * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * @param {String} kind Captions, subtitles, chapters, descriptions, or metadata * @param {String=} label Optional label * @param {String=} language Optional language */ vjs.Player.prototype.addTextTrack = function(kind, label, language) { return this.tech && this.tech['addTextTrack'](kind, label, language); }; vjs.Player.prototype.addRemoteTextTrack = function(options) { return this.tech && this.tech['addRemoteTextTrack'](options); }; vjs.Player.prototype.removeRemoteTextTrack = function(track) { this.tech && this.tech['removeRemoteTextTrack'](track); }; // Methods to add support for // initialTime: function(){ return this.techCall('initialTime'); }, // startOffsetTime: function(){ return this.techCall('startOffsetTime'); }, // played: function(){ return this.techCall('played'); }, // seekable: function(){ return this.techCall('seekable'); }, // videoTracks: function(){ return this.techCall('videoTracks'); }, // audioTracks: function(){ return this.techCall('audioTracks'); }, // videoWidth: function(){ return this.techCall('videoWidth'); }, // videoHeight: function(){ return this.techCall('videoHeight'); }, // defaultPlaybackRate: function(){ return this.techCall('defaultPlaybackRate'); }, // mediaGroup: function(){ return this.techCall('mediaGroup'); }, // controller: function(){ return this.techCall('controller'); }, // defaultMuted: function(){ return this.techCall('defaultMuted'); } // TODO // currentSrcList: the array of sources including other formats and bitrates // playList: array of source lists in order of playback /** * Container of main controls * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor * @extends vjs.Component */ vjs.ControlBar = vjs.Component.extend(); vjs.ControlBar.prototype.options_ = { loadEvent: 'play', children: { 'playToggle': {}, 'currentTimeDisplay': {}, 'timeDivider': {}, 'durationDisplay': {}, 'remainingTimeDisplay': {}, 'liveDisplay': {}, 'progressControl': {}, 'fullscreenToggle': {}, 'volumeControl': {}, 'muteToggle': {}, // 'volumeMenuButton': {}, 'playbackRateMenuButton': {}, 'subtitlesButton': {}, 'captionsButton': {}, 'chaptersButton': {} } }; vjs.ControlBar.prototype.createEl = function(){ return vjs.createEl('div', { className: 'vjs-control-bar' }); }; /** * Displays the live indicator * TODO - Future make it click to snap to live * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.LiveDisplay = vjs.Component.extend({ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.LiveDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-live-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE'), 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Button to toggle between play and pause * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.PlayToggle = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.on(player, 'play', this.onPlay); this.on(player, 'pause', this.onPause); } }); vjs.PlayToggle.prototype.buttonText = 'Play'; vjs.PlayToggle.prototype.buildCSSClass = function(){ return 'vjs-play-control ' + vjs.Button.prototype.buildCSSClass.call(this); }; // OnClick - Toggle between play and pause vjs.PlayToggle.prototype.onClick = function(){ if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; // OnPlay - Add the vjs-playing class to the element so it can change appearance vjs.PlayToggle.prototype.onPlay = function(){ this.removeClass('vjs-paused'); this.addClass('vjs-playing'); this.el_.children[0].children[0].innerHTML = this.localize('Pause'); // change the button text to "Pause" }; // OnPause - Add the vjs-paused class to the element so it can change appearance vjs.PlayToggle.prototype.onPause = function(){ this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.el_.children[0].children[0].innerHTML = this.localize('Play'); // change the button text to "Play" }; /** * Displays the current time * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.CurrentTimeDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } }); vjs.CurrentTimeDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-current-time-display', innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00', // label the current time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; vjs.CurrentTimeDisplay.prototype.updateContent = function(){ // Allows for smooth scrubbing, when player can't keep up. var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Current Time') + '</span> ' + vjs.formatTime(time, this.player_.duration()); }; /** * Displays the duration * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.DurationDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // this might need to be changed to 'durationchange' instead of 'timeupdate' eventually, // however the durationchange event fires before this.player_.duration() is set, // so the value cannot be written out using this method. // Once the order of durationchange and this.player_.duration() being set is figured out, // this can be updated. this.on(player, 'timeupdate', this.updateContent); this.on(player, 'loadedmetadata', this.updateContent); } }); vjs.DurationDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-duration-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> ' + '0:00', // label the duration time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; vjs.DurationDisplay.prototype.updateContent = function(){ var duration = this.player_.duration(); if (duration) { this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> ' + vjs.formatTime(duration); // label the duration time for screen reader users } }; /** * The separator between the current time and duration * * Can be hidden if it's not needed in the design. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.TimeDivider = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.TimeDivider.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; /** * Displays the time left in the video * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.RemainingTimeDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } }); vjs.RemainingTimeDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-remaining-time-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> ' + '-0:00', // label the remaining time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; vjs.RemainingTimeDisplay.prototype.updateContent = function(){ if (this.player_.duration()) { this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> ' + '-'+ vjs.formatTime(this.player_.remainingTime()); } // Allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); // this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration()); }; /** * Toggle fullscreen video * @param {vjs.Player|Object} player * @param {Object=} options * @class * @extends vjs.Button */ vjs.FullscreenToggle = vjs.Button.extend({ /** * @constructor * @memberof vjs.FullscreenToggle * @instance */ init: function(player, options){ vjs.Button.call(this, player, options); } }); vjs.FullscreenToggle.prototype.buttonText = 'Fullscreen'; vjs.FullscreenToggle.prototype.buildCSSClass = function(){ return 'vjs-fullscreen-control ' + vjs.Button.prototype.buildCSSClass.call(this); }; vjs.FullscreenToggle.prototype.onClick = function(){ if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); this.controlText_.innerHTML = this.localize('Non-Fullscreen'); } else { this.player_.exitFullscreen(); this.controlText_.innerHTML = this.localize('Fullscreen'); } }; /** * The Progress Control component contains the seek bar, load progress, * and play progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.ProgressControl = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.ProgressControl.prototype.options_ = { children: { 'seekBar': {} } }; vjs.ProgressControl.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; /** * Seek Bar and holder for the progress bars * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SeekBar = vjs.Slider.extend({ /** @constructor */ init: function(player, options){ vjs.Slider.call(this, player, options); this.on(player, 'timeupdate', this.updateARIAAttributes); player.ready(vjs.bind(this, this.updateARIAAttributes)); } }); vjs.SeekBar.prototype.options_ = { children: { 'loadProgressBar': {}, 'playProgressBar': {}, 'seekHandle': {} }, 'barName': 'playProgressBar', 'handleName': 'seekHandle' }; vjs.SeekBar.prototype.playerEvent = 'timeupdate'; vjs.SeekBar.prototype.createEl = function(){ return vjs.Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder', 'aria-label': 'video progress bar' }); }; vjs.SeekBar.prototype.updateARIAAttributes = function(){ // Allows for smooth scrubbing, when player can't keep up. var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('aria-valuenow',vjs.round(this.getPercent()*100, 2)); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuetext',vjs.formatTime(time, this.player_.duration())); // human readable value of progress bar (time complete) }; vjs.SeekBar.prototype.getPercent = function(){ return this.player_.currentTime() / this.player_.duration(); }; vjs.SeekBar.prototype.onMouseDown = function(event){ vjs.Slider.prototype.onMouseDown.call(this, event); this.player_.scrubbing = true; this.player_.addClass('vjs-scrubbing'); this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); }; vjs.SeekBar.prototype.onMouseMove = function(event){ var newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime == this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; vjs.SeekBar.prototype.onMouseUp = function(event){ vjs.Slider.prototype.onMouseUp.call(this, event); this.player_.scrubbing = false; this.player_.removeClass('vjs-scrubbing'); if (this.videoWasPlaying) { this.player_.play(); } }; vjs.SeekBar.prototype.stepForward = function(){ this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users }; vjs.SeekBar.prototype.stepBack = function(){ this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users }; /** * Shows load progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.LoadProgressBar = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); this.on(player, 'progress', this.update); } }); vjs.LoadProgressBar.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>' }); }; vjs.LoadProgressBar.prototype.update = function(){ var i, start, end, part, buffered = this.player_.buffered(), duration = this.player_.duration(), bufferedEnd = this.player_.bufferedEnd(), children = this.el_.children, // get the percent width of a time compared to the total end percentify = function (time, end){ var percent = (time / end) || 0; // no NaN return (percent * 100) + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedEnd, duration); // add child elements to represent the individual buffered time ranges for (i = 0; i < buffered.length; i++) { start = buffered.start(i), end = buffered.end(i), part = children[i]; if (!part) { part = this.el_.appendChild(vjs.createEl()); } // set the percent based on the width of the progress bar (bufferedEnd) part.style.left = percentify(start, bufferedEnd); part.style.width = percentify(end - start, bufferedEnd); } // remove unused buffered range elements for (i = children.length; i > buffered.length; i--) { this.el_.removeChild(children[i-1]); } }; /** * Shows play progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PlayProgressBar = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.PlayProgressBar.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); }; /** * The Seek Handle shows the current position of the playhead during playback, * and can be dragged to adjust the playhead. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SeekHandle = vjs.SliderHandle.extend({ init: function(player, options) { vjs.SliderHandle.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } }); /** * The default value for the handle content, which may be read by screen readers * * @type {String} * @private */ vjs.SeekHandle.prototype.defaultValue = '00:00'; /** @inheritDoc */ vjs.SeekHandle.prototype.createEl = function() { return vjs.SliderHandle.prototype.createEl.call(this, 'div', { className: 'vjs-seek-handle', 'aria-live': 'off' }); }; vjs.SeekHandle.prototype.updateContent = function() { var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.innerHTML = '<span class="vjs-control-text">' + vjs.formatTime(time, this.player_.duration()) + '</span>'; }; /** * The component for controlling the volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeControl = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // hide volume controls when they're not supported by the current tech if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } }); vjs.VolumeControl.prototype.options_ = { children: { 'volumeBar': {} } }; vjs.VolumeControl.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control' }); }; /** * The bar that contains the volume level and can be clicked on to adjust the level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeBar = vjs.Slider.extend({ /** @constructor */ init: function(player, options){ vjs.Slider.call(this, player, options); this.on(player, 'volumechange', this.updateARIAAttributes); player.ready(vjs.bind(this, this.updateARIAAttributes)); } }); vjs.VolumeBar.prototype.updateARIAAttributes = function(){ // Current value of volume bar as a percentage this.el_.setAttribute('aria-valuenow',vjs.round(this.player_.volume()*100, 2)); this.el_.setAttribute('aria-valuetext',vjs.round(this.player_.volume()*100, 2)+'%'); }; vjs.VolumeBar.prototype.options_ = { children: { 'volumeLevel': {}, 'volumeHandle': {} }, 'barName': 'volumeLevel', 'handleName': 'volumeHandle' }; vjs.VolumeBar.prototype.playerEvent = 'volumechange'; vjs.VolumeBar.prototype.createEl = function(){ return vjs.Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar', 'aria-label': 'volume level' }); }; vjs.VolumeBar.prototype.onMouseMove = function(event) { if (this.player_.muted()) { this.player_.muted(false); } this.player_.volume(this.calculateDistance(event)); }; vjs.VolumeBar.prototype.getPercent = function(){ if (this.player_.muted()) { return 0; } else { return this.player_.volume(); } }; vjs.VolumeBar.prototype.stepForward = function(){ this.player_.volume(this.player_.volume() + 0.1); }; vjs.VolumeBar.prototype.stepBack = function(){ this.player_.volume(this.player_.volume() - 0.1); }; /** * Shows volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeLevel = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.VolumeLevel.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; /** * The volume handle can be dragged to adjust the volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeHandle = vjs.SliderHandle.extend(); vjs.VolumeHandle.prototype.defaultValue = '00:00'; /** @inheritDoc */ vjs.VolumeHandle.prototype.createEl = function(){ return vjs.SliderHandle.prototype.createEl.call(this, 'div', { className: 'vjs-volume-handle' }); }; /** * A button component for muting the audio * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.MuteToggle = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.on(player, 'volumechange', this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } }); vjs.MuteToggle.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-mute-control vjs-control', innerHTML: '<div><span class="vjs-control-text">' + this.localize('Mute') + '</span></div>' }); }; vjs.MuteToggle.prototype.onClick = function(){ this.player_.muted( this.player_.muted() ? false : true ); }; vjs.MuteToggle.prototype.update = function(){ var vol = this.player_.volume(), level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // Don't rewrite the button text if the actual text doesn't change. // This causes unnecessary and confusing information for screen reader users. // This check is needed because this function gets called every time the volume level is changed. if(this.player_.muted()){ if(this.el_.children[0].children[0].innerHTML!=this.localize('Unmute')){ this.el_.children[0].children[0].innerHTML = this.localize('Unmute'); // change the button text to "Unmute" } } else { if(this.el_.children[0].children[0].innerHTML!=this.localize('Mute')){ this.el_.children[0].children[0].innerHTML = this.localize('Mute'); // change the button text to "Mute" } } /* TODO improve muted icon classes */ for (var i = 0; i < 4; i++) { vjs.removeClass(this.el_, 'vjs-vol-'+i); } vjs.addClass(this.el_, 'vjs-vol-'+level); }; /** * Menu button with a popup for showing the volume slider. * @constructor */ vjs.VolumeMenuButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ vjs.MenuButton.call(this, player, options); // Same listeners as MuteToggle this.on(player, 'volumechange', this.volumeUpdate); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); this.addClass('vjs-menu-button'); } }); vjs.VolumeMenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player_, { contentElType: 'div' }); var vc = new vjs.VolumeBar(this.player_, this.options_['volumeBar']); vc.on('focus', function() { menu.lockShowing(); }); vc.on('blur', function() { menu.unlockShowing(); }); menu.addChild(vc); return menu; }; vjs.VolumeMenuButton.prototype.onClick = function(){ vjs.MuteToggle.prototype.onClick.call(this); vjs.MenuButton.prototype.onClick.call(this); }; vjs.VolumeMenuButton.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-volume-menu-button vjs-menu-button vjs-control', innerHTML: '<div><span class="vjs-control-text">' + this.localize('Mute') + '</span></div>' }); }; vjs.VolumeMenuButton.prototype.volumeUpdate = vjs.MuteToggle.prototype.update; /** * The component for controlling the playback rate * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PlaybackRateMenuButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ vjs.MenuButton.call(this, player, options); this.updateVisibility(); this.updateLabel(); this.on(player, 'loadstart', this.updateVisibility); this.on(player, 'ratechange', this.updateLabel); } }); vjs.PlaybackRateMenuButton.prototype.buttonText = 'Playback Rate'; vjs.PlaybackRateMenuButton.prototype.className = 'vjs-playback-rate'; vjs.PlaybackRateMenuButton.prototype.createEl = function(){ var el = vjs.MenuButton.prototype.createEl.call(this); this.labelEl_ = vjs.createEl('div', { className: 'vjs-playback-rate-value', innerHTML: 1.0 }); el.appendChild(this.labelEl_); return el; }; // Menu creation vjs.PlaybackRateMenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player()); var rates = this.player().options()['playbackRates']; if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild( new vjs.PlaybackRateMenuItem(this.player(), { 'rate': rates[i] + 'x'}) ); } } return menu; }; vjs.PlaybackRateMenuButton.prototype.updateARIAAttributes = function(){ // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); }; vjs.PlaybackRateMenuButton.prototype.onClick = function(){ // select next rate option var currentRate = this.player().playbackRate(); var rates = this.player().options()['playbackRates']; // this will select first one if the last one currently selected var newRate = rates[0]; for (var i = 0; i <rates.length ; i++) { if (rates[i] > currentRate) { newRate = rates[i]; break; } } this.player().playbackRate(newRate); }; vjs.PlaybackRateMenuButton.prototype.playbackRateSupported = function(){ return this.player().tech && this.player().tech['featuresPlaybackRate'] && this.player().options()['playbackRates'] && this.player().options()['playbackRates'].length > 0 ; }; /** * Hide playback rate controls when they're no playback rate options to select */ vjs.PlaybackRateMenuButton.prototype.updateVisibility = function(){ if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } }; /** * Update button label when rate changed */ vjs.PlaybackRateMenuButton.prototype.updateLabel = function(){ if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; /** * The specific menu item type for selecting a playback rate * * @constructor */ vjs.PlaybackRateMenuItem = vjs.MenuItem.extend({ contentElType: 'button', /** @constructor */ init: function(player, options){ var label = this.label = options['rate']; var rate = this.rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options['label'] = label; options['selected'] = rate === 1; vjs.MenuItem.call(this, player, options); this.on(player, 'ratechange', this.update); } }); vjs.PlaybackRateMenuItem.prototype.onClick = function(){ vjs.MenuItem.prototype.onClick.call(this); this.player().playbackRate(this.rate); }; vjs.PlaybackRateMenuItem.prototype.update = function(){ this.selected(this.player().playbackRate() == this.rate); }; /* Poster Image ================================================================================ */ /** * The component that handles showing the poster image. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PosterImage = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.update(); player.on('posterchange', vjs.bind(this, this.update)); } }); /** * Clean up the poster image */ vjs.PosterImage.prototype.dispose = function(){ this.player().off('posterchange', this.update); vjs.Button.prototype.dispose.call(this); }; /** * Create the poster image element * @return {Element} */ vjs.PosterImage.prototype.createEl = function(){ var el = vjs.createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); // To ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. For browsers that // do not support `background-size` (e.g. IE8), fall back on using a regular // img element. if (!vjs.BACKGROUND_SIZE_SUPPORTED) { this.fallbackImg_ = vjs.createEl('img'); el.appendChild(this.fallbackImg_); } return el; }; /** * Event handler for updates to the player's poster source */ vjs.PosterImage.prototype.update = function(){ var url = this.player().poster(); this.setSrc(url); // If there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { this.show(); } else { this.hide(); } }; /** * Set the poster source depending on the display method */ vjs.PosterImage.prototype.setSrc = function(url){ var backgroundImage; if (this.fallbackImg_) { this.fallbackImg_.src = url; } else { backgroundImage = ''; // Any falsey values should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundImage = 'url("' + url + '")'; } this.el_.style.backgroundImage = backgroundImage; } }; /** * Event handler for clicks on the poster image */ vjs.PosterImage.prototype.onClick = function(){ // We don't want a click to trigger playback when controls are disabled // but CSS should be hiding the poster to prevent that from happening this.player_.play(); }; /* Loading Spinner ================================================================================ */ /** * Loading spinner for waiting events * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.LoadingSpinner = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // MOVING DISPLAY HANDLING TO CSS // player.on('canplay', vjs.bind(this, this.hide)); // player.on('canplaythrough', vjs.bind(this, this.hide)); // player.on('playing', vjs.bind(this, this.hide)); // player.on('seeking', vjs.bind(this, this.show)); // in some browsers seeking does not trigger the 'playing' event, // so we also need to trap 'seeked' if we are going to set a // 'seeking' event // player.on('seeked', vjs.bind(this, this.hide)); // player.on('ended', vjs.bind(this, this.hide)); // Not showing spinner on stalled any more. Browsers may stall and then not trigger any events that would remove the spinner. // Checked in Chrome 16 and Safari 5.1.2. http://help.videojs.com/discussions/problems/883-why-is-the-download-progress-showing // player.on('stalled', vjs.bind(this, this.show)); // player.on('waiting', vjs.bind(this, this.show)); } }); vjs.LoadingSpinner.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner' }); }; /* Big Play Button ================================================================================ */ /** * Initial play button. Shows before the video has played. The hiding of the * big play button is done via CSS and player states. * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.BigPlayButton = vjs.Button.extend(); vjs.BigPlayButton.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-big-play-button', innerHTML: '<span aria-hidden="true"></span>', 'aria-label': 'play video' }); }; vjs.BigPlayButton.prototype.onClick = function(){ this.player_.play(); }; /** * Display that an error has occurred making the video unplayable * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.ErrorDisplay = vjs.Component.extend({ init: function(player, options){ vjs.Component.call(this, player, options); this.update(); this.on(player, 'error', this.update); } }); vjs.ErrorDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-error-display' }); this.contentEl_ = vjs.createEl('div'); el.appendChild(this.contentEl_); return el; }; vjs.ErrorDisplay.prototype.update = function(){ if (this.player().error()) { this.contentEl_.innerHTML = this.localize(this.player().error().message); } }; (function() { var createTrackHelper; /** * @fileoverview Media Technology Controller - Base class for media playback * technology controllers like Flash and HTML5 */ /** * Base class for media (HTML5 Video, Flash) controllers * @param {vjs.Player|Object} player Central player instance * @param {Object=} options Options object * @constructor */ vjs.MediaTechController = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ options = options || {}; // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; vjs.Component.call(this, player, options, ready); // Manually track progress in cases where the browser/flash player doesn't report it. if (!this['featuresProgressEvents']) { this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!this['featuresTimeupdateEvents']) { this.manualTimeUpdatesOn(); } this.initControlsListeners(); if (!this['featuresNativeTextTracks']) { this.emulateTextTracks(); } this.initTextTrackListeners(); } }); /** * Set up click and touch listeners for the playback element * On desktops, a click on the video itself will toggle playback, * on a mobile device a click on the video toggles controls. * (toggling controls is done by toggling the user state between active and * inactive) * * A tap can signal that a user has become active, or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * * In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * * Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold on * any controls will still keep the user active */ vjs.MediaTechController.prototype.initControlsListeners = function(){ var player, activateControls; player = this.player(); activateControls = function(){ if (player.controls() && !player.usingNativeControls()) { this.addControlsListeners(); } }; // Set up event listeners once the tech is ready and has an element to apply // listeners to this.ready(activateControls); this.on(player, 'controlsenabled', activateControls); this.on(player, 'controlsdisabled', this.removeControlsListeners); // if we're loading the playback object after it has started loading or playing the // video (often with autoplay on) then the loadstart event has already fired and we // need to fire it manually because many things rely on it. // Long term we might consider how we would do this for other events like 'canplay' // that may also have fired. this.ready(function(){ if (this.networkState && this.networkState() > 0) { this.player().trigger('loadstart'); } }); }; vjs.MediaTechController.prototype.addControlsListeners = function(){ var userWasActive; // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on('mousedown', this.onClick); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on('touchstart', function(event) { userWasActive = this.player_.userActive(); }); this.on('touchmove', function(event) { if (userWasActive){ this.player().reportUserActivity(); } }); this.on('touchend', function(event) { // Stop the mouse events from also happening event.preventDefault(); }); // Turn on component tap events this.emitTapEvents(); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on('tap', this.onTap); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. */ vjs.MediaTechController.prototype.removeControlsListeners = function(){ // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off('tap'); this.off('touchstart'); this.off('touchmove'); this.off('touchleave'); this.off('touchcancel'); this.off('touchend'); this.off('click'); this.off('mousedown'); }; /** * Handle a click on the media element. By default will play/pause the media. */ vjs.MediaTechController.prototype.onClick = function(event){ // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) return; // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.player().controls()) { if (this.player().paused()) { this.player().play(); } else { this.player().pause(); } } }; /** * Handle a tap on the media element. By default it will toggle the user * activity state, which hides and shows the controls. */ vjs.MediaTechController.prototype.onTap = function(){ this.player().userActive(!this.player().userActive()); }; /* Fallbacks for unsupported event types ================================================================================ */ // Manually trigger progress events based on changes to the buffered amount // Many flash players and older HTML5 browsers don't send progress or progress-like events vjs.MediaTechController.prototype.manualProgressOn = function(){ this.manualProgress = true; // Trigger progress watching when a source begins loading this.trackProgress(); }; vjs.MediaTechController.prototype.manualProgressOff = function(){ this.manualProgress = false; this.stopTrackingProgress(); }; vjs.MediaTechController.prototype.trackProgress = function(){ this.progressInterval = this.setInterval(function(){ // Don't trigger unless buffered amount is greater than last time var bufferedPercent = this.player().bufferedPercent(); if (this.bufferedPercent_ != bufferedPercent) { this.player().trigger('progress'); } this.bufferedPercent_ = bufferedPercent; if (bufferedPercent === 1) { this.stopTrackingProgress(); } }, 500); }; vjs.MediaTechController.prototype.stopTrackingProgress = function(){ this.clearInterval(this.progressInterval); }; /*! Time Tracking -------------------------------------------------------------- */ vjs.MediaTechController.prototype.manualTimeUpdatesOn = function(){ var player = this.player_; this.manualTimeUpdates = true; this.on(player, 'play', this.trackCurrentTime); this.on(player, 'pause', this.stopTrackingCurrentTime); // timeupdate is also called by .currentTime whenever current time is set // Watch for native timeupdate event this.one('timeupdate', function(){ // Update known progress support for this playback technology this['featuresTimeupdateEvents'] = true; // Turn off manual progress tracking this.manualTimeUpdatesOff(); }); }; vjs.MediaTechController.prototype.manualTimeUpdatesOff = function(){ var player = this.player_; this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off(player, 'play', this.trackCurrentTime); this.off(player, 'pause', this.stopTrackingCurrentTime); }; vjs.MediaTechController.prototype.trackCurrentTime = function(){ if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function(){ this.player().trigger('timeupdate'); }, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }; // Turn off play progress tracking (when paused or dragging) vjs.MediaTechController.prototype.stopTrackingCurrentTime = function(){ this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.player().trigger('timeupdate'); }; vjs.MediaTechController.prototype.dispose = function() { // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } vjs.Component.prototype.dispose.call(this); }; vjs.MediaTechController.prototype.setCurrentTime = function() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { this.player().trigger('timeupdate'); } }; // TODO: Consider looking at moving this into the text track display directly // https://github.com/videojs/video.js/issues/1863 vjs.MediaTechController.prototype.initTextTrackListeners = function() { var player = this.player_, tracks, textTrackListChanges = function() { var textTrackDisplay = player.getChild('textTrackDisplay'), controlBar; if (textTrackDisplay) { textTrackDisplay.updateDisplay(); } }; tracks = this.textTracks(); if (!tracks) { return; } tracks.addEventListener('removetrack', textTrackListChanges); tracks.addEventListener('addtrack', textTrackListChanges); this.on('dispose', vjs.bind(this, function() { tracks.removeEventListener('removetrack', textTrackListChanges); tracks.removeEventListener('addtrack', textTrackListChanges); })); }; vjs.MediaTechController.prototype.emulateTextTracks = function() { var player = this.player_, textTracksChanges, tracks, script; if (!window['WebVTT']) { script = document.createElement('script'); script.src = player.options()['vtt.js'] || '../node_modules/vtt.js/dist/vtt.js'; player.el().appendChild(script); window['WebVTT'] = true; } tracks = this.textTracks(); if (!tracks) { return; } textTracksChanges = function() { var i, track, textTrackDisplay; textTrackDisplay = player.getChild('textTrackDisplay'), textTrackDisplay.updateDisplay(); for (i = 0; i < this.length; i++) { track = this[i]; track.removeEventListener('cuechange', vjs.bind(textTrackDisplay, textTrackDisplay.updateDisplay)); if (track.mode === 'showing') { track.addEventListener('cuechange', vjs.bind(textTrackDisplay, textTrackDisplay.updateDisplay)); } } }; tracks.addEventListener('change', textTracksChanges); this.on('dispose', vjs.bind(this, function() { tracks.removeEventListener('change', textTracksChanges); })); }; /** * Provide default methods for text tracks. * * Html5 tech overrides these. */ /** * List of associated text tracks * @type {Array} * @private */ vjs.MediaTechController.prototype.textTracks_; vjs.MediaTechController.prototype.textTracks = function() { this.player_.textTracks_ = this.player_.textTracks_ || new vjs.TextTrackList(); return this.player_.textTracks_; }; vjs.MediaTechController.prototype.remoteTextTracks = function() { this.player_.remoteTextTracks_ = this.player_.remoteTextTracks_ || new vjs.TextTrackList(); return this.player_.remoteTextTracks_; }; createTrackHelper = function(self, kind, label, language, options) { var tracks = self.textTracks(), track; options = options || {}; options['kind'] = kind; if (label) { options['label'] = label; } if (language) { options['language'] = language; } options['player'] = self.player_; track = new vjs.TextTrack(options); tracks.addTrack_(track); return track; }; vjs.MediaTechController.prototype.addTextTrack = function(kind, label, language) { if (!kind) { throw new Error('TextTrack kind is required but was not provided'); } return createTrackHelper(this, kind, label, language); }; vjs.MediaTechController.prototype.addRemoteTextTrack = function(options) { var track = createTrackHelper(this, options['kind'], options['label'], options['language'], options); this.remoteTextTracks().addTrack_(track); return { track: track }; }; vjs.MediaTechController.prototype.removeRemoteTextTrack = function(track) { this.textTracks().removeTrack_(track); this.remoteTextTracks().removeTrack_(track); }; /** * Provide a default setPoster method for techs * * Poster support for techs should be optional, so we don't want techs to * break if they don't have a way to set a poster. */ vjs.MediaTechController.prototype.setPoster = function(){}; vjs.MediaTechController.prototype['featuresVolumeControl'] = true; // Resizing plugins using request fullscreen reloads the plugin vjs.MediaTechController.prototype['featuresFullscreenResize'] = false; vjs.MediaTechController.prototype['featuresPlaybackRate'] = false; // Optional events that we can manually mimic with timers // currently not triggered by video-js-swf vjs.MediaTechController.prototype['featuresProgressEvents'] = false; vjs.MediaTechController.prototype['featuresTimeupdateEvents'] = false; vjs.MediaTechController.prototype['featuresNativeTextTracks'] = false; /** * A functional mixin for techs that want to use the Source Handler pattern. * * ##### EXAMPLE: * * videojs.MediaTechController.withSourceHandlers.call(MyTech); * */ vjs.MediaTechController.withSourceHandlers = function(Tech){ /** * Register a source handler * Source handlers are scripts for handling specific formats. * The source handler pattern is used for adaptive formats (HLS, DASH) that * manually load video data and feed it into a Source Buffer (Media Source Extensions) * @param {Function} handler The source handler * @param {Boolean} first Register it before any existing handlers */ Tech.registerSourceHandler = function(handler, index){ var handlers = Tech.sourceHandlers; if (!handlers) { handlers = Tech.sourceHandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /** * Return the first source handler that supports the source * TODO: Answer question: should 'probably' be prioritized over 'maybe' * @param {Object} source The source object * @returns {Object} The first source handler that supports the source * @returns {null} Null if no source handler is found */ Tech.selectSourceHandler = function(source){ var handlers = Tech.sourceHandlers || [], can; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canHandleSource(source); if (can) { return handlers[i]; } } return null; }; /** * Check if the tech can support the given source * @param {Object} srcObj The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Tech.canPlaySource = function(srcObj){ var sh = Tech.selectSourceHandler(srcObj); if (sh) { return sh.canHandleSource(srcObj); } return ''; }; /** * Create a function for setting the source using a source object * and source handlers. * Should never be called unless a source handler was found. * @param {Object} source A source object with src and type keys * @return {vjs.MediaTechController} self */ Tech.prototype.setSource = function(source){ var sh = Tech.selectSourceHandler(source); if (!sh) { // Fall back to a native source hander when unsupported sources are // deliberately set if (Tech.nativeSourceHandler) { sh = Tech.nativeSourceHandler; } else { vjs.log.error('No source hander found for the current source.'); } } // Dispose any existing source handler this.disposeSourceHandler(); this.off('dispose', this.disposeSourceHandler); this.currentSource_ = source; this.sourceHandler_ = sh.handleSource(source, this); this.on('dispose', this.disposeSourceHandler); return this; }; /** * Clean up any existing source handler */ Tech.prototype.disposeSourceHandler = function(){ if (this.sourceHandler_ && this.sourceHandler_.dispose) { this.sourceHandler_.dispose(); } }; }; vjs.media = {}; })(); /** * @fileoverview HTML5 Media Controller - Wrapper for HTML5 Media API */ /** * HTML5 Media Controller - Wrapper for HTML5 Media API * @param {vjs.Player|Object} player * @param {Object=} options * @param {Function=} ready * @constructor */ vjs.Html5 = vjs.MediaTechController.extend({ /** @constructor */ init: function(player, options, ready){ var nodes, nodesLength, i, node, nodeName, removeNodes; if (options['nativeCaptions'] === false || options['nativeTextTracks'] === false) { this['featuresNativeTextTracks'] = false; } vjs.MediaTechController.call(this, player, options, ready); this.setupTriggers(); var source = options['source']; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (this.el_.currentSrc !== source.src || (player.tag && player.tag.initNetworkState_ === 3))) { this.setSource(source); } if (this.el_.hasChildNodes()) { nodes = this.el_.childNodes; nodesLength = nodes.length; removeNodes = []; while (nodesLength--) { node = nodes[nodesLength]; nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { if (!this['featuresNativeTextTracks']) { // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks removeNodes.push(node); } else { this.remoteTextTracks().addTrack_(node['track']); } } } for (i=0; i<removeNodes.length; i++) { this.el_.removeChild(removeNodes[i]); } } if (this['featuresNativeTextTracks']) { this.on('loadstart', vjs.bind(this, this.hideCaptions)); } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if (vjs.TOUCH_ENABLED && player.options()['nativeControlsForTouch'] === true) { this.useNativeControls(); } // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly player.ready(function(){ if (this.src() && this.tag && this.options_['autoplay'] && this.paused()) { delete this.tag['poster']; // Chrome Fix. Fixed in Chrome v16. this.play(); } }); this.triggerReady(); } }); vjs.Html5.prototype.dispose = function(){ vjs.Html5.disposeMediaElement(this.el_); vjs.MediaTechController.prototype.dispose.call(this); }; vjs.Html5.prototype.createEl = function(){ var player = this.player_, track, trackEl, i, // If possible, reuse original tag for HTML5 playback technology element el = player.tag, attributes, newEl, clone; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. if (!el || this['movingMediaElementInDOM'] === false) { // If the original tag is still there, clone and remove it. if (el) { clone = el.cloneNode(false); vjs.Html5.disposeMediaElement(el); el = clone; player.tag = null; } else { el = vjs.createEl('video'); // determine if native controls should be used attributes = videojs.util.mergeOptions({}, player.tagAttributes); if (!vjs.TOUCH_ENABLED || player.options()['nativeControlsForTouch'] !== true) { delete attributes.controls; } vjs.setElementAttributes(el, vjs.obj.merge(attributes, { id:player.id() + '_html5_api', 'class':'vjs-tech' }) ); } // associate the player with the new tag el['player'] = player; if (player.options_.tracks) { for (i = 0; i < player.options_.tracks.length; i++) { track = player.options_.tracks[i]; trackEl = document.createElement('track'); trackEl.kind = track.kind; trackEl.label = track.label; trackEl.srclang = track.srclang; trackEl.src = track.src; if ('default' in track) { trackEl.setAttribute('default', 'default'); } el.appendChild(trackEl); } } vjs.insertFirst(el, player.el()); } // Update specific tag settings, in case they were overridden var settingsAttrs = ['autoplay','preload','loop','muted']; for (i = settingsAttrs.length - 1; i >= 0; i--) { var attr = settingsAttrs[i]; var overwriteAttrs = {}; if (typeof player.options_[attr] !== 'undefined') { overwriteAttrs[attr] = player.options_[attr]; } vjs.setElementAttributes(el, overwriteAttrs); } return el; // jenniisawesome = true; }; vjs.Html5.prototype.hideCaptions = function() { var tracks = this.el_.querySelectorAll('track'), track, i = tracks.length, kinds = { 'captions': 1, 'subtitles': 1 }; while (i--) { track = tracks[i].track; if ((track && track['kind'] in kinds) && (!tracks[i]['default'])) { track.mode = 'disabled'; } } }; // Make video events trigger player events // May seem verbose here, but makes other APIs possible. // Triggers removed using this.off when disposed vjs.Html5.prototype.setupTriggers = function(){ for (var i = vjs.Html5.Events.length - 1; i >= 0; i--) { this.on(vjs.Html5.Events[i], this.eventHandler); } }; vjs.Html5.prototype.eventHandler = function(evt){ // In the case of an error on the video element, set the error prop // on the player and let the player handle triggering the event. On // some platforms, error events fire that do not cause the error // property on the video element to be set. See #1465 for an example. if (evt.type == 'error' && this.error()) { this.player().error(this.error().code); // in some cases we pass the event directly to the player } else { // No need for media events to bubble up. evt.bubbles = false; this.player().trigger(evt); } }; vjs.Html5.prototype.useNativeControls = function(){ var tech, player, controlsOn, controlsOff, cleanUp; tech = this; player = this.player(); // If the player controls are enabled turn on the native controls tech.setControls(player.controls()); // Update the native controls when player controls state is updated controlsOn = function(){ tech.setControls(true); }; controlsOff = function(){ tech.setControls(false); }; player.on('controlsenabled', controlsOn); player.on('controlsdisabled', controlsOff); // Clean up when not using native controls anymore cleanUp = function(){ player.off('controlsenabled', controlsOn); player.off('controlsdisabled', controlsOff); }; tech.on('dispose', cleanUp); player.on('usingcustomcontrols', cleanUp); // Update the state of the player to using native controls player.usingNativeControls(true); }; vjs.Html5.prototype.play = function(){ this.el_.play(); }; vjs.Html5.prototype.pause = function(){ this.el_.pause(); }; vjs.Html5.prototype.paused = function(){ return this.el_.paused; }; vjs.Html5.prototype.currentTime = function(){ return this.el_.currentTime; }; vjs.Html5.prototype.setCurrentTime = function(seconds){ try { this.el_.currentTime = seconds; } catch(e) { vjs.log(e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; vjs.Html5.prototype.duration = function(){ return this.el_.duration || 0; }; vjs.Html5.prototype.buffered = function(){ return this.el_.buffered; }; vjs.Html5.prototype.volume = function(){ return this.el_.volume; }; vjs.Html5.prototype.setVolume = function(percentAsDecimal){ this.el_.volume = percentAsDecimal; }; vjs.Html5.prototype.muted = function(){ return this.el_.muted; }; vjs.Html5.prototype.setMuted = function(muted){ this.el_.muted = muted; }; vjs.Html5.prototype.width = function(){ return this.el_.offsetWidth; }; vjs.Html5.prototype.height = function(){ return this.el_.offsetHeight; }; vjs.Html5.prototype.supportsFullScreen = function(){ if (typeof this.el_.webkitEnterFullScreen == 'function') { // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(vjs.USER_AGENT) || !/Chrome|Mac OS X 10.5/.test(vjs.USER_AGENT)) { return true; } } return false; }; vjs.Html5.prototype.enterFullScreen = function(){ var video = this.el_; if ('webkitDisplayingFullscreen' in video) { this.one('webkitbeginfullscreen', function() { this.player_.isFullscreen(true); this.one('webkitendfullscreen', function() { this.player_.isFullscreen(false); this.player_.trigger('fullscreenchange'); }); this.player_.trigger('fullscreenchange'); }); } if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop this.setTimeout(function(){ video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; vjs.Html5.prototype.exitFullScreen = function(){ this.el_.webkitExitFullScreen(); }; // Checks to see if the element's reported URI (either from `el_.src` // or `el_.currentSrc`) is a blob-uri and, if so, returns the uri that // was passed into the source-handler when it was first invoked instead // of the blob-uri vjs.Html5.prototype.returnOriginalIfBlobURI_ = function (elementURI, originalURI) { var blobURIRegExp = /^blob\:/i; // If originalURI is undefined then we are probably in a non-source-handler-enabled // tech that inherits from the Html5 tech so we should just return the elementURI // regardless of it's blobby-ness if (originalURI && elementURI && blobURIRegExp.test(elementURI)) { return originalURI; } return elementURI; }; vjs.Html5.prototype.src = function(src) { var elementSrc = this.el_.src; if (src === undefined) { return this.returnOriginalIfBlobURI_(elementSrc, this.source_); } else { // Setting src through `src` instead of `setSrc` will be deprecated this.setSrc(src); } }; vjs.Html5.prototype.setSrc = function(src) { this.el_.src = src; }; vjs.Html5.prototype.load = function(){ this.el_.load(); }; vjs.Html5.prototype.currentSrc = function(){ var elementSrc = this.el_.currentSrc; if (!this.currentSource_) { return elementSrc; } return this.returnOriginalIfBlobURI_(elementSrc, this.currentSource_.src); }; vjs.Html5.prototype.poster = function(){ return this.el_.poster; }; vjs.Html5.prototype.setPoster = function(val){ this.el_.poster = val; }; vjs.Html5.prototype.preload = function(){ return this.el_.preload; }; vjs.Html5.prototype.setPreload = function(val){ this.el_.preload = val; }; vjs.Html5.prototype.autoplay = function(){ return this.el_.autoplay; }; vjs.Html5.prototype.setAutoplay = function(val){ this.el_.autoplay = val; }; vjs.Html5.prototype.controls = function(){ return this.el_.controls; }; vjs.Html5.prototype.setControls = function(val){ this.el_.controls = !!val; }; vjs.Html5.prototype.loop = function(){ return this.el_.loop; }; vjs.Html5.prototype.setLoop = function(val){ this.el_.loop = val; }; vjs.Html5.prototype.error = function(){ return this.el_.error; }; vjs.Html5.prototype.seeking = function(){ return this.el_.seeking; }; vjs.Html5.prototype.seekable = function(){ return this.el_.seekable; }; vjs.Html5.prototype.ended = function(){ return this.el_.ended; }; vjs.Html5.prototype.defaultMuted = function(){ return this.el_.defaultMuted; }; vjs.Html5.prototype.playbackRate = function(){ return this.el_.playbackRate; }; vjs.Html5.prototype.setPlaybackRate = function(val){ this.el_.playbackRate = val; }; vjs.Html5.prototype.networkState = function(){ return this.el_.networkState; }; vjs.Html5.prototype.readyState = function(){ return this.el_.readyState; }; vjs.Html5.prototype.textTracks = function() { if (!this['featuresNativeTextTracks']) { return vjs.MediaTechController.prototype.textTracks.call(this); } return this.el_.textTracks; }; vjs.Html5.prototype.addTextTrack = function(kind, label, language) { if (!this['featuresNativeTextTracks']) { return vjs.MediaTechController.prototype.addTextTrack.call(this, kind, label, language); } return this.el_.addTextTrack(kind, label, language); }; vjs.Html5.prototype.addRemoteTextTrack = function(options) { if (!this['featuresNativeTextTracks']) { return vjs.MediaTechController.prototype.addRemoteTextTrack.call(this, options); } var track = document.createElement('track'); options = options || {}; if (options['kind']) { track['kind'] = options['kind']; } if (options['label']) { track['label'] = options['label']; } if (options['language'] || options['srclang']) { track['srclang'] = options['language'] || options['srclang']; } if (options['default']) { track['default'] = options['default']; } if (options['id']) { track['id'] = options['id']; } if (options['src']) { track['src'] = options['src']; } this.el().appendChild(track); if (track.track['kind'] === 'metadata') { track['track']['mode'] = 'hidden'; } else { track['track']['mode'] = 'disabled'; } track['onload'] = function() { var tt = track['track']; if (track.readyState >= 2) { if (tt['kind'] === 'metadata' && tt['mode'] !== 'hidden') { tt['mode'] = 'hidden'; } else if (tt['kind'] !== 'metadata' && tt['mode'] !== 'disabled') { tt['mode'] = 'disabled'; } track['onload'] = null; } }; this.remoteTextTracks().addTrack_(track.track); return track; }; vjs.Html5.prototype.removeRemoteTextTrack = function(track) { if (!this['featuresNativeTextTracks']) { return vjs.MediaTechController.prototype.removeRemoteTextTrack.call(this, track); } var tracks, i; this.remoteTextTracks().removeTrack_(track); tracks = this.el()['querySelectorAll']('track'); for (i = 0; i < tracks.length; i++) { if (tracks[i] === track || tracks[i]['track'] === track) { tracks[i]['parentNode']['removeChild'](tracks[i]); break; } } }; /* HTML5 Support Testing ---------------------------------------------------- */ /** * Check if HTML5 video is supported by this browser/device * @return {Boolean} */ vjs.Html5.isSupported = function(){ // IE9 with no Media Player is a LIAR! (#984) try { vjs.TEST_VID['volume'] = 0.5; } catch (e) { return false; } return !!vjs.TEST_VID.canPlayType; }; // Add Source Handler pattern functions to this tech vjs.MediaTechController.withSourceHandlers(vjs.Html5); /* * Override the withSourceHandler mixin's methods with our own because * the HTML5 Media Element returns blob urls when utilizing MSE and we * want to still return proper source urls even when in that case */ (function(){ var origSetSource = vjs.Html5.prototype.setSource, origDisposeSourceHandler = vjs.Html5.prototype.disposeSourceHandler; vjs.Html5.prototype.setSource = function (source) { var retVal = origSetSource.call(this, source); this.source_ = source.src; return retVal; }; vjs.Html5.prototype.disposeSourceHandler = function () { this.source_ = undefined; return origDisposeSourceHandler.call(this); }; })(); /** * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * @param {Object} source The source object * @param {vjs.Html5} tech The instance of the HTML5 tech */ vjs.Html5.nativeSourceHandler = {}; /** * Check if the video element can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ vjs.Html5.nativeSourceHandler.canHandleSource = function(source){ var match, ext; function canPlayType(type){ // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return vjs.TEST_VID.canPlayType(type); } catch(e) { return ''; } } // If a type was provided we should rely on that if (source.type) { return canPlayType(source.type); } else if (source.src) { // If no type, fall back to checking 'video/[EXTENSION]' match = source.src.match(/\.([^.\/\?]+)(\?[^\/]+)?$/i); ext = match && match[1]; return canPlayType('video/'+ext); } return ''; }; /** * Pass the source to the video element * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {vjs.Html5} tech The instance of the Html5 tech */ vjs.Html5.nativeSourceHandler.handleSource = function(source, tech){ tech.setSrc(source.src); }; /** * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ vjs.Html5.nativeSourceHandler.dispose = function(){}; // Register the native source handler vjs.Html5.registerSourceHandler(vjs.Html5.nativeSourceHandler); /** * Check if the volume can be changed in this browser/device. * Volume cannot be changed in a lot of mobile devices. * Specifically, it can't be changed from 1 on iOS. * @return {Boolean} */ vjs.Html5.canControlVolume = function(){ var volume = vjs.TEST_VID.volume; vjs.TEST_VID.volume = (volume / 2) + 0.1; return volume !== vjs.TEST_VID.volume; }; /** * Check if playbackRate is supported in this browser/device. * @return {[type]} [description] */ vjs.Html5.canControlPlaybackRate = function(){ var playbackRate = vjs.TEST_VID.playbackRate; vjs.TEST_VID.playbackRate = (playbackRate / 2) + 0.1; return playbackRate !== vjs.TEST_VID.playbackRate; }; /** * Check to see if native text tracks are supported by this browser/device * @return {Boolean} */ vjs.Html5.supportsNativeTextTracks = function() { var supportsTextTracks; // Figure out native text track support // If mode is a number, we cannot change it because it'll disappear from view. // Browsers with numeric modes include IE10 and older (<=2013) samsung android models. // Firefox isn't playing nice either with modifying the mode // TODO: Investigate firefox: https://github.com/videojs/video.js/issues/1862 supportsTextTracks = !!vjs.TEST_VID.textTracks; if (supportsTextTracks && vjs.TEST_VID.textTracks.length > 0) { supportsTextTracks = typeof vjs.TEST_VID.textTracks[0]['mode'] !== 'number'; } if (supportsTextTracks && vjs.IS_FIREFOX) { supportsTextTracks = false; } return supportsTextTracks; }; /** * Set the tech's volume control support status * @type {Boolean} */ vjs.Html5.prototype['featuresVolumeControl'] = vjs.Html5.canControlVolume(); /** * Set the tech's playbackRate support status * @type {Boolean} */ vjs.Html5.prototype['featuresPlaybackRate'] = vjs.Html5.canControlPlaybackRate(); /** * Set the tech's status on moving the video element. * In iOS, if you move a video element in the DOM, it breaks video playback. * @type {Boolean} */ vjs.Html5.prototype['movingMediaElementInDOM'] = !vjs.IS_IOS; /** * Set the the tech's fullscreen resize support status. * HTML video is able to automatically resize when going to fullscreen. * (No longer appears to be used. Can probably be removed.) */ vjs.Html5.prototype['featuresFullscreenResize'] = true; /** * Set the tech's progress event support status * (this disables the manual progress events of the MediaTechController) */ vjs.Html5.prototype['featuresProgressEvents'] = true; /** * Sets the tech's status on native text track support * @type {Boolean} */ vjs.Html5.prototype['featuresNativeTextTracks'] = vjs.Html5.supportsNativeTextTracks(); // HTML5 Feature detection and Device Fixes --------------------------------- // (function() { var canPlayType, mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i, mp4RE = /^video\/mp4/i; vjs.Html5.patchCanPlayType = function() { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so if (vjs.ANDROID_VERSION >= 4.0) { if (!canPlayType) { canPlayType = vjs.TEST_VID.constructor.prototype.canPlayType; } vjs.TEST_VID.constructor.prototype.canPlayType = function(type) { if (type && mpegurlRE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } // Override Android 2.2 and less canPlayType method which is broken if (vjs.IS_OLD_ANDROID) { if (!canPlayType) { canPlayType = vjs.TEST_VID.constructor.prototype.canPlayType; } vjs.TEST_VID.constructor.prototype.canPlayType = function(type){ if (type && mp4RE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; vjs.Html5.unpatchCanPlayType = function() { var r = vjs.TEST_VID.constructor.prototype.canPlayType; vjs.TEST_VID.constructor.prototype.canPlayType = canPlayType; canPlayType = null; return r; }; // by default, patch the video element vjs.Html5.patchCanPlayType(); })(); // List of all HTML5 events (various uses). vjs.Html5.Events = 'loadstart,suspend,abort,error,emptied,stalled,loadedmetadata,loadeddata,canplay,canplaythrough,playing,waiting,seeking,seeked,ended,durationchange,timeupdate,progress,play,pause,ratechange,volumechange'.split(','); vjs.Html5.disposeMediaElement = function(el){ if (!el) { return; } el['player'] = null; if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while(el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function() { try { el.load(); } catch (e) { // not supported } })(); } }; /** * @fileoverview VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ /** * Flash Media Controller - Wrapper for fallback SWF API * * @param {vjs.Player} player * @param {Object=} options * @param {Function=} ready * @constructor */ vjs.Flash = vjs.MediaTechController.extend({ /** @constructor */ init: function(player, options, ready){ vjs.MediaTechController.call(this, player, options, ready); var source = options['source'], // Generate ID for swf object objId = player.id()+'_flash_api', // Store player options in local var for optimization // TODO: switch to using player methods instead of options // e.g. player.autoplay(); playerOptions = player.options_, // Merge default flashvars with ones passed in to init flashVars = vjs.obj.merge({ // SWF Callback Functions 'readyFunction': 'videojs.Flash.onReady', 'eventProxyFunction': 'videojs.Flash.onEvent', 'errorEventProxyFunction': 'videojs.Flash.onError', // Player Settings 'autoplay': playerOptions.autoplay, 'preload': playerOptions.preload, 'loop': playerOptions.loop, 'muted': playerOptions.muted }, options['flashVars']), // Merge default parames with ones passed in params = vjs.obj.merge({ 'wmode': 'opaque', // Opaque is needed to overlay controls, but can affect playback performance 'bgcolor': '#000000' // Using bgcolor prevents a white flash when the object is loading }, options['params']), // Merge default attributes with ones passed in attributes = vjs.obj.merge({ 'id': objId, 'name': objId, // Both ID and Name needed or swf to identify itself 'class': 'vjs-tech' }, options['attributes']) ; // If source was supplied pass as a flash var. if (source) { this.ready(function(){ this.setSource(source); }); } // Add placeholder to player div vjs.insertFirst(this.el_, options['parentEl']); // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options['startTime']) { this.ready(function(){ this.load(); this.play(); this['currentTime'](options['startTime']); }); } // firefox doesn't bubble mousemove events to parent. videojs/video-js-swf#37 // bugzilla bug: https://bugzilla.mozilla.org/show_bug.cgi?id=836786 if (vjs.IS_FIREFOX) { this.ready(function(){ this.on('mousemove', function(){ // since it's a custom event, don't bubble higher than the player this.player().trigger({ 'type':'mousemove', 'bubbles': false }); }); }); } // native click events on the SWF aren't triggered on IE11, Win8.1RT // use stageclick events triggered from inside the SWF instead player.on('stageclick', player.reportUserActivity); this.el_ = vjs.Flash.embed(options['swf'], this.el_, flashVars, params, attributes); } }); vjs.Flash.prototype.dispose = function(){ vjs.MediaTechController.prototype.dispose.call(this); }; vjs.Flash.prototype.play = function(){ this.el_.vjs_play(); }; vjs.Flash.prototype.pause = function(){ this.el_.vjs_pause(); }; vjs.Flash.prototype.src = function(src){ if (src === undefined) { return this['currentSrc'](); } // Setting src through `src` not `setSrc` will be deprecated return this.setSrc(src); }; vjs.Flash.prototype.setSrc = function(src){ // Make sure source URL is absolute. src = vjs.getAbsoluteURL(src); this.el_.vjs_src(src); // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.player_.autoplay()) { var tech = this; this.setTimeout(function(){ tech.play(); }, 0); } }; vjs.Flash.prototype['setCurrentTime'] = function(time){ this.lastSeekTarget_ = time; this.el_.vjs_setProperty('currentTime', time); vjs.MediaTechController.prototype.setCurrentTime.call(this); }; vjs.Flash.prototype['currentTime'] = function(time){ // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastSeekTarget_ || 0; } return this.el_.vjs_getProperty('currentTime'); }; vjs.Flash.prototype['currentSrc'] = function(){ if (this.currentSource_) { return this.currentSource_.src; } else { return this.el_.vjs_getProperty('currentSrc'); } }; vjs.Flash.prototype.load = function(){ this.el_.vjs_load(); }; vjs.Flash.prototype.poster = function(){ this.el_.vjs_getProperty('poster'); }; vjs.Flash.prototype['setPoster'] = function(){ // poster images are not handled by the Flash tech so make this a no-op }; vjs.Flash.prototype.seekable = function() { var duration = this.duration(); if (duration === 0) { // The SWF reports a duration of zero when the actual duration is unknown return vjs.createTimeRange(); } return vjs.createTimeRange(0, this.duration()); }; vjs.Flash.prototype.buffered = function(){ if (!this.el_.vjs_getProperty) { return vjs.createTimeRange(); } return vjs.createTimeRange(0, this.el_.vjs_getProperty('buffered')); }; vjs.Flash.prototype.duration = function(){ if (!this.el_.vjs_getProperty) { return 0; } return this.el_.vjs_getProperty('duration'); }; vjs.Flash.prototype.supportsFullScreen = function(){ return false; // Flash does not allow fullscreen through javascript }; vjs.Flash.prototype.enterFullScreen = function(){ return false; }; (function(){ // Create setters and getters for attributes var api = vjs.Flash.prototype, readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','), readOnly = 'error,networkState,readyState,seeking,initialTime,startOffsetTime,paused,played,ended,videoTracks,audioTracks,videoWidth,videoHeight'.split(','), // Overridden: buffered, currentTime, currentSrc i; function createSetter(attr){ var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); api['set'+attrUpper] = function(val){ return this.el_.vjs_setProperty(attr, val); }; } function createGetter(attr) { api[attr] = function(){ return this.el_.vjs_getProperty(attr); }; } // Create getter and setters for all read/write attributes for (i = 0; i < readWrite.length; i++) { createGetter(readWrite[i]); createSetter(readWrite[i]); } // Create getters for read-only attributes for (i = 0; i < readOnly.length; i++) { createGetter(readOnly[i]); } })(); /* Flash Support Testing -------------------------------------------------------- */ vjs.Flash.isSupported = function(){ return vjs.Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; // Add Source Handler pattern functions to this tech vjs.MediaTechController.withSourceHandlers(vjs.Flash); /** * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * @param {Object} source The source object * @param {vjs.Flash} tech The instance of the Flash tech */ vjs.Flash.nativeSourceHandler = {}; /** * Check Flash can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ vjs.Flash.nativeSourceHandler.canHandleSource = function(source){ var type; if (!source.type) { return ''; } // Strip code information from the type because we don't get that specific type = source.type.replace(/;.*/,'').toLowerCase(); if (type in vjs.Flash.formats) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {vjs.Flash} tech The instance of the Flash tech */ vjs.Flash.nativeSourceHandler.handleSource = function(source, tech){ tech.setSrc(source.src); }; /** * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ vjs.Flash.nativeSourceHandler.dispose = function(){}; // Register the native source handler vjs.Flash.registerSourceHandler(vjs.Flash.nativeSourceHandler); vjs.Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; vjs.Flash['onReady'] = function(currSwf){ var el, player; el = vjs.el(currSwf); // get player from the player div property player = el && el.parentNode && el.parentNode['player']; // if there is no el or player then the tech has been disposed // and the tech element was removed from the player div if (player) { // reference player on tech element el['player'] = player; // check that the flash object is really ready vjs.Flash['checkReady'](player.tech); } }; // The SWF isn't always ready when it says it is. Sometimes the API functions still need to be added to the object. // If it's not ready, we set a timeout to check again shortly. vjs.Flash['checkReady'] = function(tech){ // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if API property exists if (tech.el().vjs_getProperty) { // tell tech it's ready tech.triggerReady(); } else { // wait longer this.setTimeout(function(){ vjs.Flash['checkReady'](tech); }, 50); } }; // Trigger events from the swf on the player vjs.Flash['onEvent'] = function(swfID, eventName){ var player = vjs.el(swfID)['player']; player.trigger(eventName); }; // Log errors from the swf vjs.Flash['onError'] = function(swfID, err){ var player = vjs.el(swfID)['player']; var msg = 'FLASH: '+err; if (err == 'srcnotfound') { player.error({ code: 4, message: msg }); // errors we haven't categorized into the media errors } else { player.error(msg); } }; // Flash Version Check vjs.Flash.version = function(){ var version = '0,0,0'; // IE try { version = new window.ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch(e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin){ version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch(err) {} } return version.split(','); }; // Flash embedding method. Only used in non-iframe mode vjs.Flash.embed = function(swf, placeHolder, flashVars, params, attributes){ var code = vjs.Flash.getEmbedCode(swf, flashVars, params, attributes), // Get element by embedding code and retrieving created element obj = vjs.createEl('div', { innerHTML: code }).childNodes[0], par = placeHolder.parentNode ; placeHolder.parentNode.replaceChild(obj, placeHolder); obj[vjs.expando] = placeHolder[vjs.expando]; // IE6 seems to have an issue where it won't initialize the swf object after injecting it. // This is a dumb fix var newObj = par.childNodes[0]; setTimeout(function(){ newObj.style.display = 'block'; }, 1000); return obj; }; vjs.Flash.getEmbedCode = function(swf, flashVars, params, attributes){ var objTag = '<object type="application/x-shockwave-flash" ', flashVarsString = '', paramsString = '', attrsString = ''; // Convert flash vars to string if (flashVars) { vjs.obj.each(flashVars, function(key, val){ flashVarsString += (key + '=' + val + '&amp;'); }); } // Add swf, flashVars, and other default params params = vjs.obj.merge({ 'movie': swf, 'flashvars': flashVarsString, 'allowScriptAccess': 'always', // Required to talk to swf 'allowNetworking': 'all' // All should be default, but having security issues. }, params); // Create param tags string vjs.obj.each(params, function(key, val){ paramsString += '<param name="'+key+'" value="'+val+'" />'; }); attributes = vjs.obj.merge({ // Add swf to attributes (need both for IE and Others to work) 'data': swf, // Default to 100% width/height 'width': '100%', 'height': '100%' }, attributes); // Create Attributes string vjs.obj.each(attributes, function(key, val){ attrsString += (key + '="' + val + '" '); }); return objTag + attrsString + '>' + paramsString + '</object>'; }; vjs.Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; vjs.Flash.streamFromParts = function(connection, stream) { return connection + '&' + stream; }; vjs.Flash.streamToParts = function(src) { var parts = { connection: '', stream: '' }; if (! src) { return parts; } // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.indexOf('&'); var streamBegin; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; vjs.Flash.isStreamingType = function(srcType) { return srcType in vjs.Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid vjs.Flash.RTMP_RE = /^rtmp[set]?:\/\//i; vjs.Flash.isStreamingSrc = function(src) { return vjs.Flash.RTMP_RE.test(src); }; /** * A source handler for RTMP urls * @type {Object} */ vjs.Flash.rtmpSourceHandler = {}; /** * Check Flash can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ vjs.Flash.rtmpSourceHandler.canHandleSource = function(source){ if (vjs.Flash.isStreamingType(source.type) || vjs.Flash.isStreamingSrc(source.src)) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {vjs.Flash} tech The instance of the Flash tech */ vjs.Flash.rtmpSourceHandler.handleSource = function(source, tech){ var srcParts = vjs.Flash.streamToParts(source.src); tech['setRtmpConnection'](srcParts.connection); tech['setRtmpStream'](srcParts.stream); }; // Register the native source handler vjs.Flash.registerSourceHandler(vjs.Flash.rtmpSourceHandler); /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @constructor */ vjs.MediaLoader = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ vjs.Component.call(this, player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!player.options_['sources'] || player.options_['sources'].length === 0) { for (var i=0,j=player.options_['techOrder']; i<j.length; i++) { var techName = vjs.capitalize(j[i]), tech = window['videojs'][techName]; // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech(techName); break; } } } else { // // Loop through playback technologies (HTML5, Flash) and check for support. // // Then load the best source. // // A few assumptions here: // // All playback technologies respect preload false. player.src(player.options_['sources']); } } }); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode * * enum TextTrackMode { "disabled", "hidden", "showing" }; */ vjs.TextTrackMode = { 'disabled': 'disabled', 'hidden': 'hidden', 'showing': 'showing' }; /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackkind * * enum TextTrackKind { "subtitles", "captions", "descriptions", "chapters", "metadata" }; */ vjs.TextTrackKind = { 'subtitles': 'subtitles', 'captions': 'captions', 'descriptions': 'descriptions', 'chapters': 'chapters', 'metadata': 'metadata' }; (function() { /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack * * interface TextTrack : EventTarget { * readonly attribute TextTrackKind kind; * readonly attribute DOMString label; * readonly attribute DOMString language; * * readonly attribute DOMString id; * readonly attribute DOMString inBandMetadataTrackDispatchType; * * attribute TextTrackMode mode; * * readonly attribute TextTrackCueList? cues; * readonly attribute TextTrackCueList? activeCues; * * void addCue(TextTrackCue cue); * void removeCue(TextTrackCue cue); * * attribute EventHandler oncuechange; * }; */ vjs.TextTrack = function(options) { var tt, id, mode, kind, label, language, cues, activeCues, timeupdateHandler, changed, prop; options = options || {}; if (!options['player']) { throw new Error('A player was not provided.'); } tt = this; if (vjs.IS_IE8) { tt = document.createElement('custom'); for (prop in vjs.TextTrack.prototype) { tt[prop] = vjs.TextTrack.prototype[prop]; } } tt.player_ = options['player']; mode = vjs.TextTrackMode[options['mode']] || 'disabled'; kind = vjs.TextTrackKind[options['kind']] || 'subtitles'; label = options['label'] || ''; language = options['language'] || options['srclang'] || ''; id = options['id'] || 'vjs_text_track_' + vjs.guid++; if (kind === 'metadata' || kind === 'chapters') { mode = 'hidden'; } tt.cues_ = []; tt.activeCues_ = []; cues = new vjs.TextTrackCueList(tt.cues_); activeCues = new vjs.TextTrackCueList(tt.activeCues_); changed = false; timeupdateHandler = vjs.bind(tt, function() { this['activeCues']; if (changed) { this['trigger']('cuechange'); changed = false; } }); if (mode !== 'disabled') { tt.player_.on('timeupdate', timeupdateHandler); } Object.defineProperty(tt, 'kind', { get: function() { return kind; }, set: Function.prototype }); Object.defineProperty(tt, 'label', { get: function() { return label; }, set: Function.prototype }); Object.defineProperty(tt, 'language', { get: function() { return language; }, set: Function.prototype }); Object.defineProperty(tt, 'id', { get: function() { return id; }, set: Function.prototype }); Object.defineProperty(tt, 'mode', { get: function() { return mode; }, set: function(newMode) { if (!vjs.TextTrackMode[newMode]) { return; } mode = newMode; if (mode === 'showing') { this.player_.on('timeupdate', timeupdateHandler); } this.trigger('modechange'); } }); Object.defineProperty(tt, 'cues', { get: function() { if (!this.loaded_) { return null; } return cues; }, set: Function.prototype }); Object.defineProperty(tt, 'activeCues', { get: function() { var i, l, active, ct, cue; if (!this.loaded_) { return null; } if (this['cues'].length === 0) { return activeCues; // nothing to do } ct = this.player_.currentTime(); i = 0; l = this['cues'].length; active = []; for (; i < l; i++) { cue = this['cues'][i]; if (cue['startTime'] <= ct && cue['endTime'] >= ct) { active.push(cue); } else if (cue['startTime'] === cue['endTime'] && cue['startTime'] <= ct && cue['startTime'] + 0.5 >= ct) { active.push(cue); } } changed = false; if (active.length !== this.activeCues_.length) { changed = true; } else { for (i = 0; i < active.length; i++) { if (indexOf.call(this.activeCues_, active[i]) === -1) { changed = true; } } } this.activeCues_ = active; activeCues.setCues_(this.activeCues_); return activeCues; }, set: Function.prototype }); if (options.src) { loadTrack(options.src, tt); } else { tt.loaded_ = true; } if (vjs.IS_IE8) { return tt; } }; vjs.TextTrack.prototype = vjs.obj.create(vjs.EventEmitter.prototype); vjs.TextTrack.prototype.constructor = vjs.TextTrack; /* * cuechange - One or more cues in the track have become active or stopped being active. */ vjs.TextTrack.prototype.allowedEvents_ = { 'cuechange': 'cuechange' }; vjs.TextTrack.prototype.addCue = function(cue) { var tracks = this.player_.textTracks(), i = 0; if (tracks) { for (; i < tracks.length; i++) { if (tracks[i] !== this) { tracks[i].removeCue(cue); } } } this.cues_.push(cue); this['cues'].setCues_(this.cues_); }; vjs.TextTrack.prototype.removeCue = function(removeCue) { var i = 0, l = this.cues_.length, cue, removed = false; for (; i < l; i++) { cue = this.cues_[i]; if (cue === removeCue) { this.cues_.splice(i, 1); removed = true; } } if (removed) { this.cues.setCues_(this.cues_); } }; /* * Downloading stuff happens below this point */ var loadTrack, parseCues, indexOf; loadTrack = function(src, track) { vjs.xhr(src, vjs.bind(this, function(err, response, responseBody){ if (err) { return vjs.log.error(err); } track.loaded_ = true; parseCues(responseBody, track); })); }; parseCues = function(srcContent, track) { if (typeof window['WebVTT'] !== 'function') { //try again a bit later return window.setTimeout(function() { parseCues(srcContent, track); }, 25); } var parser = new window['WebVTT']['Parser'](window, window['vttjs'], window['WebVTT']['StringDecoder']()); parser['oncue'] = function(cue) { track.addCue(cue); }; parser['onparsingerror'] = function(error) { vjs.log.error(error); }; parser['parse'](srcContent); parser['flush'](); }; indexOf = function(searchElement, fromIndex) { var k; if (this == null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (len === 0) { return -1; } var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } if (n >= len) { return -1; } k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); while (k < len) { if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; })(); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist * * interface TextTrackList : EventTarget { * readonly attribute unsigned long length; * getter TextTrack (unsigned long index); * TextTrack? getTrackById(DOMString id); * * attribute EventHandler onchange; * attribute EventHandler onaddtrack; * attribute EventHandler onremovetrack; * }; */ vjs.TextTrackList = function(tracks) { var list = this, prop, i = 0; if (vjs.IS_IE8) { list = document.createElement('custom'); for (prop in vjs.TextTrackList.prototype) { list[prop] = vjs.TextTrackList.prototype[prop]; } } tracks = tracks || []; list.tracks_ = []; Object.defineProperty(list, 'length', { get: function() { return this.tracks_.length; } }); for (; i < tracks.length; i++) { list.addTrack_(tracks[i]); } if (vjs.IS_IE8) { return list; } }; vjs.TextTrackList.prototype = vjs.obj.create(vjs.EventEmitter.prototype); vjs.TextTrackList.prototype.constructor = vjs.TextTrackList; /* * change - One or more tracks in the track list have been enabled or disabled. * addtrack - A track has been added to the track list. * removetrack - A track has been removed from the track list. */ vjs.TextTrackList.prototype.allowedEvents_ = { 'change': 'change', 'addtrack': 'addtrack', 'removetrack': 'removetrack' }; // emulate attribute EventHandler support to allow for feature detection (function() { var event; for (event in vjs.TextTrackList.prototype.allowedEvents_) { vjs.TextTrackList.prototype['on' + event] = null; } })(); vjs.TextTrackList.prototype.addTrack_ = function(track) { var index = this.tracks_.length; if (!(''+index in this)) { Object.defineProperty(this, index, { get: function() { return this.tracks_[index]; } }); } track.addEventListener('modechange', vjs.bind(this, function() { this.trigger('change'); })); this.tracks_.push(track); this.trigger({ type: 'addtrack', track: track }); }; vjs.TextTrackList.prototype.removeTrack_ = function(rtrack) { var i = 0, l = this.length, result = null, track; for (; i < l; i++) { track = this[i]; if (track === rtrack) { this.tracks_.splice(i, 1); break; } } this.trigger({ type: 'removetrack', track: rtrack }); }; vjs.TextTrackList.prototype.getTrackById = function(id) { var i = 0, l = this.length, result = null, track; for (; i < l; i++) { track = this[i]; if (track.id === id) { result = track; break; } } return result; }; /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist * * interface TextTrackCueList { * readonly attribute unsigned long length; * getter TextTrackCue (unsigned long index); * TextTrackCue? getCueById(DOMString id); * }; */ vjs.TextTrackCueList = function(cues) { var list = this, prop; if (vjs.IS_IE8) { list = document.createElement('custom'); for (prop in vjs.TextTrackCueList.prototype) { list[prop] = vjs.TextTrackCueList.prototype[prop]; } } vjs.TextTrackCueList.prototype.setCues_.call(list, cues); Object.defineProperty(list, 'length', { get: function() { return this.length_; } }); if (vjs.IS_IE8) { return list; } }; vjs.TextTrackCueList.prototype.setCues_ = function(cues) { var oldLength = this.length || 0, i = 0, l = cues.length, defineProp; this.cues_ = cues; this.length_ = cues.length; defineProp = function(i) { if (!(''+i in this)) { Object.defineProperty(this, '' + i, { get: function() { return this.cues_[i]; } }); } }; if (oldLength < l) { i = oldLength; for(; i < l; i++) { defineProp.call(this, i); } } }; vjs.TextTrackCueList.prototype.getCueById = function(id) { var i = 0, l = this.length, result = null, cue; for (; i < l; i++) { cue = this[i]; if (cue.id === id) { result = cue; break; } } return result; }; (function() { 'use strict'; /* Text Track Display ============================================================================= */ // Global container for both subtitle and captions text. Simple div container. /** * The component for displaying text track cues * * @constructor */ vjs.TextTrackDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ vjs.Component.call(this, player, options, ready); player.on('loadstart', vjs.bind(this, this.toggleDisplay)); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. player.ready(vjs.bind(this, function() { if (player.tech && player.tech['featuresNativeTextTracks']) { this.hide(); return; } var i, tracks, track; player.on('fullscreenchange', vjs.bind(this, this.updateDisplay)); tracks = player.options_['tracks'] || []; for (i = 0; i < tracks.length; i++) { track = tracks[i]; this.player_.addRemoteTextTrack(track); } })); } }); vjs.TextTrackDisplay.prototype.toggleDisplay = function() { if (this.player_.tech && this.player_.tech['featuresNativeTextTracks']) { this.hide(); } else { this.show(); } }; vjs.TextTrackDisplay.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }); }; vjs.TextTrackDisplay.prototype.clearDisplay = function() { if (typeof window['WebVTT'] === 'function') { window['WebVTT']['processCues'](window, [], this.el_); } }; // Add cue HTML to display var constructColor = function(color, opacity) { return 'rgba(' + // color looks like "#f0e" parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')'; }; var darkGray = '#222'; var lightGray = '#ccc'; var fontMap = { monospace: 'monospace', sansSerif: 'sans-serif', serif: 'serif', monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace', monospaceSerif: '"Courier New", monospace', proportionalSansSerif: 'sans-serif', proportionalSerif: 'serif', casual: '"Comic Sans MS", Impact, fantasy', script: '"Monotype Corsiva", cursive', smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif' }; var tryUpdateStyle = function(el, style, rule) { // some style changes will throw an error, particularly in IE8. Those should be noops. try { el.style[style] = rule; } catch (e) {} }; vjs.TextTrackDisplay.prototype.updateDisplay = function() { var tracks = this.player_.textTracks(), i = 0, track; this.clearDisplay(); if (!tracks) { return; } for (; i < tracks.length; i++) { track = tracks[i]; if (track['mode'] === 'showing') { this.updateForTrack(track); } } }; vjs.TextTrackDisplay.prototype.updateForTrack = function(track) { if (typeof window['WebVTT'] !== 'function' || !track['activeCues']) { return; } var i = 0, property, cueDiv, overrides = this.player_['textTrackSettings'].getValues(), fontSize, cues = []; for (; i < track['activeCues'].length; i++) { cues.push(track['activeCues'][i]); } window['WebVTT']['processCues'](window, track['activeCues'], this.el_); i = cues.length; while (i--) { cueDiv = cues[i].displayState; if (overrides.color) { cueDiv.firstChild.style.color = overrides.color; } if (overrides.textOpacity) { tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity)); } if (overrides.backgroundColor) { cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor; } if (overrides.backgroundOpacity) { tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity)); } if (overrides.windowColor) { if (overrides.windowOpacity) { tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity)); } else { cueDiv.style.backgroundColor = overrides.windowColor; } } if (overrides.edgeStyle) { if (overrides.edgeStyle === 'dropshadow') { cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray; } else if (overrides.edgeStyle === 'raised') { cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray; } else if (overrides.edgeStyle === 'depressed') { cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray; } else if (overrides.edgeStyle === 'uniform') { cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray; } } if (overrides.fontPercent && overrides.fontPercent !== 1) { fontSize = window.parseFloat(cueDiv.style.fontSize); cueDiv.style.fontSize = (fontSize * overrides.fontPercent) + 'px'; cueDiv.style.height = 'auto'; cueDiv.style.top = 'auto'; cueDiv.style.bottom = '2px'; } if (overrides.fontFamily && overrides.fontFamily !== 'default') { if (overrides.fontFamily === 'small-caps') { cueDiv.firstChild.style.fontVariant = 'small-caps'; } else { cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily]; } } } }; /** * The specific menu item type for selecting a language within a text track kind * * @constructor */ vjs.TextTrackMenuItem = vjs.MenuItem.extend({ /** @constructor */ init: function(player, options){ var track = this.track = options['track'], tracks = player.textTracks(), changeHandler, event; if (tracks) { changeHandler = vjs.bind(this, function() { var selected = this.track['mode'] === 'showing', track, i, l; if (this instanceof vjs.OffTextTrackMenuItem) { selected = true; i = 0, l = tracks.length; for (; i < l; i++) { track = tracks[i]; if (track['kind'] === this.track['kind'] && track['mode'] === 'showing') { selected = false; break; } } } this.selected(selected); }); tracks.addEventListener('change', changeHandler); player.on('dispose', function() { tracks.removeEventListener('change', changeHandler); }); } // Modify options for parent MenuItem class's init. options['label'] = track['label'] || track['language'] || 'Unknown'; options['selected'] = track['default'] || track['mode'] === 'showing'; vjs.MenuItem.call(this, player, options); // iOS7 doesn't dispatch change events to TextTrackLists when an // associated track's mode changes. Without something like // Object.observe() (also not present on iOS7), it's not // possible to detect changes to the mode attribute and polyfill // the change event. As a poor substitute, we manually dispatch // change events whenever the controls modify the mode. if (tracks && tracks.onchange === undefined) { this.on(['tap', 'click'], function() { if (typeof window.Event !== 'object') { // Android 2.3 throws an Illegal Constructor error for window.Event try { event = new window.Event('change'); } catch(err){} } if (!event) { event = document.createEvent('Event'); event.initEvent('change', true, true); } tracks.dispatchEvent(event); }); } } }); vjs.TextTrackMenuItem.prototype.onClick = function(){ var kind = this.track['kind'], tracks = this.player_.textTracks(), mode, track, i = 0; vjs.MenuItem.prototype.onClick.call(this); if (!tracks) { return; } for (; i < tracks.length; i++) { track = tracks[i]; if (track['kind'] !== kind) { continue; } if (track === this.track) { track['mode'] = 'showing'; } else { track['mode'] = 'disabled'; } } }; /** * A special menu item for turning of a specific type of text track * * @constructor */ vjs.OffTextTrackMenuItem = vjs.TextTrackMenuItem.extend({ /** @constructor */ init: function(player, options){ // Create pseudo track info // Requires options['kind'] options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'] + ' off', 'default': false, 'mode': 'disabled' }; vjs.TextTrackMenuItem.call(this, player, options); this.selected(true); } }); vjs.CaptionSettingsMenuItem = vjs.TextTrackMenuItem.extend({ init: function(player, options) { options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'] + ' settings', 'default': false, mode: 'disabled' }; vjs.TextTrackMenuItem.call(this, player, options); this.addClass('vjs-texttrack-settings'); } }); vjs.CaptionSettingsMenuItem.prototype.onClick = function() { this.player().getChild('textTrackSettings').show(); }; /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @constructor */ vjs.TextTrackButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ var tracks, updateHandler; vjs.MenuButton.call(this, player, options); tracks = this.player_.textTracks(); if (this.items.length <= 1) { this.hide(); } if (!tracks) { return; } updateHandler = vjs.bind(this, this.update); tracks.addEventListener('removetrack', updateHandler); tracks.addEventListener('addtrack', updateHandler); this.player_.on('dispose', function() { tracks.removeEventListener('removetrack', updateHandler); tracks.removeEventListener('addtrack', updateHandler); }); } }); // Create a menu item for each text track vjs.TextTrackButton.prototype.createItems = function(){ var items = [], track, tracks; if (this instanceof vjs.CaptionsButton && !(this.player().tech && this.player().tech['featuresNativeTextTracks'])) { items.push(new vjs.CaptionSettingsMenuItem(this.player_, { 'kind': this.kind_ })); } // Add an OFF menu item to turn all tracks off items.push(new vjs.OffTextTrackMenuItem(this.player_, { 'kind': this.kind_ })); tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { track = tracks[i]; // only add tracks that are of the appropriate kind and have a label if (track['kind'] === this.kind_) { items.push(new vjs.TextTrackMenuItem(this.player_, { 'track': track })); } } return items; }; /** * The button component for toggling and selecting captions * * @constructor */ vjs.CaptionsButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Captions Menu'); } }); vjs.CaptionsButton.prototype.kind_ = 'captions'; vjs.CaptionsButton.prototype.buttonText = 'Captions'; vjs.CaptionsButton.prototype.className = 'vjs-captions-button'; vjs.CaptionsButton.prototype.update = function() { var threshold = 2; vjs.TextTrackButton.prototype.update.call(this); // if native, then threshold is 1 because no settings button if (this.player().tech && this.player().tech['featuresNativeTextTracks']) { threshold = 1; } if (this.items && this.items.length > threshold) { this.show(); } else { this.hide(); } }; /** * The button component for toggling and selecting subtitles * * @constructor */ vjs.SubtitlesButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Subtitles Menu'); } }); vjs.SubtitlesButton.prototype.kind_ = 'subtitles'; vjs.SubtitlesButton.prototype.buttonText = 'Subtitles'; vjs.SubtitlesButton.prototype.className = 'vjs-subtitles-button'; // Chapters act much differently than other text tracks // Cues are navigation vs. other tracks of alternative languages /** * The button component for toggling and selecting chapters * * @constructor */ vjs.ChaptersButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Chapters Menu'); } }); vjs.ChaptersButton.prototype.kind_ = 'chapters'; vjs.ChaptersButton.prototype.buttonText = 'Chapters'; vjs.ChaptersButton.prototype.className = 'vjs-chapters-button'; // Create a menu item for each text track vjs.ChaptersButton.prototype.createItems = function(){ var items = [], track, tracks; tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { track = tracks[i]; if (track['kind'] === this.kind_) { items.push(new vjs.TextTrackMenuItem(this.player_, { 'track': track })); } } return items; }; vjs.ChaptersButton.prototype.createMenu = function(){ var tracks = this.player_.textTracks() || [], i = 0, l = tracks.length, track, chaptersTrack, items = this.items = []; for (; i < l; i++) { track = tracks[i]; if (track['kind'] == this.kind_) { if (!track.cues) { track['mode'] = 'hidden'; /* jshint loopfunc:true */ // TODO see if we can figure out a better way of doing this https://github.com/videojs/video.js/issues/1864 window.setTimeout(vjs.bind(this, function() { this.createMenu(); }), 100); /* jshint loopfunc:false */ } else { chaptersTrack = track; break; } } } var menu = this.menu; if (menu === undefined) { menu = new vjs.Menu(this.player_); menu.contentEl().appendChild(vjs.createEl('li', { className: 'vjs-menu-title', innerHTML: vjs.capitalize(this.kind_), tabindex: -1 })); } if (chaptersTrack) { var cues = chaptersTrack['cues'], cue, mi; i = 0; l = cues.length; for (; i < l; i++) { cue = cues[i]; mi = new vjs.ChaptersTrackMenuItem(this.player_, { 'track': chaptersTrack, 'cue': cue }); items.push(mi); menu.addChild(mi); } this.addChild(menu); } if (this.items.length > 0) { this.show(); } return menu; }; /** * @constructor */ vjs.ChaptersTrackMenuItem = vjs.MenuItem.extend({ /** @constructor */ init: function(player, options){ var track = this.track = options['track'], cue = this.cue = options['cue'], currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options['label'] = cue.text; options['selected'] = (cue['startTime'] <= currentTime && currentTime < cue['endTime']); vjs.MenuItem.call(this, player, options); track.addEventListener('cuechange', vjs.bind(this, this.update)); } }); vjs.ChaptersTrackMenuItem.prototype.onClick = function(){ vjs.MenuItem.prototype.onClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; vjs.ChaptersTrackMenuItem.prototype.update = function(){ var cue = this.cue, currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue['startTime'] <= currentTime && currentTime < cue['endTime']); }; })(); (function() { 'use strict'; vjs.TextTrackSettings = vjs.Component.extend({ init: function(player, options) { vjs.Component.call(this, player, options); this.hide(); vjs.on(this.el().querySelector('.vjs-done-button'), 'click', vjs.bind(this, function() { this.saveSettings(); this.hide(); })); vjs.on(this.el().querySelector('.vjs-default-button'), 'click', vjs.bind(this, function() { this.el().querySelector('.vjs-fg-color > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-color > select').selectedIndex = 0; this.el().querySelector('.window-color > select').selectedIndex = 0; this.el().querySelector('.vjs-text-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-window-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-edge-style select').selectedIndex = 0; this.el().querySelector('.vjs-font-family select').selectedIndex = 0; this.el().querySelector('.vjs-font-percent select').selectedIndex = 2; this.updateDisplay(); })); vjs.on(this.el().querySelector('.vjs-fg-color > select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-bg-color > select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.window-color > select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-text-opacity > select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-bg-opacity > select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-window-opacity > select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-font-percent select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-edge-style select'), 'change', vjs.bind(this, this.updateDisplay)); vjs.on(this.el().querySelector('.vjs-font-family select'), 'change', vjs.bind(this, this.updateDisplay)); if (player.options()['persistTextTrackSettings']) { this.restoreSettings(); } } }); vjs.TextTrackSettings.prototype.createEl = function() { return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-caption-settings vjs-modal-overlay', innerHTML: captionOptionsMenuTemplate() }); }; vjs.TextTrackSettings.prototype.getValues = function() { var el, bgOpacity, textOpacity, windowOpacity, textEdge, fontFamily, fgColor, bgColor, windowColor, result, name, fontPercent; el = this.el(); textEdge = getSelectedOptionValue(el.querySelector('.vjs-edge-style select')); fontFamily = getSelectedOptionValue(el.querySelector('.vjs-font-family select')); fgColor = getSelectedOptionValue(el.querySelector('.vjs-fg-color > select')); textOpacity = getSelectedOptionValue(el.querySelector('.vjs-text-opacity > select')); bgColor = getSelectedOptionValue(el.querySelector('.vjs-bg-color > select')); bgOpacity = getSelectedOptionValue(el.querySelector('.vjs-bg-opacity > select')); windowColor = getSelectedOptionValue(el.querySelector('.window-color > select')); windowOpacity = getSelectedOptionValue(el.querySelector('.vjs-window-opacity > select')); fontPercent = window['parseFloat'](getSelectedOptionValue(el.querySelector('.vjs-font-percent > select'))); result = { 'backgroundOpacity': bgOpacity, 'textOpacity': textOpacity, 'windowOpacity': windowOpacity, 'edgeStyle': textEdge, 'fontFamily': fontFamily, 'color': fgColor, 'backgroundColor': bgColor, 'windowColor': windowColor, 'fontPercent': fontPercent }; for (name in result) { if (result[name] === '' || result[name] === 'none' || (name === 'fontPercent' && result[name] === 1.00)) { delete result[name]; } } return result; }; vjs.TextTrackSettings.prototype.setValues = function(values) { var el = this.el(), fontPercent; setSelectedOption(el.querySelector('.vjs-edge-style select'), values.edgeStyle); setSelectedOption(el.querySelector('.vjs-font-family select'), values.fontFamily); setSelectedOption(el.querySelector('.vjs-fg-color > select'), values.color); setSelectedOption(el.querySelector('.vjs-text-opacity > select'), values.textOpacity); setSelectedOption(el.querySelector('.vjs-bg-color > select'), values.backgroundColor); setSelectedOption(el.querySelector('.vjs-bg-opacity > select'), values.backgroundOpacity); setSelectedOption(el.querySelector('.window-color > select'), values.windowColor); setSelectedOption(el.querySelector('.vjs-window-opacity > select'), values.windowOpacity); fontPercent = values.fontPercent; if (fontPercent) { fontPercent = fontPercent.toFixed(2); } setSelectedOption(el.querySelector('.vjs-font-percent > select'), fontPercent); }; vjs.TextTrackSettings.prototype.restoreSettings = function() { var values; try { values = JSON.parse(window.localStorage.getItem('vjs-text-track-settings')); } catch (e) {} if (values) { this.setValues(values); } }; vjs.TextTrackSettings.prototype.saveSettings = function() { var values; if (!this.player_.options()['persistTextTrackSettings']) { return; } values = this.getValues(); try { if (!vjs.isEmpty(values)) { window.localStorage.setItem('vjs-text-track-settings', JSON.stringify(values)); } else { window.localStorage.removeItem('vjs-text-track-settings'); } } catch (e) {} }; vjs.TextTrackSettings.prototype.updateDisplay = function() { var ttDisplay = this.player_.getChild('textTrackDisplay'); if (ttDisplay) { ttDisplay.updateDisplay(); } }; function getSelectedOptionValue(target) { var selectedOption; // not all browsers support selectedOptions, so, fallback to options if (target.selectedOptions) { selectedOption = target.selectedOptions[0]; } else if (target.options) { selectedOption = target.options[target.options.selectedIndex]; } return selectedOption.value; } function setSelectedOption(target, value) { var i, option; if (!value) { return; } for (i = 0; i < target.options.length; i++) { option = target.options[i]; if (option.value === value) { break; } } target.selectedIndex = i; } function captionOptionsMenuTemplate() { return '<div class="vjs-tracksettings">' + '<div class="vjs-tracksettings-colors">' + '<div class="vjs-fg-color vjs-tracksetting">' + '<label class="vjs-label">Foreground</label>' + '<select>' + '<option value="">---</option>' + '<option value="#FFF">White</option>' + '<option value="#000">Black</option>' + '<option value="#F00">Red</option>' + '<option value="#0F0">Green</option>' + '<option value="#00F">Blue</option>' + '<option value="#FF0">Yellow</option>' + '<option value="#F0F">Magenta</option>' + '<option value="#0FF">Cyan</option>' + '</select>' + '<span class="vjs-text-opacity vjs-opacity">' + '<select>' + '<option value="">---</option>' + '<option value="1">Opaque</option>' + '<option value="0.5">Semi-Opaque</option>' + '</select>' + '</span>' + '</div>' + // vjs-fg-color '<div class="vjs-bg-color vjs-tracksetting">' + '<label class="vjs-label">Background</label>' + '<select>' + '<option value="">---</option>' + '<option value="#FFF">White</option>' + '<option value="#000">Black</option>' + '<option value="#F00">Red</option>' + '<option value="#0F0">Green</option>' + '<option value="#00F">Blue</option>' + '<option value="#FF0">Yellow</option>' + '<option value="#F0F">Magenta</option>' + '<option value="#0FF">Cyan</option>' + '</select>' + '<span class="vjs-bg-opacity vjs-opacity">' + '<select>' + '<option value="">---</option>' + '<option value="1">Opaque</option>' + '<option value="0.5">Semi-Transparent</option>' + '<option value="0">Transparent</option>' + '</select>' + '</span>' + '</div>' + // vjs-bg-color '<div class="window-color vjs-tracksetting">' + '<label class="vjs-label">Window</label>' + '<select>' + '<option value="">---</option>' + '<option value="#FFF">White</option>' + '<option value="#000">Black</option>' + '<option value="#F00">Red</option>' + '<option value="#0F0">Green</option>' + '<option value="#00F">Blue</option>' + '<option value="#FF0">Yellow</option>' + '<option value="#F0F">Magenta</option>' + '<option value="#0FF">Cyan</option>' + '</select>' + '<span class="vjs-window-opacity vjs-opacity">' + '<select>' + '<option value="">---</option>' + '<option value="1">Opaque</option>' + '<option value="0.5">Semi-Transparent</option>' + '<option value="0">Transparent</option>' + '</select>' + '</span>' + '</div>' + // vjs-window-color '</div>' + // vjs-tracksettings '<div class="vjs-tracksettings-font">' + '<div class="vjs-font-percent vjs-tracksetting">' + '<label class="vjs-label">Font Size</label>' + '<select>' + '<option value="0.50">50%</option>' + '<option value="0.75">75%</option>' + '<option value="1.00" selected>100%</option>' + '<option value="1.25">125%</option>' + '<option value="1.50">150%</option>' + '<option value="1.75">175%</option>' + '<option value="2.00">200%</option>' + '<option value="3.00">300%</option>' + '<option value="4.00">400%</option>' + '</select>' + '</div>' + // vjs-font-percent '<div class="vjs-edge-style vjs-tracksetting">' + '<label class="vjs-label">Text Edge Style</label>' + '<select>' + '<option value="none">None</option>' + '<option value="raised">Raised</option>' + '<option value="depressed">Depressed</option>' + '<option value="uniform">Uniform</option>' + '<option value="dropshadow">Dropshadow</option>' + '</select>' + '</div>' + // vjs-edge-style '<div class="vjs-font-family vjs-tracksetting">' + '<label class="vjs-label">Font Family</label>' + '<select>' + '<option value="">Default</option>' + '<option value="monospaceSerif">Monospace Serif</option>' + '<option value="proportionalSerif">Proportional Serif</option>' + '<option value="monospaceSansSerif">Monospace Sans-Serif</option>' + '<option value="proportionalSansSerif">Proportional Sans-Serif</option>' + '<option value="casual">Casual</option>' + '<option value="script">Script</option>' + '<option value="small-caps">Small Caps</option>' + '</select>' + '</div>' + // vjs-font-family '</div>' + '</div>' + '<div class="vjs-tracksettings-controls">' + '<button class="vjs-default-button">Defaults</button>' + '<button class="vjs-done-button">Done</button>' + '</div>'; } })(); /** * @fileoverview Add JSON support * @suppress {undefinedVars} * (Compiler doesn't like JSON not being declared) */ /** * Javascript JSON implementation * (Parse Method Only) * https://github.com/douglascrockford/JSON-js/blob/master/json2.js * Only using for parse method when parsing data-setup attribute JSON. * @suppress {undefinedVars} * @namespace * @private */ vjs.JSON; if (typeof window.JSON !== 'undefined' && typeof window.JSON.parse === 'function') { vjs.JSON = window.JSON; } else { vjs.JSON = {}; var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; /** * parse the json * * @memberof vjs.JSON * @param {String} text The JSON string to parse * @param {Function=} [reviver] Optional function that can transform the results * @return {Object|Array} The parsed JSON */ vjs.JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({'': j}, '') : j; } throw new SyntaxError('JSON.parse(): invalid or malformed JSON data'); }; } /** * @fileoverview Functions for automatically setting up a player * based on the data-setup attribute of the video tag */ // Automatically set up any tags that have a data-setup attribute vjs.autoSetup = function(){ var options, mediaEl, player, i, e; // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop through each list of elements // to build up a new, combined list of elements. var vids = document.getElementsByTagName('video'); var audios = document.getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for(i=0, e=vids.length; i<e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for(i=0, e=audios.length; i<e; i++) { mediaEls.push(audios[i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (i=0,e=mediaEls.length; i<e; i++) { mediaEl = mediaEls[i]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl['player'] === undefined) { options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. player = videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { vjs.autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!vjs.windowLoaded) { vjs.autoSetupTimeout(1); } }; // Pause to let the DOM keep processing vjs.autoSetupTimeout = function(wait){ setTimeout(vjs.autoSetup, wait); }; if (document.readyState === 'complete') { vjs.windowLoaded = true; } else { vjs.one(window, 'load', function(){ vjs.windowLoaded = true; }); } // Run Auto-load players // You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version) vjs.autoSetupTimeout(1); /** * the method for registering a video.js plugin * * @param {String} name The name of the plugin * @param {Function} init The function that is run when the player inits */ vjs.plugin = function(name, init){ vjs.Player.prototype[name] = init; }; /* vtt.js - v0.12.1 (https://github.com/mozilla/vtt.js) built on 08-07-2015 */ (function(root) { var vttjs = root.vttjs = {}; var cueShim = vttjs.VTTCue; var regionShim = vttjs.VTTRegion; var oldVTTCue = root.VTTCue; var oldVTTRegion = root.VTTRegion; vttjs.shim = function() { vttjs.VTTCue = cueShim; vttjs.VTTRegion = regionShim; }; vttjs.restore = function() { vttjs.VTTCue = oldVTTCue; vttjs.VTTRegion = oldVTTRegion; }; }(this)); /** * Copyright 2013 vtt.js Contributors * * 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. */ (function(root, vttjs) { var autoKeyword = "auto"; var directionSetting = { "": true, "lr": true, "rl": true }; var alignSetting = { "start": true, "middle": true, "end": true, "left": true, "right": true }; function findDirectionSetting(value) { if (typeof value !== "string") { return false; } var dir = directionSetting[value.toLowerCase()]; return dir ? value.toLowerCase() : false; } function findAlignSetting(value) { if (typeof value !== "string") { return false; } var align = alignSetting[value.toLowerCase()]; return align ? value.toLowerCase() : false; } function extend(obj) { var i = 1; for (; i < arguments.length; i++) { var cobj = arguments[i]; for (var p in cobj) { obj[p] = cobj[p]; } } return obj; } function VTTCue(startTime, endTime, text) { var cue = this; var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var baseObj = {}; if (isIE8) { cue = document.createElement('custom'); } else { baseObj.enumerable = true; } /** * Shim implementation specific properties. These properties are not in * the spec. */ // Lets us know when the VTTCue's data has changed in such a way that we need // to recompute its display state. This lets us compute its display state // lazily. cue.hasBeenReset = false; /** * VTTCue and TextTrackCue properties * http://dev.w3.org/html5/webvtt/#vttcue-interface */ var _id = ""; var _pauseOnExit = false; var _startTime = startTime; var _endTime = endTime; var _text = text; var _region = null; var _vertical = ""; var _snapToLines = true; var _line = "auto"; var _lineAlign = "start"; var _position = 50; var _positionAlign = "middle"; var _size = 50; var _align = "middle"; Object.defineProperty(cue, "id", extend({}, baseObj, { get: function() { return _id; }, set: function(value) { _id = "" + value; } })); Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, { get: function() { return _pauseOnExit; }, set: function(value) { _pauseOnExit = !!value; } })); Object.defineProperty(cue, "startTime", extend({}, baseObj, { get: function() { return _startTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Start time must be set to a number."); } _startTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "endTime", extend({}, baseObj, { get: function() { return _endTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("End time must be set to a number."); } _endTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "text", extend({}, baseObj, { get: function() { return _text; }, set: function(value) { _text = "" + value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "region", extend({}, baseObj, { get: function() { return _region; }, set: function(value) { _region = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "vertical", extend({}, baseObj, { get: function() { return _vertical; }, set: function(value) { var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _vertical = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "snapToLines", extend({}, baseObj, { get: function() { return _snapToLines; }, set: function(value) { _snapToLines = !!value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "line", extend({}, baseObj, { get: function() { return _line; }, set: function(value) { if (typeof value !== "number" && value !== autoKeyword) { throw new SyntaxError("An invalid number or illegal string was specified."); } _line = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "lineAlign", extend({}, baseObj, { get: function() { return _lineAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _lineAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "position", extend({}, baseObj, { get: function() { return _position; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Position must be between 0 and 100."); } _position = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "positionAlign", extend({}, baseObj, { get: function() { return _positionAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _positionAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "size", extend({}, baseObj, { get: function() { return _size; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Size must be between 0 and 100."); } _size = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "align", extend({}, baseObj, { get: function() { return _align; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _align = setting; this.hasBeenReset = true; } })); /** * Other <track> spec defined properties */ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state cue.displayState = undefined; if (isIE8) { return cue; } } /** * VTTCue methods */ VTTCue.prototype.getCueAsHTML = function() { // Assume WebVTT.convertCueToDOMTree is on the global. return WebVTT.convertCueToDOMTree(window, this.text); }; root.VTTCue = root.VTTCue || VTTCue; vttjs.VTTCue = VTTCue; }(this, (this.vttjs || {}))); /** * Copyright 2013 vtt.js Contributors * * 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. */ (function(root, vttjs) { var scrollSetting = { "": true, "up": true }; function findScrollSetting(value) { if (typeof value !== "string") { return false; } var scroll = scrollSetting[value.toLowerCase()]; return scroll ? value.toLowerCase() : false; } function isValidPercentValue(value) { return typeof value === "number" && (value >= 0 && value <= 100); } // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface function VTTRegion() { var _width = 100; var _lines = 3; var _regionAnchorX = 0; var _regionAnchorY = 100; var _viewportAnchorX = 0; var _viewportAnchorY = 100; var _scroll = ""; Object.defineProperties(this, { "width": { enumerable: true, get: function() { return _width; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("Width must be between 0 and 100."); } _width = value; } }, "lines": { enumerable: true, get: function() { return _lines; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Lines must be set to a number."); } _lines = value; } }, "regionAnchorY": { enumerable: true, get: function() { return _regionAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("RegionAnchorX must be between 0 and 100."); } _regionAnchorY = value; } }, "regionAnchorX": { enumerable: true, get: function() { return _regionAnchorX; }, set: function(value) { if(!isValidPercentValue(value)) { throw new Error("RegionAnchorY must be between 0 and 100."); } _regionAnchorX = value; } }, "viewportAnchorY": { enumerable: true, get: function() { return _viewportAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorY must be between 0 and 100."); } _viewportAnchorY = value; } }, "viewportAnchorX": { enumerable: true, get: function() { return _viewportAnchorX; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorX must be between 0 and 100."); } _viewportAnchorX = value; } }, "scroll": { enumerable: true, get: function() { return _scroll; }, set: function(value) { var setting = findScrollSetting(value); // Have to check for false as an empty string is a legal value. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _scroll = setting; } } }); } root.VTTRegion = root.VTTRegion || VTTRegion; vttjs.VTTRegion = VTTRegion; }(this, (this.vttjs || {}))); /** * Copyright 2013 vtt.js Contributors * * 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. */ /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ (function(global) { var _objCreate = Object.create || (function() { function F() {} return function(o) { if (arguments.length !== 1) { throw new Error('Object.create shim only accepts one parameter.'); } F.prototype = o; return new F(); }; })(); // Creates a new ParserError object from an errorData object. The errorData // object should have default code and message properties. The default message // property can be overriden by passing in a message parameter. // See ParsingError.Errors below for acceptable errors. function ParsingError(errorData, message) { this.name = "ParsingError"; this.code = errorData.code; this.message = message || errorData.message; } ParsingError.prototype = _objCreate(Error.prototype); ParsingError.prototype.constructor = ParsingError; // ParsingError metadata for acceptable ParsingErrors. ParsingError.Errors = { BadSignature: { code: 0, message: "Malformed WebVTT signature." }, BadTimeStamp: { code: 1, message: "Malformed time stamp." } }; // Try to parse input as a time stamp. function parseTimeStamp(input) { function computeSeconds(h, m, s, f) { return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000; } var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/); if (!m) { return null; } if (m[3]) { // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds] return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]); } else if (m[1] > 59) { // Timestamp takes the form of [hours]:[minutes].[milliseconds] // First position is hours as it's over 59. return computeSeconds(m[1], m[2], 0, m[4]); } else { // Timestamp takes the form of [minutes]:[seconds].[milliseconds] return computeSeconds(0, m[1], m[2], m[4]); } } // A settings object holds key/value pairs and will ignore anything but the first // assignment to a specific key. function Settings() { this.values = _objCreate(null); } Settings.prototype = { // Only accept the first assignment to any key. set: function(k, v) { if (!this.get(k) && v !== "") { this.values[k] = v; } }, // Return the value for a key, or a default value. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with // a number of possible default values as properties where 'defaultKey' is // the key of the property that will be chosen; otherwise it's assumed to be // a single value. get: function(k, dflt, defaultKey) { if (defaultKey) { return this.has(k) ? this.values[k] : dflt[defaultKey]; } return this.has(k) ? this.values[k] : dflt; }, // Check whether we have a value for a key. has: function(k) { return k in this.values; }, // Accept a setting if its one of the given alternatives. alt: function(k, v, a) { for (var n = 0; n < a.length; ++n) { if (v === a[n]) { this.set(k, v); break; } } }, // Accept a setting if its a valid (signed) integer. integer: function(k, v) { if (/^-?\d+$/.test(v)) { // integer this.set(k, parseInt(v, 10)); } }, // Accept a setting if its a valid percentage. percent: function(k, v) { var m; if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) { v = parseFloat(v); if (v >= 0 && v <= 100) { this.set(k, v); return true; } } return false; } }; // Helper function to parse input into groups separated by 'groupDelim', and // interprete each group as a key/value pair separated by 'keyValueDelim'. function parseOptions(input, callback, keyValueDelim, groupDelim) { var groups = groupDelim ? input.split(groupDelim) : [input]; for (var i in groups) { if (typeof groups[i] !== "string") { continue; } var kv = groups[i].split(keyValueDelim); if (kv.length !== 2) { continue; } var k = kv[0]; var v = kv[1]; callback(k, v); } } function parseCue(input, cue, regionList) { // Remember the original input if we need to throw an error. var oInput = input; // 4.1 WebVTT timestamp function consumeTimeStamp() { var ts = parseTimeStamp(input); if (ts === null) { throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput); } // Remove time stamp from input. input = input.replace(/^[^\sa-zA-Z-]+/, ""); return ts; } // 4.4.2 WebVTT cue settings function consumeCueSettings(input, cue) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "region": // Find the last region we parsed with the same region id. for (var i = regionList.length - 1; i >= 0; i--) { if (regionList[i].id === v) { settings.set(k, regionList[i].region); break; } } break; case "vertical": settings.alt(k, v, ["rl", "lr"]); break; case "line": var vals = v.split(","), vals0 = vals[0]; settings.integer(k, vals0); settings.percent(k, vals0) ? settings.set("snapToLines", false) : null; settings.alt(k, vals0, ["auto"]); if (vals.length === 2) { settings.alt("lineAlign", vals[1], ["start", "middle", "end"]); } break; case "position": vals = v.split(","); settings.percent(k, vals[0]); if (vals.length === 2) { settings.alt("positionAlign", vals[1], ["start", "middle", "end"]); } break; case "size": settings.percent(k, v); break; case "align": settings.alt(k, v, ["start", "middle", "end", "left", "right"]); break; } }, /:/, /\s/); // Apply default values for any missing fields. cue.region = settings.get("region", null); cue.vertical = settings.get("vertical", ""); cue.line = settings.get("line", "auto"); cue.lineAlign = settings.get("lineAlign", "start"); cue.snapToLines = settings.get("snapToLines", true); cue.size = settings.get("size", 100); cue.align = settings.get("align", "middle"); cue.position = settings.get("position", { start: 0, left: 0, middle: 50, end: 100, right: 100 }, cue.align); cue.positionAlign = settings.get("positionAlign", { start: "start", left: "start", middle: "middle", end: "end", right: "end" }, cue.align); } function skipWhitespace() { input = input.replace(/^\s+/, ""); } // 4.1 WebVTT cue timings. skipWhitespace(); cue.startTime = consumeTimeStamp(); // (1) collect cue start time skipWhitespace(); if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->" throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput); } input = input.substr(3); skipWhitespace(); cue.endTime = consumeTimeStamp(); // (5) collect cue end time // 4.1 WebVTT cue settings list. skipWhitespace(); consumeCueSettings(input, cue); } var ESCAPE = { "&amp;": "&", "&lt;": "<", "&gt;": ">", "&lrm;": "\u200e", "&rlm;": "\u200f", "&nbsp;": "\u00a0" }; var TAG_NAME = { c: "span", i: "i", b: "b", u: "u", ruby: "ruby", rt: "rt", v: "span", lang: "span" }; var TAG_ANNOTATION = { v: "title", lang: "lang" }; var NEEDS_PARENT = { rt: "ruby" }; // Parse content into a document fragment. function parseContent(window, input) { function nextToken() { // Check for end-of-string. if (!input) { return null; } // Consume 'n' characters from the input. function consume(result) { input = input.substr(result.length); return result; } var m = input.match(/^([^<]*)(<[^>]+>?)?/); // If there is some text before the next tag, return it, otherwise return // the tag. return consume(m[1] ? m[1] : m[2]); } // Unescape a string 's'. function unescape1(e) { return ESCAPE[e]; } function unescape(s) { while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) { s = s.replace(m[0], unescape1); } return s; } function shouldAdd(current, element) { return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName; } // Create an element for this tag. function createElement(type, annotation) { var tagName = TAG_NAME[type]; if (!tagName) { return null; } var element = window.document.createElement(tagName); element.localName = tagName; var name = TAG_ANNOTATION[type]; if (name && annotation) { element[name] = annotation.trim(); } return element; } var rootDiv = window.document.createElement("div"), current = rootDiv, t, tagStack = []; while ((t = nextToken()) !== null) { if (t[0] === '<') { if (t[1] === "/") { // If the closing tag matches, move back up to the parent node. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) { tagStack.pop(); current = current.parentNode; } // Otherwise just ignore the end tag. continue; } var ts = parseTimeStamp(t.substr(1, t.length - 2)); var node; if (ts) { // Timestamps are lead nodes as well. node = window.document.createProcessingInstruction("timestamp", ts); current.appendChild(node); continue; } var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/); // If we can't parse the tag, skip to the next tag. if (!m) { continue; } // Try to construct an element, and ignore the tag if we couldn't. node = createElement(m[1], m[3]); if (!node) { continue; } // Determine if the tag should be added based on the context of where it // is placed in the cuetext. if (!shouldAdd(current, node)) { continue; } // Set the class list (as a list of classes, separated by space). if (m[2]) { node.className = m[2].substr(1).replace('.', ' '); } // Append the node to the current node, and enter the scope of the new // node. tagStack.push(m[1]); current.appendChild(node); current = node; continue; } // Text nodes are leaf nodes. current.appendChild(window.document.createTextNode(unescape(t))); } return rootDiv; } // This is a list of all the Unicode characters that have a strong // right-to-left category. What this means is that these characters are // written right-to-left for sure. It was generated by pulling all the strong // right-to-left characters out of the Unicode data table. That table can // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt var strongRTLChars = [0x05BE, 0x05C0, 0x05C3, 0x05C6, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0x0608, 0x060B, 0x060D, 0x061B, 0x061E, 0x061F, 0x0620, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, 0x0638, 0x0639, 0x063A, 0x063B, 0x063C, 0x063D, 0x063E, 0x063F, 0x0640, 0x0641, 0x0642, 0x0643, 0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A, 0x066D, 0x066E, 0x066F, 0x0671, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0x0677, 0x0678, 0x0679, 0x067A, 0x067B, 0x067C, 0x067D, 0x067E, 0x067F, 0x0680, 0x0681, 0x0682, 0x0683, 0x0684, 0x0685, 0x0686, 0x0687, 0x0688, 0x0689, 0x068A, 0x068B, 0x068C, 0x068D, 0x068E, 0x068F, 0x0690, 0x0691, 0x0692, 0x0693, 0x0694, 0x0695, 0x0696, 0x0697, 0x0698, 0x0699, 0x069A, 0x069B, 0x069C, 0x069D, 0x069E, 0x069F, 0x06A0, 0x06A1, 0x06A2, 0x06A3, 0x06A4, 0x06A5, 0x06A6, 0x06A7, 0x06A8, 0x06A9, 0x06AA, 0x06AB, 0x06AC, 0x06AD, 0x06AE, 0x06AF, 0x06B0, 0x06B1, 0x06B2, 0x06B3, 0x06B4, 0x06B5, 0x06B6, 0x06B7, 0x06B8, 0x06B9, 0x06BA, 0x06BB, 0x06BC, 0x06BD, 0x06BE, 0x06BF, 0x06C0, 0x06C1, 0x06C2, 0x06C3, 0x06C4, 0x06C5, 0x06C6, 0x06C7, 0x06C8, 0x06C9, 0x06CA, 0x06CB, 0x06CC, 0x06CD, 0x06CE, 0x06CF, 0x06D0, 0x06D1, 0x06D2, 0x06D3, 0x06D4, 0x06D5, 0x06E5, 0x06E6, 0x06EE, 0x06EF, 0x06FA, 0x06FB, 0x06FC, 0x06FD, 0x06FE, 0x06FF, 0x0700, 0x0701, 0x0702, 0x0703, 0x0704, 0x0705, 0x0706, 0x0707, 0x0708, 0x0709, 0x070A, 0x070B, 0x070C, 0x070D, 0x070F, 0x0710, 0x0712, 0x0713, 0x0714, 0x0715, 0x0716, 0x0717, 0x0718, 0x0719, 0x071A, 0x071B, 0x071C, 0x071D, 0x071E, 0x071F, 0x0720, 0x0721, 0x0722, 0x0723, 0x0724, 0x0725, 0x0726, 0x0727, 0x0728, 0x0729, 0x072A, 0x072B, 0x072C, 0x072D, 0x072E, 0x072F, 0x074D, 0x074E, 0x074F, 0x0750, 0x0751, 0x0752, 0x0753, 0x0754, 0x0755, 0x0756, 0x0757, 0x0758, 0x0759, 0x075A, 0x075B, 0x075C, 0x075D, 0x075E, 0x075F, 0x0760, 0x0761, 0x0762, 0x0763, 0x0764, 0x0765, 0x0766, 0x0767, 0x0768, 0x0769, 0x076A, 0x076B, 0x076C, 0x076D, 0x076E, 0x076F, 0x0770, 0x0771, 0x0772, 0x0773, 0x0774, 0x0775, 0x0776, 0x0777, 0x0778, 0x0779, 0x077A, 0x077B, 0x077C, 0x077D, 0x077E, 0x077F, 0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0786, 0x0787, 0x0788, 0x0789, 0x078A, 0x078B, 0x078C, 0x078D, 0x078E, 0x078F, 0x0790, 0x0791, 0x0792, 0x0793, 0x0794, 0x0795, 0x0796, 0x0797, 0x0798, 0x0799, 0x079A, 0x079B, 0x079C, 0x079D, 0x079E, 0x079F, 0x07A0, 0x07A1, 0x07A2, 0x07A3, 0x07A4, 0x07A5, 0x07B1, 0x07C0, 0x07C1, 0x07C2, 0x07C3, 0x07C4, 0x07C5, 0x07C6, 0x07C7, 0x07C8, 0x07C9, 0x07CA, 0x07CB, 0x07CC, 0x07CD, 0x07CE, 0x07CF, 0x07D0, 0x07D1, 0x07D2, 0x07D3, 0x07D4, 0x07D5, 0x07D6, 0x07D7, 0x07D8, 0x07D9, 0x07DA, 0x07DB, 0x07DC, 0x07DD, 0x07DE, 0x07DF, 0x07E0, 0x07E1, 0x07E2, 0x07E3, 0x07E4, 0x07E5, 0x07E6, 0x07E7, 0x07E8, 0x07E9, 0x07EA, 0x07F4, 0x07F5, 0x07FA, 0x0800, 0x0801, 0x0802, 0x0803, 0x0804, 0x0805, 0x0806, 0x0807, 0x0808, 0x0809, 0x080A, 0x080B, 0x080C, 0x080D, 0x080E, 0x080F, 0x0810, 0x0811, 0x0812, 0x0813, 0x0814, 0x0815, 0x081A, 0x0824, 0x0828, 0x0830, 0x0831, 0x0832, 0x0833, 0x0834, 0x0835, 0x0836, 0x0837, 0x0838, 0x0839, 0x083A, 0x083B, 0x083C, 0x083D, 0x083E, 0x0840, 0x0841, 0x0842, 0x0843, 0x0844, 0x0845, 0x0846, 0x0847, 0x0848, 0x0849, 0x084A, 0x084B, 0x084C, 0x084D, 0x084E, 0x084F, 0x0850, 0x0851, 0x0852, 0x0853, 0x0854, 0x0855, 0x0856, 0x0857, 0x0858, 0x085E, 0x08A0, 0x08A2, 0x08A3, 0x08A4, 0x08A5, 0x08A6, 0x08A7, 0x08A8, 0x08A9, 0x08AA, 0x08AB, 0x08AC, 0x200F, 0xFB1D, 0xFB1F, 0xFB20, 0xFB21, 0xFB22, 0xFB23, 0xFB24, 0xFB25, 0xFB26, 0xFB27, 0xFB28, 0xFB2A, 0xFB2B, 0xFB2C, 0xFB2D, 0xFB2E, 0xFB2F, 0xFB30, 0xFB31, 0xFB32, 0xFB33, 0xFB34, 0xFB35, 0xFB36, 0xFB38, 0xFB39, 0xFB3A, 0xFB3B, 0xFB3C, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44, 0xFB46, 0xFB47, 0xFB48, 0xFB49, 0xFB4A, 0xFB4B, 0xFB4C, 0xFB4D, 0xFB4E, 0xFB4F, 0xFB50, 0xFB51, 0xFB52, 0xFB53, 0xFB54, 0xFB55, 0xFB56, 0xFB57, 0xFB58, 0xFB59, 0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D, 0xFB5E, 0xFB5F, 0xFB60, 0xFB61, 0xFB62, 0xFB63, 0xFB64, 0xFB65, 0xFB66, 0xFB67, 0xFB68, 0xFB69, 0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D, 0xFB6E, 0xFB6F, 0xFB70, 0xFB71, 0xFB72, 0xFB73, 0xFB74, 0xFB75, 0xFB76, 0xFB77, 0xFB78, 0xFB79, 0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D, 0xFB7E, 0xFB7F, 0xFB80, 0xFB81, 0xFB82, 0xFB83, 0xFB84, 0xFB85, 0xFB86, 0xFB87, 0xFB88, 0xFB89, 0xFB8A, 0xFB8B, 0xFB8C, 0xFB8D, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91, 0xFB92, 0xFB93, 0xFB94, 0xFB95, 0xFB96, 0xFB97, 0xFB98, 0xFB99, 0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D, 0xFB9E, 0xFB9F, 0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3, 0xFBA4, 0xFBA5, 0xFBA6, 0xFBA7, 0xFBA8, 0xFBA9, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD, 0xFBAE, 0xFBAF, 0xFBB0, 0xFBB1, 0xFBB2, 0xFBB3, 0xFBB4, 0xFBB5, 0xFBB6, 0xFBB7, 0xFBB8, 0xFBB9, 0xFBBA, 0xFBBB, 0xFBBC, 0xFBBD, 0xFBBE, 0xFBBF, 0xFBC0, 0xFBC1, 0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6, 0xFBD7, 0xFBD8, 0xFBD9, 0xFBDA, 0xFBDB, 0xFBDC, 0xFBDD, 0xFBDE, 0xFBDF, 0xFBE0, 0xFBE1, 0xFBE2, 0xFBE3, 0xFBE4, 0xFBE5, 0xFBE6, 0xFBE7, 0xFBE8, 0xFBE9, 0xFBEA, 0xFBEB, 0xFBEC, 0xFBED, 0xFBEE, 0xFBEF, 0xFBF0, 0xFBF1, 0xFBF2, 0xFBF3, 0xFBF4, 0xFBF5, 0xFBF6, 0xFBF7, 0xFBF8, 0xFBF9, 0xFBFA, 0xFBFB, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF, 0xFC00, 0xFC01, 0xFC02, 0xFC03, 0xFC04, 0xFC05, 0xFC06, 0xFC07, 0xFC08, 0xFC09, 0xFC0A, 0xFC0B, 0xFC0C, 0xFC0D, 0xFC0E, 0xFC0F, 0xFC10, 0xFC11, 0xFC12, 0xFC13, 0xFC14, 0xFC15, 0xFC16, 0xFC17, 0xFC18, 0xFC19, 0xFC1A, 0xFC1B, 0xFC1C, 0xFC1D, 0xFC1E, 0xFC1F, 0xFC20, 0xFC21, 0xFC22, 0xFC23, 0xFC24, 0xFC25, 0xFC26, 0xFC27, 0xFC28, 0xFC29, 0xFC2A, 0xFC2B, 0xFC2C, 0xFC2D, 0xFC2E, 0xFC2F, 0xFC30, 0xFC31, 0xFC32, 0xFC33, 0xFC34, 0xFC35, 0xFC36, 0xFC37, 0xFC38, 0xFC39, 0xFC3A, 0xFC3B, 0xFC3C, 0xFC3D, 0xFC3E, 0xFC3F, 0xFC40, 0xFC41, 0xFC42, 0xFC43, 0xFC44, 0xFC45, 0xFC46, 0xFC47, 0xFC48, 0xFC49, 0xFC4A, 0xFC4B, 0xFC4C, 0xFC4D, 0xFC4E, 0xFC4F, 0xFC50, 0xFC51, 0xFC52, 0xFC53, 0xFC54, 0xFC55, 0xFC56, 0xFC57, 0xFC58, 0xFC59, 0xFC5A, 0xFC5B, 0xFC5C, 0xFC5D, 0xFC5E, 0xFC5F, 0xFC60, 0xFC61, 0xFC62, 0xFC63, 0xFC64, 0xFC65, 0xFC66, 0xFC67, 0xFC68, 0xFC69, 0xFC6A, 0xFC6B, 0xFC6C, 0xFC6D, 0xFC6E, 0xFC6F, 0xFC70, 0xFC71, 0xFC72, 0xFC73, 0xFC74, 0xFC75, 0xFC76, 0xFC77, 0xFC78, 0xFC79, 0xFC7A, 0xFC7B, 0xFC7C, 0xFC7D, 0xFC7E, 0xFC7F, 0xFC80, 0xFC81, 0xFC82, 0xFC83, 0xFC84, 0xFC85, 0xFC86, 0xFC87, 0xFC88, 0xFC89, 0xFC8A, 0xFC8B, 0xFC8C, 0xFC8D, 0xFC8E, 0xFC8F, 0xFC90, 0xFC91, 0xFC92, 0xFC93, 0xFC94, 0xFC95, 0xFC96, 0xFC97, 0xFC98, 0xFC99, 0xFC9A, 0xFC9B, 0xFC9C, 0xFC9D, 0xFC9E, 0xFC9F, 0xFCA0, 0xFCA1, 0xFCA2, 0xFCA3, 0xFCA4, 0xFCA5, 0xFCA6, 0xFCA7, 0xFCA8, 0xFCA9, 0xFCAA, 0xFCAB, 0xFCAC, 0xFCAD, 0xFCAE, 0xFCAF, 0xFCB0, 0xFCB1, 0xFCB2, 0xFCB3, 0xFCB4, 0xFCB5, 0xFCB6, 0xFCB7, 0xFCB8, 0xFCB9, 0xFCBA, 0xFCBB, 0xFCBC, 0xFCBD, 0xFCBE, 0xFCBF, 0xFCC0, 0xFCC1, 0xFCC2, 0xFCC3, 0xFCC4, 0xFCC5, 0xFCC6, 0xFCC7, 0xFCC8, 0xFCC9, 0xFCCA, 0xFCCB, 0xFCCC, 0xFCCD, 0xFCCE, 0xFCCF, 0xFCD0, 0xFCD1, 0xFCD2, 0xFCD3, 0xFCD4, 0xFCD5, 0xFCD6, 0xFCD7, 0xFCD8, 0xFCD9, 0xFCDA, 0xFCDB, 0xFCDC, 0xFCDD, 0xFCDE, 0xFCDF, 0xFCE0, 0xFCE1, 0xFCE2, 0xFCE3, 0xFCE4, 0xFCE5, 0xFCE6, 0xFCE7, 0xFCE8, 0xFCE9, 0xFCEA, 0xFCEB, 0xFCEC, 0xFCED, 0xFCEE, 0xFCEF, 0xFCF0, 0xFCF1, 0xFCF2, 0xFCF3, 0xFCF4, 0xFCF5, 0xFCF6, 0xFCF7, 0xFCF8, 0xFCF9, 0xFCFA, 0xFCFB, 0xFCFC, 0xFCFD, 0xFCFE, 0xFCFF, 0xFD00, 0xFD01, 0xFD02, 0xFD03, 0xFD04, 0xFD05, 0xFD06, 0xFD07, 0xFD08, 0xFD09, 0xFD0A, 0xFD0B, 0xFD0C, 0xFD0D, 0xFD0E, 0xFD0F, 0xFD10, 0xFD11, 0xFD12, 0xFD13, 0xFD14, 0xFD15, 0xFD16, 0xFD17, 0xFD18, 0xFD19, 0xFD1A, 0xFD1B, 0xFD1C, 0xFD1D, 0xFD1E, 0xFD1F, 0xFD20, 0xFD21, 0xFD22, 0xFD23, 0xFD24, 0xFD25, 0xFD26, 0xFD27, 0xFD28, 0xFD29, 0xFD2A, 0xFD2B, 0xFD2C, 0xFD2D, 0xFD2E, 0xFD2F, 0xFD30, 0xFD31, 0xFD32, 0xFD33, 0xFD34, 0xFD35, 0xFD36, 0xFD37, 0xFD38, 0xFD39, 0xFD3A, 0xFD3B, 0xFD3C, 0xFD3D, 0xFD50, 0xFD51, 0xFD52, 0xFD53, 0xFD54, 0xFD55, 0xFD56, 0xFD57, 0xFD58, 0xFD59, 0xFD5A, 0xFD5B, 0xFD5C, 0xFD5D, 0xFD5E, 0xFD5F, 0xFD60, 0xFD61, 0xFD62, 0xFD63, 0xFD64, 0xFD65, 0xFD66, 0xFD67, 0xFD68, 0xFD69, 0xFD6A, 0xFD6B, 0xFD6C, 0xFD6D, 0xFD6E, 0xFD6F, 0xFD70, 0xFD71, 0xFD72, 0xFD73, 0xFD74, 0xFD75, 0xFD76, 0xFD77, 0xFD78, 0xFD79, 0xFD7A, 0xFD7B, 0xFD7C, 0xFD7D, 0xFD7E, 0xFD7F, 0xFD80, 0xFD81, 0xFD82, 0xFD83, 0xFD84, 0xFD85, 0xFD86, 0xFD87, 0xFD88, 0xFD89, 0xFD8A, 0xFD8B, 0xFD8C, 0xFD8D, 0xFD8E, 0xFD8F, 0xFD92, 0xFD93, 0xFD94, 0xFD95, 0xFD96, 0xFD97, 0xFD98, 0xFD99, 0xFD9A, 0xFD9B, 0xFD9C, 0xFD9D, 0xFD9E, 0xFD9F, 0xFDA0, 0xFDA1, 0xFDA2, 0xFDA3, 0xFDA4, 0xFDA5, 0xFDA6, 0xFDA7, 0xFDA8, 0xFDA9, 0xFDAA, 0xFDAB, 0xFDAC, 0xFDAD, 0xFDAE, 0xFDAF, 0xFDB0, 0xFDB1, 0xFDB2, 0xFDB3, 0xFDB4, 0xFDB5, 0xFDB6, 0xFDB7, 0xFDB8, 0xFDB9, 0xFDBA, 0xFDBB, 0xFDBC, 0xFDBD, 0xFDBE, 0xFDBF, 0xFDC0, 0xFDC1, 0xFDC2, 0xFDC3, 0xFDC4, 0xFDC5, 0xFDC6, 0xFDC7, 0xFDF0, 0xFDF1, 0xFDF2, 0xFDF3, 0xFDF4, 0xFDF5, 0xFDF6, 0xFDF7, 0xFDF8, 0xFDF9, 0xFDFA, 0xFDFB, 0xFDFC, 0xFE70, 0xFE71, 0xFE72, 0xFE73, 0xFE74, 0xFE76, 0xFE77, 0xFE78, 0xFE79, 0xFE7A, 0xFE7B, 0xFE7C, 0xFE7D, 0xFE7E, 0xFE7F, 0xFE80, 0xFE81, 0xFE82, 0xFE83, 0xFE84, 0xFE85, 0xFE86, 0xFE87, 0xFE88, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C, 0xFE8D, 0xFE8E, 0xFE8F, 0xFE90, 0xFE91, 0xFE92, 0xFE93, 0xFE94, 0xFE95, 0xFE96, 0xFE97, 0xFE98, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C, 0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4, 0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8, 0xFEA9, 0xFEAA, 0xFEAB, 0xFEAC, 0xFEAD, 0xFEAE, 0xFEAF, 0xFEB0, 0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8, 0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0, 0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8, 0xFEC9, 0xFECA, 0xFECB, 0xFECC, 0xFECD, 0xFECE, 0xFECF, 0xFED0, 0xFED1, 0xFED2, 0xFED3, 0xFED4, 0xFED5, 0xFED6, 0xFED7, 0xFED8, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC, 0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4, 0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC, 0xFEED, 0xFEEE, 0xFEEF, 0xFEF0, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4, 0xFEF5, 0xFEF6, 0xFEF7, 0xFEF8, 0xFEF9, 0xFEFA, 0xFEFB, 0xFEFC, 0x10800, 0x10801, 0x10802, 0x10803, 0x10804, 0x10805, 0x10808, 0x1080A, 0x1080B, 0x1080C, 0x1080D, 0x1080E, 0x1080F, 0x10810, 0x10811, 0x10812, 0x10813, 0x10814, 0x10815, 0x10816, 0x10817, 0x10818, 0x10819, 0x1081A, 0x1081B, 0x1081C, 0x1081D, 0x1081E, 0x1081F, 0x10820, 0x10821, 0x10822, 0x10823, 0x10824, 0x10825, 0x10826, 0x10827, 0x10828, 0x10829, 0x1082A, 0x1082B, 0x1082C, 0x1082D, 0x1082E, 0x1082F, 0x10830, 0x10831, 0x10832, 0x10833, 0x10834, 0x10835, 0x10837, 0x10838, 0x1083C, 0x1083F, 0x10840, 0x10841, 0x10842, 0x10843, 0x10844, 0x10845, 0x10846, 0x10847, 0x10848, 0x10849, 0x1084A, 0x1084B, 0x1084C, 0x1084D, 0x1084E, 0x1084F, 0x10850, 0x10851, 0x10852, 0x10853, 0x10854, 0x10855, 0x10857, 0x10858, 0x10859, 0x1085A, 0x1085B, 0x1085C, 0x1085D, 0x1085E, 0x1085F, 0x10900, 0x10901, 0x10902, 0x10903, 0x10904, 0x10905, 0x10906, 0x10907, 0x10908, 0x10909, 0x1090A, 0x1090B, 0x1090C, 0x1090D, 0x1090E, 0x1090F, 0x10910, 0x10911, 0x10912, 0x10913, 0x10914, 0x10915, 0x10916, 0x10917, 0x10918, 0x10919, 0x1091A, 0x1091B, 0x10920, 0x10921, 0x10922, 0x10923, 0x10924, 0x10925, 0x10926, 0x10927, 0x10928, 0x10929, 0x1092A, 0x1092B, 0x1092C, 0x1092D, 0x1092E, 0x1092F, 0x10930, 0x10931, 0x10932, 0x10933, 0x10934, 0x10935, 0x10936, 0x10937, 0x10938, 0x10939, 0x1093F, 0x10980, 0x10981, 0x10982, 0x10983, 0x10984, 0x10985, 0x10986, 0x10987, 0x10988, 0x10989, 0x1098A, 0x1098B, 0x1098C, 0x1098D, 0x1098E, 0x1098F, 0x10990, 0x10991, 0x10992, 0x10993, 0x10994, 0x10995, 0x10996, 0x10997, 0x10998, 0x10999, 0x1099A, 0x1099B, 0x1099C, 0x1099D, 0x1099E, 0x1099F, 0x109A0, 0x109A1, 0x109A2, 0x109A3, 0x109A4, 0x109A5, 0x109A6, 0x109A7, 0x109A8, 0x109A9, 0x109AA, 0x109AB, 0x109AC, 0x109AD, 0x109AE, 0x109AF, 0x109B0, 0x109B1, 0x109B2, 0x109B3, 0x109B4, 0x109B5, 0x109B6, 0x109B7, 0x109BE, 0x109BF, 0x10A00, 0x10A10, 0x10A11, 0x10A12, 0x10A13, 0x10A15, 0x10A16, 0x10A17, 0x10A19, 0x10A1A, 0x10A1B, 0x10A1C, 0x10A1D, 0x10A1E, 0x10A1F, 0x10A20, 0x10A21, 0x10A22, 0x10A23, 0x10A24, 0x10A25, 0x10A26, 0x10A27, 0x10A28, 0x10A29, 0x10A2A, 0x10A2B, 0x10A2C, 0x10A2D, 0x10A2E, 0x10A2F, 0x10A30, 0x10A31, 0x10A32, 0x10A33, 0x10A40, 0x10A41, 0x10A42, 0x10A43, 0x10A44, 0x10A45, 0x10A46, 0x10A47, 0x10A50, 0x10A51, 0x10A52, 0x10A53, 0x10A54, 0x10A55, 0x10A56, 0x10A57, 0x10A58, 0x10A60, 0x10A61, 0x10A62, 0x10A63, 0x10A64, 0x10A65, 0x10A66, 0x10A67, 0x10A68, 0x10A69, 0x10A6A, 0x10A6B, 0x10A6C, 0x10A6D, 0x10A6E, 0x10A6F, 0x10A70, 0x10A71, 0x10A72, 0x10A73, 0x10A74, 0x10A75, 0x10A76, 0x10A77, 0x10A78, 0x10A79, 0x10A7A, 0x10A7B, 0x10A7C, 0x10A7D, 0x10A7E, 0x10A7F, 0x10B00, 0x10B01, 0x10B02, 0x10B03, 0x10B04, 0x10B05, 0x10B06, 0x10B07, 0x10B08, 0x10B09, 0x10B0A, 0x10B0B, 0x10B0C, 0x10B0D, 0x10B0E, 0x10B0F, 0x10B10, 0x10B11, 0x10B12, 0x10B13, 0x10B14, 0x10B15, 0x10B16, 0x10B17, 0x10B18, 0x10B19, 0x10B1A, 0x10B1B, 0x10B1C, 0x10B1D, 0x10B1E, 0x10B1F, 0x10B20, 0x10B21, 0x10B22, 0x10B23, 0x10B24, 0x10B25, 0x10B26, 0x10B27, 0x10B28, 0x10B29, 0x10B2A, 0x10B2B, 0x10B2C, 0x10B2D, 0x10B2E, 0x10B2F, 0x10B30, 0x10B31, 0x10B32, 0x10B33, 0x10B34, 0x10B35, 0x10B40, 0x10B41, 0x10B42, 0x10B43, 0x10B44, 0x10B45, 0x10B46, 0x10B47, 0x10B48, 0x10B49, 0x10B4A, 0x10B4B, 0x10B4C, 0x10B4D, 0x10B4E, 0x10B4F, 0x10B50, 0x10B51, 0x10B52, 0x10B53, 0x10B54, 0x10B55, 0x10B58, 0x10B59, 0x10B5A, 0x10B5B, 0x10B5C, 0x10B5D, 0x10B5E, 0x10B5F, 0x10B60, 0x10B61, 0x10B62, 0x10B63, 0x10B64, 0x10B65, 0x10B66, 0x10B67, 0x10B68, 0x10B69, 0x10B6A, 0x10B6B, 0x10B6C, 0x10B6D, 0x10B6E, 0x10B6F, 0x10B70, 0x10B71, 0x10B72, 0x10B78, 0x10B79, 0x10B7A, 0x10B7B, 0x10B7C, 0x10B7D, 0x10B7E, 0x10B7F, 0x10C00, 0x10C01, 0x10C02, 0x10C03, 0x10C04, 0x10C05, 0x10C06, 0x10C07, 0x10C08, 0x10C09, 0x10C0A, 0x10C0B, 0x10C0C, 0x10C0D, 0x10C0E, 0x10C0F, 0x10C10, 0x10C11, 0x10C12, 0x10C13, 0x10C14, 0x10C15, 0x10C16, 0x10C17, 0x10C18, 0x10C19, 0x10C1A, 0x10C1B, 0x10C1C, 0x10C1D, 0x10C1E, 0x10C1F, 0x10C20, 0x10C21, 0x10C22, 0x10C23, 0x10C24, 0x10C25, 0x10C26, 0x10C27, 0x10C28, 0x10C29, 0x10C2A, 0x10C2B, 0x10C2C, 0x10C2D, 0x10C2E, 0x10C2F, 0x10C30, 0x10C31, 0x10C32, 0x10C33, 0x10C34, 0x10C35, 0x10C36, 0x10C37, 0x10C38, 0x10C39, 0x10C3A, 0x10C3B, 0x10C3C, 0x10C3D, 0x10C3E, 0x10C3F, 0x10C40, 0x10C41, 0x10C42, 0x10C43, 0x10C44, 0x10C45, 0x10C46, 0x10C47, 0x10C48, 0x1EE00, 0x1EE01, 0x1EE02, 0x1EE03, 0x1EE05, 0x1EE06, 0x1EE07, 0x1EE08, 0x1EE09, 0x1EE0A, 0x1EE0B, 0x1EE0C, 0x1EE0D, 0x1EE0E, 0x1EE0F, 0x1EE10, 0x1EE11, 0x1EE12, 0x1EE13, 0x1EE14, 0x1EE15, 0x1EE16, 0x1EE17, 0x1EE18, 0x1EE19, 0x1EE1A, 0x1EE1B, 0x1EE1C, 0x1EE1D, 0x1EE1E, 0x1EE1F, 0x1EE21, 0x1EE22, 0x1EE24, 0x1EE27, 0x1EE29, 0x1EE2A, 0x1EE2B, 0x1EE2C, 0x1EE2D, 0x1EE2E, 0x1EE2F, 0x1EE30, 0x1EE31, 0x1EE32, 0x1EE34, 0x1EE35, 0x1EE36, 0x1EE37, 0x1EE39, 0x1EE3B, 0x1EE42, 0x1EE47, 0x1EE49, 0x1EE4B, 0x1EE4D, 0x1EE4E, 0x1EE4F, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59, 0x1EE5B, 0x1EE5D, 0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE67, 0x1EE68, 0x1EE69, 0x1EE6A, 0x1EE6C, 0x1EE6D, 0x1EE6E, 0x1EE6F, 0x1EE70, 0x1EE71, 0x1EE72, 0x1EE74, 0x1EE75, 0x1EE76, 0x1EE77, 0x1EE79, 0x1EE7A, 0x1EE7B, 0x1EE7C, 0x1EE7E, 0x1EE80, 0x1EE81, 0x1EE82, 0x1EE83, 0x1EE84, 0x1EE85, 0x1EE86, 0x1EE87, 0x1EE88, 0x1EE89, 0x1EE8B, 0x1EE8C, 0x1EE8D, 0x1EE8E, 0x1EE8F, 0x1EE90, 0x1EE91, 0x1EE92, 0x1EE93, 0x1EE94, 0x1EE95, 0x1EE96, 0x1EE97, 0x1EE98, 0x1EE99, 0x1EE9A, 0x1EE9B, 0x1EEA1, 0x1EEA2, 0x1EEA3, 0x1EEA5, 0x1EEA6, 0x1EEA7, 0x1EEA8, 0x1EEA9, 0x1EEAB, 0x1EEAC, 0x1EEAD, 0x1EEAE, 0x1EEAF, 0x1EEB0, 0x1EEB1, 0x1EEB2, 0x1EEB3, 0x1EEB4, 0x1EEB5, 0x1EEB6, 0x1EEB7, 0x1EEB8, 0x1EEB9, 0x1EEBA, 0x1EEBB, 0x10FFFD]; function determineBidi(cueDiv) { var nodeStack = [], text = "", charCode; if (!cueDiv || !cueDiv.childNodes) { return "ltr"; } function pushNodes(nodeStack, node) { for (var i = node.childNodes.length - 1; i >= 0; i--) { nodeStack.push(node.childNodes[i]); } } function nextTextNode(nodeStack) { if (!nodeStack || !nodeStack.length) { return null; } var node = nodeStack.pop(), text = node.textContent || node.innerText; if (text) { // TODO: This should match all unicode type B characters (paragraph // separator characters). See issue #115. var m = text.match(/^.*(\n|\r)/); if (m) { nodeStack.length = 0; return m[0]; } return text; } if (node.tagName === "ruby") { return nextTextNode(nodeStack); } if (node.childNodes) { pushNodes(nodeStack, node); return nextTextNode(nodeStack); } } pushNodes(nodeStack, cueDiv); while ((text = nextTextNode(nodeStack))) { for (var i = 0; i < text.length; i++) { charCode = text.charCodeAt(i); for (var j = 0; j < strongRTLChars.length; j++) { if (strongRTLChars[j] === charCode) { return "rtl"; } } } } return "ltr"; } function computeLinePos(cue) { if (typeof cue.line === "number" && (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) { return cue.line; } if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) { return -1; } var track = cue.track, trackList = track.textTrackList, count = 0; for (var i = 0; i < trackList.length && trackList[i] !== track; i++) { if (trackList[i].mode === "showing") { count++; } } return ++count * -1; } function StyleBox() { } // Apply styles to a div. If there is no div passed then it defaults to the // div on 'this'. StyleBox.prototype.applyStyles = function(styles, div) { div = div || this.div; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { div.style[prop] = styles[prop]; } } }; StyleBox.prototype.formatStyle = function(val, unit) { return val === 0 ? 0 : val + unit; }; // Constructs the computed display state of the cue (a div). Places the div // into the overlay which should be a block level element (usually a div). function CueStyleBox(window, cue, styleOptions) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var color = "rgba(255, 255, 255, 1)"; var backgroundColor = "rgba(0, 0, 0, 0.8)"; if (isIE8) { color = "rgb(255, 255, 255)"; backgroundColor = "rgb(0, 0, 0)"; } StyleBox.call(this); this.cue = cue; // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will // have inline positioning and will function as the cue background box. this.cueDiv = parseContent(window, cue.text); var styles = { color: color, backgroundColor: backgroundColor, position: "relative", left: 0, right: 0, top: 0, bottom: 0, display: "inline" }; if (!isIE8) { styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl"; styles.unicodeBidi = "plaintext"; } this.applyStyles(styles, this.cueDiv); // Create an absolutely positioned div that will be used to position the cue // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS // mirrors of them except "middle" which is "center" in CSS. this.div = window.document.createElement("div"); styles = { textAlign: cue.align === "middle" ? "center" : cue.align, font: styleOptions.font, whiteSpace: "pre-line", position: "absolute" }; if (!isIE8) { styles.direction = determineBidi(this.cueDiv); styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl". stylesunicodeBidi = "plaintext"; } this.applyStyles(styles); this.div.appendChild(this.cueDiv); // Calculate the distance from the reference edge of the viewport to the text // position of the cue box. The reference edge will be resolved later when // the box orientation styles are applied. var textPos = 0; switch (cue.positionAlign) { case "start": textPos = cue.position; break; case "middle": textPos = cue.position - (cue.size / 2); break; case "end": textPos = cue.position - cue.size; break; } // Horizontal box orientation; textPos is the distance from the left edge of the // area to the left edge of the box and cue.size is the distance extending to // the right from there. if (cue.vertical === "") { this.applyStyles({ left: this.formatStyle(textPos, "%"), width: this.formatStyle(cue.size, "%") }); // Vertical box orientation; textPos is the distance from the top edge of the // area to the top edge of the box and cue.size is the height extending // downwards from there. } else { this.applyStyles({ top: this.formatStyle(textPos, "%"), height: this.formatStyle(cue.size, "%") }); } this.move = function(box) { this.applyStyles({ top: this.formatStyle(box.top, "px"), bottom: this.formatStyle(box.bottom, "px"), left: this.formatStyle(box.left, "px"), right: this.formatStyle(box.right, "px"), height: this.formatStyle(box.height, "px"), width: this.formatStyle(box.width, "px") }); }; } CueStyleBox.prototype = _objCreate(StyleBox.prototype); CueStyleBox.prototype.constructor = CueStyleBox; // Represents the co-ordinates of an Element in a way that we can easily // compute things with such as if it overlaps or intersects with another Element. // Can initialize it with either a StyleBox or another BoxPosition. function BoxPosition(obj) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); // Either a BoxPosition was passed in and we need to copy it, or a StyleBox // was passed in and we need to copy the results of 'getBoundingClientRect' // as the object returned is readonly. All co-ordinate values are in reference // to the viewport origin (top left). var lh, height, width, top; if (obj.div) { height = obj.div.offsetHeight; width = obj.div.offsetWidth; top = obj.div.offsetTop; var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects(); obj = obj.div.getBoundingClientRect(); // In certain cases the outter div will be slightly larger then the sum of // the inner div's lines. This could be due to bold text, etc, on some platforms. // In this case we should get the average line height and use that. This will // result in the desired behaviour. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length) : 0; } this.left = obj.left; this.right = obj.right; this.top = obj.top || top; this.height = obj.height || height; this.bottom = obj.bottom || (top + (obj.height || height)); this.width = obj.width || width; this.lineHeight = lh !== undefined ? lh : obj.lineHeight; if (isIE8 && !this.lineHeight) { this.lineHeight = 13; } } // Move the box along a particular axis. Optionally pass in an amount to move // the box. If no amount is passed then the default is the line height of the // box. BoxPosition.prototype.move = function(axis, toMove) { toMove = toMove !== undefined ? toMove : this.lineHeight; switch (axis) { case "+x": this.left += toMove; this.right += toMove; break; case "-x": this.left -= toMove; this.right -= toMove; break; case "+y": this.top += toMove; this.bottom += toMove; break; case "-y": this.top -= toMove; this.bottom -= toMove; break; } }; // Check if this box overlaps another box, b2. BoxPosition.prototype.overlaps = function(b2) { return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top; }; // Check if this box overlaps any other boxes in boxes. BoxPosition.prototype.overlapsAny = function(boxes) { for (var i = 0; i < boxes.length; i++) { if (this.overlaps(boxes[i])) { return true; } } return false; }; // Check if this box is within another box. BoxPosition.prototype.within = function(container) { return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right; }; // Check if this box is entirely within the container or it is overlapping // on the edge opposite of the axis direction passed. For example, if "+x" is // passed and the box is overlapping on the left edge of the container, then // return true. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) { switch (axis) { case "+x": return this.left < container.left; case "-x": return this.right > container.right; case "+y": return this.top < container.top; case "-y": return this.bottom > container.bottom; } }; // Find the percentage of the area that this box is overlapping with another // box. BoxPosition.prototype.intersectPercentage = function(b2) { var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)), y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)), intersectArea = x * y; return intersectArea / (this.height * this.width); }; // Convert the positions from this box to CSS compatible positions using // the reference container's positions. This has to be done because this // box's positions are in reference to the viewport origin, whereas, CSS // values are in referecne to their respective edges. BoxPosition.prototype.toCSSCompatValues = function(reference) { return { top: this.top - reference.top, bottom: reference.bottom - this.bottom, left: this.left - reference.left, right: reference.right - this.right, height: this.height, width: this.width }; }; // Get an object that represents the box's position without anything extra. // Can pass a StyleBox, HTMLElement, or another BoxPositon. BoxPosition.getSimpleBoxPosition = function(obj) { var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0; var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0; var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0; obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj; var ret = { left: obj.left, right: obj.right, top: obj.top || top, height: obj.height || height, bottom: obj.bottom || (top + (obj.height || height)), width: obj.width || width }; return ret; }; // Move a StyleBox to its specified, or next best, position. The containerBox // is the box that contains the StyleBox, such as a div. boxPositions are // a list of other boxes that the styleBox can't overlap with. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) { // Find the best position for a cue box, b, on the video. The axis parameter // is a list of axis, the order of which, it will move the box along. For example: // Passing ["+x", "-x"] will move the box first along the x axis in the positive // direction. If it doesn't find a good position for it there it will then move // it along the x axis in the negative direction. function findBestPosition(b, axis) { var bestPosition, specifiedPosition = new BoxPosition(b), percentage = 1; // Highest possible so the first thing we get is better. for (var i = 0; i < axis.length; i++) { while (b.overlapsOppositeAxis(containerBox, axis[i]) || (b.within(containerBox) && b.overlapsAny(boxPositions))) { b.move(axis[i]); } // We found a spot where we aren't overlapping anything. This is our // best position. if (b.within(containerBox)) { return b; } var p = b.intersectPercentage(containerBox); // If we're outside the container box less then we were on our last try // then remember this position as the best position. if (percentage > p) { bestPosition = new BoxPosition(b); percentage = p; } // Reset the box position to the specified position. b = new BoxPosition(specifiedPosition); } return bestPosition || specifiedPosition; } var boxPosition = new BoxPosition(styleBox), cue = styleBox.cue, linePos = computeLinePos(cue), axis = []; // If we have a line number to align the cue to. if (cue.snapToLines) { var size; switch (cue.vertical) { case "": axis = [ "+y", "-y" ]; size = "height"; break; case "rl": axis = [ "+x", "-x" ]; size = "width"; break; case "lr": axis = [ "-x", "+x" ]; size = "width"; break; } var step = boxPosition.lineHeight, position = step * Math.round(linePos), maxPosition = containerBox[size] + step, initialAxis = axis[0]; // If the specified intial position is greater then the max position then // clamp the box to the amount of steps it would take for the box to // reach the max position. if (Math.abs(position) > maxPosition) { position = position < 0 ? -1 : 1; position *= Math.ceil(maxPosition / step) * step; } // If computed line position returns negative then line numbers are // relative to the bottom of the video instead of the top. Therefore, we // need to increase our initial position by the length or width of the // video, depending on the writing direction, and reverse our axis directions. if (linePos < 0) { position += cue.vertical === "" ? containerBox.height : containerBox.width; axis = axis.reverse(); } // Move the box to the specified position. This may not be its best // position. boxPosition.move(initialAxis, position); } else { // If we have a percentage line value for the cue. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100; switch (cue.lineAlign) { case "middle": linePos -= (calculatedPercentage / 2); break; case "end": linePos -= calculatedPercentage; break; } // Apply initial line position to the cue box. switch (cue.vertical) { case "": styleBox.applyStyles({ top: styleBox.formatStyle(linePos, "%") }); break; case "rl": styleBox.applyStyles({ left: styleBox.formatStyle(linePos, "%") }); break; case "lr": styleBox.applyStyles({ right: styleBox.formatStyle(linePos, "%") }); break; } axis = [ "+y", "-x", "+x", "-y" ]; // Get the box position again after we've applied the specified positioning // to it. boxPosition = new BoxPosition(styleBox); } var bestPosition = findBestPosition(boxPosition, axis); styleBox.move(bestPosition.toCSSCompatValues(containerBox)); } function WebVTT() { // Nothing } // Helper to allow strings to be decoded instead of the default binary utf8 data. WebVTT.StringDecoder = function() { return { decode: function(data) { if (!data) { return ""; } if (typeof data !== "string") { throw new Error("Error - expected string data."); } return decodeURIComponent(encodeURIComponent(data)); } }; }; WebVTT.convertCueToDOMTree = function(window, cuetext) { if (!window || !cuetext) { return null; } return parseContent(window, cuetext); }; var FONT_SIZE_PERCENT = 0.05; var FONT_STYLE = "sans-serif"; var CUE_BACKGROUND_PADDING = "1.5%"; // Runs the processing model over the cues and regions passed to it. // @param overlay A block level element (usually a div) that the computed cues // and regions will be placed into. WebVTT.processCues = function(window, cues, overlay) { if (!window || !cues || !overlay) { return null; } // Remove all previous children. while (overlay.firstChild) { overlay.removeChild(overlay.firstChild); } var paddedOverlay = window.document.createElement("div"); paddedOverlay.style.position = "absolute"; paddedOverlay.style.left = "0"; paddedOverlay.style.right = "0"; paddedOverlay.style.top = "0"; paddedOverlay.style.bottom = "0"; paddedOverlay.style.margin = CUE_BACKGROUND_PADDING; overlay.appendChild(paddedOverlay); // Determine if we need to compute the display states of the cues. This could // be the case if a cue's state has been changed since the last computation or // if it has not been computed yet. function shouldCompute(cues) { for (var i = 0; i < cues.length; i++) { if (cues[i].hasBeenReset || !cues[i].displayState) { return true; } } return false; } // We don't need to recompute the cues' display states. Just reuse them. if (!shouldCompute(cues)) { for (var i = 0; i < cues.length; i++) { paddedOverlay.appendChild(cues[i].displayState); } return; } var boxPositions = [], containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay), fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100; var styleOptions = { font: fontSize + "px " + FONT_STYLE }; (function() { var styleBox, cue; for (var i = 0; i < cues.length; i++) { cue = cues[i]; // Compute the intial position and styles of the cue div. styleBox = new CueStyleBox(window, cue, styleOptions); paddedOverlay.appendChild(styleBox.div); // Move the cue div to it's correct line position. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions); // Remember the computed div so that we don't have to recompute it later // if we don't have too. cue.displayState = styleBox.div; boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox)); } })(); }; WebVTT.Parser = function(window, vttjs, decoder) { if (!decoder) { decoder = vttjs; vttjs = {}; } if (!vttjs) { vttjs = {}; } this.window = window; this.vttjs = vttjs; this.state = "INITIAL"; this.buffer = ""; this.decoder = decoder || new TextDecoder("utf8"); this.regionList = []; }; WebVTT.Parser.prototype = { // If the error is a ParsingError then report it to the consumer if // possible. If it's not a ParsingError then throw it like normal. reportOrThrowError: function(e) { if (e instanceof ParsingError) { this.onparsingerror && this.onparsingerror(e); } else { throw e; } }, parse: function (data) { var self = this; // If there is no data then we won't decode it, but will just try to parse // whatever is in buffer already. This may occur in circumstances, for // example when flush() is called. if (data) { // Try to decode the data that we received. self.buffer += self.decoder.decode(data, {stream: true}); } function collectNextLine() { var buffer = self.buffer; var pos = 0; while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') { ++pos; } var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below. if (buffer[pos] === '\r') { ++pos; } if (buffer[pos] === '\n') { ++pos; } self.buffer = buffer.substr(pos); return line; } // 3.4 WebVTT region and WebVTT region settings syntax function parseRegion(input) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "id": settings.set(k, v); break; case "width": settings.percent(k, v); break; case "lines": settings.integer(k, v); break; case "regionanchor": case "viewportanchor": var xy = v.split(','); if (xy.length !== 2) { break; } // We have to make sure both x and y parse, so use a temporary // settings object here. var anchor = new Settings(); anchor.percent("x", xy[0]); anchor.percent("y", xy[1]); if (!anchor.has("x") || !anchor.has("y")) { break; } settings.set(k + "X", anchor.get("x")); settings.set(k + "Y", anchor.get("y")); break; case "scroll": settings.alt(k, v, ["up"]); break; } }, /=/, /\s/); // Create the region, using default values for any values that were not // specified. if (settings.has("id")) { var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)(); region.width = settings.get("width", 100); region.lines = settings.get("lines", 3); region.regionAnchorX = settings.get("regionanchorX", 0); region.regionAnchorY = settings.get("regionanchorY", 100); region.viewportAnchorX = settings.get("viewportanchorX", 0); region.viewportAnchorY = settings.get("viewportanchorY", 100); region.scroll = settings.get("scroll", ""); // Register the region. self.onregion && self.onregion(region); // Remember the VTTRegion for later in case we parse any VTTCues that // reference it. self.regionList.push({ id: settings.get("id"), region: region }); } } // 3.2 WebVTT metadata header syntax function parseHeader(input) { parseOptions(input, function (k, v) { switch (k) { case "Region": // 3.3 WebVTT region metadata header syntax parseRegion(v); break; } }, /:/); } // 5.1 WebVTT file parsing. try { var line; if (self.state === "INITIAL") { // We can't start parsing until we have the first line. if (!/\r\n|\n/.test(self.buffer)) { return this; } line = collectNextLine(); var m = line.match(/^WEBVTT([ \t].*)?$/); if (!m || !m[0]) { throw new ParsingError(ParsingError.Errors.BadSignature); } self.state = "HEADER"; } var alreadyCollectedLine = false; while (self.buffer) { // We can't parse a line until we have the full line. if (!/\r\n|\n/.test(self.buffer)) { return this; } if (!alreadyCollectedLine) { line = collectNextLine(); } else { alreadyCollectedLine = false; } switch (self.state) { case "HEADER": // 13-18 - Allow a header (metadata) under the WEBVTT line. if (/:/.test(line)) { parseHeader(line); } else if (!line) { // An empty line terminates the header and starts the body (cues). self.state = "ID"; } continue; case "NOTE": // Ignore NOTE blocks. if (!line) { self.state = "ID"; } continue; case "ID": // Check for the start of NOTE blocks. if (/^NOTE($|[ \t])/.test(line)) { self.state = "NOTE"; break; } // 19-29 - Allow any number of line terminators, then initialize new cue values. if (!line) { continue; } self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, ""); self.state = "CUE"; // 30-39 - Check if self line contains an optional identifier or timing data. if (line.indexOf("-->") === -1) { self.cue.id = line; continue; } // Process line as start of a cue. /*falls through*/ case "CUE": // 40 - Collect cue timings and settings. try { parseCue(line, self.cue, self.regionList); } catch (e) { self.reportOrThrowError(e); // In case of an error ignore rest of the cue. self.cue = null; self.state = "BADCUE"; continue; } self.state = "CUETEXT"; continue; case "CUETEXT": var hasSubstring = line.indexOf("-->") !== -1; // 34 - If we have an empty line then report the cue. // 35 - If we have the special substring '-->' then report the cue, // but do not collect the line as we need to process the current // one as a new cue. if (!line || hasSubstring && (alreadyCollectedLine = true)) { // We are done parsing self cue. self.oncue && self.oncue(self.cue); self.cue = null; self.state = "ID"; continue; } if (self.cue.text) { self.cue.text += "\n"; } self.cue.text += line; continue; case "BADCUE": // BADCUE // 54-62 - Collect and discard the remaining cue. if (!line) { self.state = "ID"; } continue; } } } catch (e) { self.reportOrThrowError(e); // If we are currently parsing a cue, report what we have. if (self.state === "CUETEXT" && self.cue && self.oncue) { self.oncue(self.cue); } self.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise // another exception occurred so enter BADCUE state. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE"; } return this; }, flush: function () { var self = this; try { // Finish decoding the stream. self.buffer += self.decoder.decode(); // Synthesize the end of the current cue or region. if (self.cue || self.state === "HEADER") { self.buffer += "\n\n"; self.parse(); } // If we've flushed, parsed, and we're still on the INITIAL state then // that means we don't have enough of the stream to parse the first // line. if (self.state === "INITIAL") { throw new ParsingError(ParsingError.Errors.BadSignature); } } catch(e) { self.reportOrThrowError(e); } self.onflush && self.onflush(); return this; } }; global.WebVTT = WebVTT; }(this, (this.vttjs || {})));
from distutils.core import setup, Extension demos_encrypt = Extension('demos_encrypt', sources = ['/Users/carey/Downloads/EC-ElGamal/BNsupport.cpp', '/Users/carey/Downloads/EC-ElGamal/bn_pair.cpp', '/Users/carey/Downloads/EC-ElGamal/zzn12a.cpp', '/Users/carey/Downloads/EC-ElGamal/ecn2.cpp', '/Users/carey/Downloads/EC-ElGamal/zzn4.cpp', '/Users/carey/Downloads/EC-ElGamal/zzn2.cpp', '/Users/carey/Downloads/EC-ElGamal/big.cpp', '/Users/carey/Downloads/EC-ElGamal/zzn.cpp', '/Users/carey/Downloads/EC-ElGamal/ecn.cpp'], include_dirs = ['/Users/carey/Downloads/EC-ElGamal'], library_dirs = ['/Users/carey/Downloads/EC-ElGamal'], extra_link_args=[''], libraries=['miracl']) setup (name = 'demos_encrypt', version = '1.0', description = 'This is the demos2 package', ext_modules = [demos_encrypt])
/* eslint no-underscore-dangle: "off" */ import { Button, Checkbox, Form, Input, Select, message } from 'antd'; // import classNames from 'classnames/bind'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createStakeholder } from '../../../../../../common/API'; import { addStakeholder, updateStakeholder } from '../../../../actions'; // import styles from './styles.css'; // const cx = classNames.bind(styles); const FormItem = Form.Item; const { Option } = Select; const CheckboxGroup = Checkbox.Group; class StakeholderForm extends Component { // state = { errorMsg: '', submitting: false }; state = { submitting: false }; componentDidMount() { const { stakeholder, form } = this.props; if (stakeholder) { const formFields = Object.keys(form.getFieldsValue()); // set field values only available in a form to prevent // antd warning i.e you cannot set field before registering it. const fieldsValues = {}; formFields.forEach(field => { if (field === 'role') { fieldsValues[field] = stakeholder[field] && stakeholder[field]._id; } else { fieldsValues[field] = stakeholder[field]; } return fieldsValues[field]; }); form.setFieldsValue(fieldsValues); } } componentWillReceiveProps(nextProps) { if (nextProps.updatingStakeholder !== this.props.updatingStakeholder) { if (!nextProps.updatingStakeholder) { // stakeholder updating done, close the form this.props.onCancel(); } } } handleSubmit = e => { e.preventDefault(); const { form } = this.props; form.validateFieldsAndScroll((err, data) => { if (!err) { const { stakeholder } = this.props; if (stakeholder) { this.patchStakeholder(stakeholder._id, data); } else { this.createStakeholder(data); } } }); }; /** * Create stakeholder helper function */ createStakeholder = data => { const { onCancel } = this.props; this.setState({ submitting: true }); createStakeholder(data) .then(result => { // submitted successfully this.props.addStakeholder(result); this.setState({ submitting: false }); message.success('New stakeholder successfully added'); onCancel(); }) .catch(() => { // There is an error upon submitting this.setState({ submitting: false }); message.error('Adding new stakeholder failed'); }); }; patchStakeholder = (stakeholderId, updates) => { this.props.updateStakeholder(stakeholderId, updates); }; render() { const { onCancel, form, phases, types, predRoles, stakeholder, updatingStakeholder, } = this.props; const { submitting } = this.state; const { getFieldDecorator } = form; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 4 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 16 }, }, }; const tailFormItemLayout = { wrapperCol: { xs: { span: 24, offset: 0, }, sm: { span: 16, offset: 8, }, }, }; const prefixSelector = getFieldDecorator('prefix', { initialValue: '255', })( <Select style={{ width: 80 }}> <Option value="255">+255</Option> <Option value="254">+254</Option> </Select> ); return ( <div> <Form onSubmit={this.handleSubmit}> <FormItem label="Name" {...formItemLayout}> {getFieldDecorator('name', { rules: [ { required: true, message: 'Please input stakeholder name!' }, ], })(<Input placeholder="Stakeholder Name" />)} </FormItem> <FormItem label="Mobile" {...formItemLayout}> {getFieldDecorator('mobile', { rules: [ { required: true, message: 'Please input mobile number!' }, ], })( <Input addonBefore={prefixSelector} placeholder="Mobile Number" /> )} </FormItem> <FormItem label="Email" {...formItemLayout}> {getFieldDecorator('email', { rules: [ { type: 'email', message: 'The input is not valid E-mail!', }, { required: true, message: 'Please input stakeholder E-mail!', }, ], })(<Input placeholder="Email" />)} </FormItem> <FormItem label="Type" {...formItemLayout}> {getFieldDecorator('type', { rules: [ { required: true, message: 'Please select stakeholder category', }, ], })( <Select placeholder="Select Type"> {types.map(type => ( <Option key={type} value={type}> {type} </Option> ))} </Select> )} </FormItem> <FormItem label="Role" {...formItemLayout}> {getFieldDecorator('role')( <Select placeholder="Select Role"> {predRoles.map(predRole => ( <Option key={predRole._id} value={predRole._id}> {predRole.name} </Option> ))} </Select> )} </FormItem> <FormItem label="Physical Address" {...formItemLayout}> {getFieldDecorator('physicalAddress')( <Input placeholder="Physical Address" /> )} </FormItem> <FormItem label="Postal Address" {...formItemLayout}> {getFieldDecorator('postalAddress')( <Input placeholder="Postal Address" /> )} </FormItem> <FormItem label="Fax" {...formItemLayout}> {getFieldDecorator('fax')(<Input placeholder="Fax" />)} </FormItem> <FormItem label="Website" {...formItemLayout}> {getFieldDecorator('website')(<Input placeholder="Website" />)} </FormItem> <FormItem label="Phase" {...formItemLayout}> {getFieldDecorator('phases', { initialValue: ['Mitigation'] })( <CheckboxGroup options={phases} /> )} </FormItem> <FormItem {...tailFormItemLayout}> <Button onClick={onCancel}>Cancel</Button> {stakeholder ? ( <Button type="primary" htmlType="submit" style={{ marginLeft: 8 }} loading={updatingStakeholder} > Update </Button> ) : ( <Button type="primary" htmlType="submit" style={{ marginLeft: 8 }} loading={submitting} > Save </Button> )} </FormItem> </Form> </div> ); } } const mapStateToProps = state => { const { schema, predRoles, updatingStakeholder } = state.stakeholders; const { phases, type } = schema.properties; return { phases: phases.enum, types: type.enum.reverse(), predRoles: predRoles.data, updatingStakeholder, }; }; export default connect( mapStateToProps, { addStakeholder, updateStakeholder, } )(Form.create()(StakeholderForm));
import { test } from '../qunit'; import { localeModule } from '../qunit-locale'; import moment from '../../moment'; localeModule('gom-deva'); test('parse', function (assert) { var i, tests = 'जानेवारी जाने._फेब्रुवारी फेब्रु._मार्च मार्च_एप्रील एप्री._मे मे_जून जून_जुलय जुल._ऑगस्ट ऑग._सप्टेंबर सप्टें._ऑक्टोबर ऑक्टो._नोव्हेंबर नोव्हें._डिसेंबर डिसें.'.split( '_' ); function equalTest(input, mmm, i) { assert.equal( moment(input, mmm).month(), i, input + ' should be month ' + (i + 1) ); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ [ 'dddd, MMMM Do YYYY, h:mm:ss a', 'आयतार, फेब्रुवारीच्या 14वेर 2010, 3:25:50 दनपारां', ], ['ddd, h A', 'आयत., 3 दनपारां'], ['M Mo MM MMMM MMM', '2 2 02 फेब्रुवारी फेब्रु.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14वेर 14'], ['d do dddd ddd dd', '0 0 आयतार आयत. आ'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '7 7 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'दनपारां दनपारां'], ['[वर्साचो] DDDo[वो दीस]', 'वर्साचो 45वो दीस'], ['LTS', 'दनपारां 3:25:50 वाजतां'], ['L', '14-02-2010'], ['LL', '14 फेब्रुवारी 2010'], ['LLL', '14 फेब्रुवारी 2010 दनपारां 3:25 वाजतां'], ['LLLL', 'आयतार, फेब्रुवारीच्या 14वेर, 2010, दनपारां 3:25 वाजतां'], ['l', '14-2-2010'], ['ll', '14 फेब्रु. 2010'], ['lll', '14 फेब्रु. 2010 दनपारां 3:25 वाजतां'], ['llll', 'आयत., 14 फेब्रु. 2010, दनपारां 3:25 वाजतां'], ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var i, expected = 'जानेवारी जाने._फेब्रुवारी फेब्रु._मार्च मार्च_एप्रील एप्री._मे मे_जून जून_जुलय जुल._ऑगस्ट ऑग._सप्टेंबर सप्टें._ऑक्टोबर ऑक्टो._नोव्हेंबर नोव्हें._डिसेंबर डिसें.'.split( '_' ); for (i = 0; i < expected.length; i++) { assert.equal( moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i] ); } }); test('format week', function (assert) { var i, expected = 'आयतार आयत. आ_सोमार सोम. सो_मंगळार मंगळ. मं_बुधवार बुध. बु_बिरेस्तार ब्रेस्त. ब्रे_सुक्रार सुक्र. सु_शेनवार शेन. शे'.split( '_' ); for (i = 0; i < expected.length; i++) { assert.equal( moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i] ); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal( start.from(moment([2007, 1, 28]).add({ s: 44 }), true), 'थोडे सॅकंड', '44 seconds = a few seconds' ); assert.equal( start.from(moment([2007, 1, 28]).add({ s: 45 }), true), 'एक मिनूट', '45 seconds = a minute' ); assert.equal( start.from(moment([2007, 1, 28]).add({ s: 89 }), true), 'एक मिनूट', '89 seconds = a minute' ); assert.equal( start.from(moment([2007, 1, 28]).add({ s: 90 }), true), '2 मिणटां', '90 seconds = 2 minutes' ); assert.equal( start.from(moment([2007, 1, 28]).add({ m: 44 }), true), '44 मिणटां', '44 minutes = 44 minutes' ); assert.equal( start.from(moment([2007, 1, 28]).add({ m: 45 }), true), 'एक वर', '45 minutes = an hour' ); assert.equal( start.from(moment([2007, 1, 28]).add({ m: 89 }), true), 'एक वर', '89 minutes = an hour' ); assert.equal( start.from(moment([2007, 1, 28]).add({ m: 90 }), true), '2 वरां', '90 minutes = 2 hours' ); assert.equal( start.from(moment([2007, 1, 28]).add({ h: 5 }), true), '5 वरां', '5 hours = 5 hours' ); assert.equal( start.from(moment([2007, 1, 28]).add({ h: 21 }), true), '21 वरां', '21 hours = 21 hours' ); assert.equal( start.from(moment([2007, 1, 28]).add({ h: 22 }), true), 'एक दीस', '22 hours = a day' ); assert.equal( start.from(moment([2007, 1, 28]).add({ h: 35 }), true), 'एक दीस', '35 hours = a day' ); assert.equal( start.from(moment([2007, 1, 28]).add({ h: 36 }), true), '2 दीस', '36 hours = 2 days' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 1 }), true), 'एक दीस', '1 day = a day' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 5 }), true), '5 दीस', '5 days = 5 days' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 25 }), true), '25 दीस', '25 days = 25 days' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 26 }), true), 'एक म्हयनो', '26 days = a month' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 30 }), true), 'एक म्हयनो', '30 days = a month' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 43 }), true), 'एक म्हयनो', '43 days = a month' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 46 }), true), '2 म्हयने', '46 days = 2 months' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 74 }), true), '2 म्हयने', '75 days = 2 months' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 76 }), true), '3 म्हयने', '76 days = 3 months' ); assert.equal( start.from(moment([2007, 1, 28]).add({ M: 1 }), true), 'एक म्हयनो', '1 month = a month' ); assert.equal( start.from(moment([2007, 1, 28]).add({ M: 5 }), true), '5 म्हयने', '5 months = 5 months' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 345 }), true), 'एक वर्स', '345 days = a year' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 548 }), true), '2 वर्सां', '548 days = 2 years' ); assert.equal( start.from(moment([2007, 1, 28]).add({ y: 1 }), true), 'एक वर्स', '1 year = a year' ); assert.equal( start.from(moment([2007, 1, 28]).add({ y: 5 }), true), '5 वर्सां', '5 years = 5 years' ); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'थोडया सॅकंडांनी', 'prefix'); assert.equal(moment(0).from(30000), 'थोडे सॅकंड आदीं', 'suffix'); }); test('now from now', function (assert) { assert.equal( moment().fromNow(), 'थोडे सॅकंड आदीं', 'now from now should display as in the past' ); }); test('fromNow', function (assert) { assert.equal( moment().add({ s: 30 }).fromNow(), 'थोडया सॅकंडांनी', 'in a few seconds' ); assert.equal(moment().add({ d: 5 }).fromNow(), '5 दिसांनी', 'in 5 days'); }); test('ago', function (assert) { assert.equal( moment().subtract({ h: 3 }).fromNow(), '3 वरां आदीं', '3 hours ago' ); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal( moment(a).calendar(), 'आयज दनपारां 12:00 वाजतां', 'today at the same time' ); assert.equal( moment(a).add({ m: 25 }).calendar(), 'आयज दनपारां 12:25 वाजतां', 'Now plus 25 min' ); assert.equal( moment(a).add({ h: 1 }).calendar(), 'आयज दनपारां 1:00 वाजतां', 'Now plus 1 hour' ); assert.equal( moment(a).add({ d: 1 }).calendar(), 'फाल्यां दनपारां 12:00 वाजतां', 'tomorrow at the same time' ); assert.equal( moment(a).subtract({ h: 1 }).calendar(), 'आयज सकाळीं 11:00 वाजतां', 'Now minus 1 hour' ); assert.equal( moment(a).subtract({ d: 1 }).calendar(), 'काल दनपारां 12:00 वाजतां', 'yesterday at the same time' ); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({ d: i }); assert.equal( m.calendar(), m.format('[फुडलो] dddd[,] LT'), 'Today + ' + i + ' days current time' ); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal( m.calendar(), m.format('[फुडलो] dddd[,] LT'), 'Today + ' + i + ' days beginning of day' ); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal( m.calendar(), m.format('[फुडलो] dddd[,] LT'), 'Today + ' + i + ' days end of day' ); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({ d: i }); assert.equal( m.calendar(), m.format('[फाटलो] dddd[,] LT'), 'Today - ' + i + ' days current time' ); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal( m.calendar(), m.format('[फाटलो] dddd[,] LT'), 'Today - ' + i + ' days beginning of day' ); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal( m.calendar(), m.format('[फाटलो] dddd[,] LT'), 'Today - ' + i + ' days end of day' ); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({ w: 1 }), weeksFromNow = moment().add({ w: 1 }); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal( weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week' ); weeksAgo = moment().subtract({ w: 2 }); weeksFromNow = moment().add({ w: 2 }); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal( weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks' ); }); test('weeks year starting sunday format', function (assert) { assert.equal( moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1' ); assert.equal( moment([2012, 0, 2]).format('w ww wo'), '1 01 1', 'Jan 2 2012 should be week 1' ); assert.equal( moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2' ); assert.equal( moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 should be week 2' ); assert.equal( moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3' ); });
import itertools from microbenchmarks._metric import MetricType from microbenchmarks._utils import get_ti_arch, tags2name import taichi as ti class Funcs(): def __init__(self): self._funcs = {} def add_func(self, tag_list: list, func): self._funcs[tags2name(tag_list)] = {'tags': tag_list, 'func': func} def get_func(self, tags): for name, item in self._funcs.items(): if set(item['tags']).issubset(tags): return item['func'] return None class BenchmarkPlan: def __init__(self, name='plan', arch='x64', basic_repeat_times=1): self.name = name self.arch = arch self.basic_repeat_times = basic_repeat_times self.info = {'name': self.name} self.plan = {} # {'tags': [...], 'result': None} self.items = [] self.funcs = Funcs() def create_plan(self, *items): self.items = list(items) items_list = [[self.name]] for item in self.items: items_list.append(item.get_tags()) self.info[item.name] = item.get_tags() case_list = list(itertools.product(*items_list)) #items generate cases for tags in case_list: self.plan[tags2name(tags)] = {'tags': tags, 'result': None} def add_func(self, tag_list, func): self.funcs.add_func(tag_list, func) def run(self): for case, plan in self.plan.items(): tag_list = plan['tags'] MetricType.init_taichi(self.arch, tag_list) _ms = self.funcs.get_func(tag_list)(self.arch, self.basic_repeat_times, **self._get_kwargs(tag_list)) plan['result'] = _ms print(f'{tag_list}={_ms}') ti.reset() rdict = {'results': self.plan, 'info': self.info} return rdict def _get_kwargs(self, tags): kwargs = {} tags = tags[1:] # tags = [case_name, item1_tag, item2_tag, ...] for item, tag in zip(self.items, tags): kwargs[item.name] = item.impl(tag) return kwargs
/** @namespace x3dom.nodeTypes */ /* * X3DOM JavaScript Library * http://www.x3dom.org * * (C)2009 Fraunhofer IGD, Darmstadt, Germany * Dual licensed under the MIT and GPL */ /* ### FontStyle ### */ x3dom.registerNodeType( "FontStyle", "Text", defineClass(x3dom.nodeTypes.X3DFontStyleNode, /** * Constructor for FontStyle * @constructs x3dom.nodeTypes.FontStyle * @x3d 3.3 * @component Text * @status full * @extends x3dom.nodeTypes.X3DFontStyleNode * @param {Object} [ctx=null] - context object, containing initial settings like namespace * @classdesc The FontStyle node defines the size, family, and style used for Text nodes, as well as the direction of the text strings and any language-specific rendering techniques used for non-English text. */ function (ctx) { x3dom.nodeTypes.FontStyle.superClass.call(this, ctx); /** * Defines the text family. * @var {x3dom.fields.MFString} family * @memberof x3dom.nodeTypes.FontStyle * @initvalue ['SERIF'] * @field x3d * @instance */ this.addField_MFString(ctx, 'family', ['SERIF']); /** * Specifies whether the text is shown horizontally or vertically. * @var {x3dom.fields.SFBool} horizontal * @memberof x3dom.nodeTypes.FontStyle * @initvalue true * @field x3d * @instance */ this.addField_SFBool(ctx, 'horizontal', true); /** * Specifies where the text is anchored. The default of ["MIDDLE", "MIDDLE"] deviates from the ISO spec. default * of ["BEGIN", "FIRST"] for backward compatibiliy reasons. * @var {x3dom.fields.MFString} justify * @range ["BEGIN","END","FIRST","MIDDLE",""] * @memberof x3dom.nodeTypes.FontStyle * @initvalue ['MIDDLE', 'MIDDLE'] * @field x3d * @instance */ this.addField_MFString(ctx, 'justify', ['MIDDLE', 'MIDDLE']); /** * The language field specifies the context of the language for the text string in the form of a language and a country in which that language is used. * @var {x3dom.fields.SFString} language * @memberof x3dom.nodeTypes.FontStyle * @initvalue "" * @field x3d * @instance */ this.addField_SFString(ctx, 'language', ""); /** * Specifies whether the text is shown from left to right or from right to left. * @var {x3dom.fields.SFBool} leftToRight * @memberof x3dom.nodeTypes.FontStyle * @initvalue true * @field x3d * @instance */ this.addField_SFBool(ctx, 'leftToRight', true); /** * Sets the size of the text. * @var {x3dom.fields.SFFloat} size * @range [0, inf] * @memberof x3dom.nodeTypes.FontStyle * @initvalue 1.0 * @field x3d * @instance */ this.addField_SFFloat(ctx, 'size', 1.0); /** * Sets the spacing between lines of text, relative to the text size. * @var {x3dom.fields.SFFloat} spacing * @range [0, inf] * @memberof x3dom.nodeTypes.FontStyle * @initvalue 1.0 * @field x3d * @instance */ this.addField_SFFloat(ctx, 'spacing', 1.0); /** * Sets the text style. * @var {x3dom.fields.SFString} style * @range ["PLAIN","BOLD","ITALIC","BOLDITALIC",""] * @memberof x3dom.nodeTypes.FontStyle * @initvalue "PLAIN" * @field x3d * @instance */ this.addField_SFString(ctx, 'style', "PLAIN"); /** * Specifies whether the text flows from top to bottom or from bottom to top. * @var {x3dom.fields.SFBool} topToBottom * @memberof x3dom.nodeTypes.FontStyle * @initvalue true * @field x3d * @instance */ this.addField_SFBool(ctx, 'topToBottom', true); /** * Sets the quality of the text rendering as an oversampling factor. * @var {x3dom.fields.SFFloat} quality * @range [0, inf] * @memberof x3dom.nodeTypes.FontStyle * @initvalue 2.0 * @field x3dom * @instance */ this.addField_SFFloat(ctx, 'quality', 2.0); }, { fieldChanged: function(fieldName) { if (fieldName == 'family' || fieldName == 'horizontal' || fieldName == 'justify' || fieldName == 'language' || fieldName == 'leftToRight' || fieldName == 'size' || fieldName == 'spacing' || fieldName == 'style' || fieldName == 'topToBottom') { Array.forEach(this._parentNodes, function (node) { Array.forEach(node._parentNodes, function (textnode) { textnode.setAllDirty(); }); }); } } } ) ); x3dom.nodeTypes.FontStyle.defaultNode = function() { if (!x3dom.nodeTypes.FontStyle._defaultNode) { x3dom.nodeTypes.FontStyle._defaultNode = new x3dom.nodeTypes.FontStyle(); x3dom.nodeTypes.FontStyle._defaultNode.nodeChanged(); } return x3dom.nodeTypes.FontStyle._defaultNode; };
import { API_V1 } from '../../../../lib/util/Constants'; import { list as mockList, offlineActivityInstance as mockInstance, activitiesPage0 as mockPage0, activitiesPage1 as mockPage1 } from '../../../mock/Activities'; import { token } from '../../../mock/Token'; import { WorkerConfig } from '../../../mock/WorkerConfig'; const chai = require('chai'); const assert = chai.assert; const expect = chai.expect; chai.use(require('chai-datetime')); chai.should(); const sinon = require('sinon'); import Configuration from '../../../../lib/util/Configuration'; import ActivitiesEntity from '../../../../lib/data/ActivitiesEntity'; import Request from '../../../../lib/util/Request'; import Worker from '../../../../lib/Worker'; import Routes from '../../../../lib/util/Routes'; describe('Activities', () => { const worker = new Worker(token, WorkerConfig); const config = new Configuration(token); const routes = new Routes('WSxxx', 'WKxxx'); sinon.stub(worker, 'getRoutes').returns(routes); describe('constructor', () => { it('should throw an error if the worker is missing', () => { (() => { new ActivitiesEntity(); }).should.throw(/worker is a required parameter/); }); it('should use the default pageSize=1000, if none provided', () => { const activitiesServices = new ActivitiesEntity(worker, new Request(config)); assert.equal(activitiesServices._pageSize, 1000); }); it('should use the pageSize, if provided', () => { const activitiesServices = new ActivitiesEntity(worker, new Request(config), { pageSize: 50 }); assert.equal(activitiesServices._pageSize, 50); }); }); describe('#fetchActivities', () => { let sandbox; const requestURL = 'Workspaces/WSxxx/Activities'; beforeEach(() => { sandbox = sinon.sandbox.create(); }); afterEach(() => { sandbox.restore(); }); it('should fetch all activities', () => { const requestParams = { PageSize: 1000 }; sandbox.stub(Request.prototype, 'get').withArgs(requestURL, API_V1, requestParams).returns(Promise.resolve(mockList)); const activitiesServices = new ActivitiesEntity(worker, new Request(config)); return activitiesServices.fetchActivities().then(() => { expect(activitiesServices.activities.size).to.equal(mockList.contents.length); activitiesServices.activities.forEach(activity => { if (activity.name === 'Offline') { expect(activity.accountSid).to.equal(mockInstance.account_sid); expect(activity.sid).to.equal(mockInstance.sid); expect(activity.dateCreated).to.equalDate(new Date(mockInstance.date_created * 1000)); expect(activity.dateUpdated).to.equalDate(new Date(mockInstance.date_updated * 1000)); expect(activity.available).to.equal(mockInstance.available); expect(activity.isCurrent).to.equal(false); expect(activity.name).to.equal(mockInstance.friendly_name); } }); }); }); it('should paginate for the next page if needed', () => { const requestParamsPage0 = { PageSize: 5 }; const requestParamsPage1 = { PageSize: 5, AfterSid: 'WAxx5' }; const s = sandbox.stub(Request.prototype, 'get'); s.withArgs(requestURL, API_V1, requestParamsPage0).returns(Promise.resolve(mockPage0)); s.withArgs(requestURL, API_V1, requestParamsPage1).returns(Promise.resolve(mockPage1)); const activitiesServices = new ActivitiesEntity(worker, new Request(config), { pageSize: 5 }); return activitiesServices.fetchActivities().then(() => { expect(activitiesServices.activities.size).to.equal(mockPage0.total); activitiesServices.activities.forEach(activity => { if (activity.name === 'Offline') { expect(activity.accountSid).to.equal(mockInstance.account_sid); expect(activity.sid).to.equal(mockInstance.sid); expect(activity.dateCreated).to.equalDate(new Date(mockInstance.date_created * 1000)); expect(activity.dateUpdated).to.equalDate(new Date(mockInstance.date_updated * 1000)); expect(activity.available).to.equal(mockInstance.available); expect(activity.isCurrent).to.equal(false); expect(activity.name).to.equal(mockInstance.friendly_name); } }); }); }); }); });
#------------------------------------------ EXTRACT DATA FROM pdf_json ------------------------------------------------- # # Insert cite spans from json files into our database, # primary key(paper_id,ref_id), foreign key:(paper_id) # we are going to have 6 columns: paper_id, paragraph_number,start_text, end_text, text_span, ref_id # #-------------------------------------------------------------------------------------------------------------------------------- import pandas as pd import unicodedata import re import string import csv import os, json import itertools from joblib import Parallel, delayed import collections from collections import Counter,defaultdict,OrderedDict,namedtuple import mysql.connector from settings import DB_CREDS cnx = mysql.connector.connect( host = DB_CREDS['host'], user = DB_CREDS['user'], passwd = DB_CREDS['pass'], database = DB_CREDS['db'] ) cursor = cnx.cursor() #get all json files from pdf_json folder path_to_json = 'pdf_json/' json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')] for index, js in enumerate(json_files): with open(os.path.join(path_to_json, js)) as json_file: json_text = json.load(json_file) paper_id = json_text['paper_id'] #get cite spans for spot, j in enumerate(json_text['abstract']): if json_text['abstract'][spot]['cite_spans'] != []: for count, k in enumerate(json_text['abstract'][spot]['cite_spans']): start = json_text['abstract'][spot]['cite_spans'][count]['start'] end = json_text['abstract'][spot]['cite_spans'][count]['end'] text = json_text['abstract'][spot]['cite_spans'][count]['text'] ref_id = json_text['abstract'][spot]['cite_spans'][count]['ref_id'] span_data = (paper_id,spot,start,end,text,ref_id) add_data = ("INSERT IGNORE INTO cite_span_abstract " "(paper_id,paragraph_number,start_text,end_text,text_span,ref_id)" "VALUES (%s,%s,%s,%s,%s,%s)") cursor.execute(add_data,span_data) cnx.commit() cursor.close() cnx.close()
var app = angular.module("ToDoApp") app.controller("AddTaskController", function ($scope, TaskDbService, $location, UserDbService) { if (!UserDbService.isAuthenticated()) { $location.path('/login') } $scope.task = TaskDbService.newTask(); $scope.isNew = true; $scope.saveTask = function () { TaskDbService.addTask($scope.task) $location.path('/') }; $scope.cancelTask = function () { $location.path('/') } });
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createFastDomNode } from '../../../../base/browser/fastDomNode.js'; import { ViewPart } from '../../view/viewPart.js'; export class Margin extends ViewPart { constructor(context) { super(context); const options = this._context.configuration.options; const layoutInfo = options.get(128 /* layoutInfo */); this._canUseLayerHinting = !options.get(26 /* disableLayerHinting */); this._contentLeft = layoutInfo.contentLeft; this._glyphMarginLeft = layoutInfo.glyphMarginLeft; this._glyphMarginWidth = layoutInfo.glyphMarginWidth; this._domNode = createFastDomNode(document.createElement('div')); this._domNode.setClassName(Margin.OUTER_CLASS_NAME); this._domNode.setPosition('absolute'); this._domNode.setAttribute('role', 'presentation'); this._domNode.setAttribute('aria-hidden', 'true'); this._glyphMarginBackgroundDomNode = createFastDomNode(document.createElement('div')); this._glyphMarginBackgroundDomNode.setClassName(Margin.CLASS_NAME); this._domNode.appendChild(this._glyphMarginBackgroundDomNode); } dispose() { super.dispose(); } getDomNode() { return this._domNode; } // --- begin event handlers onConfigurationChanged(e) { const options = this._context.configuration.options; const layoutInfo = options.get(128 /* layoutInfo */); this._canUseLayerHinting = !options.get(26 /* disableLayerHinting */); this._contentLeft = layoutInfo.contentLeft; this._glyphMarginLeft = layoutInfo.glyphMarginLeft; this._glyphMarginWidth = layoutInfo.glyphMarginWidth; return true; } onScrollChanged(e) { return super.onScrollChanged(e) || e.scrollTopChanged; } // --- end event handlers prepareRender(ctx) { // Nothing to read } render(ctx) { this._domNode.setLayerHinting(this._canUseLayerHinting); this._domNode.setContain('strict'); const adjustedScrollTop = ctx.scrollTop - ctx.bigNumbersDelta; this._domNode.setTop(-adjustedScrollTop); const height = Math.min(ctx.scrollHeight, 1000000); this._domNode.setHeight(height); this._domNode.setWidth(this._contentLeft); this._glyphMarginBackgroundDomNode.setLeft(this._glyphMarginLeft); this._glyphMarginBackgroundDomNode.setWidth(this._glyphMarginWidth); this._glyphMarginBackgroundDomNode.setHeight(height); } } Margin.CLASS_NAME = 'glyph-margin'; Margin.OUTER_CLASS_NAME = 'margin';
from flask import current_app as app class userProductReview: def __init__(self, product_id, product_name, seller_id, seller_fname, seller_lname, num_stars, date, description, upvotes, images): self.product_id = product_id self.product_name = product_name self.seller_id = seller_id self.seller_name = seller_fname + ' ' + seller_lname self.num_stars = num_stars self.date = date self.description = description self.upvotes = upvotes self.images = images @staticmethod ##method to get all product reviews written by user with user_id in reverse chronological order def get(user_id): rows = app.db.execute(''' SELECT pr.product_id, p.name, pr.seller_id, a.firstname, a.lastname, num_stars, date, pr.description, upvotes, pr.images FROM ProductReview pr, Product p, Account a WHERE pr.buyer_id = :user_id AND pr.product_id = p.product_id AND pr.seller_id = a.account_id ORDER BY date DESC ''', user_id=user_id) return [userProductReview(*row) for row in rows] if rows is not None else None @staticmethod ##Method to submit a product review authored by user with user_id def submit_product_review(user_id, product_id, seller_id, num_stars, date, description, upvotes, image1, image2, image3): try: app.db.execute(''' INSERT INTO ProductReview VALUES (:user_id, :product_id, :seller_id, :num_stars, :date, :description, :upvotes, :images) ''', user_id=user_id, product_id=product_id, seller_id=seller_id, num_stars=num_stars, date=date, description=description, upvotes=upvotes, images=[image1, image2, image3]) except Exception as e: print(e) @staticmethod ##Method to update a selected product review authored by user with user_id def update_product_review(user_id, product_id, seller_id, num_stars, date, description, upvotes, image1, image2, image3): try: app.db.execute(''' UPDATE ProductReview SET (num_stars, date, description, upvotes, images) = (:num_stars, :date, :description, :upvotes, :images) WHERE buyer_id = :user_id AND product_id = :product_id AND seller_id = :seller_id ''', user_id=user_id, product_id=product_id, seller_id=seller_id, num_stars=num_stars, date=date, upvotes=upvotes, description=description, images=[image1, image2, image3]) except Exception as e: print(e) @staticmethod ##Method to delete a selected product review authored by user with user_id def delete_product_review(user_id, product_id, seller_id): try: app.db.execute(''' DELETE FROM ProductReview WHERE buyer_id = :user_id AND product_id = :product_id AND seller_id = :seller_id ''', user_id=user_id, product_id=product_id, seller_id=seller_id) except Exception as e: print(e) @staticmethod ##Method to upvote a product review def upvote_product_review(user_id, product_id, seller_id, upvotes): try: app.db.execute(''' UPDATE ProductReview SET upvotes = :upvotes WHERE buyer_id = :user_id AND product_id = :product_id AND seller_id = :seller_id ''', user_id=user_id, product_id=product_id, seller_id=seller_id, upvotes=str(int(upvotes)+1)) except Exception as e: print(e) class userSellerReview: def __init__(self, seller_id, fname, lname, num_stars, date, description, upvotes, images): self.seller_id = seller_id self.name = fname + ' ' + lname self.num_stars = num_stars self.date = date self.description = description self.upvotes = upvotes self.images = images @staticmethod ##method to get all seller reviews written by user with user_id in reverse chronological order def get(user_id): rows = app.db.execute(''' SELECT seller_id, firstname, lastname, num_stars, date, sr.description, upvotes, images FROM SellerReview sr, Account a WHERE sr.buyer_id = :user_id AND a.account_id = sr.seller_id ORDER BY date DESC ''', user_id=user_id) return [userSellerReview(*row) for row in rows] if rows is not None else None @staticmethod ##Method to submit a seller review authored by user with user_id def submit_seller_review(user_id, seller_id, num_stars, date, description, upvotes, image1, image2, image3): try: app.db.execute(''' INSERT INTO SellerReview VALUES (:user_id, :seller_id, :num_stars, :date, :description, :upvotes, :images) ''', user_id=user_id, seller_id=seller_id, num_stars=num_stars, date=date, description=description, upvotes=upvotes, images=[image1, image2, image3]) except Exception as e: print(e) @staticmethod ##Method to update a selected seller review authored by user with user_id def update_seller_review(user_id, seller_id, num_stars, date, description, upvotes, image1, image2, image3): try: app.db.execute(''' UPDATE SellerReview SET (num_stars, date, description, upvotes, images) = (:num_stars, :date, :description, :upvotes, :images) WHERE buyer_id = :user_id AND seller_id = :seller_id ''', user_id=user_id, seller_id=seller_id, num_stars=num_stars, date=date, description=description, upvotes=upvotes, images=[image1, image2, image3]) except Exception as e: print(e) @staticmethod ##Method to delete a selected seller review authored by user with user_id def delete_seller_review(user_id, seller_id): try: app.db.execute(''' DELETE FROM SellerReview WHERE buyer_id = :user_id AND seller_id = :seller_id ''', user_id=user_id, seller_id=seller_id) except Exception as e: print(e) @staticmethod ##Method to upvote a seller review def upvote_seller_review(user_id, seller_id, upvotes): try: app.db.execute(''' UPDATE SellerReview SET upvotes = :upvotes WHERE buyer_id = :user_id AND seller_id = :seller_id ''', user_id=user_id, seller_id=seller_id, upvotes=str(int(upvotes)+1)) except Exception as e: print(e)
# -*- coding: utf-8 -*- import re def replace(input): output = input output = re.sub(u'\u1000', u'\u0075', output) # ka_gyi output = re.sub(u'\u1001', u'\u0063', output) # ka_kway output = re.sub(u'\u1002', u'\u002a', output) # ga_nge output = re.sub(u'\u1003', u'\u0043', output) # ga_gyi output = re.sub(u'\u1004', u'\u0069', output) # nga output = re.sub(u'\u1005', u'\u0070', output) # sa_lone output = re.sub(u'\u1006', u'\u0071', output) # sa_lane output = re.sub(u'\u1007', u'\u005a', output) # za_gwe output = re.sub(u'\u1009', u'\u00da', output) # nya_shay output = re.sub(u'\u100a', u'\u006e', output) # nya output = re.sub(u'\u100b', u'\u0023', output) # tata_lin_gyake output = re.sub(u'\u100c', u'\u0058', output) # ta_wen_bae output = re.sub(u'\u100d', u'\u0021', output) # da_yin_guat output = re.sub(u'\u100e', u'\u00a1', output) # da_yin_mot output = re.sub(u'\u100f', u'\u0050', output) # na_gyi output = re.sub(u'\u1010', u'\u0077', output) # da_wen_bu output = re.sub(u'\u1011', u'\u0078', output) # ta_sin_too output = re.sub(u'\u1012', u'\u0027', output) # da_dway output = re.sub(u'\u1013', u'\u0022', output) # da_aut_chai output = re.sub(u'\u1014', u'\u0065', output) # na_nge output = re.sub(u'\u1015', u'\u0079', output) # pa_saut output = re.sub(u'\u1016', u'\u007a', output) # pa_oo_htoke output = re.sub(u'\u1017', u'\u0041', output) # ba_lat_chai output = re.sub(u'\u1018', u'\u0062', output) # ba_gone output = re.sub(u'\u1019', u'\u0072', output) # ma output = re.sub(u'\u101a', u'\u002c', output) # ya_pat_lat output = re.sub(u'\u101b', u'\u0026', output) # ya_gaut output = re.sub(u'\u101c', u'\u0076', output) # la output = re.sub(u'\u101d', u'\u0030', output) # wa output = re.sub(u'\u101e', u'\u006f', output) # ta output = re.sub(u'\u101f', u'\u005b', output) # ha output = re.sub(u'\u1020', u'\u0056', output) # la_gyi output = re.sub(u'\u1021', u'\u0074', output) # aa output = re.sub(u'\u1023', u'\u00a3', output) # 2kagyi output = re.sub(u'\u1024', u'\u00fe', output) # II output = re.sub(u'\u1025', u'\u004f', output) # oo output = re.sub(u'\u1027', u'\u007b', output) # at_kayar_aa output = re.sub(u'\u102b', u'\u0067', output) # yaychar_ashay output = re.sub(u'\u102c', u'\u006d', output) # yaychar output = re.sub(u'\u102d', u'\u0064', output) # long_gyi_tin output = re.sub(u'\u102e', u'\u0044', output) # long_gyi_tin_sanke output = re.sub(u'\u102f', u'\u004b', output) # 1_chuang_ngin output = re.sub(u'\u1030', u'\u004c', output) # 2_chuang_ngin output = re.sub(u'\u1031', u'\u0061', output) # ta_wai_toe output = re.sub(u'\u1032', u'\u004a', output) # naut_htoe_pyit output = re.sub(u'\u1036', u'\u0048', output) # tay_tay_tin output = re.sub(u'\u1037', u'\u0068', output) # aut_myit output = re.sub(u'\u1038', u'\u003b', output) # wa_sa_paut output = re.sub(u'\u103a', u'\u0066', output) # nga_tat output = re.sub(u'\u103b', u'\u0073', output) # ya_pint output = re.sub(u'\u103c', u'\u006a', output) # ya_yit output = re.sub(u'\u103d', u'\u0047', output) # wa_swe output = re.sub(u'\u103e', u'\u0053', output) # ha_toe output = re.sub(u'\u103f', u'\u00f3', output) # ta_gyi output = re.sub(u'\u1040', u'\u0030', output) # 0 output = re.sub(u'\u1041', u'\u0031', output) # 1 output = re.sub(u'\u1042', u'\u0032', output) # 2 output = re.sub(u'\u1043', u'\u0033', output) # 3 output = re.sub(u'\u1044', u'\u0034', output) # 4 output = re.sub(u'\u1045', u'\u0035', output) # 5 output = re.sub(u'\u1046', u'\u0036', output) # 6 output = re.sub(u'\u1047', u'\u0037', output) # 7 output = re.sub(u'\u1048', u'\u0038', output) # 8 output = re.sub(u'\u1049', u'\u0039', output) # 9 output = re.sub(u'\u104a', u'\u003f', output) # pot_kalay output = re.sub(u'\u104b', u'\u002f', output) # pot_ma output = re.sub(u'\u104c', u'\u00fc', output) # nai output = re.sub(u'\u104d', u'\u00ed', output) # yue output = re.sub(u'\u104e', u'\u00a4', output) # la_guang output = output.replace(u'\u104f', u'\u005c') # at_kayar_ee return output def precompose(input): output = input output = re.sub(u'\u1008', u'\u0070\u0073', output) # za_myin_zwe output = re.sub(u'\u1026', u'\u004f\u0044', output) # oo_with_longgyitinsanke output = re.sub(u'\u1029', u'\u006a\u006f', output) # aww output = re.sub(u'\u102a', u'\u0061\u006a\u006f\u006d\u006f', output) # aww_with_tawaetoe output = re.sub(u'\u0067\u0066', u'\u003a', output) # yaychar_shayhtoe output = re.sub(u'\u007e\u0047', u'\u003c', output) # yayit_agyi_with_waswe output = re.sub(u'\u0060\u0047', u'\u003e', output) # yayit_with_waswe output = re.sub(u'\u0050\u1039\u0021', u'\u0040', output) # nagyi_dayinguat output = re.sub(u'\u0053\u006b', u'\u0049', output) # hatoe_1cn output = re.sub(u'\u0073\u0053', u'\u0051', output) # yapint_hatoe output = re.sub(u'\u0073\u0047', u'\u0052', output) # yapint_waswe output = re.sub(u'\u0047\u0053', u'\u0054', output) # waswe_hatoe output = re.sub(u'\u0073\u0054', u'\u0057', output) # yapint_waswe_hatoe output = re.sub(u'\u0053\u006c', u'\u00aa', output) # hatoe_2cn output = re.sub(u'\u00da\u006d', u'\u00d3', output) # nya_yaychar # pr_sint output = re.sub(u'\u0023\u1039\u0023', u'\u00a5', output) # twice_ttlg output = re.sub(u'\u1039\u0043', u'\u00a2', output) # gagyi output = re.sub(u'\u1039\u0078', u'\u00a6', output) # ta_sin_too output = re.sub(u'\u1039\u0022', u'\u00a8', output) # da_aut_chait output = re.sub(u'\u1039\u0063', u'\u00a9', output) # ka_kway output = re.sub(u'\u1039\u0072', u'\u00ae', output) # ma output = re.sub(u'\u1039\u0058', u'\u00b2', output) # ta_wen_bae output = re.sub(u'\u1039\u0023', u'\u00b3', output) # ddlg output = re.sub(u'\u1039\u0027', u'\u00b4', output) # da_dway output = re.sub(u'\u0021\u1039\u00a1', u'\u00b9', output) # dyg_dym output = output.replace(u'\u1039\u002a', u'\u00be') # ga_nge output = re.sub(u'\u1039\u0041', u'\u00c1', output) # ba_lat_chai output = re.sub(u'\u1039\u0077', u'\u00c5', output) # da_wen_bu output = re.sub(u'\u1039\u005a', u'\u00c6', output) # za_gwe output = re.sub(u'\u1039\u0062', u'\u00c7', output) # ba_gone output = re.sub(u'\u1039\u0077\u0047', u'\u00c9', output) # dwa output = re.sub(u'\u1039\u0070\u0073', u'\u00d1', output) # za_myin_zwe output = re.sub(u'\u1039\u0050', u'\u00d6', output) # na_gyi output = re.sub(u'\u0021\u1039\u0021', u'\u00d7', output) # twice_dyg output = re.sub(u'\u1039\u0079', u'\u00dc', output) # pa_saut output = re.sub(u'\u1039\u0071', u'\u00e4', output) # sa_lane output = re.sub(u'\u1039\u007a', u'\u00e6', output) # pa_oo_htoke output = re.sub(u'\u1039\u0065', u'\u00e9', output) # na_nge output = re.sub(u'\u1039\u0070', u'\u00f6', output) # sa_lone output = re.sub(u'\u1039\u0075', u'\u00fa', output) # ka_gyi output = re.sub(u'\u1039\u0076', u'\u2019', output) # la return output def logical2visual(input): output = input # 1=letters 2=pr_sint 3=yayit 4=yapint 5=waswe 6=hatoe 7=tawaetoe 8=nga_tat 9=aumyit 10=yaychar output = re.sub( u'([\u1000-\u1021])((?:\u1039[\u1000-\u1021])?)((?:\u103c)?)((?:\u103b)?)((?:\u103d)?)((?:\u103e)?)((?:\u1031)?)((?:\u103a)?)((?:\u1037)?)((:\u102c)?)', '\\7\\3\\1\\2\\4\\5\\6\\8\\9\\10', output) # ngatat and wasapaut output = re.sub(u'\u1038\u1039', u'\u1039\u1038', output) # nga_sint output = re.sub(u'\u102d\u1036', u'\u00f0', output) output = re.sub(u'\u1004\u103a\u1039', u'\u0046', output) # normal output = re.sub(u'(\u0046)((?:\u1031)?)([\u1000-\u1021])', '\\2\\3\\1', output) output = re.sub(u'([\u1000-\u1021])\u0046\u102d', u'\\1\u00d8', output) # with_longyitin output = re.sub(u'([\u1000-\u1021])\u0046\u102e', u'\\1\u00d0', output) # with_longgyitinsanke output = re.sub(u'([\u1000-\u1021])\u0046\u1036', u'\\1\u00f8', output) # with_taytaytin return output def shape(input): output = input # ya_yit output = re.sub(u'\u103c([\u1000\u1003\u1006\u100f\u1010\u1011\u1018\u101a\u101c\u101e\u101f\u1021])', u'\u004d\\1', output) # ya_yit_agyi output = re.sub(u'\u103c([\u1000-\u1021])([\u102d\u102e\u1036])', u'\u004e\\1\\2', output) # yayit with long_gyi_din(sanke) output = re.sub(u'\u004d([\u1000-\u1021])([\u102d\u102e\u1036])', u'\u0042\\1\\2', output) # yayit_agi with long_gyi_din(sanke) output = re.sub(u'\u103c([\u1000-\u1021])(\u103d)', u'\u0060\\1\\2', output) # yayit with waswe output = re.sub(u'\u004d([\u1000-\u1021])(\u103d)', u'\u007e\\1\\2', output) # yayit_agyi with waswe output = re.sub(u'\u103c([\u1000-\u1021])(\u1039[\u1000-\u1021])', u'\u0060\\1\\2', output) # yayit with pr_sint output = re.sub(u'\u004d([\u1000-\u1021])(\u1039[\u1000-\u1021])', u'\u007e\\1\\2', output) # yayit_agyi with pr_sint # ta/na_chuang_ngin output = re.sub(u'([\u1000-\u1007])((?:[\u102d\u102e])?)((?:\u103e)?)\u102f', u'\\1\\2\\3\u006b', output) # 1cn with some letters output = re.sub(u'([\u1009-\u100b])((?:[\u102d\u102e])?)((?:\u103e)?)\u102f', u'\\1\\2\\3\u006b', output) # 1cn with some letters output = re.sub(u'([\u100e-\u101f])((?:[\u102d\u102e])?)((?:\u103e)?)\u102f', u'\\1\\2\\3\u006b', output) # 1cn with some letters output = re.sub(u'(\u1021)((?:[\u102d\u102e])?)((?:\u103e)?)\u102f', u'\\1\\2\\3\u006b', output) # 1cn with some letters output = re.sub(u'([\u1000-\u1007])((?:[\u102d\u102e])?)((?:\u103e)?)\u1030', u'\\1\\2\\3\u006c', output) # 2cn with some letters output = re.sub(u'([\u1009-\u100b])((?:[\u102d\u102e])?)((?:\u103e)?)\u1030', u'\\1\\2\\3\u006c', output) # 2cn with some letters output = re.sub(u'([\u100e-\u101f])((?:[\u102d\u102e])?)((?:\u103e)?)\u1030', u'\\1\\2\\3\u006c', output) # 2cn with some letters output = re.sub(u'(\u1021)((?:[\u102d\u102e])?)((?:\u103e)?)\u1030', u'\\1\\2\\3\u006c', output) # 2cn with some letters output = re.sub(u'\u004d([\u1000-\u1021])\u006b', u'\u00ea\\1', output) # yayit_agyi_with_1cn output = re.sub(u'\u103c([\u1000-\u1021])\u006b', u'\u00fb\\1', output) # yayit_with_1cn output = re.sub(u'([\u006a\u0042\u004d\u004e\u0060])([\u1000-\u1021])((?:[\u102d\u102e])?)((?:\u0047)?)\u006b', u'\\1\\2\\3\\4\u004b', output) # 1cn output = re.sub(u'([\u006a\u0042\u004d\u004e\u0060])([\u1000-\u1021])((?:[\u102d\u102e])?)((?:\u0047)?)\u006c', u'\\1\\2\\3\\4\u004c', output) # 2cn output = re.sub(u'\u1039([\u1000-\u1021])((?:[\u102d\u102e])?)\u006b', u'\u1039\\1\\2\u004b', output) # 1cn output = re.sub(u'\u1039([\u1000-\u1021])((?:[\u102d\u102e])?)\u006c', u'\u1039\\1\\2\u004c', output) # 1cn # hatoe output = re.sub(u'\u100a\u103e', u'\u100a\u00a7', output) # nya with hatoe # oo output = re.sub(u'\u1009(\u103a)', u'\u1025\\1', output) # nyapyat_to_oo # nag_nge_apyat output = re.sub(u'\u1014((?:[\u102d\u102e\u1032])?)([\u103d\u103e\u102f\u1030\u006b\u006c])', u'\u0045\\1\\2', output) output = re.sub(u'\u1014\u1039([\u1000-\u1021])', u'\u0045\u1039\\1', output) # 2cn with prsint # aut_myit output = re.sub(u'([\u1014\u102f\u1030\u006b\u006c])((?:[\u1032\u1036])?)\u1037', u'\\1\\2\u0059', output) output = re.sub(u'([\u103d\u103e])((?:[\u1032\u1036])?)\u1037', u'\\1\\2\u0055', output) output = re.sub(u'(\u103d\u103e)\u1037', u'\\1\u0055', output) # yaguat output = re.sub(u'\u101b((?:[\u102d\u102e\u1032])?)([\u102f\u1030\u103d\u006b\u006c])', u'\u00bd\\1\\2', output) # nya output = re.sub(u'\u100a(\u103d\u103e)', u'\u00f1\\1', output) # with waswe_hatoe return output def convert(input): output = logical2visual(input) output = shape(output) output = replace(output) output = precompose(output) return output
app.controller("HomeController", function ($scope,$http,$location,$stateParams,$window) { $scope.init = function () { $http.get(apiUrl + '/posts') .then(function (res) { $scope.posts = res.data.data.posts; $scope.viewby = 10; $scope.totalItems = $scope.posts.length; $scope.currentPage = 1; $scope.itemsPerPage = $scope.viewby; $scope.maxSize = 5; //Number of pager buttons to show $scope.setPage = function (pageNo) { $scope.currentPage = pageNo; }; }); }; $scope.scrollTop = function () { $('body,html').animate({ scrollTop : 0 // Scroll to top of body }, 300); $scope.limit = 4; }; $scope.detailPost = function(post) { if(post.id) { $location.path('/post/' + post.id); } }; $scope.counter = function(post) { $scope.counter = post.counter; if(post.id) { $http.post(apiUrl + '/posts/' + post.id + '/counter',{counter:$scope.counter}) .then(function(res) { if(res.data.status == 'ok') { console.log(res.data.data.counter); } }) } }; $scope.limit = 4; $scope.loadMore = function() { $scope.limit = $scope.limit + 4; } });
macDetailCallback("58e876200000/28",[{"a":"Riddargatan 18 Stockholm SE 11451","o":"Coala Life AB","d":"2016-05-15","t":"add","s":"ieee","c":"SE"}]);
import React from 'react' import Helmet from 'react-helmet' const Head = ({title, description, url}) => ( <Helmet title={title}> <meta name='description' content={description} /> <link rel='apple-touch-icon' sizes='180x180' href='/favicon/apple-touch-icon.png' /> <link rel='icon' type='image/png' sizes='32x32' href='/favicon/favicon-32x32.png' /> <link rel='icon' type='image/png' sizes='16x16' href='/favicon/favicon-16x16.png' /> <link rel='manifest' href='/favicon/site.webmanifest' /> <link rel='mask-icon' href='/favicon/safari-pinned-tab.svg' color='#004ba0' /> <link rel='shortcut icon' href='/favicon/favicon.ico' /> <meta name='msapplication-TileColor' content='#004ba0' /> <meta name='msapplication-config' content='/favicon/browserconfig.xml' /> <meta name='theme-color' content='#ffffff' /> <meta property='fb:app_id' content='366384430479764' /> <meta property='og:title' content={title} /> <meta property='og:url' content={url} /> <meta property='og:description' content={description} /> <meta property='og:type' content='website' /> <meta property='og:image' content='/img/logo-200w.png' /> <meta property='og:image:width' content='200' /> <meta property='og:image:height' content='200' /> <meta name='twitter:card' content='summary' /> </Helmet> ) export default Head
/* Magic Mirror * Module: MMM-Farevarsel * * By mabahj * MIT Licensed * Based on MMM-Rest by Dirk Melchers */ var NodeHelper = require('node_helper'); var request = require('request'); var Parser = require('rss-parser'); // https://www.npmjs.com/package/rss-parser module.exports = NodeHelper.create({ start: function () { this.parser = null; console.log(this.name + ' helper started ...'); }, socketNotificationReceived: function(notification, payload) { if (notification === 'MMM_REST_REQUEST') { var that = this; let fullUrl=payload.url+'?county='+payload.county; // FIXME: Have to to figure out how to add user agent (https://api.met.no/conditions_service.html) request({ url: fullUrl, method: 'GET' }, function(error, response, body) { //console.log("MMM_REST response:"+response.statusCode); if (!error && response.statusCode == 200) { this.parser = new Parser({ customFields: { item: ['description','description'], } }); this.parser.parseString(response.body, function(err, feed) { //console.log(feed.title); alerts=[]; feed.items.forEach(function(entry) { let sections=entry.title.split(','); let alertTitle=sections[0]; let alertColor=sections[1]; if (alertColor.indexOf("gult") != -1) { alertColor="YELLOW"; } else if (alertColor.indexOf("rødt") != -1) { alertColor="RED"; } else if (alertColor.indexOf("oransje") != -1) { alertColor="ORANGE"; } else { alertColor="???"; } let description=entry.description description=description.replace("Update: ", ""); // Remove prefix we do not need description=description.replace("Alert: ", ""); // Remove prefix we do not need let alert={ title: sections[0], color: alertColor, text: description } alerts.push(alert); console.log("MMM-Farevarsel fetched alert:" + alert.text); }) that.sendSocketNotification('MMM_REST_RESPONSE', alerts); }); } }); } } });
import React, { useState, useEffect, useRef } from 'react'; import { Button, makeStyles } from '@material-ui/core'; import {useSelector,useDispatch} from 'react-redux'; import Notify from '@customComponent/Notify'; import CompContainer from '@customComponent/CompContainer'; import {ListGroupItem1} from '@customComponent/ListGroupItem'; import Mtable from '@customComponent/Mtable'; import {fetchPlayer_model} from '@ducks/PlayerModelsDuck' import useTableActions from '@customComponent/useTableActions'; import { addPlayer_model, deletePlayer_model, updatePlayer_model } from '../../Redux/Ducks/PlayerModelsDuck'; import { MTableEditRow } from 'material-table'; const useStyles =makeStyles(theme=>({ container:{ padding:'10px' } })); export default function PlayerModels() { const classes = useStyles(); const toast = Notify(); const [pic, setPic] = useState(); const {players,loading,fetching} = useSelector(state => state.playerModels); const dispatch = useDispatch() const [columns, setColumns] = useState([ { title:'ID', field:'id', width:'50px', headerStyle: { padding:'16px 10px', textAlign:'center' }, editable: 'never' }, { field: 'image', render:rowData => <img src={`${rowData.image}`} style={{height:'50px'}} />, editComponent:rowData=><input accept="image/*" onChange={(e)=>setPic(e.target.files[0])} type="file" /> }, { title:'Player', field: 'name', // render:rowData => <ListGroupItem1 image={rowData.image} label={rowData.name} />, }, { title:'Model Id', field:'model_id', }, { title:'Position', field:'position', }, { title:'Type', field:'type', lookup:{ 1:<img src={`/images/logo/ball1.png`} style={{height:'25px'}} />, 2:<img src={`/images/logo/ball2.png`} style={{height:'25px'}} /> } } ]); const tabelActions = { add:addPlayer_model, update:updatePlayer_model, delete:deletePlayer_model, } const {handleAddRow,handleUpdateRow,handleDeleteRow} = useTableActions(tabelActions) const handleAdd = (newData)=>{ console.log({newData}) const formData = new FormData(); const data = { name:newData.name, model_id:newData.model_id, position:newData.position, type:newData.type }; formData.append('image',pic); formData.append('data',JSON.stringify(data)); return handleAddRow(formData) } const handleUpdate = (newData)=>{ console.log({newData}) const data = { id:newData.id, model_id: newData.model_id, name: newData.name, position: newData.position, type: newData.type }; return handleUpdateRow(data) } useEffect(()=>{ dispatch(fetchPlayer_model()) },[]) return ( <CompContainer title='Player Models'> <Mtable columns={columns} data={players} loading={loading || fetching} paging={true} handleAddRow={handleAdd} handleUpdateRow={handleUpdate} handleDeleteRow={(oldData)=>handleDeleteRow(oldData.id)} editable={true} /> </CompContainer> ) }
module.exports = [ { active: false, title: "DSL (2Mbs, 5ms RTT)", id: "dsl", speed: 200, latency: 5, urls: [], order: 1 }, { active: false, title: "4G (4Mbs, 20ms RTT)", id: "4g", speed: 400, latency: 10, urls: [], order: 2 }, { active: false, title: "3G (750kbs, 100ms RTT)", id: "3g", speed: 75, latency: 50, urls: [], order: 3 }, { active: false, id: "good-2g", title: "Good 2G (450kbs, 150ms RTT)", speed: 45, latency: 75, urls: [], order: 4 }, { active: false, id: "2g", title: "Regular 2G (250kbs, 300ms RTT)", speed: 25, latency: 150, urls: [], order: 5 }, { active: false, id: "gprs", title: "GPRS (50kbs, 500ms RTT)", speed: 5, latency: 250, urls: [], order: 6 } ];
/*! * DevExtreme (dx.messages.it.js) * Version: 19.2.5 * Build date: Mon Dec 16 2019 * * Copyright (c) 2012 - 2019 Developer Express Inc. ALL RIGHTS RESERVED * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/ */ "use strict"; ! function(root, factory) { if ("function" === typeof define && define.amd) { define(function(require) { factory(require("devextreme/localization")) }) } else { if ("object" === typeof module && module.exports) { factory(require("devextreme/localization")) } else { factory(DevExpress.localization) } } }(this, function(localization) { localization.loadMessages({ it: { Yes: "S\xec", No: "No", Cancel: "Annulla", Clear: "Cancella", Done: "Fatto", Loading: "Caricamento...", Select: "Seleziona...", Search: "Cerca", Back: "Indietro", OK: "OK", "dxCollectionWidget-noDataText": "Nessun dato da mostrare", "dxDropDownEditor-selectLabel": "Seleziona", "validation-required": "Richiesto", "validation-required-formatted": "{0} \xe8 richiesto", "validation-numeric": "Il valore deve essere numerico", "validation-numeric-formatted": "{0} deve essere numerico", "validation-range": "Il valore non \xe8 compreso nell'intervallo", "validation-range-formatted": "{0} non \xe8 compreso nell'intervallo", "validation-stringLength": "Lunghezza del valore errata", "validation-stringLength-formatted": "La lunghezza di {0} \xe8 errata", "validation-custom": "Il valore non \xe8 corretto", "validation-custom-formatted": "{0} non \xe8 corretto", "validation-async": "Il valore non \xe8 corretto", "validation-async-formatted": "{0} non \xe8 corretto", "validation-compare": "I valori non corrispondono", "validation-compare-formatted": "{0} non corrisponde", "validation-pattern": "Il valore non \xe8 corretto", "validation-pattern-formatted": "{0} non \xe8 corretto", "validation-email": "L'Email non \xe8 corretta", "validation-email-formatted": "{0} non \xe8 una email corretta", "validation-mask": "Il valore non \xe8 corretto", "dxLookup-searchPlaceholder": "Lunghezza minima: {0}", "dxList-pullingDownText": "Trascina in basso per aggiornare...", "dxList-pulledDownText": "Rilascia per aggiornare...", "dxList-refreshingText": "Aggiornamento...", "dxList-pageLoadingText": "Caricamento...", "dxList-nextButtonText": "Carica altri risultati", "dxList-selectAll": "Seleziona tutti", "dxListEditDecorator-delete": "Elimina", "dxListEditDecorator-more": "Ancora", "dxScrollView-pullingDownText": "Trascina in basso per aggiornare...", "dxScrollView-pulledDownText": "Rilascia per aggiornare...", "dxScrollView-refreshingText": "Aggiornamento...", "dxScrollView-reachBottomText": "Caricamento...", "dxDateBox-simulatedDataPickerTitleTime": "Seleziona orario", "dxDateBox-simulatedDataPickerTitleDate": "Seleziona data", "dxDateBox-simulatedDataPickerTitleDateTime": "Seleziona data e ora", "dxDateBox-validation-datetime": "Il valore deve essere una data o un orario", "dxFileUploader-selectFile": "Seleziona file", "dxFileUploader-dropFile": "o trascina il file qui", "dxFileUploader-bytes": "bytes", "dxFileUploader-kb": "kb", "dxFileUploader-Mb": "Mb", "dxFileUploader-Gb": "Gb", "dxFileUploader-upload": "Carica", "dxFileUploader-uploaded": "Caricato", "dxFileUploader-readyToUpload": "Pronto per caricare", "dxFileUploader-uploadFailedMessage": "Caricamento fallito", "dxFileUploader-invalidFileExtension": "", "dxFileUploader-invalidMaxFileSize": "", "dxFileUploader-invalidMinFileSize": "", "dxRangeSlider-ariaFrom": "Da", "dxRangeSlider-ariaTill": "fino a", "dxSwitch-switchedOnText": "ON", "dxSwitch-switchedOffText": "OFF", "dxForm-optionalMark": "opzionale", "dxForm-requiredMessage": "{0} \xe8 richiesto", "dxNumberBox-invalidValueMessage": "Il valore deve essere numerico", "dxNumberBox-noDataText": "Nessun dato", "dxDataGrid-columnChooserTitle": "Selezione colonne", "dxDataGrid-columnChooserEmptyText": "Trascina qui una colonna per nasconderla", "dxDataGrid-groupContinuesMessage": "Pagina successiva", "dxDataGrid-groupContinuedMessage": "Continua da pagina precedente", "dxDataGrid-groupHeaderText": "Raggruppa per questa colonna", "dxDataGrid-ungroupHeaderText": "Separa", "dxDataGrid-ungroupAllText": "Separa tutti", "dxDataGrid-editingEditRow": "Modifica", "dxDataGrid-editingSaveRowChanges": "Salva", "dxDataGrid-editingCancelRowChanges": "Annulla", "dxDataGrid-editingDeleteRow": "Elimina", "dxDataGrid-editingUndeleteRow": "Ripristina", "dxDataGrid-editingConfirmDeleteMessage": "Sei certo di voler eliminare questo record?", "dxDataGrid-validationCancelChanges": "Annulla le modifiche", "dxDataGrid-groupPanelEmptyText": "Trascina qui l'intestazione di una colonna per raggrupparla", "dxDataGrid-noDataText": "Nessun dato", "dxDataGrid-searchPanelPlaceholder": "Cerca...", "dxDataGrid-filterRowShowAllText": "(Tutti)", "dxDataGrid-filterRowResetOperationText": "Annulla", "dxDataGrid-filterRowOperationEquals": "Uguale", "dxDataGrid-filterRowOperationNotEquals": "Diverso", "dxDataGrid-filterRowOperationLess": "Minore di", "dxDataGrid-filterRowOperationLessOrEquals": "Minore o uguale a", "dxDataGrid-filterRowOperationGreater": "Maggiore di", "dxDataGrid-filterRowOperationGreaterOrEquals": "Maggiore o uguale a", "dxDataGrid-filterRowOperationStartsWith": "Inizia con", "dxDataGrid-filterRowOperationContains": "Contiene", "dxDataGrid-filterRowOperationNotContains": "Non contiene", "dxDataGrid-filterRowOperationEndsWith": "Termina con", "dxDataGrid-filterRowOperationBetween": "Compreso", "dxDataGrid-filterRowOperationBetweenStartText": "Inizio", "dxDataGrid-filterRowOperationBetweenEndText": "Fine", "dxDataGrid-applyFilterText": "Applica filtro", "dxDataGrid-trueText": "vero", "dxDataGrid-falseText": "falso", "dxDataGrid-sortingAscendingText": "Ordinamento ascendente", "dxDataGrid-sortingDescendingText": "Ordinamento discendente", "dxDataGrid-sortingClearText": "Annulla ordinamento", "dxDataGrid-editingSaveAllChanges": "Salva le modifiche", "dxDataGrid-editingCancelAllChanges": "Annulla le modifiche", "dxDataGrid-editingAddRow": "Aggiungi una riga", "dxDataGrid-summaryMin": "Min: {0}", "dxDataGrid-summaryMinOtherColumn": "Min di {1} \xe8 {0}", "dxDataGrid-summaryMax": "Max: {0}", "dxDataGrid-summaryMaxOtherColumn": "Max di {1} \xe8 {0}", "dxDataGrid-summaryAvg": "Media: {0}", "dxDataGrid-summaryAvgOtherColumn": "Media di {1} \xe8 {0}", "dxDataGrid-summarySum": "Somma: {0}", "dxDataGrid-summarySumOtherColumn": "Somma di {1} \xe8 {0}", "dxDataGrid-summaryCount": "Elementi: {0}", "dxDataGrid-columnFixingFix": "Blocca", "dxDataGrid-columnFixingUnfix": "Sblocca", "dxDataGrid-columnFixingLeftPosition": "Alla sinistra", "dxDataGrid-columnFixingRightPosition": "Alla destra", "dxDataGrid-exportTo": "Esporta", "dxDataGrid-exportToExcel": "Esporta in Excel", "dxDataGrid-excelFormat": "File Excel", "dxDataGrid-selectedRows": "Righe selezionate", "dxDataGrid-exportSelectedRows": "Esporta le righe selezionate", "dxDataGrid-exportAll": "Esporta tutti i dati", "dxDataGrid-headerFilterEmptyValue": "(vuoto)", "dxDataGrid-headerFilterOK": "OK", "dxDataGrid-headerFilterCancel": "Annulla", "dxDataGrid-ariaColumn": "Colonna", "dxDataGrid-ariaValue": "Valore", "dxDataGrid-ariaFilterCell": "Filtra cella", "dxDataGrid-ariaCollapse": "Chiudi", "dxDataGrid-ariaExpand": "Espandi", "dxDataGrid-ariaDataGrid": "Griglia dati", "dxDataGrid-ariaSearchInGrid": "Cerca nella griglia", "dxDataGrid-ariaSelectAll": "Seleziona tutti", "dxDataGrid-ariaSelectRow": "Seleziona riga", "dxDataGrid-filterBuilderPopupTitle": "Composizione filtro", "dxDataGrid-filterPanelCreateFilter": "Nuovo filtro", "dxDataGrid-filterPanelClearFilter": "Cancella", "dxDataGrid-filterPanelFilterEnabledHint": "Attiva il filtro", "dxTreeList-ariaTreeList": "Albero", "dxTreeList-editingAddRowToNode": "Aggiungi", "dxPager-infoText": "Pagina {0} di {1} ({2} elementi)", "dxPager-pagesCountText": "di", "dxPivotGrid-grandTotal": "Totale", "dxPivotGrid-total": "{0} Totale", "dxPivotGrid-fieldChooserTitle": "Selezione campi", "dxPivotGrid-showFieldChooser": "Mostra selezione campi", "dxPivotGrid-expandAll": "Espandi tutto", "dxPivotGrid-collapseAll": "Comprimi tutto", "dxPivotGrid-sortColumnBySummary": 'Ordina "{0}" per questa colonna', "dxPivotGrid-sortRowBySummary": 'Ordina "{0}" per questa riga', "dxPivotGrid-removeAllSorting": "Rimuovi ordinamenti", "dxPivotGrid-dataNotAvailable": "N/A", "dxPivotGrid-rowFields": "Campi riga", "dxPivotGrid-columnFields": "Campi colonna", "dxPivotGrid-dataFields": "Campi dati", "dxPivotGrid-filterFields": "Campi filtro", "dxPivotGrid-allFields": "Tutti i campi", "dxPivotGrid-columnFieldArea": "Trascina qui i campi colonna", "dxPivotGrid-dataFieldArea": "Trascina qui i campi dati", "dxPivotGrid-rowFieldArea": "Trascina qui i campi riga", "dxPivotGrid-filterFieldArea": "Trascina qui i campi filtro", "dxScheduler-editorLabelTitle": "Oggetto", "dxScheduler-editorLabelStartDate": "Data inizio", "dxScheduler-editorLabelEndDate": "Data fine", "dxScheduler-editorLabelDescription": "Descrizione", "dxScheduler-editorLabelRecurrence": "Ripeti", "dxScheduler-openAppointment": "Apri appuntamento", "dxScheduler-recurrenceNever": "Mai", "dxScheduler-recurrenceDaily": "Giornaliero", "dxScheduler-recurrenceWeekly": "Settimanale", "dxScheduler-recurrenceMonthly": "Mensile", "dxScheduler-recurrenceYearly": "Annuale", "dxScheduler-recurrenceRepeatEvery": "Ogni", "dxScheduler-recurrenceRepeatOn": "Repeat On", "dxScheduler-recurrenceEnd": "Termina ripetizione", "dxScheduler-recurrenceAfter": "Dopo", "dxScheduler-recurrenceOn": "Di", "dxScheduler-recurrenceRepeatDaily": "giorno(i)", "dxScheduler-recurrenceRepeatWeekly": "settimana(e)", "dxScheduler-recurrenceRepeatMonthly": "mese(i)", "dxScheduler-recurrenceRepeatYearly": "anno(i)", "dxScheduler-switcherDay": "Giorno", "dxScheduler-switcherWeek": "Settimana", "dxScheduler-switcherWorkWeek": "Settimana lavorativa", "dxScheduler-switcherMonth": "Mese", "dxScheduler-switcherAgenda": "Agenda", "dxScheduler-switcherTimelineDay": "Cronologia giornaliera", "dxScheduler-switcherTimelineWeek": "Cronologia settimanale", "dxScheduler-switcherTimelineWorkWeek": "Cronologia settimana lavorativa", "dxScheduler-switcherTimelineMonth": "Cronologia mensile", "dxScheduler-recurrenceRepeatOnDate": "alla data", "dxScheduler-recurrenceRepeatCount": "occorrenza(e)", "dxScheduler-allDay": "Tutto il giorno", "dxScheduler-confirmRecurrenceEditMessage": "Vuoi modificare solo questo appuntamento o tutte le sue ricorrenze?", "dxScheduler-confirmRecurrenceDeleteMessage": "Vuoi eliminare solo questo appuntamento o tutte le sue ricorrenze?", "dxScheduler-confirmRecurrenceEditSeries": "Modifica serie", "dxScheduler-confirmRecurrenceDeleteSeries": "Elimina serie", "dxScheduler-confirmRecurrenceEditOccurrence": "Modifica appuntamento", "dxScheduler-confirmRecurrenceDeleteOccurrence": "Elimina appuntamento", "dxScheduler-noTimezoneTitle": "Nessun fuso orario", "dxScheduler-moreAppointments": "{0} ancora", "dxCalendar-todayButtonText": "Oggi", "dxCalendar-ariaWidgetName": "Calendario", "dxColorView-ariaRed": "Rosso", "dxColorView-ariaGreen": "Verde", "dxColorView-ariaBlue": "Blu", "dxColorView-ariaAlpha": "Trasparenza", "dxColorView-ariaHex": "Colore", "dxTagBox-selected": "{0} selezionati", "dxTagBox-allSelected": "Tutti selezionati ({0})", "dxTagBox-moreSelected": "{0} ancora", "vizExport-printingButtonText": "Stampa", "vizExport-titleMenuText": "Esportazione/Stampa", "vizExport-exportButtonText": "{0} file", "dxFilterBuilder-and": "E", "dxFilterBuilder-or": "O", "dxFilterBuilder-notAnd": "E non", "dxFilterBuilder-notOr": "O non", "dxFilterBuilder-addCondition": "Aggiungi condizione", "dxFilterBuilder-addGroup": "Aggiungi gruppo", "dxFilterBuilder-enterValueText": "<inserire un valore>", "dxFilterBuilder-filterOperationEquals": "Uguale a", "dxFilterBuilder-filterOperationNotEquals": "Diverso da", "dxFilterBuilder-filterOperationLess": "Minore di", "dxFilterBuilder-filterOperationLessOrEquals": "Minore o uguale a", "dxFilterBuilder-filterOperationGreater": "Maggiore di", "dxFilterBuilder-filterOperationGreaterOrEquals": "Maggiore o uguale a", "dxFilterBuilder-filterOperationStartsWith": "Inizia con", "dxFilterBuilder-filterOperationContains": "Contiene", "dxFilterBuilder-filterOperationNotContains": "Non contiene", "dxFilterBuilder-filterOperationEndsWith": "Termina con", "dxFilterBuilder-filterOperationIsBlank": "\xc8 vuoto", "dxFilterBuilder-filterOperationIsNotBlank": "Non \xe8 vuoto", "dxFilterBuilder-filterOperationBetween": "Compreso", "dxFilterBuilder-filterOperationAnyOf": "Include", "dxFilterBuilder-filterOperationNoneOf": "Non include", "dxHtmlEditor-dialogColorCaption": "Cambia il colore del testo", "dxHtmlEditor-dialogBackgroundCaption": "Cambia il colore di sfondo", "dxHtmlEditor-dialogLinkCaption": "Aggiungi link", "dxHtmlEditor-dialogLinkUrlField": "URL", "dxHtmlEditor-dialogLinkTextField": "Testo", "dxHtmlEditor-dialogLinkTargetField": "Apri link in una nuova finestra", "dxHtmlEditor-dialogImageCaption": "Agguingi Immagine", "dxHtmlEditor-dialogImageUrlField": "URL", "dxHtmlEditor-dialogImageAltField": "Testo alternativo", "dxHtmlEditor-dialogImageWidthField": "Larghezza (px)", "dxHtmlEditor-dialogImageHeightField": "Altezza (px)", "dxHtmlEditor-heading": "Intestazione", "dxHtmlEditor-normalText": "Testo Normale", "dxFileManager-newDirectoryName": "TODO", "dxFileManager-rootDirectoryName": "TODO", "dxFileManager-errorNoAccess": "TODO", "dxFileManager-errorDirectoryExistsFormat": "TODO", "dxFileManager-errorFileExistsFormat": "TODO", "dxFileManager-errorFileNotFoundFormat": "TODO", "dxFileManager-errorDirectoryNotFoundFormat": "TODO", "dxFileManager-errorWrongFileExtension": "TODO", "dxFileManager-errorMaxFileSizeExceeded": "TODO", "dxFileManager-errorInvalidSymbols": "TODO", "dxFileManager-errorDefault": "TODO", "dxDiagram-categoryGeneral": "TODO", "dxDiagram-categoryFlowchart": "TODO", "dxDiagram-categoryOrgChart": "TODO", "dxDiagram-categoryContainers": "TODO", "dxDiagram-categoryCustom": "TODO", "dxDiagram-commandProperties": "TODO", "dxDiagram-commandExport": "TODO", "dxDiagram-commandExportToSvg": "TODO", "dxDiagram-commandExportToPng": "TODO", "dxDiagram-commandExportToJpg": "TODO", "dxDiagram-commandUndo": "TODO", "dxDiagram-commandRedo": "TODO", "dxDiagram-commandFontName": "TODO", "dxDiagram-commandFontSize": "TODO", "dxDiagram-commandBold": "TODO", "dxDiagram-commandItalic": "TODO", "dxDiagram-commandUnderline": "TODO", "dxDiagram-commandTextColor": "TODO", "dxDiagram-commandLineColor": "TODO", "dxDiagram-commandFillColor": "TODO", "dxDiagram-commandAlignLeft": "TODO", "dxDiagram-commandAlignCenter": "TODO", "dxDiagram-commandAlignRight": "TODO", "dxDiagram-commandConnectorLineType": "TODO", "dxDiagram-commandConnectorLineStraight": "TODO", "dxDiagram-commandConnectorLineOrthogonal": "TODO", "dxDiagram-commandConnectorLineStart": "TODO", "dxDiagram-commandConnectorLineEnd": "TODO", "dxDiagram-commandConnectorLineNone": "TODO", "dxDiagram-commandConnectorLineArrow": "TODO", "dxDiagram-commandAutoLayout": "TODO", "dxDiagram-commandAutoLayoutTree": "TODO", "dxDiagram-commandAutoLayoutLayered": "TODO", "dxDiagram-commandAutoLayoutHorizontal": "TODO", "dxDiagram-commandAutoLayoutVertical": "TODO", "dxDiagram-commandFullscreen": "TODO", "dxDiagram-commandUnits": "TODO", "dxDiagram-commandPageSize": "TODO", "dxDiagram-commandPageOrientation": "TODO", "dxDiagram-commandPageOrientationLandscape": "TODO", "dxDiagram-commandPageOrientationPortrait": "TODO", "dxDiagram-commandPageColor": "TODO", "dxDiagram-commandShowGrid": "TODO", "dxDiagram-commandSnapToGrid": "TODO", "dxDiagram-commandGridSize": "TODO", "dxDiagram-commandZoomLevel": "TODO", "dxDiagram-commandAutoZoom": "TODO", "dxDiagram-commandSimpleView": "TODO", "dxDiagram-commandCut": "TODO", "dxDiagram-commandCopy": "TODO", "dxDiagram-commandPaste": "TODO", "dxDiagram-commandSelectAll": "TODO", "dxDiagram-commandDelete": "TODO", "dxDiagram-commandBringToFront": "TODO", "dxDiagram-commandSendToBack": "TODO", "dxDiagram-commandLock": "TODO", "dxDiagram-commandUnlock": "TODO", "dxDiagram-commandInsertShapeImage": "TODO", "dxDiagram-commandEditShapeImage": "TODO", "dxDiagram-commandDeleteShapeImage": "TODO", "dxDiagram-unitIn": "TODO", "dxDiagram-unitCm": "TODO", "dxDiagram-unitPx": "TODO", "dxDiagram-dialogButtonOK": "TODO", "dxDiagram-dialogButtonCancel": "TODO", "dxDiagram-dialogInsertShapeImageTitle": "TODO", "dxDiagram-dialogEditShapeImageTitle": "TODO", "dxDiagram-dialogEditShapeImageSelectButton": "TODO", "dxDiagram-dialogEditShapeImageLabelText": "TODO" } }) });
var fs = require('fs') var path = require('path') var mr = require('npm-registry-mock') var test = require('tap').test var common = require('../common-tap') var server var pkg = common.pkg var cache = common.cache var json = { name: 'prune', description: 'fixture', version: '0.0.1', main: 'index.js', dependencies: { underscore: '1.3.1' }, devDependencies: { mkdirp: '*' } } var EXEC_OPTS = { cwd: pkg, npm_config_depth: 'Infinity' } test('setup', function (t) { fs.writeFileSync( path.join(pkg, 'package.json'), JSON.stringify(json, null, 2) ) mr({ port: common.port }, function (er, s) { server = s t.end() }) }) test('npm install', function (t) { common.npm([ 'install', '--cache', cache, '--registry', common.registry, '--loglevel', 'silent', '--production', 'false' ], EXEC_OPTS, function (err, code, stdout, stderr) { if (err) throw err t.notOk(code, 'exit ok') t.notOk(stderr, 'Should not get data on stderr: ' + stderr) t.end() }) }) test('npm install test-package', function (t) { common.npm([ 'install', 'test-package', '--cache', cache, '--registry', common.registry, '--no-save', '--loglevel', 'silent', '--production', 'false' ], EXEC_OPTS, function (err, code, stdout, stderr) { if (err) throw err t.notOk(code, 'exit ok') t.notOk(stderr, 'Should not get data on stderr: ' + stderr) t.end() }) }) test('setup: verify installs', function (t) { var dirs = fs.readdirSync(pkg + '/node_modules').sort() t.same(dirs, [ 'test-package', 'mkdirp', 'underscore' ].sort()) t.end() }) test('dev: npm prune', function (t) { common.npm([ 'prune', '--loglevel', 'silent', '--production', 'false' ], EXEC_OPTS, function (err, code, stdout, stderr) { if (err) throw err t.notOk(code, 'exit ok') t.notOk(stderr, 'Should not get data on stderr: ' + stderr) t.end() }) }) test('dev: verify installs', function (t) { var dirs = fs.readdirSync(pkg + '/node_modules').sort() t.same(dirs, [ 'mkdirp', 'underscore' ]) t.end() }) test('production: npm prune', function (t) { common.npm([ 'prune', '--loglevel', 'silent', '--parseable', '--production' ], EXEC_OPTS, function (err, code, stdout) { if (err) throw err t.notOk(code, 'exit ok') t.equal(stdout.trim(), 'remove\tmkdirp\t0.3.5\tnode_modules/mkdirp') t.end() }) }) test('pruduction: verify installs', function (t) { var dirs = fs.readdirSync(pkg + '/node_modules').sort() t.same(dirs, [ 'underscore' ]) t.end() }) test('cleanup', function (t) { server.close() t.end() })
const User = require('../models/User'); const encryption = require('../utilities/encryption'); const passport = require('passport'); module.exports = { register: { post: (req, res) => { let userData = req.body; if (userData.password && userData.password !== userData.confirmedPassword) { userData.error = 'Passwords do not match'; return res.status(404).send({ error: 'Passwords do not match', message: 'Need data here? Look under /server/controllers/user.js.' }); } let salt = encryption.generateSalt(); userData.salt = salt; if (userData.password) { userData.password = encryption.generateHashedPassword(salt, userData.password); } User.create(userData) .then(user => { //TODO: check if user exist res.status(200).send({ success: true, message: 'You successfully registered user now Please login' }); }) .catch(error => { userData.error = error; res.status(404).send({ error: error, message: 'Need data here? Look under /server/controllers/user.js.' }); }); }, }, login: { post: (req, res, next) => { let userData = req.body; User.findOne({ username: userData.username }).then(user => { if (!user || !user.authenticate(userData.password)) { return res.status(404).send({ error: 'Wrong credentials', message: 'Need data here? Look under /server/controllers/user.js.' }); } return passport.authenticate('passport', (err, token, userData) => { if (err) { if (err.name === 'IncorrectCredentialsError') { return res.status(200).json({ success: false, message: err.message }) } return res.status(200).json({ success: false, message: 'Could not process the form.' }) } return res.json({ success: true, message: 'You have successfully logged in!', token, user: userData }) })(req, res, next) }) }, }, logout: (req, res) => { req.logout(); res.status(200).end(); } };
from __future__ import print_function import numpy as np import torch def write_data(filename, data): with open(filename, 'w') as fw: for e in data: fw.write(str(e)) fw.write("\n") def read_data(filename): with open(filename, 'r') as fr: result = fr.readlines() fr.close() data = [] for i in range(len(result)): # str.rstrip(): 删除字符串末尾字符 data.append(eval(result[i].rstrip('\n'))) return data def get_mean_and_std(data): """ 返回 data的均值和标准差(默认为 "总体标准差"; axis 决定计算标准差的维度) :param data: 数据 :return: data的均值和标准差 """ return [np.mean(data), np.std(data)] def get_numerical_characteristics(data): """ 返回数据(data)的 4 个数字特征(numerical characteristics): 1. mean:均值 2. std:标准差 3. skewness: 偏度 4. kurtosis: 峰度 :param data: 数据 :return: 一维数据: torch.Size([4]) """ mean = torch.mean(data) diffs = data - mean var = torch.mean(torch.pow(diffs, 2.0)) std = torch.pow(var, 0.5) z_scores = diffs / std # 偏度:数据分布偏斜方向、程度的度量, 是数据分布非对称程度的数字特征 # 定义: 偏度是样本的三阶标准化矩 skewness = torch.mean(torch.pow(z_scores, 3.0)) # excess kurtosis, should be 0 for Gaussian # 峰度(kurtosis): 表征概率密度分布曲线在平均值处峰值高低的特征数 # 若峰度(kurtosis) > 3, 峰的形状会比较尖, 会比正态分布峰陡峭 kurtoses = torch.mean(torch.pow(z_scores, 4.0)) - 3.0 # reshape(1, ):将常量转化为torch.Size([1])型张量(Tensor) final = torch.cat((mean.reshape(1, ), std.reshape(1, ), skewness.reshape(1, ), kurtoses.reshape(1, ))) return final def decorate_with_diffs(data, exponent, remove_raw_data=False): """ L2 norm: ||x-mean|| decorate_with_diffs 作用: 将原始数据(original data)以及 L2 norm 一起返回, 使 鉴别器 D 了解更多目标数据分布的信息 :param data: Tensor: 张量 :param exponent: 幂次 :param remove_raw_data: 是否移除原始数据 :return: torch.cat([data, diffs], dim=1), dim=0, 同型张量(Tensor)按行合并; dim=1, 同型张量(Tensor)按列合并; """ # dim=0, 行; dim=1, 列; keepdim: 做 mean后, 保持原数据的维度空间, 即, 原原数据为2维, mean 后仍为2维 mean = torch.mean(data.data, dim=1, keepdim=True) # 利用广播(broadcast)机制进行张量(Tensor)乘法 mean_broadcast = torch.mul(torch.ones(data.size()), mean.tolist()[0][0]) # data - data.mean[0] diffs = torch.pow(data - mean_broadcast, exponent) if remove_raw_data: return torch.cat([diffs], dim=1) else: # diffs: 返回样本数据与样本平均值的偏离程度(可以是n次方(exponent)) # 并将样本的偏离程度信息与原始样本一同输入到神经网络中 return torch.cat([data, diffs], dim=1)
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); exports.__esModule = true; exports.default = void 0; var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose")); var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _classnames = _interopRequireDefault(require("classnames")); var _addEventListener = _interopRequireDefault(require("dom-helpers/addEventListener")); var _canUseDOM = _interopRequireDefault(require("dom-helpers/canUseDOM")); var _ownerDocument = _interopRequireDefault(require("dom-helpers/ownerDocument")); var _removeEventListener = _interopRequireDefault(require("dom-helpers/removeEventListener")); var _scrollbarSize = _interopRequireDefault(require("dom-helpers/scrollbarSize")); var _useCallbackRef2 = _interopRequireDefault(require("@restart/hooks/useCallbackRef")); var _useEventCallback = _interopRequireDefault(require("@restart/hooks/useEventCallback")); var _useWillUnmount = _interopRequireDefault(require("@restart/hooks/useWillUnmount")); var _transitionEnd = _interopRequireDefault(require("dom-helpers/transitionEnd")); var _react = _interopRequireWildcard(require("react")); var _Modal = _interopRequireDefault(require("react-overlays/Modal")); var _warning = _interopRequireDefault(require("warning")); var _BootstrapModalManager = _interopRequireDefault(require("./BootstrapModalManager")); var _Fade = _interopRequireDefault(require("./Fade")); var _ModalBody = _interopRequireDefault(require("./ModalBody")); var _ModalContext = _interopRequireDefault(require("./ModalContext")); var _ModalDialog = _interopRequireDefault(require("./ModalDialog")); var _ModalFooter = _interopRequireDefault(require("./ModalFooter")); var _ModalHeader = _interopRequireDefault(require("./ModalHeader")); var _ModalTitle = _interopRequireDefault(require("./ModalTitle")); var _ThemeProvider = require("./ThemeProvider"); var _excluded = ["bsPrefix", "className", "style", "dialogClassName", "contentClassName", "children", "dialogAs", "aria-labelledby", "show", "animation", "backdrop", "keyboard", "onEscapeKeyDown", "onShow", "onHide", "container", "autoFocus", "enforceFocus", "restoreFocus", "restoreFocusOptions", "onEntered", "onExit", "onExiting", "onEnter", "onEntering", "onExited", "backdropClassName", "manager"]; function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } var manager; var defaultProps = { show: false, backdrop: true, keyboard: true, autoFocus: true, enforceFocus: true, restoreFocus: true, animation: true, dialogAs: _ModalDialog.default }; /* eslint-disable no-use-before-define, react/no-multi-comp */ function DialogTransition(props) { return /*#__PURE__*/_react.default.createElement(_Fade.default, (0, _extends2.default)({}, props, { timeout: null })); } function BackdropTransition(props) { return /*#__PURE__*/_react.default.createElement(_Fade.default, (0, _extends2.default)({}, props, { timeout: null })); } /* eslint-enable no-use-before-define */ var Modal = /*#__PURE__*/_react.default.forwardRef(function (_ref, ref) { var bsPrefix = _ref.bsPrefix, className = _ref.className, style = _ref.style, dialogClassName = _ref.dialogClassName, contentClassName = _ref.contentClassName, children = _ref.children, Dialog = _ref.dialogAs, ariaLabelledby = _ref['aria-labelledby'], show = _ref.show, animation = _ref.animation, backdrop = _ref.backdrop, keyboard = _ref.keyboard, onEscapeKeyDown = _ref.onEscapeKeyDown, onShow = _ref.onShow, onHide = _ref.onHide, container = _ref.container, autoFocus = _ref.autoFocus, enforceFocus = _ref.enforceFocus, restoreFocus = _ref.restoreFocus, restoreFocusOptions = _ref.restoreFocusOptions, onEntered = _ref.onEntered, onExit = _ref.onExit, onExiting = _ref.onExiting, onEnter = _ref.onEnter, onEntering = _ref.onEntering, onExited = _ref.onExited, backdropClassName = _ref.backdropClassName, propsManager = _ref.manager, props = (0, _objectWithoutPropertiesLoose2.default)(_ref, _excluded); var _useState = (0, _react.useState)({}), modalStyle = _useState[0], setStyle = _useState[1]; var _useState2 = (0, _react.useState)(false), animateStaticModal = _useState2[0], setAnimateStaticModal = _useState2[1]; var waitingForMouseUpRef = (0, _react.useRef)(false); var ignoreBackdropClickRef = (0, _react.useRef)(false); var removeStaticModalAnimationRef = (0, _react.useRef)(null); // TODO: what's this type var _useCallbackRef = (0, _useCallbackRef2.default)(), modal = _useCallbackRef[0], setModalRef = _useCallbackRef[1]; var handleHide = (0, _useEventCallback.default)(onHide); bsPrefix = (0, _ThemeProvider.useBootstrapPrefix)(bsPrefix, 'modal'); (0, _react.useImperativeHandle)(ref, function () { return { get _modal() { process.env.NODE_ENV !== "production" ? (0, _warning.default)(false, 'Accessing `_modal` is not supported and will be removed in a future release') : void 0; return modal; } }; }, [modal]); var modalContext = (0, _react.useMemo)(function () { return { onHide: handleHide }; }, [handleHide]); function getModalManager() { if (propsManager) return propsManager; if (!manager) manager = new _BootstrapModalManager.default(); return manager; } function updateDialogStyle(node) { if (!_canUseDOM.default) return; var containerIsOverflowing = getModalManager().isContainerOverflowing(modal); var modalIsOverflowing = node.scrollHeight > (0, _ownerDocument.default)(node).documentElement.clientHeight; setStyle({ paddingRight: containerIsOverflowing && !modalIsOverflowing ? (0, _scrollbarSize.default)() : undefined, paddingLeft: !containerIsOverflowing && modalIsOverflowing ? (0, _scrollbarSize.default)() : undefined }); } var handleWindowResize = (0, _useEventCallback.default)(function () { if (modal) { updateDialogStyle(modal.dialog); } }); (0, _useWillUnmount.default)(function () { (0, _removeEventListener.default)(window, 'resize', handleWindowResize); if (removeStaticModalAnimationRef.current) { removeStaticModalAnimationRef.current(); } }); // We prevent the modal from closing during a drag by detecting where the // the click originates from. If it starts in the modal and then ends outside // don't close. var handleDialogMouseDown = function handleDialogMouseDown() { waitingForMouseUpRef.current = true; }; var handleMouseUp = function handleMouseUp(e) { if (waitingForMouseUpRef.current && modal && e.target === modal.dialog) { ignoreBackdropClickRef.current = true; } waitingForMouseUpRef.current = false; }; var handleStaticModalAnimation = function handleStaticModalAnimation() { setAnimateStaticModal(true); removeStaticModalAnimationRef.current = (0, _transitionEnd.default)(modal.dialog, function () { setAnimateStaticModal(false); }); }; var handleStaticBackdropClick = function handleStaticBackdropClick(e) { if (e.target !== e.currentTarget) { return; } handleStaticModalAnimation(); }; var handleClick = function handleClick(e) { if (backdrop === 'static') { handleStaticBackdropClick(e); return; } if (ignoreBackdropClickRef.current || e.target !== e.currentTarget) { ignoreBackdropClickRef.current = false; return; } onHide(); }; var handleEscapeKeyDown = function handleEscapeKeyDown(e) { if (!keyboard && backdrop === 'static') { // Call preventDefault to stop modal from closing in react-overlays, // then play our animation. e.preventDefault(); handleStaticModalAnimation(); } else if (keyboard && onEscapeKeyDown) { onEscapeKeyDown(e); } }; var handleEnter = function handleEnter(node) { if (node) { node.style.display = 'block'; updateDialogStyle(node); } for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (onEnter) onEnter.apply(void 0, [node].concat(args)); }; var handleExit = function handleExit(node) { if (removeStaticModalAnimationRef.current) { removeStaticModalAnimationRef.current(); } for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } if (onExit) onExit.apply(void 0, [node].concat(args)); }; var handleEntering = function handleEntering(node) { for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } if (onEntering) onEntering.apply(void 0, [node].concat(args)); // FIXME: This should work even when animation is disabled. (0, _addEventListener.default)(window, 'resize', handleWindowResize); }; var handleExited = function handleExited(node) { if (node) node.style.display = ''; // RHL removes it sometimes for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { args[_key4 - 1] = arguments[_key4]; } if (onExited) onExited.apply(void 0, args); // FIXME: This should work even when animation is disabled. (0, _removeEventListener.default)(window, 'resize', handleWindowResize); }; var renderBackdrop = (0, _react.useCallback)(function (backdropProps) { return /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({}, backdropProps, { className: (0, _classnames.default)(bsPrefix + "-backdrop", backdropClassName, !animation && 'show') })); }, [animation, backdropClassName, bsPrefix]); var baseModalStyle = (0, _extends2.default)({}, style, modalStyle); // Sets `display` always block when `animation` is false if (!animation) { baseModalStyle.display = 'block'; } var renderDialog = function renderDialog(dialogProps) { return /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({ role: "dialog" }, dialogProps, { style: baseModalStyle, className: (0, _classnames.default)(className, bsPrefix, animateStaticModal && bsPrefix + "-static"), onClick: backdrop ? handleClick : undefined, onMouseUp: handleMouseUp, "aria-labelledby": ariaLabelledby }), /*#__PURE__*/_react.default.createElement(Dialog, (0, _extends2.default)({}, props, { onMouseDown: handleDialogMouseDown, className: dialogClassName, contentClassName: contentClassName }), children)); }; return /*#__PURE__*/_react.default.createElement(_ModalContext.default.Provider, { value: modalContext }, /*#__PURE__*/_react.default.createElement(_Modal.default, { show: show, ref: setModalRef, backdrop: backdrop, container: container, keyboard: true // Always set true - see handleEscapeKeyDown , autoFocus: autoFocus, enforceFocus: enforceFocus, restoreFocus: restoreFocus, restoreFocusOptions: restoreFocusOptions, onEscapeKeyDown: handleEscapeKeyDown, onShow: onShow, onHide: onHide, onEnter: handleEnter, onEntering: handleEntering, onEntered: onEntered, onExit: handleExit, onExiting: onExiting, onExited: handleExited, manager: getModalManager(), containerClassName: bsPrefix + "-open", transition: animation ? DialogTransition : undefined, backdropTransition: animation ? BackdropTransition : undefined, renderBackdrop: renderBackdrop, renderDialog: renderDialog })); }); Modal.displayName = 'Modal'; Modal.defaultProps = defaultProps; Modal.Body = _ModalBody.default; Modal.Header = _ModalHeader.default; Modal.Title = _ModalTitle.default; Modal.Footer = _ModalFooter.default; Modal.Dialog = _ModalDialog.default; Modal.TRANSITION_DURATION = 300; Modal.BACKDROP_TRANSITION_DURATION = 150; var _default = Modal; exports.default = _default; module.exports = exports["default"];
require('./bootstrap'); import $ from 'jquery'; window.jQuery = $; window.$ = $; import Alpine from 'alpinejs'; window.Alpine = Alpine; Alpine.start();
import arrow from django.db import models from django.utils.translation import ugettext_lazy as _ from common.models import Address, User, Company from common.utils import CURRENCY_CODES from accounts.models import Account from phonenumber_field.modelfields import PhoneNumberField from teams.models import Teams class Invoice(models.Model): """Model definition for Invoice.""" INVOICE_STATUS = ( ("Draft", "Draft"), ("Sent", "Sent"), ("Paid", "Paid"), ("Pending", "Pending"), ("Cancelled", "Cancel"), ) invoice_title = models.CharField(_("Invoice Title"), max_length=50) invoice_number = models.CharField(_("Invoice Number"), max_length=50) from_address = models.ForeignKey( Address, related_name="invoice_from_address", on_delete=models.SET_NULL, null=True, ) to_address = models.ForeignKey( Address, related_name="invoice_to_address", on_delete=models.SET_NULL, null=True ) name = models.CharField(_("Name"), max_length=100) email = models.EmailField(_("Email")) assigned_to = models.ManyToManyField(User, related_name="invoice_assigned_to") # quantity is the number of hours worked quantity = models.PositiveIntegerField(default=0) # rate is the rate charged rate = models.DecimalField(default=0, max_digits=12, decimal_places=2) # total amount is product of rate and quantity total_amount = models.DecimalField( blank=True, null=True, max_digits=12, decimal_places=2 ) currency = models.CharField( max_length=3, choices=CURRENCY_CODES, blank=True, null=True ) phone = PhoneNumberField(null=True, blank=True) created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey( User, related_name="invoice_created_by", on_delete=models.SET_NULL, null=True ) amount_due = models.DecimalField( blank=True, null=True, max_digits=12, decimal_places=2 ) amount_paid = models.DecimalField( blank=True, null=True, max_digits=12, decimal_places=2 ) is_email_sent = models.BooleanField(default=False) status = models.CharField(choices=INVOICE_STATUS, max_length=15, default="Draft") details = models.TextField(_("Details"), null=True, blank=True) due_date = models.DateField(blank=True, null=True) accounts = models.ManyToManyField(Account, related_name="accounts_invoices") teams = models.ManyToManyField(Teams, related_name="invoices_teams") company = models.ForeignKey( Company, on_delete=models.SET_NULL, null=True, blank=True ) class Meta: """Meta definition for Invoice.""" verbose_name = "Invoice" verbose_name_plural = "Invoices" def __str__(self): """Unicode representation of Invoice.""" return self.invoice_number def formatted_total_amount(self): return self.currency + " " + str(self.total_amount) def formatted_rate(self): return str(self.rate) + " " + self.currency def formatted_total_quantity(self): return str(self.quantity) + " " + "Hours" def is_draft(self): if self.status == "Draft": return True else: return False def is_sent(self): if self.status == "Sent" and self.is_email_sent == False: return True else: return False def is_resent(self): if self.status == "Sent" and self.is_email_sent == True: return True else: return False def is_paid_or_cancelled(self): if self.status in ["Paid", "Cancelled"]: return True else: return False @property def created_on_arrow(self): return arrow.get(self.created_on).humanize() @property def get_team_users(self): team_user_ids = list(self.teams.values_list("users__id", flat=True)) return User.objects.filter(id__in=team_user_ids) @property def get_team_and_assigned_users(self): team_user_ids = list(self.teams.values_list("users__id", flat=True)) assigned_user_ids = list(self.assigned_to.values_list("id", flat=True)) user_ids = team_user_ids + assigned_user_ids return User.objects.filter(id__in=user_ids) @property def get_assigned_users_not_in_teams(self): team_user_ids = list(self.teams.values_list("users__id", flat=True)) assigned_user_ids = list(self.assigned_to.values_list("id", flat=True)) user_ids = set(assigned_user_ids) - set(team_user_ids) return User.objects.filter(id__in=list(user_ids)) class InvoiceHistory(models.Model): """Model definition for InvoiceHistory. This model is used to track/keep a record of the updates made to original invoice object.""" INVOICE_STATUS = ( ("Draft", "Draft"), ("Sent", "Sent"), ("Paid", "Paid"), ("Pending", "Pending"), ("Cancelled", "Cancel"), ) invoice = models.ForeignKey( Invoice, on_delete=models.CASCADE, related_name="invoice_history" ) invoice_title = models.CharField(_("Invoice Title"), max_length=50) invoice_number = models.CharField(_("Invoice Number"), max_length=50) from_address = models.ForeignKey( Address, related_name="invoice_history_from_address", on_delete=models.SET_NULL, null=True, ) to_address = models.ForeignKey( Address, related_name="invoice_history_to_address", on_delete=models.SET_NULL, null=True, ) name = models.CharField(_("Name"), max_length=100) email = models.EmailField(_("Email")) assigned_to = models.ManyToManyField( User, related_name="invoice_history_assigned_to" ) # quantity is the number of hours worked quantity = models.PositiveIntegerField(default=0) # rate is the rate charged rate = models.DecimalField(default=0, max_digits=12, decimal_places=2) # total amount is product of rate and quantity total_amount = models.DecimalField( blank=True, null=True, max_digits=12, decimal_places=2 ) currency = models.CharField( max_length=3, choices=CURRENCY_CODES, blank=True, null=True ) phone = PhoneNumberField(null=True, blank=True) created_on = models.DateTimeField(auto_now_add=True) # created_by = models.ForeignKey( # User, related_name='invoice_history_created_by', # on_delete=models.SET_NULL, null=True) updated_by = models.ForeignKey( User, related_name="invoice_history_created_by", on_delete=models.SET_NULL, null=True, ) amount_due = models.DecimalField( blank=True, null=True, max_digits=12, decimal_places=2 ) amount_paid = models.DecimalField( blank=True, null=True, max_digits=12, decimal_places=2 ) is_email_sent = models.BooleanField(default=False) status = models.CharField(choices=INVOICE_STATUS, max_length=15, default="Draft") # details or description here stores the fields changed in the original invoice object details = models.TextField(_("Details"), null=True, blank=True) due_date = models.DateField(blank=True, null=True) def __str__(self): """Unicode representation of Invoice.""" return self.invoice_number def formatted_total_amount(self): return self.currency + " " + str(self.total_amount) def formatted_rate(self): return str(self.rate) + " " + self.currency def formatted_total_quantity(self): return str(self.quantity) + " " + "Hours" @property def created_on_arrow(self): return arrow.get(self.created_on).humanize() class Meta: ordering = ("created_on",)
import { STRICT } from '../helpers/constants'; import Symbol from 'core-js-pure/features/symbol'; import filterReject from 'core-js-pure/features/array/filter-reject'; QUnit.test('Array#filterReject', assert => { assert.isFunction(filterReject); let array = [1]; const context = {}; filterReject(array, function (value, key, that) { assert.same(arguments.length, 3, 'correct number of callback arguments'); assert.same(value, 1, 'correct value in callback'); assert.same(key, 0, 'correct index in callback'); assert.same(that, array, 'correct link to array in callback'); assert.same(this, context, 'correct callback context'); }, context); assert.deepEqual([1, 2, 3, 4, 5], filterReject([1, 2, 3, 'q', {}, 4, true, 5], it => typeof it !== 'number')); if (STRICT) { assert.throws(() => filterReject(null, () => { /* empty */ }), TypeError); assert.throws(() => filterReject(undefined, () => { /* empty */ }), TypeError); } array = []; // eslint-disable-next-line object-shorthand -- constructor array.constructor = { [Symbol.species]: function () { return { foo: 1 }; } }; assert.same(filterReject(array, Boolean).foo, 1, '@@species'); });
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M22 2H2.01L2 22l4-4h16V2zm-9 12h-2v-2h2v2zm0-4h-2V6h2v4z" /> , 'FeedbackSharp');
OC.L10N.register( "files_trashbin", { "Deleted files" : "Izbrisane datoteke", "restored" : "obnovljeno", "This application enables users to restore files that were deleted from the system." : "Program omogoča uporabniku obnovitev datotek, ki so bile predhodno izbrisane iz sistema.", "This application enables users to restore files that were deleted from the system. It displays a list of deleted files in the web interface, and has options to restore those deleted files back to the users file directories or remove them permanently from the system. Restoring a file also restores related file versions, if the versions application is enabled. When a file is deleted from a share, it can be restored in the same manner, though it is no longer shared. By default, these files remain in the trash bin for 30 days.\nTo prevent a user from running out of disk space, the Deleted files app will not utilize more than 50% of the currently available free quota for deleted files. If the deleted files exceed this limit, the app deletes the oldest files until it gets below this limit. More information is available in the Deleted Files documentation." : "Program omogoča obnovitev izbrisanih datotek. Datoteke so prikazane kot seznam v spletnem vmesniku, uporabnik pa ima možnost posamezne datoteke obnoviti v ustrezne mape, ali pa jih dokončno izbrisati. Obnovitev povrne tudi shranjene različice datoteke, če so te na voljo. Tudi datoteke, ki so bile izbrisane iz souporabe, je mogoče obnoviti, ne obnovi pa se nastavitev souporabe. Privzeto ostanejo datoteke v košu 30 dni.\nZa preprečevanje popolne zasedenosti, program ne uporabi več kot 50 % trenutno razpoložljivega prostora oziroma količinske omejitve. Če se to zgodi, se najprej do omejitve izbrišejo najstarejše datoteke. Podrobnosti o delovanju in možnostih programa so na voljo v dokumentaciji.", "Restore" : "Obnovi", "Delete permanently" : "Trajno izbriši", "Error while restoring file from trashbin" : "Prišlo je do napake med obnavljanjem datoteke iz koša", "Error while removing file from trashbin" : "Prišlo je do napake med odstranjevanjem datoteke iz koša", "Error while restoring files from trashbin" : "Prišlo je do napake med obnavljanjem datotek iz koša", "Error while emptying trashbin" : "Prišlo je do napake med praznjenjem koša", "Error while removing files from trashbin" : "Prišlo je do napake med odstranjevanjem datotek iz koša", "This operation is forbidden" : "To dejanje ni dovoljeno!", "This directory is unavailable, please check the logs or contact the administrator" : "Mapa ni na voljo. Preverite dnevnik opravil in stopite v stik s skrbnikom sistema.", "No deleted files" : "Ni izbrisanih datotek", "You will be able to recover deleted files from here" : "Izbrisane datoteke je mogoče tudi povrniti.", "No entries found in this folder" : "V tej mapi ni datotek in podmap.", "Select all" : "Izberi vse", "Name" : "Ime", "Actions" : "Dejanja", "Deleted" : "Izbrisano", "Delete" : "Izbriši" }, "nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);");
import a from '@/import-a' console.log(a.b);
const { ReactStateManagement, VueStateManagement, AngularStateManagement } = require("./StateManagement"); const Parser = require("./JavascriptManagement"); const {transform} = require("@babel/core"); /** * React Compiler * * Function that take the HTML string and translate to React * * @param {string} name Component Name * @param {string} html HTML String * @param {string} css CSS String * * @return {string} */ // eslint-disable-next-line no-unused-vars const ReactCompiler = (name, html, css) => { var CSS = ""; if (css && !global.RocketTranslator.allowSSR) CSS = `\nimport "./${name}.css"`; const RStateManagement = new ReactStateManagement(); const parse = new Parser(); //JS Parser //Get all data from HTML string RStateManagement.statesFromJS = parse.states; //Parse Lifecycles RStateManagement.setLifecycle(parse.lifecycles); if (global.RocketTranslator.allowSSR) RStateManagement.styles = css; RStateManagement.getHTMLString(html); RStateManagement.externalComponents = parse.components; //Get Methods from JS and set to Data RStateManagement.getJsData(parse.functions); RStateManagement.watchers = parse.watchers; RStateManagement.setVarsToStatesContent(parse.vars); const JSX = RStateManagement.filterHTML(html); const plugins = ["@babel/plugin-syntax-jsx"]; if (!global.RocketTranslator.jsx) plugins.push("@babel/plugin-transform-react-jsx"); //Template to Set All Data var template = `import React, {Component} from "react";${CSS} ${RStateManagement.importComponents} class ${name || "MyComponent"} extends Component { ${RStateManagement.componentData} render() { ${RStateManagement.preRender} return (${JSX}) } } export default ${name || "MyComponent"}; `; template = transform(template, {plugins}).code; return { main:template, components:RStateManagement.componentsContent }; }; /** * Vue Compiler * * Function that take the HTML string and translate to Vue * * @param {String} name Component Name * @param {string} html HTML String * @param {string} css CSS String * * @return {string} */ const VueCompiler = (name, html, css) => { const VStateManagement = new VueStateManagement(); const parse = new Parser(); //JS Parser // Set Styles const style = css !== "" ? `\n<style scoped>\n${css}</style>` : ""; //Get states declarations from JS and set to Data VStateManagement.statesFromJS = parse.states; //Parse Lifecycles VStateManagement.setLifecycle(parse.lifecycles); //Get all data from HTML string VStateManagement.getHTMLString(html); VStateManagement.externalComponents = parse.components; //Get Methods from JS and set to Data VStateManagement.getJsData(parse.functions); VStateManagement.watchers = parse.watchers; VStateManagement.setVarsToStatesContent(parse.vars); var HTML = ""; if (!global.RocketTranslator.jsx) { //Add new lines and idents to code beauty const pretty = VStateManagement .filterHTML(html) .split(/\n/) .map(e => { if (e) return `\t${e}\n`; }) .join(""); HTML = `<template>\n${pretty}</template>\n`; } //Template to Set All Data const component = `${HTML}${VStateManagement.componentData(name, html)}${style}`; return { main:component, components:VStateManagement.componentsContent }; }; /** * Angular Compiler * * Function that take the HTML string and translate to Angular * * @param {String} name Component Name * @param {string} html HTML String * @param {string} css CSS String * * @return {string} */ // eslint-disable-next-line no-unused-vars const AngularCompiler = (name, html, css) => { const AStateManagement = new AngularStateManagement(); const parse = new Parser(); //JS Parser //Get states declarations from JS and set to Data AStateManagement.statesFromJS = parse.states; //Parse Lifecycles AStateManagement.setLifecycle(parse.lifecycles); //Get all data from HTML string AStateManagement.getHTMLString(html); //Get Methods from JS and set to Data AStateManagement.getJsData(parse.functions); AStateManagement.externalComponents = parse.components; AStateManagement.watchers = parse.watchers; AStateManagement.setVarsToStatesContent(parse.vars); //Add new lines and idents to code beauty const pretty = AStateManagement .filterHTML(html) .split(/\n/) .map(e => { if (e) return `\t${e}\n`; }) .join(""); const component = `import { Component${AStateManagement.props.length > 0 ? ", Input" : ""}} from '@angular/core'; ${AStateManagement.components.map(e => `\nimport { ${e} } from "./components/${e}";`).join("")} @Component({ selector: '${AStateManagement.generateComponentName(name)}-root', template:\`${pretty}\` }) export class ${name} { ${AStateManagement.componentData} }`; return { main:component, components:AStateManagement.componentsContent }; }; module.exports = { VueCompiler, AngularCompiler, ReactCompiler };
$(function () { // when docs ready call data table var type = $('#scriptDefinition').data('type'); var targetURL = 'getCouncielDefinitionAjax'; var lang = $('#scriptDefinition').data('lang'); if(lang == 'ar'){ var arabicLanguage = { "sProcessing": "جارٍ التحميل...", "sLengthMenu": "أظهر _MENU_ مدخلات", "sZeroRecords": "لم يعثر على أية سجلات", "sInfo": "إظهار _START_ إلى _END_ من أصل _TOTAL_ مدخل", "sInfoEmpty": "يعرض 0 إلى 0 من أصل 0 سجل", "sInfoFiltered": "(منتقاة من مجموع _MAX_ مُدخل)", "sInfoPostFix": "", "sSearch": "ابحث:", "sUrl": "", "oPaginate": { "sFirst": "الأول", "sPrevious": "السابق", "sNext": "التالي", "sLast": "الأخير" } }; } else{ var arabicLanguage = {}; } $('#get-data').DataTable({ "language": arabicLanguage, processing: true, serverSide: true, ajax: { url: targetURL, type: "get", }, columns: [{ data: 'council_name', render: function (council_name) { return council_name; } }, { data: 'faculty', render: function (faculty) { return faculty; } }, { data: 'number_of_members', render: function (number_of_members) { return number_of_members; } }, { data: 'numberOfMeeting', render: function (numberOfMeeting) { return numberOfMeeting; } }, { data: 'id', orderable: false, render: function (data) { view = '<a href="councilDefinition/' + data + '" class="btn btn-sm btn-success text-white ml-2"><i class="fas fa-eye"></i> </a>'; edit = '<a href="councilDefinition/' + data + '/edit" class="btn btn-sm btn-info text-white ml-2"><i class="fas fa-marker"></i> </a>'; remove = '<a class="btn btn-sm btn-danger text-white" data-toggle="modal" data-target="#deleteModal" onclick="openModal(' + data + ')" > <i class="far fa-trash-alt"></i> </a>'; if(type == 0){ return view + '&nbsp;' + edit + '&nbsp;' + remove; } else{ return view; } } }, ] }); $('.message').slideDown(function () { setTimeout(function () { $('.message').slideUp(function () { $(this).remove(); }); }, 8000); }); }); // open modal to delete item function openModal(id) { $('#RemoveItem').val(id); } // delete Gas Station function DeleteItem() { var id = $('#RemoveItem').val(); // ajax delete data to database var targetURL = 'councilDefinition/' + id; $.ajax({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, url: targetURL, type: "POST", data: { "id": id, '_method': 'DELETE' }, success: function (response) { if (response == 1) { $('#SuccessDelete').fadeIn(200); $('#get-data').DataTable().ajax.reload(null, false); setTimeout(function () { $('#SuccessDelete').fadeOut('fast'); }, 5000); // <-- time in milliseconds } else { alert('Drawing not deleted !! try again later'); } }, error: function (err) { console.log(err); } }); }
const jwt = require("jsonwebtoken"); const mongoose = require("mongoose"); const User = mongoose.model("User"); module.exports = (req, res, next) => { const { authorization } = req.headers; if (!authorization) { return res.status(401).json({ error: "you must be logged in" }); } const token = authorization.replace("Bearer ", ""); jwt.verify(token, "hmm", (err, payload) => { if (err) { return res.status(401).json({ error: "you must be logged in" }); } const { _id } = payload; User.findById(_id).then((userdata) => { req.user = userdata; next(); }); }); };
// @ts-nocheck /* :: import type { Window } from '../types'; */ /* :: declare function getWindow(node: Node | Window): Window; */ /** * @param node */ export default function getWindow(node) { if (node.toString() !== '[object Window]') { const ownerDocument = node.ownerDocument; return ownerDocument ? ownerDocument.defaultView : window; } return node; } //# sourceMappingURL=getWindow.js.map
'use strict'; // Partytypes module config angular.module('partytypes').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Party type', 'partytypes', 'dropdown', 'partytypes(/create)?', false, ['admin']); Menus.addSubMenuItem('topbar', 'partytypes', 'List partytypes', 'partytypes'); Menus.addSubMenuItem('topbar', 'partytypes', 'New partytype', 'partytypes/create'); } ]);
import requests from bs4 import BeautifulSoup import os import sys import configparser import re import concurrent.futures from tqdm import tqdm import dhash from PIL import Image from time import sleep import gettext #Initialisation global date global resolution global hash_keys global duplicates duplicates = [] hash_keys = dict() #reading config file conf = configparser.ConfigParser() conf.read("config.cfg") resolution = conf.get('config', 'resolution') langs = conf.get('config', 'langs') langs = langs.replace(' ', '').replace('"', '').replace("'", '').strip('[]').split(',') screenshot = conf.get('config', 'screenshot') == "True" devblog = conf.get('config', 'devblog') == "True" date = int(conf.get('config', 'date')) overwriteMode = conf.get('tool config', 'overwriteMode') == "True" language = conf.get('tool config', 'language') if language == "fr" : fr = gettext.translation('lang', localedir='locale', languages=['fr']) fr.install() else : #elif language == "en" : _ = lambda s: s print(_("This tool will download wallpapers from the WarThunder website in a wallpapers folder in the same folder as this tool. The duration will depends on what you want to download and on your bandwidth")) print(_("To change parameters (ie : what to download), edit the config.cfg file.\n")) print(_("Curent parameters :")) print(_("Resolution : "), resolution) print(_("Download website(s) : "), langs) print(_("Download screenshot : "), screenshot) print(_("Download wallpapers from devblogs : "), devblog) print(_("Will not download images prior to : "), date) #Creating a wallpapers folder, if already exists but empty continue, else prompt the user to delete it try : os.makedirs('wallpapers/') print(_("Creating a wallpapers folder !")) except : if overwriteMode : pass elif os.listdir('wallpapers/') != [] : input(_("Please delete the wallpapers folder, this tool will create one.\nPress ENTER to exit.")) sys.exit() else : pass input(_("Press ENTER to confirm")) print(_("\nSearching wallpapers")) def download(url, img_number, pbar, img_type) : global date if img_type == "wallpaper" : filename = 'wallpapers/wallpaper_' + str(img_number) + '_temp.jpg' elif img_type == "screenshot" : filename = 'wallpapers/screenshot_' + str(img_number) + '_temp.jpg' else : filename = 'wallpapers/devblog_' + str(img_number) + '_temp.jpg' r = requests.get(url, stream = True) x = re.compile(r"\d\d\d\d") #to extract the date if int(x.findall(r.headers['Last-Modified'])[0]) >= date : #download only if it's recent enough img_data = r.content with open(filename, 'wb') as handler: handler.write(img_data) pbar.update(approx_file_size) else : pbar.total -= approx_file_size pbar.refresh() def removeDoubles() : #To check if an image is a double we check the hash of each files, if we find duplicates we remove the first one #We use dhash and not just hash to remove duplicates pictures with different logos global duplicates file_list = os.listdir('wallpapers/') with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor: pbar = tqdm(total=len(file_list), unit='images') for i in range(0, len(file_list), 10) : #working 10 files at a time workinglist = file_list[i:i+10] executor.submit(hashThreaded, workinglist, pbar) pbar.close() print(_("Removing %s doubles !") % (str(len(duplicates)))) for index in duplicates : #removing duplicates os.remove('wallpapers/' + index[0]) def hashThreaded(workinglist, pbar) : global hash_keys global duplicates for index, filename in enumerate(workinglist) : if os.path.isfile('wallpapers/' + filename) : try : image = Image.open('wallpapers/' + filename) #try to open the image, if it fails, delete it row, col = dhash.dhash_row_col(image) filehash = dhash.format_hex(row, col) if filehash not in hash_keys : hash_keys[filehash] = index else: duplicates.append((filename,hash_keys[filehash])) except : os.remove('wallpapers/' + filename) pbar.update(1) def getWallpapers(page, lang) : sublist=[] url = "https://warthunder.com/" + lang + "/media/wallpapers/page/" + str(page) r = requests.get(url, stream = True) if r.status_code != 200 : return [] soup = BeautifulSoup(r.text, 'html.parser') links = soup.find_all('div', {'class': 'wallpapers__dimensions'}) image_links = [] for link in links : try : #getting every link for images in the page image_links.append(link.find('a', {'class': 'wallpapers__dimensions-link gallery galleryScreenshot'}, text = resolution)['href'].replace('//', 'http://')) except : pass for i in range(len(image_links)) : img_link = image_links[i] sublist.append(img_link) if len(image_links) != 0 : print(_("%s more images were found from %s for a total of %s images\r") % (len(image_links), url, str(len(masterlist))), end="") return sublist masterlist = [] #Looping through each language the user selected for lang in langs : page = 1 stop = False with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor : while stop == False : #looping until it gets a 404 error thread1 = executor.submit(getWallpapers, page, lang) page += 1 thread2 = executor.submit(getWallpapers, page, lang) page += 1 thread3 = executor.submit(getWallpapers, page, lang) page += 1 thread4 = executor.submit(getWallpapers, page, lang) page += 1 masterlist.extend(thread1.result()) masterlist.extend(thread2.result()) masterlist.extend(thread3.result()) masterlist.extend(thread4.result()) if thread4.result() == [] : stop = True approx_file_size = 750000 #in byte, estimated approx_file_size_total = len(masterlist)*approx_file_size print(_("\nChecking %s images") % (str(len(masterlist)))) #Starting download with concurrent.futures.ThreadPoolExecutor(max_workers=12) as executor: pbar = tqdm(total=approx_file_size_total, unit='B', unit_scale=True) for img_number, img_link in enumerate(masterlist) : executor.submit(download, img_link, img_number, pbar, "wallpaper") pbar.close() print(_("Downloaded %s images so far") % (str(len(os.listdir('wallpapers/'))))) #screenshots def getScreenshots(page, lang) : sublist=[] url = "https://warthunder.com/" + lang + "/media/screenshots/page/" + str(page) r = requests.get(url, stream = True) if r.status_code != 200 : return [] soup = BeautifulSoup(r.text, 'html.parser') links = soup.find_all('div', {'class': 'wallpapers__image'}) image_links = [] for link in links : try : #getting every link for images in the page image_links.append(link.find('a', {'class': 'gallery galleryMode'})['href'].replace('//', 'http://')) except : pass for i in range(len(image_links)) : img_link = image_links[i] sublist.append(img_link) if len(image_links) != 0 : print(_("%s more images were found from %s for a total of %s images\r") % (len(image_links), url, str(len(masterlist))), end="") return sublist #Pretty same as above but for the screenshot page which has more or less the same structure if screenshot : masterlist = [] print(_("\nSearching screenshots")) for lang in langs : page = 1 stop = False with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor : while stop == False : #looping until it gets a 404 error thread1 = executor.submit(getScreenshots, page, lang) page += 1 thread2 = executor.submit(getScreenshots, page, lang) page += 1 thread3 = executor.submit(getScreenshots, page, lang) page += 1 thread4 = executor.submit(getScreenshots, page, lang) page += 1 masterlist.extend(thread1.result()) masterlist.extend(thread2.result()) masterlist.extend(thread3.result()) masterlist.extend(thread4.result()) if thread4.result() == [] : stop = True approx_file_size_total = len(masterlist)*approx_file_size print(_("\nChecking %s images") % (str(len(masterlist)))) #Starting download with concurrent.futures.ThreadPoolExecutor(max_workers=12) as executor: pbar = tqdm(total=approx_file_size_total, unit='B', unit_scale=True) for img_number, img_link in enumerate(masterlist) : executor.submit(download, img_link, img_number, pbar, "screenshot") pbar.close() print(_("Downloaded %s images so far") % (str(len(os.listdir('wallpapers/'))))) #devblogs #devblog are quite differents as we are getting devblogs links then getting the wallpaper link if it exists and then saving it as temp once again def getDevblog(page) : global resolution global date sublist=[] url = "https://warthunder.com/en/news/page/" + str(page) + "/?tags=Development" r = requests.get(url, stream = True) if r.status_code != 200 : return [] soup = BeautifulSoup(r.text, 'html.parser') links = soup.find_all('div', {'class': 'news-item'}) image_links = [] for link in links : try : #getting every link for images in the page image_links.append("https://warthunder.com" + link.find("div", {"class": "news-item__anons"}).find('a', {'class': 'news-item__title'})['href']) except : pass for i in range(len(image_links)) : url_page = image_links[i] r = requests.get(url_page, stream = True) if r.status_code == 429 : sleep(1) continue x = re.compile(r"\d\d\d\d") #to extract the date if int(x.findall(r.headers['Last-Modified'])[0]) >= date : #To avoid looking up older devblogs but it's pretty unreliable soup = BeautifulSoup(r.text, 'html.parser') try : img_link = soup.find("a", text = resolution)["href"] if img_link.startswith("http") : #Some older devblogs have a different file managing structure pass else : img_link = "https://static.warthunder.com/" + img_link sublist.append(img_link) except : pass sleep(0.5) #to avoid status code 429 if sublist != [] : print(_("%s more images were found from %s for a total of %s images\r") % (len(sublist), url, str(len(masterlist))), end="") return sublist if devblog : masterlist = [] nombres_images = 0 print(_("Searching wallpapers from devblogs.")) page = 1 stop = False with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor : while stop == False : #looping until it gets a 404 error thread1 = executor.submit(getDevblog, page) page += 1 thread2 = executor.submit(getDevblog, page) page += 1 thread3 = executor.submit(getDevblog, page) page += 1 thread4 = executor.submit(getDevblog, page) page += 1 masterlist.extend(thread1.result()) masterlist.extend(thread2.result()) masterlist.extend(thread3.result()) masterlist.extend(thread4.result()) if thread4.result() == [] : stop = True approx_file_size_total = len(masterlist)*approx_file_size print(_("\nChecking %s images") % (str(len(masterlist)))) #Starting download with concurrent.futures.ThreadPoolExecutor(max_workers=12) as executor: pbar = tqdm(total=approx_file_size_total, unit='B', unit_scale=True) for img_number, img_link in enumerate(masterlist) : executor.submit(download, img_link, img_number, pbar, "devblog") pbar.close() print(_("Downloaded %s images so far") % (str(len(os.listdir('wallpapers/'))))) print(_("Cleaning up")) removeDoubles() print(_("Reorganising files")) file_list = os.listdir('wallpapers/') #We now have an incomplete count (ie : 0 - 1 - 3 - 7 - 8...) and we want an homogeneous one #We do it first for screenshot by extracting files strating by "screenshot_" #note : a should be faster by using recursion but performance isn't really that much of a concern here filetypes = ["wallpaper_"] if screenshot : filetypes.append("screenshot_") if devblog : filetypes.append("devblog_") for filetype in filetypes : working_file_list = [x for x in file_list if filetype in x] file_max = 0 for file in working_file_list : if int(file.replace(filetype, "").replace("_temp", "").replace(".jpg", "")) > file_max : file_max = int(file.replace(filetype, "").replace("_temp", "").replace(".jpg", "")) for i in range(len(working_file_list)) : #renaming files to fill the gap os.replace('wallpapers/' + working_file_list[i], "wallpapers/" + filetype + str(i) + ".jpg") #Conclusion print(_("%s unique images saved in the wallpapers folder !") % (str(len(os.listdir('wallpapers/'))))) print(_("Thank you for using this tool made with %s by Rudlu") % ("♥")) input(_("Press ENTER to exit"))
/** * Theme: Metrica - Responsive Bootstrap 4 Admin Dashboard * Author: Mannatthemes * chartist Js */ //smil-animations Chart var chart = new Chartist.Line('#smil-animations', { labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], series: [ [12, 9, 7, 8, 5, 4, 6, 2, 3, 3, 4, 6], [4, 5, 3, 7, 3, 5, 5, 3, 4, 4, 5, 5], [5, 3, 4, 5, 6, 3, 3, 4, 5, 6, 3, 4], [3, 4, 5, 6, 7, 6, 4, 5, 6, 7, 6, 3] ] }, { low: 0, plugins: [ Chartist.plugins.tooltip() ] }); // Let's put a sequence number aside so we can use it in the event callbacks var seq = 0, delays = 80, durations = 500; // Once the chart is fully created we reset the sequence chart.on('created', function() { seq = 0; }); // On each drawn element by Chartist we use the Chartist.Svg API to trigger SMIL animations chart.on('draw', function(data) { seq++; if(data.type === 'line') { // If the drawn element is a line we do a simple opacity fade in. This could also be achieved using CSS3 animations. data.element.animate({ opacity: { // The delay when we like to start the animation begin: seq * delays + 1000, // Duration of the animation dur: durations, // The value where the animation should start from: 0, // The value where it should end to: 1 } }); } else if(data.type === 'label' && data.axis === 'x') { data.element.animate({ y: { begin: seq * delays, dur: durations, from: data.y + 100, to: data.y, // We can specify an easing function from Chartist.Svg.Easing easing: 'easeOutQuart' } }); } else if(data.type === 'label' && data.axis === 'y') { data.element.animate({ x: { begin: seq * delays, dur: durations, from: data.x - 100, to: data.x, easing: 'easeOutQuart' } }); } else if(data.type === 'point') { data.element.animate({ x1: { begin: seq * delays, dur: durations, from: data.x - 10, to: data.x, easing: 'easeOutQuart' }, x2: { begin: seq * delays, dur: durations, from: data.x - 10, to: data.x, easing: 'easeOutQuart' }, opacity: { begin: seq * delays, dur: durations, from: 0, to: 1, easing: 'easeOutQuart' } }); } else if(data.type === 'grid') { // Using data.axis we get x or y which we can use to construct our animation definition objects var pos1Animation = { begin: seq * delays, dur: durations, from: data[data.axis.units.pos + '1'] - 30, to: data[data.axis.units.pos + '1'], easing: 'easeOutQuart' }; var pos2Animation = { begin: seq * delays, dur: durations, from: data[data.axis.units.pos + '2'] - 100, to: data[data.axis.units.pos + '2'], easing: 'easeOutQuart' }; var animations = {}; animations[data.axis.units.pos + '1'] = pos1Animation; animations[data.axis.units.pos + '2'] = pos2Animation; animations['opacity'] = { begin: seq * delays, dur: durations, from: 0, to: 1, easing: 'easeOutQuart' }; data.element.animate(animations); } }); // For the sake of the example we update the chart every time it's created with a delay of 10 seconds chart.on('created', function() { if(window.__exampleAnimateTimeout) { clearTimeout(window.__exampleAnimateTimeout); window.__exampleAnimateTimeout = null; } window.__exampleAnimateTimeout = setTimeout(chart.update.bind(chart), 12000); }); //Simple line chart new Chartist.Line('#simple-line-chart', { labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], series: [ [12, 9, 7, 8, 5], [2, 1, 3.5, 7, 3], [1, 3, 4, 5, 6] ] }, { fullWidth: true, chartPadding: { right: 40 }, plugins: [ Chartist.plugins.tooltip() ] }); //Line Scatter Diagram var times = function(n) { return Array.apply(null, new Array(n)); }; var data = times(52).map(Math.random).reduce(function(data, rnd, index) { data.labels.push(index + 1); data.series.forEach(function(series) { series.push(Math.random() * 100) }); return data; }, { labels: [], series: times(4).map(function() { return new Array() }) }); var options = { showLine: false, axisX: { labelInterpolationFnc: function(value, index) { return index % 13 === 0 ? 'W' + value : null; } } }; var responsiveOptions = [ ['screen and (min-width: 640px)', { axisX: { labelInterpolationFnc: function(value, index) { return index % 4 === 0 ? 'W' + value : null; } } }] ]; new Chartist.Line('#scatter-diagram', data, options, responsiveOptions); //Line chart with area new Chartist.Line('#chart-with-area', { labels: [1, 2, 3, 4, 5, 6, 7, 8], series: [ [5, 9, 7, 8, 5, 3, 5, 4] ] }, { low: 0, showArea: true, plugins: [ Chartist.plugins.tooltip() ] }); //Overlapping bars on mobile var data = { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], series: [ [5, 4, 3, 7, 5, 10, 3, 4, 8, 10, 6, 8], [3, 2, 9, 5, 4, 6, 4, 6, 7, 8, 7, 4] ] }; var options = { seriesBarDistance: 10 }; var responsiveOptions = [ ['screen and (max-width: 640px)', { seriesBarDistance: 5, axisX: { labelInterpolationFnc: function (value) { return value[0]; } } }] ]; new Chartist.Bar('#overlapping-bars', data, options, responsiveOptions); //Stacked bar chart new Chartist.Bar('#stacked-bar-chart', { labels: ['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6'], series: [ [800000, 1200000, 1400000, 1300000, 1520000, 1400000], [200000, 400000, 500000, 300000, 452000, 500000], [160000, 290000, 410000, 600000, 588000, 410000] ] }, { stackBars: true, axisY: { labelInterpolationFnc: function(value) { return (value / 1000) + 'k'; } }, plugins: [ Chartist.plugins.tooltip() ] }).on('draw', function(data) { if(data.type === 'bar') { data.element.attr({ style: 'stroke-width: 30px' }); } }); //Animating a Donut with Svg.animate var chart = new Chartist.Pie('#animating-donut', { series: [20, 20, 20, ], labels: [1, 2, 3] }, { donut: true, showLabel: false, plugins: [ Chartist.plugins.tooltip() ] }); chart.on('draw', function(data) { if(data.type === 'slice') { // Get the total path length in order to use for dash array animation var pathLength = data.element._node.getTotalLength(); // Set a dasharray that matches the path length as prerequisite to animate dashoffset data.element.attr({ 'stroke-dasharray': pathLength + 'px ' + pathLength + 'px' }); // Create animation definition while also assigning an ID to the animation for later sync usage var animationDefinition = { 'stroke-dashoffset': { id: 'anim' + data.index, dur: 1000, from: -pathLength + 'px', to: '0px', easing: Chartist.Svg.Easing.easeOutQuint, // We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible) fill: 'freeze' } }; // If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation if(data.index !== 0) { animationDefinition['stroke-dashoffset'].begin = 'anim' + (data.index - 1) + '.end'; } // We need to set an initial value before the animation starts as we are not in guided mode which would do that for us data.element.attr({ 'stroke-dashoffset': -pathLength + 'px' }); // We can't use guided mode as the animations need to rely on setting begin manually // See http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-animate data.element.animate(animationDefinition, false); } }); // For the sake of the example we update the chart every time it's created with a delay of 8 seconds chart.on('created', function() { if(window.__anim21278907124) { clearTimeout(window.__anim21278907124); window.__anim21278907124 = null; } window.__anim21278907124 = setTimeout(chart.update.bind(chart), 10000); }); //Simple pie chart var data = { series: [5, 3, 4] }; var sum = function(a, b) { return a + b }; new Chartist.Pie('#simple-pie', data, { labelInterpolationFnc: function(value) { return Math.round(value / data.series.reduce(sum) * 100) + '%'; } });
const path = require('path'); const merge = require('webpack-merge'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const TerserPlugin = require('terser-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const common = require('./webpack.common'); module.exports = merge(common, { mode: 'production', output: { filename: '[name].[contentHash]-bundle.js', path: path.resolve(__dirname, 'dist'), publicPath: '/dist', }, optimization: { minimizer: [ new OptimizeCssAssetsPlugin(), new TerserPlugin(), new HtmlWebpackPlugin({ template: './client/index.html', minify: { removeAttributeQuotes: true, collapseWhitespace: true, removeComments: true, }, }), ], }, plugins: [ new MiniCssExtractPlugin({ filename: '[name]-[contentHash].css', }), new CleanWebpackPlugin(), ], module: { rules: [ { // test: /\.scss$/, test: /\.css$/, use: [ MiniCssExtractPlugin.loader, // 3. Extract css into files 'css-loader', // 2. Turns css into commonjs // "sass-loader" //1. Turns sass into css ], }, ], }, });
!function(a){var e={};function t(i){if(e[i])return e[i].exports;var n=e[i]={i:i,l:!1,exports:{}};return a[i].call(n.exports,n,n.exports,t),n.l=!0,n.exports}t.m=a,t.c=e,t.d=function(a,e,i){t.o(a,e)||Object.defineProperty(a,e,{configurable:!1,enumerable:!0,get:i})},t.n=function(a){var e=a&&a.__esModule?function(){return a.default}:function(){return a};return t.d(e,"a",e),e},t.o=function(a,e){return Object.prototype.hasOwnProperty.call(a,e)},t.p="",t(t.s=1)}({1:function(a,e,t){a.exports=t("fIwt")},fIwt:function(a,e){var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a};!function(a){var e=[],i={options:{prependExistingHelpBlock:!1,sniffHtml:!0,preventSubmit:!0,submitError:!1,submitSuccess:!1,semanticallyStrict:!1,autoAdd:{helpBlocks:!0},filter:function(){return!0}},methods:{init:function(t){var r=a.extend(!0,{},i);r.options=a.extend(!0,r.options,t);var l=a.unique(this.map(function(){return a(this).parents("form")[0]}).toArray());return a(l).bind("submit",function(e){var t=a(this),i=0,n=t.find("input,textarea,select").not("[type=submit],[type=image]").filter(r.options.filter);n.trigger("submit.validation").trigger("validationLostFocus.validation"),n.each(function(e,t){var n=a(t).parents(".form-group").first();n.hasClass("warning")&&(n.removeClass("warning").addClass("error"),i++)}),n.trigger("validationLostFocus.validation"),i?(r.options.preventSubmit&&e.preventDefault(),t.addClass("error"),a.isFunction(r.options.submitError)&&r.options.submitError(t,e,n.jqBootstrapValidation("collectErrors",!0))):(t.removeClass("error"),a.isFunction(r.options.submitSuccess)&&r.options.submitSuccess(t,e))}),this.each(function(){var t=a(this),i=t.parents(".form-group").first(),l=i.find(".help-block").first(),s=t.parents("form").first(),d=[];if(!l.length&&r.options.autoAdd&&r.options.autoAdd.helpBlocks&&(l=a('<div class="help-block" />'),i.find(".controls").append(l),e.push(l[0])),r.options.sniffHtml){var c="";if(void 0!==t.attr("pattern")&&(c="Not in the expected format\x3c!-- data-validation-pattern-message to override --\x3e",t.data("validationPatternMessage")&&(c=t.data("validationPatternMessage")),t.data("validationPatternMessage",c),t.data("validationPatternRegex",t.attr("pattern"))),void 0!==t.attr("max")||void 0!==t.attr("aria-valuemax")){var u=void 0!==t.attr("max")?t.attr("max"):t.attr("aria-valuemax");c="Too high: Maximum of '"+u+"'\x3c!-- data-validation-max-message to override --\x3e",t.data("validationMaxMessage")&&(c=t.data("validationMaxMessage")),t.data("validationMaxMessage",c),t.data("validationMaxMax",u)}if(void 0!==t.attr("min")||void 0!==t.attr("aria-valuemin")){var v=void 0!==t.attr("min")?t.attr("min"):t.attr("aria-valuemin");c="Too low: Minimum of '"+v+"'\x3c!-- data-validation-min-message to override --\x3e",t.data("validationMinMessage")&&(c=t.data("validationMinMessage")),t.data("validationMinMessage",c),t.data("validationMinMin",v)}void 0!==t.attr("maxlength")&&(c="Too long: Maximum of '"+t.attr("maxlength")+"' characters\x3c!-- data-validation-maxlength-message to override --\x3e",t.data("validationMaxlengthMessage")&&(c=t.data("validationMaxlengthMessage")),t.data("validationMaxlengthMessage",c),t.data("validationMaxlengthMaxlength",t.attr("maxlength"))),void 0!==t.attr("minlength")&&(c="Too short: Minimum of '"+t.attr("minlength")+"' characters\x3c!-- data-validation-minlength-message to override --\x3e",t.data("validationMinlengthMessage")&&(c=t.data("validationMinlengthMessage")),t.data("validationMinlengthMessage",c),t.data("validationMinlengthMinlength",t.attr("minlength"))),void 0===t.attr("required")&&void 0===t.attr("aria-required")||(c=r.builtInValidators.required.message,t.data("validationRequiredMessage")&&(c=t.data("validationRequiredMessage")),t.data("validationRequiredMessage",c)),void 0!==t.attr("type")&&"number"===t.attr("type").toLowerCase()&&(c=r.builtInValidators.number.message,t.data("validationNumberMessage")&&(c=t.data("validationNumberMessage")),t.data("validationNumberMessage",c)),void 0!==t.attr("type")&&"email"===t.attr("type").toLowerCase()&&(c="Not a valid email address\x3c!-- data-validator-validemail-message to override --\x3e",t.data("validationValidemailMessage")?c=t.data("validationValidemailMessage"):t.data("validationEmailMessage")&&(c=t.data("validationEmailMessage")),t.data("validationValidemailMessage",c)),void 0!==t.attr("minchecked")&&(c="Not enough options checked; Minimum of '"+t.attr("minchecked")+"' required\x3c!-- data-validation-minchecked-message to override --\x3e",t.data("validationMincheckedMessage")&&(c=t.data("validationMincheckedMessage")),t.data("validationMincheckedMessage",c),t.data("validationMincheckedMinchecked",t.attr("minchecked"))),void 0!==t.attr("maxchecked")&&(c="Too many options checked; Maximum of '"+t.attr("maxchecked")+"' required\x3c!-- data-validation-maxchecked-message to override --\x3e",t.data("validationMaxcheckedMessage")&&(c=t.data("validationMaxcheckedMessage")),t.data("validationMaxcheckedMessage",c),t.data("validationMaxcheckedMaxchecked",t.attr("maxchecked")))}void 0!==t.data("validation")&&(d=t.data("validation").split(",")),a.each(t.data(),function(a,e){var t=a.replace(/([A-Z])/g,",$1").split(",");"validation"===t[0]&&t[1]&&d.push(t[1])});var m=d,g=[];do{a.each(d,function(a,e){d[a]=n(e)}),d=a.unique(d),g=[],a.each(m,function(e,i){if(void 0!==t.data("validation"+i+"Shortcut"))a.each(t.data("validation"+i+"Shortcut").split(","),function(a,e){g.push(e)});else if(r.builtInValidators[i.toLowerCase()]){var o=r.builtInValidators[i.toLowerCase()];"shortcut"===o.type.toLowerCase()&&a.each(o.shortcut.split(","),function(a,e){e=n(e),g.push(e),d.push(e)})}}),m=g}while(m.length>0);var h={};a.each(d,function(e,i){var o=t.data("validation"+i+"Message"),l=void 0!==o,s=!1;if(o=o||"'"+i+"' validation failed \x3c!-- Add attribute 'data-validation-"+i.toLowerCase()+"-message' to input to change this message --\x3e",a.each(r.validatorTypes,function(e,r){void 0===h[e]&&(h[e]=[]),s||void 0===t.data("validation"+i+n(r.name))||(h[e].push(a.extend(!0,{name:n(r.name),message:o},r.init(t,i))),s=!0)}),!s&&r.builtInValidators[i.toLowerCase()]){var d=a.extend(!0,{},r.builtInValidators[i.toLowerCase()]);l&&(d.message=o);var c=d.type.toLowerCase();"shortcut"===c?s=!0:a.each(r.validatorTypes,function(e,o){void 0===h[e]&&(h[e]=[]),s||c!==e.toLowerCase()||(t.data("validation"+i+n(o.name),d[o.name.toLowerCase()]),h[c].push(a.extend(d,o.init(t,i))),s=!0)})}s||a.error("Cannot find validation info for '"+i+"'")}),l.data("original-contents",l.data("original-contents")?l.data("original-contents"):l.html()),l.data("original-role",l.data("original-role")?l.data("original-role"):l.attr("role")),i.data("original-classes",i.data("original-clases")?i.data("original-classes"):i.attr("class")),t.data("original-aria-invalid",t.data("original-aria-invalid")?t.data("original-aria-invalid"):t.attr("aria-invalid")),t.bind("validation.validation",function(e,i){var n=o(t),l=[];return a.each(h,function(e,o){(n||n.length||i&&i.includeEmpty||r.validatorTypes[e].blockSubmit&&i&&i.submitting)&&a.each(o,function(a,i){r.validatorTypes[e].validate(t,n,i)&&l.push(i.message)})}),l}),t.bind("getValidators.validation",function(){return h}),t.bind("submit.validation",function(){return t.triggerHandler("change.validation",{submitting:!0})}),t.bind(["keyup","focus","blur","click","keydown","keypress","change"].join(".validation ")+".validation",function(e,n){var d=o(t),c=[];i.find("input,textarea,select").each(function(e,i){var o=c.length;if(a.each(a(i).triggerHandler("validation.validation",n),function(a,e){c.push(e)}),c.length>o)a(i).attr("aria-invalid","true");else{var r=t.data("original-aria-invalid");a(i).attr("aria-invalid",void 0!==r&&r)}}),s.find("input,select,textarea").not(t).not('[name="'+t.attr("name")+'"]').trigger("validationLostFocus.validation"),(c=a.unique(c.sort())).length?(i.removeClass("success error").addClass("warning"),r.options.semanticallyStrict&&1===c.length?l.html(c[0]+(r.options.prependExistingHelpBlock?l.data("original-contents"):"")):l.html('<ul role="alert"><li>'+c.join("</li><li>")+"</li></ul>"+(r.options.prependExistingHelpBlock?l.data("original-contents"):""))):(i.removeClass("warning error success"),d.length>0&&i.addClass("success"),l.html(l.data("original-contents"))),"blur"===e.type&&i.removeClass("success")}),t.bind("validationLostFocus.validation",function(){i.removeClass("success")})})},destroy:function(){return this.each(function(){var t=a(this),i=t.parents(".form-group").first(),n=i.find(".help-block").first();t.unbind(".validation"),n.html(n.data("original-contents")),i.attr("class",i.data("original-classes")),t.attr("aria-invalid",t.data("original-aria-invalid")),n.attr("role",t.data("original-role")),e.indexOf(n[0])>-1&&n.remove()})},collectErrors:function(e){var t={};return this.each(function(e,i){var n=a(i),o=n.attr("name"),r=n.triggerHandler("validation.validation",{includeEmpty:!0});t[o]=a.extend(!0,r,t[o])}),a.each(t,function(a,e){0===e.length&&delete t[a]}),t},hasErrors:function(){var e=[];return this.each(function(t,i){e=e.concat(a(i).triggerHandler("getValidators.validation")?a(i).triggerHandler("validation.validation",{submitting:!0}):[])}),e.length>0},override:function(e){i=a.extend(!0,i,e)}},validatorTypes:{callback:{name:"callback",init:function(a,e){return{validatorName:e,callback:a.data("validation"+e+"Callback"),lastValue:a.val(),lastValid:!0,lastFinished:!0}},validate:function(a,e,t){if(t.lastValue===e&&t.lastFinished)return!t.lastValid;if(!0===t.lastFinished){t.lastValue=e,t.lastValid=!0,t.lastFinished=!1;var i=t,n=a;!function(a,e){for(var t=Array.prototype.slice.call(arguments).splice(2),i=a.split("."),n=i.pop(),o=0;o<i.length;o++)e=e[i[o]];e[n].apply(this,t)}(t.callback,window,a,e,function(a){i.lastValue===a.value&&(i.lastValid=a.valid,a.message&&(i.message=a.message),i.lastFinished=!0,n.data("validation"+i.validatorName+"Message",i.message),setTimeout(function(){n.trigger("change.validation")},1))})}return!1}},ajax:{name:"ajax",init:function(a,e){return{validatorName:e,url:a.data("validation"+e+"Ajax"),lastValue:a.val(),lastValid:!0,lastFinished:!0}},validate:function(e,t,i){return""+i.lastValue==""+t&&!0===i.lastFinished?!1===i.lastValid:(!0===i.lastFinished&&(i.lastValue=t,i.lastValid=!0,i.lastFinished=!1,a.ajax({url:i.url,data:"value="+t+"&field="+e.attr("name"),dataType:"json",success:function(a){""+i.lastValue==""+a.value&&(i.lastValid=!!a.valid,a.message&&(i.message=a.message),i.lastFinished=!0,e.data("validation"+i.validatorName+"Message",i.message),setTimeout(function(){e.trigger("change.validation")},1))},failure:function(){i.lastValid=!0,i.message="ajax call failed",i.lastFinished=!0,e.data("validation"+i.validatorName+"Message",i.message),setTimeout(function(){e.trigger("change.validation")},1)}})),!1)}},regex:{name:"regex",init:function(a,e){return{regex:(t=a.data("validation"+e+"Regex"),new RegExp("^"+t+"$"))};var t},validate:function(a,e,t){return!t.regex.test(e)&&!t.negative||t.regex.test(e)&&t.negative}},required:{name:"required",init:function(a,e){return{}},validate:function(a,e,t){return!(0!==e.length||t.negative)||!!(e.length>0&&t.negative)},blockSubmit:!0},match:{name:"match",init:function(a,e){var t=a.parents("form").first().find('[name="'+a.data("validation"+e+"Match")+'"]').first();return t.bind("validation.validation",function(){a.trigger("change.validation",{submitting:!0})}),{element:t}},validate:function(a,e,t){return e!==t.element.val()&&!t.negative||e===t.element.val()&&t.negative},blockSubmit:!0},max:{name:"max",init:function(a,e){return{max:a.data("validation"+e+"Max")}},validate:function(a,e,t){return parseFloat(e,10)>parseFloat(t.max,10)&&!t.negative||parseFloat(e,10)<=parseFloat(t.max,10)&&t.negative}},min:{name:"min",init:function(a,e){return{min:a.data("validation"+e+"Min")}},validate:function(a,e,t){return parseFloat(e)<parseFloat(t.min)&&!t.negative||parseFloat(e)>=parseFloat(t.min)&&t.negative}},maxlength:{name:"maxlength",init:function(a,e){return{maxlength:a.data("validation"+e+"Maxlength")}},validate:function(a,e,t){return e.length>t.maxlength&&!t.negative||e.length<=t.maxlength&&t.negative}},minlength:{name:"minlength",init:function(a,e){return{minlength:a.data("validation"+e+"Minlength")}},validate:function(a,e,t){return e.length<t.minlength&&!t.negative||e.length>=t.minlength&&t.negative}},maxchecked:{name:"maxchecked",init:function(a,e){var t=a.parents("form").first().find('[name="'+a.attr("name")+'"]');return t.bind("click.validation",function(){a.trigger("change.validation",{includeEmpty:!0})}),{maxchecked:a.data("validation"+e+"Maxchecked"),elements:t}},validate:function(a,e,t){return t.elements.filter(":checked").length>t.maxchecked&&!t.negative||t.elements.filter(":checked").length<=t.maxchecked&&t.negative},blockSubmit:!0},minchecked:{name:"minchecked",init:function(a,e){var t=a.parents("form").first().find('[name="'+a.attr("name")+'"]');return t.bind("click.validation",function(){a.trigger("change.validation",{includeEmpty:!0})}),{minchecked:a.data("validation"+e+"Minchecked"),elements:t}},validate:function(a,e,t){return t.elements.filter(":checked").length<t.minchecked&&!t.negative||t.elements.filter(":checked").length>=t.minchecked&&t.negative},blockSubmit:!0}},builtInValidators:{email:{name:"Email",type:"shortcut",shortcut:"validemail"},validemail:{name:"Validemail",type:"regex",regex:"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}",message:"Not a valid email address\x3c!-- data-validator-validemail-message to override --\x3e"},passwordagain:{name:"Passwordagain",type:"match",match:"password",message:"Does not match the given password\x3c!-- data-validator-paswordagain-message to override --\x3e"},positive:{name:"Positive",type:"shortcut",shortcut:"number,positivenumber"},negative:{name:"Negative",type:"shortcut",shortcut:"number,negativenumber"},number:{name:"Number",type:"regex",regex:"([+-]?\\d+(\\.\\d*)?([eE][+-]?[0-9]+)?)?",message:"Must be a number\x3c!-- data-validator-number-message to override --\x3e"},integer:{name:"Integer",type:"regex",regex:"[+-]?\\d+",message:"No decimal places allowed\x3c!-- data-validator-integer-message to override --\x3e"},positivenumber:{name:"Positivenumber",type:"min",min:0,message:"Must be a positive number\x3c!-- data-validator-positivenumber-message to override --\x3e"},negativenumber:{name:"Negativenumber",type:"max",max:0,message:"Must be a negative number\x3c!-- data-validator-negativenumber-message to override --\x3e"},required:{name:"Required",type:"required",message:"This is required\x3c!-- data-validator-required-message to override --\x3e"},checkone:{name:"Checkone",type:"minchecked",minchecked:1,message:"Check at least one option\x3c!-- data-validation-checkone-message to override --\x3e"}}},n=function(a){return a.toLowerCase().replace(/(^|\s)([a-z])/g,function(a,e,t){return e+t.toUpperCase()})},o=function(e){var t=e.val(),i=e.attr("type");return"checkbox"===i&&(t=e.is(":checked")?t:""),"radio"===i&&(t=a('input[name="'+e.attr("name")+'"]:checked').length>0?t:""),t};a.fn.jqBootstrapValidation=function(e){return i.methods[e]?i.methods[e].apply(this,Array.prototype.slice.call(arguments,1)):"object"!==(void 0===e?"undefined":t(e))&&e?(a.error("Method "+e+" does not exist on jQuery.jqBootstrapValidation"),null):i.methods.init.apply(this,arguments)},a.jqBootstrapValidation=function(e){a(":input").not("[type=image],[type=submit]").jqBootstrapValidation.apply(this,arguments)}}(jQuery)}});
'use strict' var tap = require('tap') var invnum = require('../index') tap.equal( invnum.next('Abc0~`!@#$%^&*()+={}[]|"\'<>?001'), 'ABC0002', 'Next invoice number' ) tap.equal( invnum.next('xjsiwe234njshd6'), 'XJSIWE234NJSHD7', 'Next invoice number' ) tap.equal( invnum.next('899ZZZ9'), '900AAA0', 'Next invoice number' )
'use strict'; angular.module('nodeAngularAppApp').config(function($urlRouterProvider,$stateProvider,$httpProvider) { $urlRouterProvider.otherwise('/'); $stateProvider.state('main', { url: '/', templateUrl: '/views/main.html' }) .state('register', { url: '/register', controller : 'RegisterCtrl', templateUrl: '/views/register.html' }) .state('login', { url: '/login', controller : 'LoginCtrl', templateUrl: '/views/login.html' }) .state('jobs', { url: '/jobs', controller : 'JobsCtrl', templateUrl: '/views/jobs.html' }) .state('logout', { url: '/logout', controller : 'LogoutCtrl' }) .state('company', { url: '/company', controller : 'CompanyCtrl', templateUrl: '/views/company.html' }) .state('farms', { url: '/farms', controller : 'FarmsCtrl', templateUrl: '/views/farms.html' }) .state('tags', { url: '/tags', controller : 'TagsCtrl', templateUrl: '/views/tags.html' }) .state('expense', { url: '/expense', controller : 'ExpenseCtrl', templateUrl: '/views/expense.html' }) .state('expense-type', { url: '/expenseType', controller : 'ExpenseTypeCtrl', templateUrl: '/views/expenseType.html' }) .state('products', { url: '/products', controller : 'ProductsCtrl', templateUrl: '/views/products.html' }) .state('animals', { url: '/animals', controller : 'AnimalsCtrl', templateUrl: '/views/animals.html' }) .state('bill-cycle', { url: '/billCycle', controller : 'BillCycleCtrl', templateUrl: '/views/billCycle.html' }) .state('customers', { url: '/customers', controller : 'CustomersCtrl', templateUrl: '/views/customers.html' }) .state('milk-delivery', { url: '/milkDelivery', controller : 'MilkDeliveryCtrl', templateUrl: '/views/milkDelivery.html' }) .state('dairy-payment', { url: '/dairyPayment', controller : 'DairyPaymentCtrl', templateUrl: '/views/dairyPayment.html' }) .state('weight', { url: '/weight', controller : 'WeightCtrl', templateUrl: '/views/weight.html' }) .state('stock', { url: '/stock', controller : 'StockCtrl', templateUrl: '/views/stock.html' }) .state('users', { url: '/users', controller : 'UsersCtrl', templateUrl: '/views/users.html' }) .state('feed-used', { url: '/feedUsed', controller : 'FeedUsedCtrl', templateUrl: '/views/feedUsed.html' }) .state('prices', { url: '/prices', controller : 'PricesCtrl', templateUrl: '/views/prices.html' }) .state('dairy-record', { url: '/dairyRecord', controller : 'DairyRecordCtrl', templateUrl: '/views/dairyRecord.html' }); $httpProvider.interceptors.push('authInterceptor'); }) .constant('API_URL','http://localhost:3000/');
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformArguments = void 0; function transformArguments() { return ['MEMORY', 'MALLOC-STATS']; } exports.transformArguments = transformArguments;
const fetch = require("node-fetch") /** * * @param {String} discordId * @returns {boolean | object} */ async function findRobloxInfo(discordId) { const url = `https://verify.eryn.io/api/user/${discordId}` const response = await fetch(url) const data = await response.json() if (data.errorCode === 404) { return false } return data } module.exports.findRobloxInfo = findRobloxInfo
import {camera, renderer, scene, controls} from './renderer.js'; import {viewCamera, viewRenderer, viewScene} from './viewBox.js'; import {status} from './status.js'; import {nowPath, chokokuPath, pointCircles, mouseX, mouseY} from './pathCanvas.js'; let removeCursorPath = false; export function render() { requestAnimationFrame(render); viewCamera.position.set(...camera.position.normalize().setLength(250).toArray()); viewCamera.lookAt(viewScene.position); renderer.render(scene, camera); viewRenderer.render(viewScene, viewCamera); controls.update(); // --------- canvas --------- if (status === 'setpath' || status === 'adjustpath') { nowPath.dashOffset += 0.5; chokokuPath.dashOffset += 0.5; if (nowPath.dashOffset >= 100) { // for stack overflow nowPath.dashOffset = 0; chokokuPath.dashOffset = 0; } if (status === 'setpath' && nowPath.segments.length > 0) { if (removeCursorPath) { // Deletes the segment at the second or later frame after setpath. nowPath.removeSegment(nowPath.segments.length - 1); } else { removeCursorPath = true; } nowPath.lineTo(mouseX, mouseY); renderer.domElement.style.cursor = "url('./static/img/chokoku-cursor.svg') 5 5, auto"; if ( nowPath.segments[0].point.x - 5 < mouseX && nowPath.segments[0].point.x + 5 > mouseX && nowPath.segments[0].point.y - 5 < mouseY && nowPath.segments[0].point.y + 5 > mouseY ) { pointCircles[0].fillColor = '#aaa'; renderer.domElement.style.cursor = 'default'; } else { pointCircles[0].fillColor = '#fff'; } } } } export function modifyRemoveCursorPath(bool) { removeCursorPath = bool; }
var controller = require('../controllers/index.controller.js'); module.exports = function (app) { app.get('/', controller.render); };
# Copyright (C) 2010-2011 Richard Lincoln # # 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. """The production package is responsible for classes which describe various kinds of generators. These classes also provide production costing information which is used to economically allocate demand among committed units and calculate reserve quantities. """ nsURI = "http://iec.ch/TC57/2013/CIM-schema-CIM100#Generation" nsPrefix = "cimGeneration"
export default { name: 'StateUpdate', props: { value: { type: String, default: '', }, }, watch: { value(current) { this.$nextTick(() => { this.$emit('change', current); }); }, }, };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SparkLine = void 0; var tslib_1 = require("tslib"); var react_1 = tslib_1.__importDefault(require("react")); var locale_1 = require("../locale"); var theme_1 = require("../theme"); var SparkLine = /** @class */ (function (_super) { tslib_1.__extends(SparkLine, _super); function SparkLine() { return _super !== null && _super.apply(this, arguments) || this; } SparkLine.prototype.normalizeValue = function (item) { if (typeof item === 'number') { return item; } else if (item && typeof item.value === 'number') { return item.value; } else { return Number(item) || 0; } }; SparkLine.prototype.renderLines = function () { var _this = this; var _a = this.props, width = _a.width, height = _a.height, value = _a.value, cx = _a.classnames; var values = value.map(function (item) { return _this.normalizeValue(item); }); var max = Math.max.apply(Math, values); var min = Math.min.apply(Math, values); var duration = max - min || 1; var gap = width / (values.length - 1); var points = []; values.forEach(function (value, index) { points.push({ x: index * gap, y: height - ((value - min) * height) / duration }); }); var lineD = points .map(function (value, index) { return (index === 0 ? 'M' : 'L') + " " + value.x + " " + value.y; }) .join(' '); var areaD = lineD + " V " + height + " L 0 " + height + " Z"; // todo 支持鼠标 hover 显示对应数据。 return (react_1.default.createElement("g", null, react_1.default.createElement("path", { className: cx("Sparkline-area"), d: areaD, stroke: "none" }), react_1.default.createElement("path", { className: cx("Sparkline-line"), d: lineD, fill: "none" }))); }; SparkLine.prototype.render = function () { var _a = this.props, cx = _a.classnames, className = _a.className, value = _a.value, width = _a.width, height = _a.height, onClick = _a.onClick; return (react_1.default.createElement("div", { className: cx('Sparkline', className, onClick ? 'Sparkline--clickable' : ''), onClick: onClick }, Array.isArray(value) && value.length > 1 ? (react_1.default.createElement("svg", { className: cx('Sparkline-svg'), width: width, height: height, viewBox: "0 0 " + width + " " + height }, this.renderLines())) : (react_1.default.createElement("span", null, "Invalid Value")))); }; SparkLine.defaultProps = { width: 100, height: 50 }; return SparkLine; }(react_1.default.Component)); exports.SparkLine = SparkLine; exports.default = theme_1.themeable(locale_1.localeable(SparkLine)); //# sourceMappingURL=./components/SparkLine.js.map
from django.db import models from django.contrib.auth.models import User import datetime as dt from django.db.models import Q class Profile(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE) profile_picture =models.ImageField(upload_to= 'profiles/', blank=True, default='profiles/default.png') bio = models.CharField(max_length=500, default='No bio') email=models.EmailField(default='No email') contact = models.CharField(max_length=80) def __str__(self): return self.bio def save_profile(self): self.save() def delete_profile(self): self.delete() @classmethod def update_bio(cls,id, bio): update_profile = cls.objects.filter(id = id).update(bio = bio) return update_profile @classmethod def get_all_profiles(cls): profile = Profile.objects.all() return profile @classmethod def search_user(cls,user): return cls.objects.filter(user__username__icontains=user).all() class Project(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='images/', default='') description = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now=True) link = models.URLField(max_length=250) country = models.CharField(max_length=50) def __str__(self): return self.title class Meta: ordering = ['-date_posted'] def save_project(self): self.save() def delete_project(self): self.delete() @classmethod def search(cls,searchterm): search = Project.objects.filter(Q(title__icontains=searchterm)|Q(description__icontains=searchterm)|Q(country__icontains=searchterm)) return search
#!/usr/bin/env node var path = require('path'), fs = require('fs'), extend = require('util')._extend, exec = require('child_process').exec, processes = []; var baseDir = path.resolve(__dirname, '..'), srcDir = path.resolve(baseDir, ''), chimpBin = path.resolve(baseDir, 'node_modules/.bin/chimp'); var appOptions = { settings: 'settings.json', port: 3000, env: { ROOT_URL: 'http://localhost:3000', VELOCITY: 1, JASMINE_CLIENT_UNIT: 0, JASMINE_SERVER_UNIT: 0, JASMINE_CLIENT_INTEGRATION: 0, JASMINE_SERVER_INTEGRATION: 1 } }; var mirrorOptions = { settings: appOptions.settings, port: 3100, env: { IS_MIRROR: 1, MONGO_URL: 'mongodb://localhost:' + 3001 + '/chimp_db', ROOT_URL: 'http://localhost:3100' }, logFile: './chimp-mirror.log' }; var chimpSwitches = ' --path=' + path.resolve('tests/features') + //' -r=' + path.resolve('tests/features/step_definitions/domain') + //' --criticalSteps=' + path.resolve('tests/features/step_definitions/critical') + ' --singleSnippetPerFile=1'; if (process.env.CI || process.env.TRAVIS || process.env.CIRCLECI) { // when not in Watch mode, Chimp existing will exit Meteor too // we also don't need Velocity for the app chimp will run against appOptions.env.VELOCITY = 0; } else { chimpSwitches += ' --watch'; } if (process.env.SIMIAN_API && process.env.SIMIAN_REPOSITORY) { chimpSwitches += ' --simianRepositoryId=' + process.env.SIMIAN_REPOSITORY; chimpSwitches += ' --simianAccessToken=' + process.env.SIMIAN_API; } if (process.env.CUCUMBER_JSON_OUTPUT) { chimpSwitches += ' --jsonOutput=' + process.env.CUCUMBER_JSON_OUTPUT; } // set this flag to start with a mirror locally (ala Velocity xolvio:cucumber style) if (process.env.WITH_MIRROR) { chimpWithMirror(); } else if (process.env.NO_METEOR) { startChimp('--ddp=' + appOptions.env.ROOT_URL + chimpSwitches); } else { chimpNoMirror(); } // ************************************************* function chimpWithMirror() { appOptions.waitForMessage = 'Started MongoDB'; startApp(function () { startMirror(function () { console.log('=> Test App running at:', mirrorOptions.env.ROOT_URL); console.log('=> Log file: tail -f', path.resolve(mirrorOptions.logFile), '\n'); startChimp('--ddp=' + mirrorOptions.env.ROOT_URL + chimpSwitches ) }); }); } function chimpNoMirror() { appOptions.waitForMessage = 'App running at'; startApp(function () { startChimp('--ddp=' + appOptions.env.ROOT_URL + chimpSwitches); }); } function startApp(callback) { startProcess({ name: 'Meteor App', command: 'meteor --settings ' + appOptions.settings + ' --port ' + appOptions.port, waitForMessage: appOptions.waitForMessage, options: { cwd: srcDir, env: extend(appOptions.env, process.env) } }, callback); } function startMirror(callback) { startProcess({ name: 'Meteor Mirror', command: 'meteor --settings ' + mirrorOptions.settings + ' --port ' + mirrorOptions.port, silent: true, logFile: mirrorOptions.logFile, waitForMessage: 'App running at', options: { cwd: srcDir, env: extend(mirrorOptions.env, process.env) } }, callback); } function startChimp(command) { startProcess({ name: 'Chimp', command: chimpBin + ' ' + command }); } function startProcess(opts, callback) { var proc = exec( opts.command, opts.options ); if (opts.waitForMessage) { proc.stdout.on('data', function waitForMessage(data) { if (data.toString().match(opts.waitForMessage)) { if (callback) { callback(); } } }); } if (!opts.silent) { proc.stdout.pipe(process.stdout); proc.stderr.pipe(process.stderr); } if (opts.logFile) { var logStream = fs.createWriteStream(opts.logFile, {flags: 'a'}); proc.stdout.pipe(logStream); proc.stderr.pipe(logStream); } proc.on('close', function (code) { console.log(opts.name, 'exited with code ' + code); for (var i = 0; i < processes.length; i += 1) { processes[i].kill(); } process.exit(code); }); processes.push(proc); }
import re import os import requests import json import dateparser import datetime import logging from .models import TagFilter TAG_FILTERS_JSON_CONF_FILE_PATH = os.getenv( "TAG_FILTERS_JSON_CONF_FILE_PATH", "/etc/nightwatch/tag-filters.json") class NotSupportedRegistry(Exception): def __init__(self, message): super().__init__(message) class CouldNotJoinRegitry(Exception): def __init__(self, message): super().__init__(message) def getTagTS(tagName, tags): for tag in tags: if tag['name'] == tagName: return tag['start_ts'] return def getTags(registry, repository, credentials={}): tags = [] def getHttp(uri, headers={}, params={}): r = requests.get(uri, params=params, headers=headers) r.raise_for_status() return r.json() try: # case Quay.io if "quay.io" in registry: uri = "https://quay.io/api/v1/repository/%s/tag/?onlyActiveTags=true" % (repository) registryInfos = getHttp(uri, headers={"X-Requested-With":""}) for tag in registryInfos['tags']: tags.append( { "name": str(tag['name']), "start_ts": datetime.datetime.fromtimestamp(tag['start_ts']) } ) return sorted(tags, key = lambda i: i['start_ts'], reverse=True) # case Dockerhub elif "docker.io" in registry: uri = "https://hub.docker.com/v2/repositories/%s/tags" % (repository) registryInfos = getHttp(uri) for tag in registryInfos['results']: tags.append( { "name": str(tag['name']), "start_ts": dateparser.parse(tag['last_updated']) } ) return sorted(tags, key = lambda i: i['start_ts'], reverse=True) else: raise NotSupportedRegistry("Tags recuperation for %s is not implemented for this registry: %s" % (repository, registry)) except (requests.RequestException, requests.HTTPError) as e: raise CouldNotJoinRegitry("Could not join this registry to retiewe tags: %s/%s" % (registry, repository)) def isValidTag(candidatTag, tagFilter): if tagFilter.operator == "include": return re.match(tagFilter.regex, candidatTag['name']) elif tagFilter.operator == "exclude": return not re.match(tagFilter.regex, candidatTag['name']) def isEligibleFilter(registry, repository, tagFilter): if tagFilter: if tagFilter.scope == "global": return True elif tagFilter.scope == "repository": for item in tagFilter.scopedItems: if item == repository: return True elif tagFilter.scope == "registry": for item in tagFilter.scopedItems: if item == registry: return True return False def getEligibleTags(registry, repository, tags): tagFilters = [] try: with open(TAG_FILTERS_JSON_CONF_FILE_PATH) as json_file: data = json.load(json_file) for tagFilter in data['tag-filters']: tagFilters.append(TagFilter(**tagFilter)) except IOError: logging.warning("Could not find tag-filters configuration file") if tags: candidatTags = [] for candidatTag in tags: validTagFlag = True for filter in tagFilters: if filter and isEligibleFilter(registry, repository, filter): if not isValidTag(candidatTag, filter): validTagFlag = False if validTagFlag: candidatTags.append(candidatTag) if len(candidatTags) > 0: return sorted( candidatTags, key = lambda i: i['start_ts'], reverse=True ) return [] def getYoungestTag(registry, repository, currentTagName, tags): currentTagTS = getTagTS(currentTagName, tags) for eligibleTag in getEligibleTags(registry, repository, tags): if eligibleTag['name'] != currentTagName: if currentTagTS and 'start_ts' in eligibleTag and eligibleTag['start_ts'] > currentTagTS: return eligibleTag elif not currentTagTS: return eligibleTag elif 'start_ts' not in eligibleTag: if eligibleTag['name'] > currentTagName: return eligibleTag return
import { getSvg, handleQuery } from "components/utils/client.js"; import gitee from "components/apis/gitee.js"; import defaultSubject from "components/apis/gitee/subject"; import defaultColor from "components/apis/gitee/color"; export default async (req, res, hasParam) => { res.statusCode = 200; res.setHeader("Content-Type", "image/svg+xml"); const { subject, owner, repo, param } = req.query; const result = hasParam === true ? await gitee(subject, owner, repo, param) : await gitee(subject, owner, repo); if (result.code === 200) { const search = { ...req.query, ...result.data, }; if (!result.data.subject && defaultSubject[subject]) { if (typeof defaultSubject[subject] === "function") { search.subject = defaultSubject[subject](req.query); } else { search.subject = defaultSubject[subject]; } } if (!result.data.color && defaultColor[subject]) { search.color = defaultColor[subject]; } return generate( res, handleQuery(search, ["subject", "status", "owner", "repo", "param"]) ); } return generate(res, { subject: "badg", status: result.data, color: "red" }); }; const generate = (res, query) => { const svg = getSvg(query); return res.end(svg); };
/* * JsSIP v0.7.9 * the Javascript SIP library * Copyright: 2012-2015 José Luis Millán <[email protected]> (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], 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', 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', ACCEPTED_BODY_TYPES: 'application/sdp, application/dtmf-relay', MAX_FORWARDS: 69, SESSION_EXPIRES: 90, MIN_SESSION_EXPIRES: 60 }; module.exports = C; },{"../package.json":48}],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(); }, receiveRequest: function(request) { //Check in-dialog request if(!this.checkInDialogRequest(request)) { return; } this.owner.receiveRequest(request); } }; },{"./Constants":1,"./Dialog/RequestSender":3,"./SIPMessage":18,"./Transactions":20,"debug":31}],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":20}],4:[function(require,module,exports){ module.exports = DigestAuthentication; /** * Dependencies. */ var debug = require('debug')('JsSIP:DigestAuthentication'); var Utils = require('./Utils'); function DigestAuthentication(ua) { this.username = ua.configuration.authorization_user; this.password = ua.configuration.password; this.cnonce = null; this.nc = 0; this.ncHex = '00000000'; this.response = null; } /** * Performs Digest authentication given a SIP request and the challenge * received in a response to that request. * Returns true if credentials were successfully generated, false otherwise. */ DigestAuthentication.prototype.authenticate = function(request, challenge) { // Inspect and validate the challenge. 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') { debug('challenge with Digest algorithm different than "MD5", authentication aborted'); return false; } } else { this.algorithm = 'MD5'; } if (! this.realm) { debug('challenge without Digest realm, authentication aborted'); return false; } if (! this.nonce) { debug('challenge without Digest nonce, authentication aborted'); 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. debug('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; this.updateNcHex(); // nc-value = 8LHEX. Max value = 'FFFFFFFF'. if (this.nc === 4294967296) { this.nc = 1; this.ncHex = '00000001'; } // Calculate the Digest "response" value. this.calculateResponse(); return true; }; /** * Generate Digest 'response' value. */ DigestAuthentication.prototype.calculateResponse = function() { var ha1, ha2; // HA1 = MD5(A1) = MD5(username:realm:password) ha1 = Utils.calculateMD5(this.username + ':' + this.realm + ':' + this.password); 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(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(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(ha1 + ':' + this.nonce + ':' + ha2); } }; /** * 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.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(', '); }; /** * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. */ DigestAuthentication.prototype.updateNcHex = function() { var hex = Number(this.nc).toString(16); this.ncHex = '00000000'.substr(0, 8-hex.length) + hex; }; },{"./Utils":24,"debug":31}],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, "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; var pos0; 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) { 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) { data.scheme = uri_scheme.toLowerCase(); })(pos0); } 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_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).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; if (/^[a-zA-Z0-9_\-]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z0-9_\\-]"); } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); if (/^[a-zA-Z0-9_\-]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z0-9_\\-]"); } } } } else { result0 = null; } return result0; } function parse_toplabel() { var result0, result1; if (/^[a-zA-Z0-9_\-]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z0-9_\\-]"); } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); if (/^[a-zA-Z0-9_\-]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z0-9_\\-]"); } } } } else { result0 = null; } 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 && value.toLowerCase();})(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":23}],7:[function(require,module,exports){ /** * Dependencies. */ var debug = require('debug')('JsSIP'); var pkg = require('../package.json'); debug('version %s', pkg.version); var rtcninja = require('rtcninja'); 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'); /** * Expose the JsSIP module. */ var JsSIP = module.exports = { C: C, Exceptions: Exceptions, Utils: Utils, UA: UA, URI: URI, NameAddrHeader: NameAddrHeader, Grammar: Grammar, // Expose the debug module. debug: require('debug'), // Expose the rtcninja module. rtcninja: rtcninja }; Object.defineProperties(JsSIP, { name: { get: function() { return pkg.title; } }, version: { get: function() { return pkg.version; } } }); },{"../package.json":48,"./Constants":1,"./Exceptions":5,"./Grammar":6,"./NameAddrHeader":9,"./UA":22,"./URI":23,"./Utils":24,"debug":31,"rtcninja":36}],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":20,"./Utils":24,"events":26,"util":30}],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":23}],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; } 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; } 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) { parsed.error('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":31}],11:[function(require,module,exports){ 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 rtcninja = require('rtcninja'); 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 rtcninja.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. }; // Custom session empty object for high level use this.data = {}; 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 (! rtcninja.hasWebRTC()) { 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:[email protected]'; 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 rtcninja.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 rtcninja.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; rtcninja.getUserMedia( mediaConstraints, userMediaSucceeded, userMediaFailed ); // 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 (! self.late_sdp) { self.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'offer', sdp:request.body}), // success remoteDescriptionSucceededOrNotNeeded, // failure function() { request.reply(488); failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_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 sesssion'); 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'); rtcninja.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-D#*,]+$/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 = { failed: 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 originalTarget = target; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } if (this.referSubscriber) { return false; } // Check target validity target = this.ua.normalizeTarget(target); if (!target) { throw new TypeError('Invalid target: '+ originalTarget); } this.referSubscriber = new RTCSession_ReferSubscriber(this); this.referSubscriber.sendRefer(target, options); }; /** * 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) { clearTimeout(this.timers.ackTimer); clearTimeout(this.timers.invite2xxTimer); if (this.late_sdp) { if (!request.body) { ended.call(this, 'remote', request, JsSIP_C.causes.MISSING_SDP); break; } this.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'answer', sdp:request.body}), // success function() { self.status = C.STATUS_CONFIRMED; }, // failure function() { ended.call(self, 'remote', request, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION); } ); } else { this.status = C.STATUS_CONFIRMED; } if (this.status === C.STATUS_CONFIRMED && !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 rtcninja.RTCPeerConnection(pcConfig, rtcConstraints); this.connection.onaddstream = function(event, stream) { self.emit('addstream', {stream: stream}); }; this.connection.onremovestream = function(event, stream) { self.emit('removestream', {stream: stream}); }; this.connection.oniceconnectionstatechange = function(event, state) { self.emit('iceconnetionstatechange', {state: state}); // 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( // success createSucceeded, // failure function(error) { self.rtcReady = true; if (onFailure) { onFailure(error); } }, // constraints constraints ); } else if (type === 'answer') { connection.createAnswer( // success createSucceeded, // failure function(error) { self.rtcReady = true; if (onFailure) { onFailure(error); } }, // constraints constraints ); } else { throw new Error('createLocalDescription() | type must be "offer" or "answer", but "' +type+ '" was given'); } // createAnswer or createOffer succeeded function createSucceeded(desc) { connection.onicecandidate = function(event, candidate) { if (! candidate) { connection.onicecandidate = null; self.rtcReady = true; if (onSuccess) { onSuccess(connection.localDescription.sdp); } onSuccess = null; } }; connection.setLocalDescription(desc, // success function() { if (connection.iceGatheringState === 'complete') { self.rtcReady = true; if (onSuccess) { onSuccess(connection.localDescription.sdp); } onSuccess = null; } }, // failure function(error) { self.rtcReady = true; if (onFailure) { onFailure(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; } } this.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'offer', sdp:request.body}), // success answer, // failure function() { request.reply(488); } ); } else { this.late_sdp = true; answer(); } function answer() { 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; } } this.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'offer', sdp:request.body}), // success 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); } ); }, // failure function() { request.reply(488); }, // Constraints. this.rtcAnswerConstraints ); } /** * 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); } else if (request.event.event !== 'refer') { request.reply(489); } else if (!this.referSubscriber) { request.reply(481, 'Subscription does not exist'); } else { this.referSubscriber.receiveNotify(request); request.reply(200); } } /** * 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; rtcninja.getUserMedia( mediaConstraints, userMediaSucceeded, userMediaFailed ); // 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, 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; } this.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'pranswer', sdp:response.body}), // success null, // failure null ); 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; } this.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'answer', sdp:response.body}), // success function() { // Handle Session Timers. handleSessionTimersInIncomingResponse.call(self, response); accepted.call(self, 'remote', response); sendRequest.call(self, JsSIP_C.ACK); confirmed.call(self, 'local', null); }, // failure function() { acceptAndTerminate.call(self, response, 488, 'Not Acceptable Here'); failed.call(self, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION); } ); 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; } self.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'answer', sdp:response.body}), // success function() { if (eventHandlers.succeeded) { eventHandlers.succeeded(response); } }, // failure function() { onFailed(); } ); } 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; } self.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'answer', sdp:response.body}), // success function() { if (eventHandlers.succeeded) { eventHandlers.succeeded(response); } }, // failure function() { onFailed(); } ); } // 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":19,"./Transactions":20,"./Utils":24,"debug":31,"events":26,"rtcninja":36,"sdp-transform":42,"util":30}],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 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; } 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-D#*]$/)) { 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): debug('onSuccessResponse'); if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); } break; default: if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); } break; } }; DTMF.prototype.onRequestTimeout = function() { debugerror('onRequestTimeout'); if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); } }; DTMF.prototype.onTransportError = function() { debugerror('onTransportError'); if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); } }; DTMF.prototype.onDialogError = function() { debugerror('onDialogError'); if (this.eventHandlers.onDialogError) { this.eventHandlers.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":31}],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":31}],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; 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 }); } } }); }; 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, satus_line: status_line }); break; case /^1[0-9]{2}$/.test(status_line.status_code): this.emit('progress', { request: request, satus_line: status_line }); break; case /^2[0-9]{2}$/.test(status_line.status_code): removeSubscriber.call(this); this.emit('accepted', { request: request, satus_line: status_line }); break; default: removeSubscriber.call(this); this.emit('failed', { request: request, satus_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":31,"events":26,"util":30}],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; // 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.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":31}],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":24,"debug":31}],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.credentials = 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) { // 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.credentials) { this.credentials = new DigestAuthentication(this.ua); } // Verify that the challenge is really valid. if (!this.credentials.authenticate(this.request, challenge)) { this.applicant.receiveResponse(response); return; } this.challenged = true; 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.cseq = cseq; } this.request.setHeader('cseq', cseq +' '+ this.method); this.request.setHeader(authorization_header_name, this.credentials.toString()); this.send(); } else { this.applicant.receiveResponse(response); } } else { this.applicant.receiveResponse(response); } } }; },{"./Constants":1,"./DigestAuthentication":4,"./Transactions":20,"./UA":22,"debug":31}],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.server.sip_uri); } // 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; } }; 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":24,"debug":31,"sdp-transform":42}],19:[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; },{}],20:[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, via_transport; 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; if (request_sender.ua.configuration.hack_via_tcp) { via_transport = 'TCP'; } else if (request_sender.ua.configuration.hack_via_ws) { via_transport = 'WS'; } else { via_transport = transport.server.scheme; } via = 'SIP/2.0/' + 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, via_transport; this.type = C.INVITE_CLIENT; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; if (request_sender.ua.configuration.hack_via_tcp) { via_transport = 'TCP'; } else if (request_sender.ua.configuration.hack_via_ws) { via_transport = 'WS'; } else { via_transport = transport.server.scheme; } via = 'SIP/2.0/' + 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, via_transport; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; if (request_sender.ua.configuration.hack_via_tcp) { via_transport = 'TCP'; } else if (request_sender.ua.configuration.hack_via_ws) { via_transport = 'WS'; } else { via_transport = transport.server.scheme; } via = 'SIP/2.0/' + 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":19,"debug":31,"events":26,"util":30}],21:[function(require,module,exports){ module.exports = Transport; var C = { // Transport status codes STATUS_READY: 0, STATUS_DISCONNECTED: 1, STATUS_ERROR: 2 }; /** * Expose C object. */ Transport.C = C; /** * Dependencies. */ var debug = require('debug')('JsSIP:Transport'); var debugerror = require('debug')('JsSIP:ERROR:Transport'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('./Constants'); var Parser = require('./Parser'); var UA = require('./UA'); var SIPMessage = require('./SIPMessage'); var sanityCheck = require('./sanityCheck'); // 'websocket' module uses the native WebSocket interface when bundled to run in a browser. var W3CWebSocket = require('websocket').w3cwebsocket; function Transport(ua, server) { this.ua = ua; this.ws = null; this.server = server; this.reconnection_attempts = 0; this.closed = false; this.connected = false; this.reconnectTimer = null; this.lastTransportError = {}; /** * Options for the Node "websocket" library. */ this.node_websocket_options = this.ua.configuration.node_websocket_options || {}; // Add our User-Agent header. this.node_websocket_options.headers = this.node_websocket_options.headers || {}; this.node_websocket_options.headers['User-Agent'] = JsSIP_C.USER_AGENT; } Transport.prototype = { /** * Connect socket. */ connect: function() { var transport = this; if(this.ws && (this.ws.readyState === this.ws.OPEN || this.ws.readyState === this.ws.CONNECTING)) { debug('WebSocket ' + this.server.ws_uri + ' is already connected'); return false; } if(this.ws) { this.ws.close(); } debug('connecting to WebSocket ' + this.server.ws_uri); this.ua.onTransportConnecting(this, (this.reconnection_attempts === 0)?1:this.reconnection_attempts); try { // Hack in case W3CWebSocket is not the class exported by Node-WebSocket // (may just happen if the above `var W3CWebSocket` line is overriden by // `var W3CWebSocket = global.W3CWebSocket`). if (W3CWebSocket.length > 3) { this.ws = new W3CWebSocket(this.server.ws_uri, 'sip', this.node_websocket_options.origin, this.node_websocket_options.headers, this.node_websocket_options.requestOptions, this.node_websocket_options.clientConfig); } else { this.ws = new W3CWebSocket(this.server.ws_uri, 'sip'); } this.ws.binaryType = 'arraybuffer'; this.ws.onopen = function() { transport.onOpen(); }; this.ws.onclose = function(e) { transport.onClose(e); }; this.ws.onmessage = function(e) { transport.onMessage(e); }; this.ws.onerror = function(e) { transport.onError(e); }; } catch(e) { debugerror('error connecting to WebSocket ' + this.server.ws_uri + ': ' + e); this.lastTransportError.code = null; this.lastTransportError.reason = e.message; this.ua.onTransportError(this); } }, /** * Disconnect socket. */ disconnect: function() { if(this.ws) { // Clear reconnectTimer clearTimeout(this.reconnectTimer); // TODO: should make this.reconnectTimer = null here? this.closed = true; debug('closing WebSocket ' + this.server.ws_uri); this.ws.close(); } // TODO: Why this?? if (this.reconnectTimer !== null) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; this.ua.onTransportDisconnected({ transport: this, code: this.lastTransportError.code, reason: this.lastTransportError.reason }); } }, /** * Send a message. */ send: function(msg) { var message = msg.toString(); if(this.ws && this.ws.readyState === this.ws.OPEN) { debug('sending WebSocket message:\n%s\n', message); this.ws.send(message); return true; } else { debugerror('unable to send message, WebSocket is not open'); return false; } }, // Transport Event Handlers onOpen: function() { this.connected = true; debug('WebSocket ' + this.server.ws_uri + ' connected'); // Clear reconnectTimer since we are not disconnected if (this.reconnectTimer !== null) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } // Reset reconnection_attempts this.reconnection_attempts = 0; // Disable closed this.closed = false; // Trigger onTransportConnected callback this.ua.onTransportConnected(this); }, onClose: function(e) { var connected_before = this.connected; this.connected = false; this.lastTransportError.code = e.code; this.lastTransportError.reason = e.reason; debug('WebSocket disconnected (code: ' + e.code + (e.reason? '| reason: ' + e.reason : '') +')'); if(e.wasClean === false) { debugerror('WebSocket abrupt disconnection'); } // Transport was connected if (connected_before === true) { this.ua.onTransportClosed(this); // Check whether the user requested to close. if(!this.closed) { this.reConnect(); } } else { // This is the first connection attempt // May be a network error (or may be UA.stop() was called) this.ua.onTransportError(this); } }, onMessage: function(e) { var message, transaction, data = e.data; // CRLF Keep Alive response from server. Ignore it. if(data === '\r\n') { debug('received WebSocket message with CRLF Keep Alive response'); return; } // WebSocket binary message. else if (typeof data !== 'string') { try { data = String.fromCharCode.apply(null, new Uint8Array(data)); } catch(evt) { debugerror('received WebSocket binary message failed to be converted into string, message discarded'); return; } debug('received WebSocket binary message:\n%s\n', data); } // WebSocket text message. else { debug('received WebSocket text message:\n%s\n', data); } message = Parser.parseMessage(data, this.ua); if (! message) { return; } if(this.ua.status === UA.C.STATUS_USER_CLOSED && message instanceof SIPMessage.IncomingRequest) { return; } // Do some sanity check if(! sanityCheck(message, this.ua, this)) { return; } if(message instanceof SIPMessage.IncomingRequest) { message.transport = this; this.ua.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.ua.transactions.ict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; case JsSIP_C.ACK: // Just in case ;-) break; default: transaction = this.ua.transactions.nict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; } } }, onError: function(e) { debugerror('WebSocket connection error: %o', e); }, /** * Reconnection attempt logic. */ reConnect: function() { var transport = this; this.reconnection_attempts += 1; if(this.reconnection_attempts > this.ua.configuration.ws_server_max_reconnection) { debugerror('maximum reconnection attempts for WebSocket ' + this.server.ws_uri); this.ua.onTransportError(this); } else { debug('trying to reconnect to WebSocket ' + this.server.ws_uri + ' (reconnection attempt ' + this.reconnection_attempts + ')'); this.reconnectTimer = setTimeout(function() { transport.connect(); transport.reconnectTimer = null; }, this.ua.configuration.ws_server_reconnection_timeout * 1000); } } }; },{"./Constants":1,"./Parser":10,"./SIPMessage":18,"./UA":22,"./sanityCheck":25,"debug":31,"websocket":45}],22:[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 rtcninja = require('rtcninja'); var JsSIP_C = require('./Constants'); var Registrator = require('./Registrator'); var RTCSession = require('./RTCSession'); var Message = require('./Message'); var Transport = require('./Transport'); var Transactions = require('./Transactions'); var Transactions = require('./Transactions'); var Utils = require('./Utils'); var Exceptions = require('./Exceptions'); var URI = require('./URI'); var Grammar = require('./Grammar'); /** * 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) { 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.transportRecoverAttempts = 0; this.transportRecoveryTimer = 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); // Initialize rtcninja if not yet done. if (! rtcninja.called) { rtcninja(); } } util.inherits(UA, events.EventEmitter); //================= // High Level API //================= /** * Connect to the WS server if status = STATUS_INIT. * Resume UA after being closed. */ UA.prototype.start = function() { debug('start()'); var server, self = this; function connect() { debug('restarting UA'); self.status = C.STATUS_READY; self.transport.connect(); } if (this.status === C.STATUS_INIT) { server = this.getNextWsServer(); this.transport = new Transport(this, server); this.transport.connect(); } else if(this.status === C.STATUS_USER_CLOSED) { if (!this.isConnected()) { connect(); } else { this.once('disconnected', 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() { if(this.transport) { return this.transport.connected; } else { return false; } }; /** * 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; } // Clear transportRecoveryTimer clearTimeout(this.transportRecoveryTimer); // 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 there are no pending non-INVITE client or server transactions and no // sessions, then disconnect now. Otherwise wait for 2 seconds. // TODO: This fails if sotp() is called once an outgoing is cancelled (no time // to send ACK for 487), so leave 2 seconds until properly re-designed. // if (this.nistTransactionsCount === 0 && this.nictTransactionsCount === 0 && num_sessions === 0) { // ua.transport.disconnect(); // } // else { setTimeout(function() { 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 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; 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 //========================== /** * Transport Close event. */ UA.prototype.onTransportClosed = function(transport) { // Run _onTransportError_ callback on every client transaction using _transport_ var type, idx, length, client_transactions = ['nict', 'ict', 'nist', 'ist']; transport.server.status = Transport.C.STATUS_DISCONNECTED; 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', { transport: transport, code: transport.lastTransportError.code, reason: transport.lastTransportError.reason }); }; /** * Unrecoverable transport event. * Connection reattempt logic has been done and didn't success. */ UA.prototype.onTransportError = function(transport) { var server; debug('transport ' + transport.server.ws_uri + ' failed | connection state set to '+ Transport.C.STATUS_ERROR); // Close sessions. // Mark this transport as 'down' and try the next one transport.server.status = Transport.C.STATUS_ERROR; this.emit('disconnected', { transport: transport, code: transport.lastTransportError.code, reason: transport.lastTransportError.reason }); // Don't attempt to recover the connection if the user closes the UA. if (this.status === C.STATUS_USER_CLOSED) { return; } server = this.getNextWsServer(); if(server) { this.transport = new Transport(this, server); this.transport.connect(); } else { this.closeSessionsOnTransportError(); if (!this.error || this.error !== C.NETWORK_ERROR) { this.status = C.STATUS_NOT_READY; this.error = C.NETWORK_ERROR; } // Transport Recovery process this.recoverTransport(); } }; /** * Transport connection event. */ UA.prototype.onTransportConnected = function(transport) { this.transport = transport; // Reset transport recovery counter this.transportRecoverAttempts = 0; transport.server.status = Transport.C.STATUS_READY; if(this.status === C.STATUS_USER_CLOSED) { return; } this.status = C.STATUS_READY; this.error = null; if(this.dynConfiguration.register) { this._registrator.register(); } this.emit('connected', { transport: transport }); }; /** * Transport connecting event */ UA.prototype.onTransportConnecting = function(transport, attempts) { this.emit('connecting', { transport: transport, attempts: attempts }); }; /** * Transport connected event */ UA.prototype.onTransportDisconnected = function(data) { this.emit('disconnected', data); }; /** * 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 (rtcninja.hasWebRTC()) { 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 { debug('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; } } }; /** * Retrieve the next server to which connect. */ UA.prototype.getNextWsServer = function() { // Order servers by weight var idx, length, ws_server, candidates = []; length = this.configuration.ws_servers.length; for (idx = 0; idx < length; idx++) { ws_server = this.configuration.ws_servers[idx]; if (ws_server.status === Transport.C.STATUS_ERROR) { continue; } else if (candidates.length === 0) { candidates.push(ws_server); } else if (ws_server.weight > candidates[0].weight) { candidates = [ws_server]; } else if (ws_server.weight === candidates[0].weight) { candidates.push(ws_server); } } idx = Math.floor((Math.random()* candidates.length)); return candidates[idx]; }; /** * Close all sessions on transport error. */ UA.prototype.closeSessionsOnTransportError = function() { var idx; // Run _transportError_ for every Session for(idx in this.sessions) { this.sessions[idx].onTransportError(); } // Call registrator _onTransportClosed_ this._registrator.onTransportClosed(); }; UA.prototype.recoverTransport = function(ua) { var idx, length, k, nextRetry, count, server; ua = ua || this; count = ua.transportRecoverAttempts; length = ua.configuration.ws_servers.length; for (idx = 0; idx < length; idx++) { ua.configuration.ws_servers[idx].status = 0; } server = ua.getNextWsServer(); k = Math.floor((Math.random() * Math.pow(2,count)) +1); nextRetry = k * ua.configuration.connection_recovery_min_interval; if (nextRetry > ua.configuration.connection_recovery_max_interval) { debug('time for next connection attempt exceeds connection_recovery_max_interval, resetting counter'); nextRetry = ua.configuration.connection_recovery_min_interval; count = 0; } debug('next connection attempt in '+ nextRetry +' seconds'); this.transportRecoveryTimer = setTimeout(function() { ua.transportRecoverAttempts = count + 1; ua.transport = new Transport(ua, server); ua.transport.connect(); }, nextRetry * 1000); }; 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', // Password password: null, // Registration parameters register_expires: 600, register: true, registrar_server: null, // Transport related parameters ws_server_max_reconnection: 3, ws_server_reconnection_timeout: 4, connection_recovery_min_interval: 2, connection_recovery_max_interval: 30, use_preloaded_route: false, // Session parameters no_answer_timeout: 60, session_timers: true, // Hacks hack_via_tcp: false, hack_via_ws: false, hack_ip_in_contact: false, // Options for Node. node_websocket_options: {} }; // 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); if (checked_value !== undefined) { settings[parameter] = checked_value; } else { throw new Exceptions.ConfigurationError(parameter, value); } } } // Sanity Checks // Connection recovery intervals. if(settings.connection_recovery_max_interval < settings.connection_recovery_min_interval) { throw new Exceptions.ConfigurationError('connection_recovery_max_interval', settings.connection_recovery_max_interval); } // 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, ''); // 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.hack_ip_in_contact) { settings.via_host = Utils.getRandomTestNetIP(); } this.contact = { pub_gruu: null, temp_gruu: null, uri: new URI('sip', Utils.createRandomToken(8), settings.via_host, null, {transport: 'ws'}), toString: function(options) { options = options || {}; var anonymous = options.anonymous || null, outbound = options.outbound || null, contact = '<'; if (anonymous) { contact += this.temp_gruu || 'sip:[email protected];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': 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', 'ws_server_max_reconnection', 'ws_server_reconnection_timeout', 'hostport_params', // Mandatory user configurable parameters 'uri', 'ws_servers', // Optional user configurable parameters 'authorization_user', 'connection_recovery_max_interval', 'connection_recovery_min_interval', 'display_name', 'hack_via_tcp', // false 'hack_via_ws', // false 'hack_ip_in_contact', //false 'instance_id', 'no_answer_timeout', // 30 seconds 'session_timers', // true 'node_websocket_options', 'password', 'register_expires', // 600 seconds 'registrar_server', 'use_preloaded_route', // Post-configuration generated parameters 'via_core_value', 'via_host' ]; for(idx in parameters) { parameter = parameters[idx]; if (['password'].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; } }, ws_servers: function(ws_servers) { var idx, length, url; /* Allow defining ws_servers parameter as: * String: "host" * Array of Strings: ["host1", "host2"] * Array of Objects: [{ws_uri:"host1", weight:1}, {ws_uri:"host2", weight:0}] * Array of Objects and Strings: [{ws_uri:"host1"}, "host2"] */ if (typeof ws_servers === 'string') { ws_servers = [{ws_uri: ws_servers}]; } else if (Array.isArray(ws_servers)) { length = ws_servers.length; for (idx = 0; idx < length; idx++) { if (typeof ws_servers[idx] === 'string') { ws_servers[idx] = {ws_uri: ws_servers[idx]}; } } } else { return; } if (ws_servers.length === 0) { return false; } length = ws_servers.length; for (idx = 0; idx < length; idx++) { if (!ws_servers[idx].ws_uri) { debug('ERROR: missing "ws_uri" attribute in ws_servers parameter'); return; } if (ws_servers[idx].weight && !Number(ws_servers[idx].weight)) { debug('ERROR: "weight" attribute in ws_servers parameter must be a Number'); return; } url = Grammar.parse(ws_servers[idx].ws_uri, 'absoluteURI'); if(url === -1) { debug('ERROR: invalid "ws_uri" attribute in ws_servers parameter: ' + ws_servers[idx].ws_uri); return; } else if(url.scheme !== 'wss' && url.scheme !== 'ws') { debug('ERROR: invalid URI scheme in ws_servers parameter: ' + url.scheme); return; } else { ws_servers[idx].sip_uri = '<sip:' + url.host + (url.port ? ':' + url.port : '') + ';transport=ws;lr>'; if (!ws_servers[idx].weight) { ws_servers[idx].weight = 0; } ws_servers[idx].status = 0; ws_servers[idx].scheme = url.scheme.toUpperCase(); } } return ws_servers; } }, 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; } } }, display_name: function(display_name) { if(Grammar.parse('"' + display_name + '"', 'display_name') === -1) { return; } else { return display_name; } }, hack_via_tcp: function(hack_via_tcp) { if (typeof hack_via_tcp === 'boolean') { return hack_via_tcp; } }, hack_via_ws: function(hack_via_ws) { if (typeof hack_via_ws === 'boolean') { return hack_via_ws; } }, hack_ip_in_contact: function(hack_ip_in_contact) { if (typeof hack_ip_in_contact === 'boolean') { return hack_ip_in_contact; } }, 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; } }, node_websocket_options: function(node_websocket_options) { return (typeof node_websocket_options === 'object') ? node_websocket_options : {}; }, password: function(password) { return String(password); }, 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; } }, use_preloaded_route: function(use_preloaded_route) { if (typeof use_preloaded_route === 'boolean') { return use_preloaded_route; } } } }; },{"./Constants":1,"./Exceptions":5,"./Grammar":6,"./Message":8,"./RTCSession":11,"./Registrator":16,"./Transactions":20,"./Transport":21,"./URI":23,"./Utils":24,"debug":31,"events":26,"rtcninja":36,"util":30}],23:[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().toLowerCase(); } }, 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":24}],24:[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.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.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(); }; },{"./Constants":1,"./Grammar":6,"./URI":23}],25:[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":24,"debug":31}],26:[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 } throw TypeError('Uncaught, unspecified "error" event.'); } } 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: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; 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) { var m; 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 { // 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.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; 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; } },{}],27:[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 } } },{}],28:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(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; clearTimeout(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) { setTimeout(drainQueue, 0); } }; // 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; }; },{}],29:[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'; } },{}],30:[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":29,"_process":28,"inherits":27}],31:[function(require,module,exports){ /** * 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() { // is webkit? http://stackoverflow.com/a/16459606/376773 return ('WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { return JSON.stringify(v); }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs() { var args = arguments; var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return args; var c = 'color: ' + this.color; args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); // 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-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); return args; } /** * 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() { var r; try { r = exports.storage.debug; } catch(e) {} return r; } /** * 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) {} } },{"./debug":32}],32:[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 = debug; 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, lowercased letter, i.e. "n". */ exports.formatters = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * * @return {Number} * @api private */ function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = Array.prototype.slice.call(arguments); args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-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; }); if ('function' === typeof exports.formatArgs) { args = exports.formatArgs.apply(self, args); } var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; } /** * 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}],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 * @return {String|Number} * @api public */ module.exports = function(val, options){ options = options || {}; if ('string' == typeof val) return parse(val); return options.long ? long(val) : short(val); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = '' + 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; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function short(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 long(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 (global){ 'use strict'; // Expose the Adapter function/object. module.exports = Adapter; // Dependencies var browser = require('bowser'), debug = require('debug')('rtcninja:Adapter'), debugerror = require('debug')('rtcninja:ERROR:Adapter'), // Internal vars getUserMedia = null, RTCPeerConnection = null, RTCSessionDescription = null, RTCIceCandidate = null, MediaStreamTrack = null, getMediaDevices = null, attachMediaStream = null, canRenegotiate = false, oldSpecRTCOfferOptions = false, browserVersion = Number(browser.version) || 0, isDesktop = !!(!browser.mobile && !browser.tablet), hasWebRTC = false, virtGlobal, virtNavigator; debugerror.log = console.warn.bind(console); // Dirty trick to get this library working in a Node-webkit env with browserified libs virtGlobal = global.window || global; // Don't fail in Node virtNavigator = virtGlobal.navigator || {}; // Constructor. function Adapter(options) { // Chrome desktop, Chrome Android, Opera desktop, Opera Android, Android native browser // or generic Webkit browser. if ( (isDesktop && browser.chrome && browserVersion >= 32) || (browser.android && browser.chrome && browserVersion >= 39) || (isDesktop && browser.opera && browserVersion >= 27) || (browser.android && browser.opera && browserVersion >= 24) || (browser.android && browser.webkit && !browser.chrome && browserVersion >= 37) || (virtNavigator.webkitGetUserMedia && virtGlobal.webkitRTCPeerConnection) ) { hasWebRTC = true; getUserMedia = virtNavigator.webkitGetUserMedia.bind(virtNavigator); RTCPeerConnection = virtGlobal.webkitRTCPeerConnection; RTCSessionDescription = virtGlobal.RTCSessionDescription; RTCIceCandidate = virtGlobal.RTCIceCandidate; MediaStreamTrack = virtGlobal.MediaStreamTrack; if (MediaStreamTrack && MediaStreamTrack.getSources) { getMediaDevices = MediaStreamTrack.getSources.bind(MediaStreamTrack); } else if (virtNavigator.getMediaDevices) { getMediaDevices = virtNavigator.getMediaDevices.bind(virtNavigator); } attachMediaStream = function (element, stream) { element.src = URL.createObjectURL(stream); return element; }; canRenegotiate = true; oldSpecRTCOfferOptions = false; // Firefox desktop, Firefox Android. } else if ( (isDesktop && browser.firefox && browserVersion >= 22) || (browser.android && browser.firefox && browserVersion >= 33) || (virtNavigator.mozGetUserMedia && virtGlobal.mozRTCPeerConnection) ) { hasWebRTC = true; getUserMedia = virtNavigator.mozGetUserMedia.bind(virtNavigator); RTCPeerConnection = virtGlobal.mozRTCPeerConnection; RTCSessionDescription = virtGlobal.mozRTCSessionDescription; RTCIceCandidate = virtGlobal.mozRTCIceCandidate; MediaStreamTrack = virtGlobal.MediaStreamTrack; attachMediaStream = function (element, stream) { element.src = URL.createObjectURL(stream); return element; }; canRenegotiate = false; oldSpecRTCOfferOptions = false; // WebRTC plugin required. For example IE or Safari with the Temasys plugin. } else if ( options.plugin && typeof options.plugin.isRequired === 'function' && options.plugin.isRequired() && typeof options.plugin.isInstalled === 'function' && options.plugin.isInstalled() ) { var pluginiface = options.plugin.interface; hasWebRTC = true; getUserMedia = pluginiface.getUserMedia; RTCPeerConnection = pluginiface.RTCPeerConnection; RTCSessionDescription = pluginiface.RTCSessionDescription; RTCIceCandidate = pluginiface.RTCIceCandidate; MediaStreamTrack = pluginiface.MediaStreamTrack; if (MediaStreamTrack && MediaStreamTrack.getSources) { getMediaDevices = MediaStreamTrack.getSources.bind(MediaStreamTrack); } else if (virtNavigator.getMediaDevices) { getMediaDevices = virtNavigator.getMediaDevices.bind(virtNavigator); } attachMediaStream = pluginiface.attachMediaStream; canRenegotiate = pluginiface.canRenegotiate; oldSpecRTCOfferOptions = true; // TODO: Update when fixed in the plugin. // Best effort (may be adater.js is loaded). } else if (virtNavigator.getUserMedia && virtGlobal.RTCPeerConnection) { hasWebRTC = true; getUserMedia = virtNavigator.getUserMedia.bind(virtNavigator); RTCPeerConnection = virtGlobal.RTCPeerConnection; RTCSessionDescription = virtGlobal.RTCSessionDescription; RTCIceCandidate = virtGlobal.RTCIceCandidate; MediaStreamTrack = virtGlobal.MediaStreamTrack; if (MediaStreamTrack && MediaStreamTrack.getSources) { getMediaDevices = MediaStreamTrack.getSources.bind(MediaStreamTrack); } else if (virtNavigator.getMediaDevices) { getMediaDevices = virtNavigator.getMediaDevices.bind(virtNavigator); } attachMediaStream = virtGlobal.attachMediaStream || function (element, stream) { element.src = URL.createObjectURL(stream); return element; }; canRenegotiate = false; oldSpecRTCOfferOptions = false; } function throwNonSupported(item) { return function () { throw new Error('rtcninja: WebRTC not supported, missing ' + item + ' [browser: ' + browser.name + ' ' + browser.version + ']'); }; } // Public API. // Expose a WebRTC checker. Adapter.hasWebRTC = function () { return hasWebRTC; }; // Expose getUserMedia. if (getUserMedia) { Adapter.getUserMedia = function (constraints, successCallback, errorCallback) { debug('getUserMedia() | constraints: %o', constraints); try { getUserMedia(constraints, function (stream) { debug('getUserMedia() | success'); if (successCallback) { successCallback(stream); } }, function (error) { debug('getUserMedia() | error:', error); if (errorCallback) { errorCallback(error); } } ); } catch (error) { debugerror('getUserMedia() | error:', error); if (errorCallback) { errorCallback(error); } } }; } else { Adapter.getUserMedia = function (constraints, successCallback, errorCallback) { debugerror('getUserMedia() | WebRTC not supported'); if (errorCallback) { errorCallback(new Error('rtcninja: WebRTC not supported, missing ' + 'getUserMedia [browser: ' + browser.name + ' ' + browser.version + ']')); } else { throwNonSupported('getUserMedia'); } }; } // Expose RTCPeerConnection. Adapter.RTCPeerConnection = RTCPeerConnection || throwNonSupported('RTCPeerConnection'); // Expose RTCSessionDescription. Adapter.RTCSessionDescription = RTCSessionDescription || throwNonSupported('RTCSessionDescription'); // Expose RTCIceCandidate. Adapter.RTCIceCandidate = RTCIceCandidate || throwNonSupported('RTCIceCandidate'); // Expose MediaStreamTrack. Adapter.MediaStreamTrack = MediaStreamTrack || throwNonSupported('MediaStreamTrack'); // Expose getMediaDevices. Adapter.getMediaDevices = getMediaDevices; // Expose MediaStreamTrack. Adapter.attachMediaStream = attachMediaStream || throwNonSupported('attachMediaStream'); // Expose canRenegotiate attribute. Adapter.canRenegotiate = canRenegotiate; // Expose closeMediaStream. Adapter.closeMediaStream = function (stream) { if (!stream) { return; } // Latest spec states that MediaStream has no stop() method and instead must // call stop() on every MediaStreamTrack. if (MediaStreamTrack && MediaStreamTrack.prototype && MediaStreamTrack.prototype.stop) { debug('closeMediaStream() | calling stop() on all the MediaStreamTrack'); 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(); } } // Deprecated by the spec, but still in use. } else if (typeof stream.stop === 'function') { debug('closeMediaStream() | calling stop() on the MediaStream'); stream.stop(); } }; // Expose fixPeerConnectionConfig. Adapter.fixPeerConnectionConfig = function (pcConfig) { var i, len, iceServer, hasUrls, hasUrl; if (!Array.isArray(pcConfig.iceServers)) { pcConfig.iceServers = []; } for (i = 0, len = pcConfig.iceServers.length; i < len; i += 1) { iceServer = pcConfig.iceServers[i]; hasUrls = iceServer.hasOwnProperty('urls'); hasUrl = iceServer.hasOwnProperty('url'); if (typeof iceServer === 'object') { // Has .urls but not .url, so add .url with a single string value. if (hasUrls && !hasUrl) { iceServer.url = (Array.isArray(iceServer.urls) ? iceServer.urls[0] : iceServer.urls); // Has .url but not .urls, so add .urls with same value. } else if (!hasUrls && hasUrl) { iceServer.urls = (Array.isArray(iceServer.url) ? iceServer.url.slice() : iceServer.url); } // Ensure .url is a single string. if (hasUrl && Array.isArray(iceServer.url)) { iceServer.url = iceServer.url[0]; } } } }; // Expose fixRTCOfferOptions. Adapter.fixRTCOfferOptions = function (options) { options = options || {}; // New spec. if (!oldSpecRTCOfferOptions) { if (options.mandatory && options.mandatory.OfferToReceiveAudio) { options.offerToReceiveAudio = 1; } if (options.mandatory && options.mandatory.OfferToReceiveVideo) { options.offerToReceiveVideo = 1; } delete options.mandatory; // Old spec. } else { if (options.offerToReceiveAudio) { options.mandatory = options.mandatory || {}; options.mandatory.OfferToReceiveAudio = true; } if (options.offerToReceiveVideo) { options.mandatory = options.mandatory || {}; options.mandatory.OfferToReceiveVideo = true; } } }; return Adapter; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"bowser":38,"debug":31}],35:[function(require,module,exports){ 'use strict'; // Expose the RTCPeerConnection class. module.exports = RTCPeerConnection; // Dependencies. var merge = require('merge'), debug = require('debug')('rtcninja:RTCPeerConnection'), debugerror = require('debug')('rtcninja:ERROR:RTCPeerConnection'), Adapter = require('./Adapter'), // Internal constants. C = { REGEXP_NORMALIZED_CANDIDATE: new RegExp(/^candidate:/i), REGEXP_FIX_CANDIDATE: new RegExp(/(^a=|\r|\n)/gi), REGEXP_RELAY_CANDIDATE: new RegExp(/ relay /i), REGEXP_SDP_CANDIDATES: new RegExp(/^a=candidate:.*\r\n/igm), REGEXP_SDP_NON_RELAY_CANDIDATES: new RegExp(/^a=candidate:(.(?!relay ))*\r\n/igm) }, // Internal variables. VAR = { normalizeCandidate: null }; debugerror.log = console.warn.bind(console); // Constructor function RTCPeerConnection(pcConfig, pcConstraints) { debug('new | pcConfig: %o', pcConfig); // Set this.pcConfig and this.options. setConfigurationAndOptions.call(this, pcConfig); // NOTE: Deprecated pcConstraints argument. this.pcConstraints = pcConstraints; // Own version of the localDescription. this.ourLocalDescription = null; // Latest values of PC attributes to avoid events with same value. this.ourSignalingState = null; this.ourIceConnectionState = null; this.ourIceGatheringState = null; // Timer for options.gatheringTimeout. this.timerGatheringTimeout = null; // Timer for options.gatheringTimeoutAfterRelay. this.timerGatheringTimeoutAfterRelay = null; // Flag to ignore new gathered ICE candidates. this.ignoreIceGathering = false; // Flag set when closed. this.closed = false; // Set RTCPeerConnection. setPeerConnection.call(this); // Set properties. setProperties.call(this); } // Public API. RTCPeerConnection.prototype.createOffer = function (successCallback, failureCallback, options) { debug('createOffer()'); var self = this; Adapter.fixRTCOfferOptions(options); this.pc.createOffer( function (offer) { if (isClosed.call(self)) { return; } debug('createOffer() | success'); if (successCallback) { successCallback(offer); } }, function (error) { if (isClosed.call(self)) { return; } debugerror('createOffer() | error:', error); if (failureCallback) { failureCallback(error); } }, options ); }; RTCPeerConnection.prototype.createAnswer = function (successCallback, failureCallback, options) { debug('createAnswer()'); var self = this; this.pc.createAnswer( function (answer) { if (isClosed.call(self)) { return; } debug('createAnswer() | success'); if (successCallback) { successCallback(answer); } }, function (error) { if (isClosed.call(self)) { return; } debugerror('createAnswer() | error:', error); if (failureCallback) { failureCallback(error); } }, options ); }; RTCPeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) { debug('setLocalDescription()'); var self = this; this.pc.setLocalDescription( description, // success. function () { if (isClosed.call(self)) { return; } debug('setLocalDescription() | success'); // Clear gathering timers. clearTimeout(self.timerGatheringTimeout); delete self.timerGatheringTimeout; clearTimeout(self.timerGatheringTimeoutAfterRelay); delete self.timerGatheringTimeoutAfterRelay; runTimerGatheringTimeout(); if (successCallback) { successCallback(); } }, // failure function (error) { if (isClosed.call(self)) { return; } debugerror('setLocalDescription() | error:', error); if (failureCallback) { failureCallback(error); } } ); // Enable (again) ICE gathering. this.ignoreIceGathering = false; // Handle gatheringTimeout. function runTimerGatheringTimeout() { if (typeof self.options.gatheringTimeout !== 'number') { return; } // If setLocalDescription was already called, it may happen that // ICE gathering is not needed, so don't run this timer. if (self.pc.iceGatheringState === 'complete') { return; } debug('setLocalDescription() | ending gathering in %d ms (gatheringTimeout option)', self.options.gatheringTimeout); self.timerGatheringTimeout = setTimeout(function () { if (isClosed.call(self)) { return; } debug('forced end of candidates after gatheringTimeout timeout'); // Clear gathering timers. delete self.timerGatheringTimeout; clearTimeout(self.timerGatheringTimeoutAfterRelay); delete self.timerGatheringTimeoutAfterRelay; // Ignore new candidates. self.ignoreIceGathering = true; if (self.onicecandidate) { self.onicecandidate({ candidate: null }, null); } }, self.options.gatheringTimeout); } }; RTCPeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) { debug('setRemoteDescription()'); var self = this; this.pc.setRemoteDescription( description, function () { if (isClosed.call(self)) { return; } debug('setRemoteDescription() | success'); if (successCallback) { successCallback(); } }, function (error) { if (isClosed.call(self)) { return; } debugerror('setRemoteDescription() | error:', error); if (failureCallback) { failureCallback(error); } } ); }; RTCPeerConnection.prototype.updateIce = function (pcConfig) { debug('updateIce() | pcConfig: %o', pcConfig); // Update this.pcConfig and this.options. setConfigurationAndOptions.call(this, pcConfig); this.pc.updateIce(this.pcConfig); // Enable (again) ICE gathering. this.ignoreIceGathering = false; }; RTCPeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) { debug('addIceCandidate() | candidate: %o', candidate); var self = this; this.pc.addIceCandidate( candidate, function () { if (isClosed.call(self)) { return; } debug('addIceCandidate() | success'); if (successCallback) { successCallback(); } }, function (error) { if (isClosed.call(self)) { return; } debugerror('addIceCandidate() | error:', error); if (failureCallback) { failureCallback(error); } } ); }; RTCPeerConnection.prototype.getConfiguration = function () { debug('getConfiguration()'); return this.pc.getConfiguration(); }; RTCPeerConnection.prototype.getLocalStreams = function () { debug('getLocalStreams()'); return this.pc.getLocalStreams(); }; RTCPeerConnection.prototype.getRemoteStreams = function () { debug('getRemoteStreams()'); return this.pc.getRemoteStreams(); }; RTCPeerConnection.prototype.getStreamById = function (streamId) { debug('getStreamById() | streamId: %s', streamId); return this.pc.getStreamById(streamId); }; RTCPeerConnection.prototype.addStream = function (stream) { debug('addStream() | stream: %s', stream); this.pc.addStream(stream); }; RTCPeerConnection.prototype.removeStream = function (stream) { debug('removeStream() | stream: %o', stream); this.pc.removeStream(stream); }; RTCPeerConnection.prototype.close = function () { debug('close()'); this.closed = true; // Clear gathering timers. clearTimeout(this.timerGatheringTimeout); delete this.timerGatheringTimeout; clearTimeout(this.timerGatheringTimeoutAfterRelay); delete this.timerGatheringTimeoutAfterRelay; this.pc.close(); }; RTCPeerConnection.prototype.createDataChannel = function () { debug('createDataChannel()'); return this.pc.createDataChannel.apply(this.pc, arguments); }; RTCPeerConnection.prototype.createDTMFSender = function (track) { debug('createDTMFSender()'); return this.pc.createDTMFSender(track); }; RTCPeerConnection.prototype.getStats = function () { debug('getStats()'); return this.pc.getStats.apply(this.pc, arguments); }; RTCPeerConnection.prototype.setIdentityProvider = function () { debug('setIdentityProvider()'); return this.pc.setIdentityProvider.apply(this.pc, arguments); }; RTCPeerConnection.prototype.getIdentityAssertion = function () { debug('getIdentityAssertion()'); return this.pc.getIdentityAssertion(); }; RTCPeerConnection.prototype.reset = function (pcConfig) { debug('reset() | pcConfig: %o', pcConfig); var pc = this.pc; // Remove events in the old PC. pc.onnegotiationneeded = null; pc.onicecandidate = null; pc.onaddstream = null; pc.onremovestream = null; pc.ondatachannel = null; pc.onsignalingstatechange = null; pc.oniceconnectionstatechange = null; pc.onicegatheringstatechange = null; pc.onidentityresult = null; pc.onpeeridentity = null; pc.onidpassertionerror = null; pc.onidpvalidationerror = null; // Clear gathering timers. clearTimeout(this.timerGatheringTimeout); delete this.timerGatheringTimeout; clearTimeout(this.timerGatheringTimeoutAfterRelay); delete this.timerGatheringTimeoutAfterRelay; // Silently close the old PC. debug('reset() | closing current peerConnection'); pc.close(); // Set this.pcConfig and this.options. setConfigurationAndOptions.call(this, pcConfig); // Create a new PC. setPeerConnection.call(this); }; // Private Helpers. function setConfigurationAndOptions(pcConfig) { // Clone pcConfig. this.pcConfig = merge(true, pcConfig); // Fix pcConfig. Adapter.fixPeerConnectionConfig(this.pcConfig); this.options = { iceTransportsRelay: (this.pcConfig.iceTransports === 'relay'), iceTransportsNone: (this.pcConfig.iceTransports === 'none'), gatheringTimeout: this.pcConfig.gatheringTimeout, gatheringTimeoutAfterRelay: this.pcConfig.gatheringTimeoutAfterRelay }; // Remove custom rtcninja.RTCPeerConnection options from pcConfig. delete this.pcConfig.gatheringTimeout; delete this.pcConfig.gatheringTimeoutAfterRelay; debug('setConfigurationAndOptions | processed pcConfig: %o', this.pcConfig); } function isClosed() { return ((this.closed) || (this.pc && this.pc.iceConnectionState === 'closed')); } function setEvents() { var self = this, pc = this.pc; pc.onnegotiationneeded = function (event) { if (isClosed.call(self)) { return; } debug('onnegotiationneeded()'); if (self.onnegotiationneeded) { self.onnegotiationneeded(event); } }; pc.onicecandidate = function (event) { var candidate, isRelay, newCandidate; if (isClosed.call(self)) { return; } if (self.ignoreIceGathering) { return; } // Ignore any candidate (event the null one) if iceTransports:'none' is set. if (self.options.iceTransportsNone) { return; } candidate = event.candidate; if (candidate) { isRelay = C.REGEXP_RELAY_CANDIDATE.test(candidate.candidate); // Ignore if just relay candidates are requested. if (self.options.iceTransportsRelay && !isRelay) { return; } // Handle gatheringTimeoutAfterRelay. if (isRelay && !self.timerGatheringTimeoutAfterRelay && (typeof self.options.gatheringTimeoutAfterRelay === 'number')) { debug('onicecandidate() | first relay candidate found, ending gathering in %d ms', self.options.gatheringTimeoutAfterRelay); self.timerGatheringTimeoutAfterRelay = setTimeout(function () { if (isClosed.call(self)) { return; } debug('forced end of candidates after timeout'); // Clear gathering timers. delete self.timerGatheringTimeoutAfterRelay; clearTimeout(self.timerGatheringTimeout); delete self.timerGatheringTimeout; // Ignore new candidates. self.ignoreIceGathering = true; if (self.onicecandidate) { self.onicecandidate({candidate: null}, null); } }, self.options.gatheringTimeoutAfterRelay); } newCandidate = new Adapter.RTCIceCandidate({ sdpMid: candidate.sdpMid, sdpMLineIndex: candidate.sdpMLineIndex, candidate: candidate.candidate }); // Force correct candidate syntax (just check it once). if (VAR.normalizeCandidate === null) { if (C.REGEXP_NORMALIZED_CANDIDATE.test(candidate.candidate)) { VAR.normalizeCandidate = false; } else { debug('onicecandidate() | normalizing ICE candidates syntax (remove "a=" and "\\r\\n")'); VAR.normalizeCandidate = true; } } if (VAR.normalizeCandidate) { newCandidate.candidate = candidate.candidate.replace(C.REGEXP_FIX_CANDIDATE, ''); } debug( 'onicecandidate() | m%d(%s) %s', newCandidate.sdpMLineIndex, newCandidate.sdpMid || 'no mid', newCandidate.candidate); if (self.onicecandidate) { self.onicecandidate(event, newCandidate); } // Null candidate (end of candidates). } else { debug('onicecandidate() | end of candidates'); // Clear gathering timers. clearTimeout(self.timerGatheringTimeout); delete self.timerGatheringTimeout; clearTimeout(self.timerGatheringTimeoutAfterRelay); delete self.timerGatheringTimeoutAfterRelay; if (self.onicecandidate) { self.onicecandidate(event, null); } } }; pc.onaddstream = function (event) { if (isClosed.call(self)) { return; } debug('onaddstream() | stream: %o', event.stream); if (self.onaddstream) { self.onaddstream(event, event.stream); } }; pc.onremovestream = function (event) { if (isClosed.call(self)) { return; } debug('onremovestream() | stream: %o', event.stream); if (self.onremovestream) { self.onremovestream(event, event.stream); } }; pc.ondatachannel = function (event) { if (isClosed.call(self)) { return; } debug('ondatachannel() | datachannel: %o', event.channel); if (self.ondatachannel) { self.ondatachannel(event, event.channel); } }; pc.onsignalingstatechange = function (event) { if (pc.signalingState === self.ourSignalingState) { return; } debug('onsignalingstatechange() | signalingState: %s', pc.signalingState); self.ourSignalingState = pc.signalingState; if (self.onsignalingstatechange) { self.onsignalingstatechange(event, pc.signalingState); } }; pc.oniceconnectionstatechange = function (event) { if (pc.iceConnectionState === self.ourIceConnectionState) { return; } debug('oniceconnectionstatechange() | iceConnectionState: %s', pc.iceConnectionState); self.ourIceConnectionState = pc.iceConnectionState; if (self.oniceconnectionstatechange) { self.oniceconnectionstatechange(event, pc.iceConnectionState); } }; pc.onicegatheringstatechange = function (event) { if (isClosed.call(self)) { return; } if (pc.iceGatheringState === self.ourIceGatheringState) { return; } debug('onicegatheringstatechange() | iceGatheringState: %s', pc.iceGatheringState); self.ourIceGatheringState = pc.iceGatheringState; if (self.onicegatheringstatechange) { self.onicegatheringstatechange(event, pc.iceGatheringState); } }; pc.onidentityresult = function (event) { if (isClosed.call(self)) { return; } debug('onidentityresult()'); if (self.onidentityresult) { self.onidentityresult(event); } }; pc.onpeeridentity = function (event) { if (isClosed.call(self)) { return; } debug('onpeeridentity()'); if (self.onpeeridentity) { self.onpeeridentity(event); } }; pc.onidpassertionerror = function (event) { if (isClosed.call(self)) { return; } debug('onidpassertionerror()'); if (self.onidpassertionerror) { self.onidpassertionerror(event); } }; pc.onidpvalidationerror = function (event) { if (isClosed.call(self)) { return; } debug('onidpvalidationerror()'); if (self.onidpvalidationerror) { self.onidpvalidationerror(event); } }; } function setPeerConnection() { // Create a RTCPeerConnection. if (!this.pcConstraints) { this.pc = new Adapter.RTCPeerConnection(this.pcConfig); } else { // NOTE: Deprecated. this.pc = new Adapter.RTCPeerConnection(this.pcConfig, this.pcConstraints); } // Set RTC events. setEvents.call(this); } function getLocalDescription() { var pc = this.pc, options = this.options, sdp = null; if (!pc.localDescription) { this.ourLocalDescription = null; return null; } // Mangle the SDP string. if (options.iceTransportsRelay) { sdp = pc.localDescription.sdp.replace(C.REGEXP_SDP_NON_RELAY_CANDIDATES, ''); } else if (options.iceTransportsNone) { sdp = pc.localDescription.sdp.replace(C.REGEXP_SDP_CANDIDATES, ''); } this.ourLocalDescription = new Adapter.RTCSessionDescription({ type: pc.localDescription.type, sdp: sdp || pc.localDescription.sdp }); return this.ourLocalDescription; } function setProperties() { var self = this; Object.defineProperties(this, { peerConnection: { get: function () { return self.pc; } }, signalingState: { get: function () { return self.pc.signalingState; } }, iceConnectionState: { get: function () { return self.pc.iceConnectionState; } }, iceGatheringState: { get: function () { return self.pc.iceGatheringState; } }, localDescription: { get: function () { return getLocalDescription.call(self); } }, remoteDescription: { get: function () { return self.pc.remoteDescription; } }, peerIdentity: { get: function () { return self.pc.peerIdentity; } } }); } },{"./Adapter":34,"debug":31,"merge":39}],36:[function(require,module,exports){ 'use strict'; module.exports = rtcninja; // Dependencies. var browser = require('bowser'), debug = require('debug')('rtcninja'), debugerror = require('debug')('rtcninja:ERROR'), version = require('./version'), Adapter = require('./Adapter'), RTCPeerConnection = require('./RTCPeerConnection'), // Internal vars. called = false; debugerror.log = console.warn.bind(console); debug('version %s', version); debug('detected browser: %s %s [mobile:%s, tablet:%s, android:%s, ios:%s]', browser.name, browser.version, !!browser.mobile, !!browser.tablet, !!browser.android, !!browser.ios); // Constructor. function rtcninja(options) { // Load adapter var iface = Adapter(options || {}); // jshint ignore:line called = true; // Expose RTCPeerConnection class. rtcninja.RTCPeerConnection = RTCPeerConnection; // Expose WebRTC API and utils. rtcninja.getUserMedia = iface.getUserMedia; rtcninja.RTCSessionDescription = iface.RTCSessionDescription; rtcninja.RTCIceCandidate = iface.RTCIceCandidate; rtcninja.MediaStreamTrack = iface.MediaStreamTrack; rtcninja.getMediaDevices = iface.getMediaDevices; rtcninja.attachMediaStream = iface.attachMediaStream; rtcninja.closeMediaStream = iface.closeMediaStream; rtcninja.canRenegotiate = iface.canRenegotiate; // Log WebRTC support. if (iface.hasWebRTC()) { debug('WebRTC supported'); return true; } else { debugerror('WebRTC not supported'); return false; } } // Public API. // If called without calling rtcninja(), call it. rtcninja.hasWebRTC = function () { if (!called) { rtcninja(); } return Adapter.hasWebRTC(); }; // Expose version property. Object.defineProperty(rtcninja, 'version', { get: function () { return version; } }); // Expose called property. Object.defineProperty(rtcninja, 'called', { get: function () { return called; } }); // Exposing stuff. rtcninja.debug = require('debug'); rtcninja.browser = browser; },{"./Adapter":34,"./RTCPeerConnection":35,"./version":37,"bowser":38,"debug":31}],37:[function(require,module,exports){ 'use strict'; // Expose the 'version' field of package.json. module.exports = require('../package.json').version; },{"../package.json":40}],38:[function(require,module,exports){ /*! * Bowser - a browser detector * https://github.com/ded/bowser * MIT License | (c) Dustin Diaz 2015 */ !function (name, definition) { if (typeof module != 'undefined' && module.exports) module.exports = definition() else if (typeof define == 'function' && define.amd) define(definition) else this[name] = definition() }('bowser', function () { /** * See useragents.js for examples of navigator.userAgent */ var t = true function detect(ua) { function getFirstMatch(regex) { var match = ua.match(regex); return (match && match.length > 1 && match[1]) || ''; } function getSecondMatch(regex) { var match = ua.match(regex); return (match && match.length > 1 && match[2]) || ''; } var iosdevice = getFirstMatch(/(ipod|iphone|ipad)/i).toLowerCase() , likeAndroid = /like android/i.test(ua) , android = !likeAndroid && /android/i.test(ua) , chromeBook = /CrOS/.test(ua) , edgeVersion = getFirstMatch(/edge\/(\d+(\.\d+)?)/i) , versionIdentifier = getFirstMatch(/version\/(\d+(\.\d+)?)/i) , tablet = /tablet/i.test(ua) , mobile = !tablet && /[^-]mobi/i.test(ua) , result if (/opera|opr/i.test(ua)) { result = { name: 'Opera' , opera: t , version: versionIdentifier || getFirstMatch(/(?:opera|opr)[\s\/](\d+(\.\d+)?)/i) } } else if (/yabrowser/i.test(ua)) { result = { name: 'Yandex Browser' , yandexbrowser: t , version: versionIdentifier || getFirstMatch(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i) } } else if (/windows phone/i.test(ua)) { result = { name: 'Windows Phone' , windowsphone: t } if (edgeVersion) { result.msedge = t result.version = edgeVersion } else { result.msie = t result.version = getFirstMatch(/iemobile\/(\d+(\.\d+)?)/i) } } else if (/msie|trident/i.test(ua)) { result = { name: 'Internet Explorer' , msie: t , version: getFirstMatch(/(?:msie |rv:)(\d+(\.\d+)?)/i) } } else if (chromeBook) { result = { name: 'Chrome' , chromeBook: t , chrome: t , version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i) } } else if (/chrome.+? edge/i.test(ua)) { result = { name: 'Microsoft Edge' , msedge: t , version: edgeVersion } } else if (/chrome|crios|crmo/i.test(ua)) { result = { name: 'Chrome' , chrome: t , version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i) } } else if (iosdevice) { result = { name : iosdevice == 'iphone' ? 'iPhone' : iosdevice == 'ipad' ? 'iPad' : 'iPod' } // WTF: version is not part of user agent in web apps if (versionIdentifier) { result.version = versionIdentifier } } else if (/sailfish/i.test(ua)) { result = { name: 'Sailfish' , sailfish: t , version: getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i) } } else if (/seamonkey\//i.test(ua)) { result = { name: 'SeaMonkey' , seamonkey: t , version: getFirstMatch(/seamonkey\/(\d+(\.\d+)?)/i) } } else if (/firefox|iceweasel/i.test(ua)) { result = { name: 'Firefox' , firefox: t , version: getFirstMatch(/(?:firefox|iceweasel)[ \/](\d+(\.\d+)?)/i) } if (/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(ua)) { result.firefoxos = t } } else if (/silk/i.test(ua)) { result = { name: 'Amazon Silk' , silk: t , version : getFirstMatch(/silk\/(\d+(\.\d+)?)/i) } } else if (android) { result = { name: 'Android' , version: versionIdentifier } } else if (/phantom/i.test(ua)) { result = { name: 'PhantomJS' , phantom: t , version: getFirstMatch(/phantomjs\/(\d+(\.\d+)?)/i) } } else if (/blackberry|\bbb\d+/i.test(ua) || /rim\stablet/i.test(ua)) { result = { name: 'BlackBerry' , blackberry: t , version: versionIdentifier || getFirstMatch(/blackberry[\d]+\/(\d+(\.\d+)?)/i) } } else if (/(web|hpw)os/i.test(ua)) { result = { name: 'WebOS' , webos: t , version: versionIdentifier || getFirstMatch(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i) }; /touchpad\//i.test(ua) && (result.touchpad = t) } else if (/bada/i.test(ua)) { result = { name: 'Bada' , bada: t , version: getFirstMatch(/dolfin\/(\d+(\.\d+)?)/i) }; } else if (/tizen/i.test(ua)) { result = { name: 'Tizen' , tizen: t , version: getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i) || versionIdentifier }; } else if (/safari/i.test(ua)) { result = { name: 'Safari' , safari: t , version: versionIdentifier } } else { result = { name: getFirstMatch(/^(.*)\/(.*) /), version: getSecondMatch(/^(.*)\/(.*) /) }; } // set webkit or gecko flag for browsers based on these engines if (!result.msedge && /(apple)?webkit/i.test(ua)) { result.name = result.name || "Webkit" result.webkit = t if (!result.version && versionIdentifier) { result.version = versionIdentifier } } else if (!result.opera && /gecko\//i.test(ua)) { result.name = result.name || "Gecko" result.gecko = t result.version = result.version || getFirstMatch(/gecko\/(\d+(\.\d+)?)/i) } // set OS flags for platforms that have multiple browsers if (!result.msedge && (android || result.silk)) { result.android = t } else if (iosdevice) { result[iosdevice] = t result.ios = t } // OS version extraction var osVersion = ''; if (result.windowsphone) { osVersion = getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i); } else if (iosdevice) { osVersion = getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i); osVersion = osVersion.replace(/[_\s]/g, '.'); } else if (android) { osVersion = getFirstMatch(/android[ \/-](\d+(\.\d+)*)/i); } else if (result.webos) { osVersion = getFirstMatch(/(?:web|hpw)os\/(\d+(\.\d+)*)/i); } else if (result.blackberry) { osVersion = getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i); } else if (result.bada) { osVersion = getFirstMatch(/bada\/(\d+(\.\d+)*)/i); } else if (result.tizen) { osVersion = getFirstMatch(/tizen[\/\s](\d+(\.\d+)*)/i); } if (osVersion) { result.osversion = osVersion; } // device type extraction var osMajorVersion = osVersion.split('.')[0]; if (tablet || iosdevice == 'ipad' || (android && (osMajorVersion == 3 || (osMajorVersion == 4 && !mobile))) || result.silk) { result.tablet = t } else if (mobile || iosdevice == 'iphone' || iosdevice == 'ipod' || android || result.blackberry || result.webos || result.bada) { result.mobile = t } // Graded Browser Support // http://developer.yahoo.com/yui/articles/gbs if (result.msedge || (result.msie && result.version >= 10) || (result.yandexbrowser && result.version >= 15) || (result.chrome && result.version >= 20) || (result.firefox && result.version >= 20.0) || (result.safari && result.version >= 6) || (result.opera && result.version >= 10.0) || (result.ios && result.osversion && result.osversion.split(".")[0] >= 6) || (result.blackberry && result.version >= 10.1) ) { result.a = t; } else if ((result.msie && result.version < 10) || (result.chrome && result.version < 20) || (result.firefox && result.version < 20.0) || (result.safari && result.version < 6) || (result.opera && result.version < 10.0) || (result.ios && result.osversion && result.osversion.split(".")[0] < 6) ) { result.c = t } else result.x = t return result } var bowser = detect(typeof navigator !== 'undefined' ? navigator.userAgent : '') bowser.test = function (browserList) { for (var i = 0; i < browserList.length; ++i) { var browserItem = browserList[i]; if (typeof browserItem=== 'string') { if (browserItem in bowser) { return true; } } } return false; } /* * Set our detect method to the main bowser object so we can * reuse it to test other user agents. * This is needed to implement future tests. */ bowser._detect = detect; return bowser }); },{}],39:[function(require,module,exports){ /*! * @name JavaScript/NodeJS Merge v1.2.0 * @author yeikos * @repository https://github.com/yeikos/js.merge * Copyright 2014 yeikos - MIT license * https://raw.github.com/yeikos/js.merge/master/LICENSE */ ;(function(isNode) { /** * Merge one or more objects * @param bool? clone * @param mixed,... arguments * @return object */ var Public = function(clone) { return merge(clone === true, false, arguments); }, publicName = 'merge'; /** * Merge two or more objects recursively * @param bool? clone * @param mixed,... arguments * @return object */ Public.recursive = function(clone) { return merge(clone === true, true, arguments); }; /** * Clone the input removing any reference * @param mixed input * @return mixed */ Public.clone = function(input) { var output = input, type = typeOf(input), index, size; if (type === 'array') { output = []; size = input.length; for (index=0;index<size;++index) output[index] = Public.clone(input[index]); } else if (type === 'object') { output = {}; for (index in input) output[index] = Public.clone(input[index]); } return output; }; /** * Merge two objects recursively * @param mixed input * @param mixed extend * @return mixed */ function merge_recursive(base, extend) { if (typeOf(base) !== 'object') return extend; for (var key in extend) { if (typeOf(base[key]) === 'object' && typeOf(extend[key]) === 'object') { base[key] = merge_recursive(base[key], extend[key]); } else { base[key] = extend[key]; } } return base; } /** * Merge two or more objects * @param bool clone * @param bool recursive * @param array argv * @return object */ function merge(clone, recursive, argv) { var result = argv[0], size = argv.length; if (clone || typeOf(result) !== 'object') result = {}; for (var index=0;index<size;++index) { var item = argv[index], type = typeOf(item); if (type !== 'object') continue; for (var key in item) { var sitem = clone ? Public.clone(item[key]) : item[key]; if (recursive) { result[key] = merge_recursive(result[key], sitem); } else { result[key] = sitem; } } } return result; } /** * Get type of variable * @param mixed input * @return string * * @see http://jsperf.com/typeofvar */ function typeOf(input) { return ({}).toString.call(input).slice(8, -1).toLowerCase(); } if (isNode) { module.exports = Public; } else { window[publicName] = Public; } })(typeof module === 'object' && module && typeof module.exports === 'object' && module.exports); },{}],40:[function(require,module,exports){ module.exports={ "name": "rtcninja", "version": "0.6.4", "description": "WebRTC API wrapper to deal with different browsers", "author": { "name": "Iñaki Baz Castillo", "email": "[email protected]", "url": "http://eface2face.com" }, "contributors": [ { "name": "Jesús Pérez", "email": "[email protected]" } ], "license": "MIT", "main": "lib/rtcninja.js", "homepage": "https://github.com/eface2face/rtcninja.js", "repository": { "type": "git", "url": "https://github.com/eface2face/rtcninja.js.git" }, "keywords": [ "webrtc" ], "engines": { "node": ">=0.10.32" }, "dependencies": { "bowser": "^1.0.0", "debug": "^2.2.0", "merge": "^1.2.0" }, "devDependencies": { "browserify": "^11.0.1", "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", "gulp-expect-file": "0.0.7", "gulp-filelog": "^0.4.1", "gulp-header": "^1.7.1", "gulp-jscs": "^2.0.0", "gulp-jscs-stylish": "^1.1.2", "gulp-jshint": "^1.11.2", "gulp-rename": "^1.2.2", "gulp-uglify": "^1.4.0", "jshint-stylish": "^2.0.1", "retire": "^1.1.1", "shelljs": "^0.5.3", "vinyl-source-stream": "^1.1.0" }, "readme": "# rtcninja.js <img src=\"http://www.pubnub.com/blog/wp-content/uploads/2014/01/google-webrtc-logo.png\" height=\"30\" width=\"30\">\n\nWebRTC API wrapper to deal with different browsers transparently, [eventually](http://iswebrtcreadyyet.com/) this library shouldn't be needed. We only have to wait until W3C group in charge [finishes the specification](https://tools.ietf.org/wg/rtcweb/) and the different browsers implement it correctly :sweat_smile:.\n\n<img src=\"http://images4.fanpop.com/image/photos/21800000/browser-fight-google-chrome-21865454-600-531.jpg\" height=\"250\" width=\"250\">\n\nSupported environments:\n* [Google Chrome](https://www.google.com/chrome/browser/desktop/index.html) (desktop & mobile)\n* [Google Canary](https://www.google.com/chrome/browser/canary.html) (desktop & mobile)\n* [Mozilla Firefox](https://www.mozilla.org/en-GB/firefox/new) (desktop & mobile)\n* [Firefox Nigthly](https://nightly.mozilla.org/) (desktop & mobile)\n* [Opera](http://www.opera.com/)\n* [Vivaldi](https://vivaldi.com/)\n* [CrossWalk](https://crosswalk-project.org/)\n* [Cordova](cordova.apache.org): iOS support, you only have to use our plugin [following these steps](https://github.com/eface2face/cordova-plugin-iosrtc#usage).\n* [Node-webkit](https://github.com/nwjs/nw.js/)\n\n\n## Installation\n\n### **npm**:\n\n```bash\n$ npm install rtcninja\n```\n\nand then:\n\n```javascript\nvar rtcninja = require('rtcninja');\n```\n\n### **bower**:\n\n```bash\n$ bower install rtcninja\n```\n\n\n## Browserified library\n\nTake a browserified version of the library from the `dist/` folder:\n\n* `dist/rtcninja.js`: The uncompressed version.\n* `dist/rtcninja.min.js`: The compressed production-ready version.\n\nThey expose the global `window.rtcninja` module.\n\n\n## Usage\n\nIn the [examples](./examples/) folder we provide a complete one.\n\n```javascript\n// Must first call it.\nrtcninja();\n\n// Then check.\nif (rtcninja.hasWebRTC()) {\n // Do something.\n}\nelse {\n // Do something.\n}\n```\n\n\n## Documentation\n\nYou can read the full [API documentation](docs/index.md) in the docs folder.\n\n\n## Issues\n\nhttps://github.com/eface2face/rtcninja.js/issues\n\n\n## Developer guide\n\n* Create a branch with a name including your user and a meaningful word about the fix/feature you're going to implement, ie: \"jesusprubio/fixstuff\"\n* Use [GitHub pull requests](https://help.github.com/articles/using-pull-requests).\n* Conventions:\n * We use [JSHint](http://jshint.com/) and [Crockford's Styleguide](http://javascript.crockford.com/code.html).\n * Please run `grunt lint` to be sure your code fits with them.\n\n\n### Debugging\n\nThe library includes the Node [debug](https://github.com/visionmedia/debug) module. In order to enable debugging:\n\nIn Node set the `DEBUG=rtcninja*` environment variable before running the application, or set it at the top of the script:\n\n```javascript\nprocess.env.DEBUG = 'rtcninja*';\n```\n\nIn the browser run `rtcninja.debug.enable('rtcninja*');` and reload the page. Note that the debugging settings are stored into the browser LocalStorage. To disable it run `rtcninja.debug.disable('rtcninja*');`.\n\n\n## Copyright & License\n\n* eFace2Face Inc.\n* [MIT](./LICENSE)\n", "readmeFilename": "README.md", "gitHead": "18789cbefdb5a6c6c038ab4f1ce8e9e3813135b0", "bugs": { "url": "https://github.com/eface2face/rtcninja.js/issues" }, "_id": "[email protected]", "scripts": {}, "_shasum": "7ede8577ce978cb431772d877967c53aadeb5e99", "_from": "rtcninja@>=0.6.4 <0.7.0" } },{}],41:[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 push:'candidates', reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/, names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'], format: function (o) { var str = "candidate:%s %d %s %d %s %d typ %s"; // NB: candidate has two optional chunks, so %void middle one if it's missing str += (o.raddr != null) ? " raddr %s rport %d" : "%v%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)/ }, { // 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"; } }); }); },{}],42:[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":43,"./writer":44}],43:[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('='); 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":41}],44:[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":41}],45:[function(require,module,exports){ var _global = (function() { return this; })(); var nativeWebSocket = _global.WebSocket || _global.MozWebSocket; var websocket_version = require('./version'); /** * Expose a W3C WebSocket class with just one or two arguments. */ function W3CWebSocket(uri, protocols) { var native_instance; if (protocols) { native_instance = new nativeWebSocket(uri, protocols); } else { native_instance = new nativeWebSocket(uri); } /** * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket * class). Since it is an Object it will be returned as it is when creating an * instance of W3CWebSocket via 'new W3CWebSocket()'. * * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2 */ return native_instance; } /** * Module exports. */ module.exports = { 'w3cwebsocket' : nativeWebSocket ? W3CWebSocket : null, 'version' : websocket_version }; },{"./version":46}],46:[function(require,module,exports){ module.exports = require('../package.json').version; },{"../package.json":47}],47:[function(require,module,exports){ module.exports={ "name": "websocket", "description": "Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.", "keywords": [ "websocket", "websockets", "socket", "networking", "comet", "push", "RFC-6455", "realtime", "server", "client" ], "author": { "name": "Brian McKelvey", "email": "[email protected]", "url": "https://www.worlize.com/" }, "contributors": [ { "name": "Iñaki Baz Castillo", "email": "[email protected]", "url": "http://dev.sipdoc.net" } ], "version": "1.0.22", "repository": { "type": "git", "url": "git+https://github.com/theturtle32/WebSocket-Node.git" }, "homepage": "https://github.com/theturtle32/WebSocket-Node", "engines": { "node": ">=0.8.0" }, "dependencies": { "debug": "~2.2.0", "nan": "~2.0.5", "typedarray-to-buffer": "~3.0.3", "yaeti": "~0.0.4" }, "devDependencies": { "buffer-equal": "^0.0.1", "faucet": "^0.0.1", "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", "gulp-jshint": "^1.11.2", "jshint-stylish": "^1.0.2", "tape": "^4.0.1" }, "config": { "verbose": false }, "scripts": { "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", "test": "faucet test/unit", "gulp": "gulp" }, "main": "index", "directories": { "lib": "./lib" }, "browser": "lib/browser.js", "license": "Apache-2.0", "gitHead": "19108bbfd7d94a5cd02dbff3495eafee9e901ca4", "bugs": { "url": "https://github.com/theturtle32/WebSocket-Node/issues" }, "_id": "[email protected]", "_shasum": "8c33e3449f879aaf518297c9744cebf812b9e3d8", "_from": "websocket@>=1.0.22 <2.0.0", "_npmVersion": "2.14.3", "_nodeVersion": "3.3.1", "_npmUser": { "name": "theturtle32", "email": "[email protected]" }, "maintainers": [ { "name": "theturtle32", "email": "[email protected]" } ], "dist": { "shasum": "8c33e3449f879aaf518297c9744cebf812b9e3d8", "tarball": "http://registry.npmjs.org/websocket/-/websocket-1.0.22.tgz" }, "_resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.22.tgz" } },{}],48:[function(require,module,exports){ module.exports={ "name": "jssip", "title": "JsSIP", "description": "the Javascript SIP library", "version": "0.7.9", "homepage": "http://jssip.net", "author": "José Luis Millán <[email protected]> (https://github.com/jmillan)", "contributors": [ "Iñaki Baz Castillo <[email protected]> (https://github.com/ibc)", "Saúl Ibarra Corretgé <[email protected]> (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.2.0", "rtcninja": "^0.6.4", "sdp-transform": "~1.5.0", "websocket": "^1.0.22" }, "devDependencies": { "browserify": "^11.2.0", "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", "gulp-expect-file": "0.0.7", "gulp-header": "^1.7.1", "gulp-jshint": "^1.11.2", "gulp-nodeunit-runner": "^0.2.2", "gulp-rename": "^1.2.2", "gulp-uglify": "^1.4.2", "gulp-util": "^3.0.6", "jshint-stylish": "^2.0.1", "pegjs": "0.7.0", "vinyl-source-stream": "^1.1.0" }, "scripts": { "test": "gulp test" } } },{}]},{},[7])(7) });
/** * Coinsecure Api Documentation * To generate an API key, please visit <a href='https://coinsecure.in/api' target='_new' class='homeapi'>https://coinsecure.in/api</a>.<br>Guidelines for use can be accessed at <a href='https://api.coinsecure.in/v1/guidelines'>https://api.coinsecure.in/v1/guidelines</a>.<br>Programming Language Libraries for use can be accessed at <a href='https://api.coinsecure.in/v1/code-libraries'>https://api.coinsecure.in/v1/code-libraries</a>. * * OpenAPI spec version: beta * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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. */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. define(['expect.js', '../../src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. factory(require('expect.js'), require('../../src/index')); } else { // Browser globals (root is window) factory(root.expect, root.CoinsecureApiDocumentation); } }(this, function(expect, CoinsecureApiDocumentation) { 'use strict'; var instance; beforeEach(function() { instance = new CoinsecureApiDocumentation.NumberOtp(); }); var getProperty = function(object, getter, property) { // Use getter method if present; otherwise, get the property directly. if (typeof object[getter] === 'function') return object[getter](); else return object[property]; } var setProperty = function(object, setter, property, value) { // Use setter method if present; otherwise, set the property directly. if (typeof object[setter] === 'function') object[setter](value); else object[property] = value; } describe('NumberOtp', function() { it('should create an instance of NumberOtp', function() { // uncomment below and update the code to test NumberOtp //var instane = new CoinsecureApiDocumentation.NumberOtp(); //expect(instance).to.be.a(CoinsecureApiDocumentation.NumberOtp); }); it('should have the property _number (base name: "number")', function() { // uncomment below and update the code to test the property _number //var instane = new CoinsecureApiDocumentation.NumberOtp(); //expect(instance).to.be(); }); it('should have the property otp (base name: "otp")', function() { // uncomment below and update the code to test the property otp //var instane = new CoinsecureApiDocumentation.NumberOtp(); //expect(instance).to.be(); }); }); }));
import _curry3 from './internal/_curry3.js'; /** * Takes a function and two values, and returns whichever value produces the * larger result when passed to the provided function. * * @func * @memberOf R * @since v0.8.0 * @category Relation * @sig Ord b => (a -> b) -> a -> a -> a * @param {Function} f * @param {*} a * @param {*} b * @return {*} * @see R.max, R.minBy * @example * * // square :: Number -> Number * const square = n => n * n; * * R.maxBy(square, -3, 2); //=> -3 * * R.reduce(R.maxBy(square), 0, [3, -5, 4, 1, -2]); //=> -5 * R.reduce(R.maxBy(square), 0, []); //=> 0 */ var maxBy = _curry3(function maxBy(f, a, b) { return f(b) > f(a) ? b : a; }); export default maxBy;
import Script from 'next/script' export default function Inline() { return ( <> {/* Attributes are forwarded */} <Script src="https://www.google-analytics.com/analytics.js" id="analytics" nonce="XUENAJFW" data-test="analytics" /> <main> <h1>Forwarded attributes</h1> <h5> Open devtools and check that attributes has been forwarded correctly. </h5> </main> </> ) }
(self.webpackChunkwar3tool=self.webpackChunkwar3tool||[]).push([[925],{7925:(e,n,t)=>{"use strict";t.r(n),t.d(n,{ToBlp:()=>c,default:()=>s}),t(1131);var r=t(8465),o=t(7294),a=t(3690);function l(){return(l=Object.assign||function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e}).apply(this,arguments)}function u(e,n,t,r,o,a,l){try{var u=e[a](l),i=u.value}catch(e){return void t(e)}u.done?n(i):Promise.resolve(i).then(r,o)}var i=r.Z.Dragger,c=function(e){!function(e){if(null==e)throw new TypeError("Cannot destructure undefined")}(e);var n,t,r={name:"file",multiple:!1,showUploadList:!1,onChange:(n=regeneratorRuntime.mark((function e(n){return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:console.info(n.file);case 1:case"end":return e.stop()}}),e)})),t=function(){var e=this,t=arguments;return new Promise((function(r,o){var a=n.apply(e,t);function l(e){u(a,r,o,l,i,"next",e)}function i(e){u(a,r,o,l,i,"throw",e)}l(void 0)}))},function(e){return t.apply(this,arguments)}),beforeUpload:function(){return!1},onDrop:function(e){console.log("Dropped files",e.dataTransfer.files)}};return o.createElement(i,l({fileList:[]},r),o.createElement(o.Fragment,null,o.createElement("p",{className:"ant-upload-drag-icon"},o.createElement(a.Z,null)),o.createElement("p",{className:"ant-upload-text"},"点击或者拖拽图片文件进来")))};const s=c}}]);
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..preprocess import SliceTiming def test_SliceTiming_inputs(): input_map = dict( ignore_exception=dict( deprecated='1.0.0', nohash=True, usedefault=True, ), in_files=dict( copyfile=False, field='scans', mandatory=True, ), matlab_cmd=dict(), mfile=dict(usedefault=True, ), num_slices=dict( field='nslices', mandatory=True, ), out_prefix=dict( field='prefix', usedefault=True, ), paths=dict(), ref_slice=dict( field='refslice', mandatory=True, ), slice_order=dict( field='so', mandatory=True, ), time_acquisition=dict( field='ta', mandatory=True, ), time_repetition=dict( field='tr', mandatory=True, ), use_mcr=dict(), use_v8struct=dict( min_ver='8', usedefault=True, ), ) inputs = SliceTiming.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], metakey) == value def test_SliceTiming_outputs(): output_map = dict(timecorrected_files=dict(), ) outputs = SliceTiming.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): assert getattr(outputs.traits()[key], metakey) == value
/* * Universal tageditor for Jeditable * * Copyright (c) 2008 Mika Tuupola * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Depends on jTagEditor jQuery plugin by Jay Salvat: * http://www.jaysalvat.com/jquery/jtageditor/ * * Project home: * http://www.appelsiini.net/projects/jeditable * * Revision: $Id: jquery.jeditable.tageditor.js 344 2008-03-24 16:02:11Z tuupola $ * */ $.editable.addInputType('tageditor', { element : function(settings, original) { var textarea = $('<textarea>'); if (settings.rows) { textarea.attr('rows', settings.rows); } else { textarea.height(settings.height); } if (settings.cols) { textarea.attr('cols', settings.cols); } else { textarea.width(settings.width); } $(this).append(textarea); return(textarea); }, plugin : function(settings, original) { $('textarea', this).jTagEditor(settings.tageditor); } });
import React from 'react'; import PropTypes from "prop-types"; import Typography from "../Typography/Typography"; import { DropDown } from '../AppointmentDetail/AppointmentDetail'; import "../AppointmentDetail/styles.scss"; import "./styles.scss"; const insurance = { description: 'Delta Dental - PPO', items: [ {name: 'Diganostic', result: '100%'}, {name: 'X-Ray', result: '100%'}, {name: 'Preventive', result: '100%'}, {name: 'Restorative', result: '80%'}, {name: 'Endo', result: '80%'}, {name: 'Perio', result: '80%'}, {name: 'Oral Surgery', result: '80%'}, {name: 'Crowns', result: '50%'}, {name: 'Prosth', result: '50%'}, {name: 'Diganostic', result: '50%'}, ], copay: { total: { name: 'Annual Max', sum: '$2000' }, items: [ {name: 'Remaining', result: '100%'}, {name: 'Pending', result: '100%'}, {name: 'Deductible', result: '100%'}, ] } } function Insurance({ open = true, status='Verified', handleClick }) { const content = <div className="appointment-detail-wrapper"> <Typography text={insurance.description} size="semibold12" color="font-black" /> <div className="appoint-detail-item-content" /> <div className="appointment-detail-item"> <div className="insurance-item-wrapper"> {insurance.items.map((item, index) => <div className="insurance-item-content"> <div className="dot-item">&bull;&nbsp;<Typography text={item.name} size="regular12" color="font-black" /></div> <Typography text={item.result} size="regular12" color="font-black" /> </div> )} <div className="appoint-detail-item-content" /> <div className="insurance-item-content"> <div className="dot-item">&bull;&nbsp;<Typography text={insurance.copay.total.name} size="semibold12" color="font-black" /></div> <Typography text={insurance.copay.total.sum} size="semibold12" color="font-black" /> </div> <div className="appoint-detail-item-content" /> <div className="insurance-item-wrapper"> {insurance.copay.items.map((item, index) => <div className="insurance-item-content"> <div className="dot-item">&bull;&nbsp;<Typography text={item.name} size="semibold12" color="font-black" /></div> <Typography text={item.result} size="semibold12" color="font-black" /> </div> )} </div> </div> </div> </div> return ( <DropDown label="Insurance" status={status} open={open} component={content} handleClick={handleClick} /> ); } Insurance.propTypes = { open: PropTypes.bool, status: PropTypes.oneOf(["Enabled", "Error", "Disabled", "Verified"]), handleClick: PropTypes.func, }; export default Insurance;
define(['util/promise'], function() { return new Promise(function(resolve) { require([ 'text!../test/unit/mocks/ontology.json', 'data/web-worker/services/ontology', 'data/web-worker/util/ajax' ], function(json, ontology, ajax) { // Hack ontology for testing var ontologyJson = JSON.parse(json), person = _.findWhere(ontologyJson.concepts, { id: 'http://lumify.io/dev#person' }); // Delete color for person if (person) { delete person.color; } // Add compound field that dependends on another compound ontologyJson.properties.push({ title: 'http://lumify.io/testing#compound1', displayName: 'Testing Compound', userVisible: true, searchable: true, dataType: 'string', validationFormula: 'dependentProp("http://lumify.io/dev#title") && ' + 'dependentProp("http://lumify.io/dev#name")', displayFormula: 'dependentProp("http://lumify.io/dev#name") + ", "' + 'dependentProp("http://lumify.io/dev#title")', dependentPropertyIris: [ 'http://lumify.io/dev#title', 'http://lumify.io/dev#name' ] }) // Add heading ontologyJson.properties.push({ title: 'http://lumify.io/testing#heading1', displayName: 'Testing Heading', userVisible: true, searchable: true, dataType: 'double', displayType: 'heading' }) ontologyJson.properties.push({ title: 'http://lumify.io/testing#integer1', displayName: 'Testing integer', userVisible: true, searchable: true, dataType: 'integer' }) ontologyJson.properties.push({ title: 'http://lumify.io/testing#number1', displayName: 'Testing number', userVisible: true, searchable: true, dataType: 'number' }) // Add video sub concept to test displayType ontologyJson.concepts.push({ id:'http://lumify.io/dev#videoSub', title:'http://lumify.io/dev#videoSub', displayName:'VideoSub', parentConcept:'http://lumify.io/dev#video', pluralDisplayName:'VideoSubs', searchable:true, properties:[] }); ajax.setNextResponse(ontologyJson); resolve(ontology.ontology()); }); }); });
import template from './sw-settings-snippet-filter-switch.html.twig'; import './sw-settings-snippet-filter-switch.scss'; const { Component } = Shopware; Component.register('sw-settings-snippet-filter-switch', { template, props: { label: { type: String, required: false, default: '' }, name: { type: String, required: true }, group: { type: String, required: false }, borderTop: { type: Boolean, required: false, default: false }, borderBottom: { type: Boolean, required: false, default: false }, type: { type: String, required: false, default: 'small', validator(value) { if (!value.length) { return true; } return ['small', 'large'].includes(value); } } }, computed: { fieldClasses() { return [ 'sw-settings-snippet-filter-switch__field', `sw-settings-snippet-filter-switch--${this.type}`, { 'border-top': this.borderTop, 'border-bottom': this.borderBottom } ].join(' '); } }, methods: { onChange(value) { const name = this.name; const group = this.group; this.$emit('change', { value, name, group }); } } });
import { headingPreview, subheaderPreview, headingTitle, } from "../../locators/heading"; import { helpIcon, link, getDataElementByValue } from "../../locators"; Then("heading children on preview is {word}", (children) => { headingPreview().invoke("text").should("contain", children); }); Then("heading title is set to {word}", (title) => { getDataElementByValue("title").should("have.text", title); }); Then("subheader on preview is {word}", (subheader) => { subheaderPreview().should("have.text", subheader); }); Then("link on preview is {word}", (helpLink) => { helpIcon().should("have.attr", "href", helpLink); }); Then("backLink on preview is {word}", (backLink) => { link().children().should("have.attr", "href", backLink); }); Then("Heading title has h1 HTML tag", () => { headingTitle().contains("This is a Title"); });
import unittest import calc class TestCalc(unittest.TestCase): def test_add(self): self.assertEqual(calc.add(10,2),12) self.assertEqual(calc.add(-1,2),1) self.assertEqual(calc.add(-10,-2),-12) self.assertEqual(calc.add(19,0),19) def test_sub(self): self.assertEqual(calc.subtract(10,2),8) self.assertEqual(calc.subtract(-1,2),-3) self.assertEqual(calc.subtract(-10,-2),-8) self.assertEqual(calc.subtract(19,0),19) def test_multiply(self): self.assertEqual(calc.multiply(10,2),20) self.assertEqual(calc.multiply(-1,2),-2) self.assertEqual(calc.multiply(-10,-2),20) self.assertEqual(calc.multiply(19,0),0) def test_divide(self): self.assertEqual(calc.divide(10,2),5) self.assertEqual(calc.divide(-1,2),-0.5) self.assertEqual(calc.divide(-10,-2),5) self.assertEqual(calc.divide(19,19),1) with self.assertRaises(ValueError): calc.divide(10,0) if __name__ == "__main__": unittest.main()
import PropTypes from 'prop-types'; import React, { PureComponent } from 'react'; import { Animated } from 'react-native'; import styles from './styles'; export default class Label extends PureComponent { static defaultProps = { numberOfLines: 1, disabled: false, restricted: false, }; static propTypes = { numberOfLines: PropTypes.number, disabled: PropTypes.bool, restricted: PropTypes.bool, fontSize: PropTypes.number.isRequired, activeFontSize: PropTypes.number.isRequired, baseColor: PropTypes.string.isRequired, tintColor: PropTypes.string.isRequired, errorColor: PropTypes.string.isRequired, focusAnimation: PropTypes .instanceOf(Animated.Value) .isRequired, labelAnimation: PropTypes .instanceOf(Animated.Value) .isRequired, contentInset: PropTypes.shape({ label: PropTypes.number, }), offset: PropTypes.shape({ x0: PropTypes.number, y0: PropTypes.number, x1: PropTypes.number, y1: PropTypes.number, }), //style: Animated.Text.propTypes.style, label: PropTypes.string, }; render() { let { label, offset, disabled, restricted, fontSize, activeFontSize, contentInset, errorColor, baseColor, tintColor, style, focusAnimation, labelAnimation, ...props } = this.props; if (null == label) { return null; } let color = disabled? baseColor: restricted? errorColor: focusAnimation.interpolate({ inputRange: [-1, 0, 1], outputRange: [errorColor, baseColor, tintColor], }); let textStyle = { lineHeight: fontSize, fontSize, color, }; let { x0, y0, x1, y1 } = offset; y0 += activeFontSize; y0 += contentInset.label; y0 += fontSize * 0.25; let containerStyle = { transform: [{ scale: labelAnimation.interpolate({ inputRange: [0, 1], outputRange: [1, activeFontSize / fontSize], }), }, { translateY: labelAnimation.interpolate({ inputRange: [0, 1], outputRange: [y0, y1], }), }, { translateX: labelAnimation.interpolate({ inputRange: [0, 1], outputRange: [x0, x1], }), }], }; return ( <Animated.View style={[styles.container, containerStyle]}> <Animated.Text style={[styles.text, style, textStyle]} {...props}> {label} </Animated.Text> </Animated.View> ); } }
/** * The `lockedgrid` component manages one or more child `grid`s that independently scroll * in the horizontal axis but are vertically synchronized. The end-user can, using column * menus or drag-drop, control which of these {@link #cfg!regions regions} contain which * columns. * * ## Locked Regions * * The `lockedgrid` always has a `center` {@link Ext.grid.locked.Region region} and by * default a `left` and `right` region. These regions are derivatives of `Ext.panel.Panel` * (to allow them to be resized and collapsed) and contain normal `grid` with a subset of * the overall set of `columns`. All keys in the `regions` config object are valid values * for a {@link Ext.grid.column.Column column}'s `locked` config. The values of each of * the properties of the `regions` config are configurations for the locked region itself. * * The layout of the locked regions is a simple `hbox` with the `center` assigned `flex:1` * and the non-center regions assigned a width based on the columns contained in that * region. The order of items in the container is determined by the `weight` assigned to * each region. Regions to the left of center have negative `weight` values, while regions * to the right of center have positive `weight` values. This distinction is important * primarily to determine the side of the region on which to display the resizer as well * as setting the direction of collapse for the region. * * ## Config and Event Delegation * * The `lockedgrid` mimics the config properties and events fired by a normal `grid`. It * does this in some cases by delegating configs to each child grid. The `regions` config * should be used to listen to events or configure a child grid independently when this * isn't desired. */ Ext.define('Ext.grid.locked.Grid', { extend: 'Ext.Panel', xtype: 'lockedgrid', alternateClassName: 'Ext.grid.LockedGrid', isLockedGrid: true, requires: [ 'Ext.layout.Box', 'Ext.layout.Fit', 'Ext.grid.Grid' ], classCls: Ext.baseCSSPrefix + 'lockedgrid', config: { /** * @cfg {Object} columnMenu * This is a config object which is used by columns in this grid to create their * header menus. * * The following column menu contains the following items. * * - Default column menu items {@link Ext.grid.Grid grid} * - "Region" menu item to provide locking sub-menu options * * This can be configured as `null` to prevent columns from showing a column menu. */ columnMenu: { items: { region: { text: 'Locked', iconCls: 'fi-lock', menu: {} } } }, /** * @cfg {Ext.grid.column.Column[]} columns (required) * An array of column definition objects which define all columns that appear in this grid. * Each column definition provides the header text for the column, and a definition of where * the data for that column comes from. * Column definition can also define the locked property * * This can also be a configuration object for a {Ext.grid.header.Container HeaderContainer} * which may override certain default configurations if necessary. For example, the special * layout may be overridden to use a simpler layout, or one can set default values shared * by all columns: * * columns: { * items: [ * { * text: "Column A" * dataIndex: "field_A", * locked: true, * width: 200 * },{ * text: "Column B", * dataIndex: "field_B", * width: 150 * }, * ... * ] * } * */ columns: null, /** * @cfg {String} defaultLockedRegion * This config determines which region corresponds to `locked: true` on a column. */ defaultLockedRegion: 'left', /** * @cfg {Object} gridDefaults * This config is applied to the child `grid` in all regions. */ gridDefaults: null, /** * @cfg {Boolean} hideHeaders * @inheritdoc Ext.grid.Grid#cfg!hideHeaders */ hideHeaders: false, /** * @cfg {Object} itemConfig * @inheritdoc Ext.grid.Grid#cfg!itemConfig */ itemConfig: {}, /** * @cfg {Object} leftGridDefaults * This config is applied to all left-side regions (those of negative 'weight'). * To set defaults for all grids within left-side regions configure the `grid` * property within this config. */ leftRegionDefaults: { locked: true, menuItem: { iconCls: 'fi-chevron-left' } }, /** * @cfg {Object} regions * This config determines the set of possible locked regions. Each key name in this * object denotes a named region (for example, "left", "right" and "center"). While * the set of names is not fixed, meaning a `lockedgrid` can have more than these * three regions, there must always be a "center" region. The center regions cannot * be hidden or collapsed or emptied of all columns. * * The values of each property in this object are configuration objects for the * {@link Ext.grid.locked.Region region}. The ordering of grids is determined by * the `weight` config. Negative values are "left" regions, while positive values * are "right" regions. The `menuLabel` is used in the column menu to allow the user * to place columns into the region. * * To add an additional left region: * * xtype: 'lockedgrid', * regions: { * left2: { * menuLabel: 'Locked (leftmost)', * weight: -20 // to the left of the standard "left" region * } * } */ regions: { left: { menuItem: { text: 'Locked (Left)' }, weight: -10 }, center: { flex: 1, menuItem: { text: 'Unlocked', iconCls: 'fi-unlock' }, weight: 0 }, right: { menuItem: { text: 'Locked (Right)' }, weight: 10 } }, /** * @cfg {Object} rightGridDefaults * This config is applied to all right-side regions (those of positive 'weight'). * To set defaults for all grids within right-side regions configure the `grid` * property within this config. */ rightRegionDefaults: { locked: true, menuItem: { iconCls: 'fi-chevron-right' } }, /** * @cfg {Ext.data.Store/Object/String} store * @inheritdoc Ext.grid.Grid#cfg!store */ store: null, /** * @cfg {Boolean} variableHeights * @inheritdoc Ext.grid.Grid#cfg!variableHeights */ variableHeights: false, /** * @cfg {Boolean} enableColumnMove * Set to `false` to disable header reorder within this grid. */ enableColumnMove: true, /** * @cfg {Boolean} grouped * @inheritdoc Ext.dataview.List#cfg!grouped */ grouped: true }, weighted: true, layout: { type: 'hbox', align: 'stretch' }, onRender: function() { this.callParent(); this.setupHeaderSync(); this.reconfigure(); }, doDestroy: function() { Ext.undefer(this.partnerTimer); this.callParent(); }, addColumn: function(columns) { var me = this, map = me.processColumns(columns), isArray = Array.isArray(columns), ret = isArray ? [] : null, grids = me.gridItems, len = grids.length, v, i, grid, toAdd; // Instead of just iterating over the map, loop // over the grids in order so that we add items // in order for (i = 0; i < len; ++i) { grid = grids[i]; toAdd = map[grid.regionKey]; if (toAdd) { v = grid.addColumn(toAdd); if (isArray) { Ext.Array.push(ret, v); } else { // processColumns always returns an array ret = v[0]; } } } if (me.getVariableHeights()) { me.doRefresh(); } return ret; }, getHorizontalOverflow: function() { var grids = this.visibleGrids, n = grids && grids.length, i; for (i = 0; i < n; ++i) { if (grids[i].getHorizontalOverflow()) { return true; } } return false; }, getRegion: function(key) { return this.regionMap[key] || null; }, getVerticalOverflow: function() { var grids = this.visibleGrids, n = grids && grids.length; // Vertical overflow is always on the right-most grid (TODO RTL) return n && grids[n - 1].getVerticalOverflow(); }, insertColumnBefore: function(column, before) { var ret; if (before === null) { ret = this.gridMap.center.addColumn(column); } else { ret = before.getParent().insertBefore(column, before); } if (this.getVariableHeights()) { this.doRefresh(); } return ret; }, removeColumn: function(column) { var ret = column.getGrid().removeColumn(column); if (this.getVariableHeights()) { this.doRefresh(); } return ret; }, createLocation: function(location) { var grid; if (location.isGridLocation && location.column) { grid = location.column.getGrid(); if (grid.getHidden()) { grid = null; location = location.record; } } if (!grid) { grid = this.regionMap.center.getGrid(); } return grid.createLocation(location); }, setLocation: function(location, options) { var grid; if (location.isGridLocation && location.column) { grid = location.column.getGrid(); if (grid.getHidden()) { grid = null; location = location.record; } } if (!grid) { grid = this.regionMap.center.getGrid(); } grid.setLocation(location, options); }, updateColumns: function(columns) { var me = this, grids = me.gridItems, map, len, i, grid; if (me.isConfiguring) { return; } map = me.processColumns(columns); ++me.bulkColumnChange; for (i = 0, len = grids.length; i < len; ++i) { grid = grids[i]; grid.setColumns(map[grid.regionKey] || []); } me.doRefresh(); --me.bulkColumnChange; }, updateGrouped: function(value) { this.relayConfig('grouped', value); }, updateHideHeaders: function(hideHeaders) { var me = this; // destroy first since relay will trigger bogus height change... me.headerSync = Ext.destroy(me.headerSync); me.relayConfig('hideHeaders', hideHeaders); me.setupHeaderSync(); }, updateEnableColumnMove: function(enabled) { var me = this, gridItems, b; if (me.isConfiguring) { return; } gridItems = me.gridItems; // update grid header reorder for (b = 0; b < gridItems.length; b++) { gridItems[b].setEnableColumnMove(enabled); } }, updateItemConfig: function(itemConfig) { this.relayConfig('itemConfig', itemConfig); }, updateMaxHeight: function(maxHeight) { this.relayConfig('maxHeight', maxHeight); }, updateRegions: function(regions) { var me = this, regionMap = me.regionMap, gridDefaults = me.getGridDefaults(), variableHeights = me.getVariableHeights(), enableColumnMove = me.getEnableColumnMove(), key, region, colMap, grid, gridMap, prev, scroller, len, i, defaultPartner, regionItems, gridItems; if (regionMap) { for (key in regionMap) { me.remove(regionMap[key]); } } me.regionMap = regionMap = {}; me.gridMap = gridMap = {}; colMap = me.processColumns(me.getColumns()); for (key in regions) { region = regions[key]; if (region) { region = me.createRegion(key, regions[key], colMap[key], gridDefaults); region = me.add(region); grid = region.getGrid(); grid.isDefaultPartner = key === me.unlockedKey; grid.setEnableColumnMove(enableColumnMove); if (variableHeights) { grid.partnerManager = me; if (grid.isDefaultPartner) { me.defaultPartner = defaultPartner = grid; } } region.on({ scope: me, collapse: 'onRegionCollapse', expand: 'onRegionExpand', hide: 'onRegionHide', show: 'onRegionShow' }); regionMap[key] = region; gridMap[key] = grid; scroller = grid.getScrollable(); if (scroller) { if (prev) { prev.addPartner(scroller, 'y'); } prev = scroller; } me.setupGrid(grid); } } // We don't add to this in the loop above because we want // the items in weighted order, so wait til everything is // added and in order me.regionItems = regionItems = me.query('>[isLockedGridRegion]'); me.gridItems = gridItems = []; for (i = 0, len = regionItems.length; i < len; ++i) { grid = regionItems[i].getGrid(); gridItems.push(grid); if (defaultPartner && grid !== defaultPartner) { grid.renderInfo = defaultPartner.renderInfo; } } me.setupHeaderSync(); }, applyStore: function(store) { return store ? Ext.data.StoreManager.lookup(store) : null; }, updateStore: function(store) { this.store = store; this.relayConfig('store', store); }, updateVariableHeights: function(variableHeights) { this.relayConfig('variableHeights', variableHeights); }, registerActionable: function(actionable) { var me = this, actionables = me.actionables || (me.actionables = []), gridItems = me.gridItems, i; if (!Ext.Array.contains(actionables, actionable)) { actionables.push(actionable); if (gridItems) { for (i = gridItems.length; i-- > 0; /* empty */) { gridItems[i].registerActionable(actionable); } } } }, unregisterActionable: function(actionable) { var actionables = this.actionables, gridItems = this.gridItems, i; if (actionables) { Ext.Array.remove(actionables, actionable); if (gridItems) { for (i = gridItems.length; i-- > 0; /* empty */) { gridItems[i].registerActionable(actionable); } } } }, statics: { relayGridMethod: function(name, collection, key, defaultResult) { collection = collection || 'visibleGrids'; key = key || 0; if (defaultResult == null) { defaultResult = null; } this.prototype[name] = function() { var grid = this[collection], ret = defaultResult; grid = grid && grid[key]; if (grid) { if (grid.isLockedGridRegion) { grid = grid.getGrid(); } ret = grid[name].apply(grid, arguments); } return ret; }; }, relayGridMethods: function(descr) { var simple = [], name, options; for (name in descr) { options = descr[name]; if (options === true) { options = simple; simple[0] = name; } else { options = options.slice(); options.unshift(name); } this.relayGridMethod.apply(this, options); } } }, privates: { bulkColumnChange: 0, partnerOffset: 200, itemConfiguring: false, lastPartnerRequest: 0, unlockedKey: 'center', claimActivePartner: function(partner) { var me = this, now = Date.now(), active = me.activePartner; me.partnerTimer = Ext.undefer(me.partnerTimer); if (!active || (now - me.lastPartnerRequest > me.partnerOffset)) { me.activePartner = partner; me.lastPartnerRequest = now; me.setActivePartner(partner); } }, configureHeaderHeights: function() { var headerSync = this.headerSync; if (headerSync) { headerSync.sync(); } }, configureItems: function() { var me = this, gridItems = me.gridItems, regionItems = me.regionItems, i, found, grid, hide, region; me.itemConfiguring = true; for (i = gridItems.length - 1; i >= 0; --i) { grid = gridItems[i]; region = regionItems[i]; me.setRegionVisibility(region); hide = true; if (!found || !grid.getVerticalOverflow()) { // Don't hide the scrollbars on hidden items, the current // logic assumes that anything after the current item has // scrollers visible. hide = false; found = me.isRegionVisible(region); } grid.setHideScrollbar(hide); } me.itemConfiguring = false; }, configurePartners: function() { var me = this, gridItems = this.gridItems, len = gridItems.length, visibleGrids, i, grid; visibleGrids = gridItems.filter(function(item) { return me.isRegionVisible(item.region); }); me.visibleGrids = visibleGrids; for (i = 0; i < len; ++i) { grid = gridItems[i]; grid.allPartners = visibleGrids; grid.partners = visibleGrids.filter(function(item) { return item !== grid; }); } }, createRegion: function(key, cfg, columns, gridDefaults) { var me = this, weight = cfg.weight, defaults; me.fireEvent('createregion', me, columns); if (weight !== 0) { defaults = weight < 0 ? me.getLeftRegionDefaults() : me.getRightRegionDefaults(); } return Ext.merge({ xtype: 'lockedgridregion', regionKey: key, lockedGrid: me, grid: Ext.apply({ regionKey: key, columnMenu: me.getColumnMenu(), columns: columns, hideHeaders: me.getHideHeaders(), grouped: me.getGrouped(), itemConfig: me.getItemConfig(), store: me.getStore(), variableHeights: me.getVariableHeights() }, gridDefaults) }, defaults, cfg); }, doHorizontalScrollCheck: function() { var grids = this.gridItems, len = grids.length, grid, scroller, i; for (i = 0; i < len; ++i) { grid = grids[i]; scroller = grid.getScrollable(); if (this.isRegionVisible(grid.region) && scroller) { scroller.setX(grid.getHorizontalOverflow() ? 'scroll' : true); } } }, doRefresh: function() { this.reconfigure(); this.refreshGrids(); this.doHorizontalScrollCheck(); this.doVerticalScrollCheck(); }, doReleaseActivePartner: function() { var me = this; if (!me.destroyed) { me.lastPartnerRequest = 0; me.activePartner = null; me.setActivePartner(me.defaultPartner); } }, doVerticalScrollCheck: function() { var grids = this.gridItems, len = grids.length, grid, scroller, region, i; for (i = 0; i < len; ++i) { grid = grids[i]; scroller = grid.getScrollable(); region = grid.region; if (region && this.isRegionVisible(region) && scroller) { if (grid.getVerticalOverflow()) { this.setGridScrollers(region, region.isHidden()); } else { this.setGridScrollers(false); } } } }, handleChangeRegion: function(region, column) { var me = this, grid = region.getGrid(), gridItems = me.gridItems, newIdx = gridItems.indexOf(grid), oldIdx = gridItems.indexOf(column.getGrid()); // The idea here is to retain the closest position possible. // If moving backwards, add it to the end. If moving forwards, // add it to the front. ++me.bulkColumnChange; if (newIdx < oldIdx) { grid.addColumn(column); } else { grid.insertColumn(0, column); } // Refreshing grid on column add or insert. grid.syncRowsToHeight(true); --me.bulkColumnChange; me.doHorizontalScrollCheck(); me.doVerticalScrollCheck(); }, handleRegionVisibilityChange: function(region, hiding) { var me = this; if (!me.itemConfiguring) { me.configurePartners(); me.refreshGrids(); me.setGridScrollers(region, hiding); me.configureHeaderHeights(); } }, isActivePartner: function(grid) { var active = this.activePartner; return active ? grid === active : grid.isDefaultPartner; }, isHeaderVisible: function(header) { return this.isRegionVisible(header.getGrid().region); }, isRegionVisible: function(region) { return !region.hasHiddenContent(); }, isLastVisibleRegion: function(region) { var regions = this.regionItems, index = regions.indexOf(region), other, i; for (i = regions.length - 1; i > index; --i) { other = regions[i]; if (!other.hasHiddenContent()) { return false; } } return true; }, onBeforeShowColumnMenu: function(grid, column, menu) { var regions = this.regionItems, len = regions.length, current = grid.region, disabled = false, items, region, i; menu = menu.getComponent('region'); if (menu) { menu = menu.getMenu(); menu.removeAll(); items = []; disabled = !!(grid.isDefaultPartner && grid.getVisibleColumns().length === 1); for (i = 0; i < len; ++i) { region = regions[i]; items.push(Ext.applyIf({ disabled: disabled || region === current, handler: this.handleChangeRegion.bind(this, region, column) }, region.getMenuItem())); } menu.add(items); } }, onColumnAdd: function(grid) { if (!this.setRegionVisibility(grid.region)) { this.refreshGrids(); } this.configureHeaderHeights(); }, onColumnHide: function(grid) { if (!this.setRegionVisibility(grid.region)) { this.refreshGrids(); } this.configureHeaderHeights(); }, onColumnRemove: function(grid, column) { var me = this; me.fireEvent('columnremove', grid, column); if (!me.setRegionVisibility(grid.region)) { me.refreshGrids(); } me.configureHeaderHeights(); }, onColumnShow: function(grid) { if (!this.setRegionVisibility(grid.region)) { this.refreshGrids(); } this.configureHeaderHeights(); }, onGridHorizontalOverflowChange: function() { if (!this.bulkColumnChange) { this.doHorizontalScrollCheck(); } }, onGridResize: function(grid) { grid.syncRowsToHeight(true); }, onGridVerticalOverflowChange: function(grid, value) { // We could call doVerticalScrollCheck here but that would cause // all grids to update every time this is called // seeing that we already know the grid that has changed we can target // just one grid per event var region = grid.region; if (value) { this.setGridScrollers(region, region.isHidden()); } else { grid.setHideScrollbar(false); } }, onRegionCollapse: function(region) { this.handleRegionVisibilityChange(region, true); }, onRegionExpand: function(region) { this.handleRegionVisibilityChange(region, false); }, onRegionHide: function(region) { this.handleRegionVisibilityChange(region, true); }, onRegionShow: function(region) { this.handleRegionVisibilityChange(region, false); }, getRegionKey: function(lockedValue) { var defaultLocked = this.getDefaultLockedRegion(), key; if (lockedValue) { key = lockedValue === true ? defaultLocked : lockedValue; } else { key = this.unlockedKey; } return key; }, processColumns: function(columns) { var me = this, map = {}, len, i, col, locked, key, arr; if (columns) { if (!Array.isArray(columns)) { columns = [columns]; } for (i = 0, len = columns.length; i < len; ++i) { col = columns[i]; locked = col.locked || (col.getLocked && col.getLocked()); key = me.getRegionKey(locked); arr = map[key]; if (!arr) { map[key] = arr = []; } arr.push(col); } } return map; }, reconfigure: function() { this.configureItems(); this.configurePartners(); this.configureHeaderHeights(); }, refreshGrids: function() { var visibleGrids = this.visibleGrids, len = visibleGrids.length, i; if (!this.rendered) { return; } for (i = 0; i < len; ++i) { visibleGrids[i].syncRowsToHeight(true); } }, relayConfig: function(name, value) { var grids = this.gridItems, i, len, setter; if (grids && !this.isConfiguring) { setter = Ext.Config.get(name).names.set; for (i = 0, len = grids.length; i < len; ++i) { grids[i][setter](value); } } }, releaseActivePartner: function(partner) { var me = this; if (me.activePartner === partner) { Ext.undefer(me.partnerTimer); me.partnerTimer = Ext.defer(me.doReleaseActivePartner, me.partnerOffset, me); } }, setActivePartner: function(partner) { var visibleGrids = this.visibleGrids; Ext.Array.remove(visibleGrids, partner); visibleGrids.unshift(partner); }, setGridScrollers: function(region, isHiding) { var gridItems = this.gridItems, len = gridItems.length, index, i, grid; if (this.isLastVisibleRegion(region)) { grid = region.getGrid(); // If this is the last visible grid and we're hiding it, the // previous grid needs to show the scroller. Otherwise, this // grid does index = gridItems.indexOf(grid) - (isHiding ? 1 : 0); for (i = 0; i < len; ++i) { gridItems[i].setHideScrollbar(grid.getVerticalOverflow() ? i < index : false); } } }, setRegionVisibility: function(region) { var grid = region.getGrid(), hidden = !!region.getHidden(); region.setHidden(grid.getVisibleColumns().length === 0); return hidden !== region.getHidden(); }, setupGrid: function(grid) { var actionables = this.actionables, i; if (actionables) { for (i = 0; i < actionables.length; ++i) { grid.registerActionable(actionables[i]); } } grid.on({ scope: this, beforeshowcolumnmenu: 'onBeforeShowColumnMenu', columnadd: 'onColumnAdd', columnhide: 'onColumnHide', columnremove: 'onColumnRemove', columnshow: 'onColumnShow', horizontaloverflowchange: 'onGridHorizontalOverflowChange', resize: 'onGridResize', verticaloverflowchange: 'onGridVerticalOverflowChange' }); }, setupHeaderSync: function() { var me = this, grids = me.gridItems, headers, i; if (!me.getHideHeaders() && !me.isConfiguring) { headers = []; for (i = 0; i < grids.length; ++i) { headers.push(grids[i].getHeaderContainer()); } Ext.destroy(me.headerSync); me.headerSync = new Ext.util.HeightSynchronizer( headers, me.isHeaderVisible.bind(me)); } } } }, function(LockedGrid) { LockedGrid.relayGridMethods({ ensureVisible: true, gatherData: true, getSelections: true, mapToItem: true, mapToRecord: true, mapToRecordIndex: true }); });
var crypto = require("crypto"); module.exports = function (app) { const algorithm = app.parameters.encryption.algorithm; const secret = app.parameters.encryption.secret; const inputEncoding = app.parameters.encryption.inputEncoding; const outputEncoding = app.parameters.encryption.outputEncoding; var encryption = {}; encryption.encrypt = function (value) { var cipher = crypto.createCipher(algorithm, secret); var crypted = cipher.update(value, inputEncoding, outputEncoding); crypted += cipher.final(outputEncoding); return crypted; }; encryption.decrypt = function (value) { var decipher = crypto.createDecipher(algorithm, secret); var decrypted = decipher.update(value, outputEncoding, inputEncoding); decrypted += decipher.final(inputEncoding); return decrypted; }; return encryption; };
import subprocess, wget, os, shutil, sys, glob if not os.path.exists('swig-scilab'): subprocess.call('git clone https://github.com/swig/swig.git -b gsoc2012-scilab swig-scilab', shell = True, stdout = sys.stdout, stderr = sys.stderr) else: subprocess.call('git pull', shell = True, cwd = 'swig-scilab', stdout = sys.stdout, stderr = sys.stderr) os.chdir('swig-scilab') if not glob.glob('pcre-*.tar.gz'): for rev in ['8.34','8.35','8.36']: try: wget.download('ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-'+rev+'.tar.gz'); break except: pass prefix = '--prefix=${PWD}/swig-scilab-bin' if '--windows' in sys.argv: compilers = " CXX=i686-w64-mingw32-g++ CC=i686-w64-mingw32-gcc " host = " --host=x86_64-unknown-linux-gnu " prefix += ' LDFLAGS="-static-libgcc -static-libstdc++ -static"' else: compilers = '' host = '' commons = dict(shell = True, stdout = sys.stdout, stderr = sys.stderr) subprocess.check_call('Tools/pcre-build.sh'+compilers+host, **commons) subprocess.check_call(compilers+'./autogen.sh', **commons) subprocess.check_call('./configure --disable-ccache --with-scilab-inc=${SCILAB_HOME}/include --with-scilab=${SCILAB_HOME}/bin/scilab-cli'+' '+prefix+compilers+host, **commons) subprocess.check_call(compilers+'make', **commons) subprocess.check_call(compilers+'make install', **commons) if '--windows' in sys.argv: subprocess.check_call('cp swig.exe swig3.0.exe', cwd='swig-scilab-bin/bin', **commons) subprocess.check_call('cp swig.exe swig2.0.exe', cwd='swig-scilab-bin/bin', **commons) else: subprocess.check_call('cp swig swig3.0', cwd='swig-scilab-bin/bin', **commons) subprocess.check_call('cp swig swig2.0', cwd='swig-scilab-bin/bin', **commons)
const NavBar = () => { return ( <div> <div></div> <div></div> </div> ) } export default NavBar
import React from 'react' import { Link, graphql, useStaticQuery } from 'gatsby' import Layout from '../components/layout' const Template = ({ data }) => { const post = data.markdownRemark return ( <Layout> <Link to='/blog'>Go back to blogs</Link> <hr/> <h1>{post.frontmatter.title}</h1> <h4>Posted by: {post.frontmatter.author}</h4> <div dangerouslySetInnerHTML={{__html: post.html }}/> </Layout> ) } export const postQuery = graphql` query BlogPostByPath($path: String!) { markdownRemark(frontmatter: { path: { eq: $path }}) { html frontmatter { path title author date } } } ` export default Template;
"use strict"; /* * @Author: Kanata You * @Date: 2021-11-18 21:54:08 * @Last Modified by: Kanata You * @Last Modified time: 2022-01-18 00:08:28 */ Object.defineProperty(exports, "__esModule", { value: true }); const globals_1 = require("@jest/globals"); const extra_semver_1 = require("./extra-semver"); (0, globals_1.describe)('install/utils/extra-semver', () => { (0, globals_1.test)('coalesceVersions', () => { (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)([])).toEqual([]); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['*'])).toEqual(['*']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['3.2.1'])).toEqual(['3.2.1']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['4.2.1 - 5.4.0'])).toEqual(['>=4.2.1 <=5.4.0']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['^4.1.2'])).toEqual(['>=4.1.2 <5.0.0-0']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['^0.2.7'])).toEqual(['>=0.2.7 <0.3.0-0']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['>3.2.10'])).toEqual(['>3.2.10']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['>=2.7.1'])).toEqual(['>=2.7.1']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['<1.8.4'])).toEqual(['<1.8.4']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['<=7.5.2'])).toEqual(['<=7.5.2']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['*', '2.5.6'])).toEqual(['2.5.6']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['2.4.3', '3.0.6', '*'])).toEqual(['2.4.3', '3.0.6']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['2.11.0', '2.11.0'])).toEqual(['2.11.0']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['>2.1.0', '2.6.2'])).toEqual(['2.6.2']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['2.1.0', '^2.6.2'])).toEqual(['2.1.0', '>=2.6.2 <3.0.0-0']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['>2.1.0', '<=1.0.10'])).toEqual(['>2.1.0', '<=1.0.10']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['>2.1.0', '>=2.2.10', '<1.0.10'])).toEqual(['>=2.2.10', '<1.0.10']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['>=4.2.1', '<=5.4.0'])).toEqual(['>=4.2.1 <=5.4.0']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['>4.2.2', '<5.4.0'])).toEqual(['>4.2.2 <5.4.0']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['^5.2.3', '<5.4.0'])).toEqual(['>=5.2.3 <6.0.0-0 <5.4.0']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['^1.2.3', '<5.4.0'])).toEqual(['>=1.2.3 <2.0.0-0']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['^0.2.3', '0.3.1'])).toEqual(['>=0.2.3 <0.3.0-0', '0.3.1']); (0, globals_1.expect)((0, extra_semver_1.coalesceVersions)(['^2.1.0', '>2.0.0'])).toEqual(['>=2.1.0 <3.0.0-0']); }); });
def flatten(l): return [item for sublist in l for item in sublist]
import React from 'react'; import PropTypes from 'prop-types'; import { compose } from 'redux'; import { connect } from 'react-redux'; import { FormattedMessage, injectIntl, intlShape } from '../../util/reactIntl'; import { isScrollingDisabled } from '../../ducks/UI.duck'; import { TopbarContainer } from '../../containers'; import { Page, LayoutSideNavigation, LayoutWrapperMain, LayoutWrapperSideNav, LayoutWrapperTopbar, LayoutWrapperFooter, Footer, TermsOfService, } from '../../components'; import config from '../../config'; import css from './TermsOfServicePage.module.css'; const TermsOfServicePageComponent = props => { const { scrollingDisabled, intl } = props; const tabs = [ { text: intl.formatMessage({ id: 'TermsOfServicePage.privacyTabTitle' }), selected: false, linkProps: { name: 'PrivacyPolicyPage', }, }, { text: intl.formatMessage({ id: 'TermsOfServicePage.tosTabTitle' }), selected: true, linkProps: { name: 'TermsOfServicePage', }, }, { text: intl.formatMessage({ id: 'TermsOfServicePage.deletionTabTitle' }), selected: false, linkProps: { name: 'DeletionPolicyPage', }, }, { text: intl.formatMessage({ id: 'PrivacyPolicyPage.nativeTimePolicy' }), selected: false, linkProps: { name: 'NativeTimePolicyPage', }, }, ]; const siteTitle = config.siteTitle; const schemaTitle = intl.formatMessage({ id: 'TermsOfServicePage.schemaTitle' }, { siteTitle }); const schema = { '@context': 'http://schema.org', '@type': 'WebPage', name: schemaTitle, }; return ( <Page title={schemaTitle} scrollingDisabled={scrollingDisabled} schema={schema}> <LayoutSideNavigation> <LayoutWrapperTopbar> <TopbarContainer currentPage="TermsOfServicePage" /> </LayoutWrapperTopbar> <LayoutWrapperSideNav tabs={tabs} /> <LayoutWrapperMain> <div className={css.content}> <h1 className={css.heading}> <FormattedMessage id="TermsOfServicePage.heading" /> </h1> <TermsOfService /> </div> </LayoutWrapperMain> <LayoutWrapperFooter> <Footer /> </LayoutWrapperFooter> </LayoutSideNavigation> </Page> ); }; const { bool } = PropTypes; TermsOfServicePageComponent.propTypes = { scrollingDisabled: bool.isRequired, // from injectIntl intl: intlShape.isRequired, }; const mapStateToProps = state => { return { scrollingDisabled: isScrollingDisabled(state), }; }; const TermsOfServicePage = compose( connect(mapStateToProps), injectIntl )(TermsOfServicePageComponent); export default TermsOfServicePage;
import React from "react"; function FormErrors(props) { if ( props.formerrors && (props.formerrors.blankfield || props.formerrors.passwordmatch) ) { return ( <div className="error container mt-2 invalid"> <div className="row justify-content-center"> {props.formerrors.passwordmatch ? "Password value does not match confirm password value" : ""} </div> <div className="row justify-content-center"> {props.formerrors.blankfield ? "All fields are required" : ""} </div> </div> ); } else if (props.searchvalidationerror) { return ( <div className="error container mt-2 invalid"> <div className="row justify-content-center">Enter a valid location</div> </div> ); } else if (props.apierrors) { return ( <div className="error container mt-2 invalid"> <div className="row justify-content-center">{props.apierrors}</div> </div> ); } else if (props.formerrors && props.formerrors.cognito) { return ( <div className="error container mt-2 invalid"> <div className="row justify-content-center"> {props.formerrors.cognito.message} </div> </div> ); } else { return <div />; } } export default FormErrors;
function ProductCtrl(ProductsService, AppSettings, $stateParams, CartService) { 'ngInject'; const vm = this; vm.imageBaseUrl = AppSettings.cdnBaseUrl; vm.productName = $stateParams.productName; vm.addToCart = CartService.addToCart; vm.quantity = 1; vm.getAvailability = function() { return vm.inStock ? 'Yes' : 'No'; } function init() { ProductsService.getProduct(vm.productName) .then(function(data) { vm.id = data.id; vm.name = data.name; vm.description = data.description; vm.price = data.display_price; vm.images = data.master.images; vm.inStock = data.master.in_stock; vm.sku = data.master.sku; }); }; init(); } export default { name: 'ProductCtrl', fn: ProductCtrl };
// @flow export * from './ScreenStyle' export * from './common/CenteredSpinnerStyle' export * from './common/ButtonStyles' export * from './common/InputStyles' export * from './common/LogoImageStyles' export * from './common/FormFieldStyle' export * from './common/CheckboxStyles' export * from './common/HeaderStyles' export * from './adSpecific/PasswordStatusStyle' export * from './common/ModalStyle' export * from './common/ModalStyles' export * from './common/ListItemStyles' export * from './common/Fonts' export * from './common/HeaderParentButtons'
from importlib import import_module from typing import Callable def load_handler(handler_id: str) -> Callable: *module_path_elements, object_name = handler_id.split(".") module = import_module(".".join(module_path_elements)) return getattr(module, object_name)
Clazz.declarePackage ("javajs.api"); c$ = Clazz.declareType (javajs.api, "Interface"); c$.getInterface = Clazz.defineMethod (c$, "getInterface", function (name) { try { var x = Clazz._4Name (name); return (x == null ? null : x.newInstance ()); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { System.out.println ("Interface.java Error creating instance for " + name + ": \n" + e); return null; } else { throw e; } } }, "~S");
'use strict'; // Declare app level module which depends on views, and components angular.module('carrefourApp', [ 'ngRoute', 'myApp.login' ]). config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) { $locationProvider.hashPrefix('!'); $routeProvider.otherwise({ redirectTo: '/login' }); }]);
/*! jQuery Fancytree Plugin - 2.34.0 - 2019-12-26T14:16:19Z * https://github.com/mar10/fancytree * Copyright (c) 2019 Martin Wendt; Licensed MIT */ /*! jQuery UI - v1.12.1 - 2018-05-20 * http://jqueryui.com * Includes: widget.js, position.js, keycode.js, scroll-parent.js, unique-id.js * Copyright jQuery Foundation and other contributors; Licensed MIT */ /* NOTE: Original jQuery UI wrapper was replaced with a simple IIFE. See README-Fancytree.md */ (function( $ ) { $.ui = $.ui || {}; var version = $.ui.version = "1.12.1"; /*! * jQuery UI Widget 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: Widget //>>group: Core //>>description: Provides a factory for creating stateful widgets with a common API. //>>docs: http://api.jqueryui.com/jQuery.widget/ //>>demos: http://jqueryui.com/widget/ var widgetUuid = 0; var widgetSlice = Array.prototype.slice; $.cleanData = ( function( orig ) { return function( elems ) { var events, elem, i; for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) { try { // Only trigger remove when necessary to save time events = $._data( elem, "events" ); if ( events && events.remove ) { $( elem ).triggerHandler( "remove" ); } // Http://bugs.jquery.com/ticket/8235 } catch ( e ) {} } orig( elems ); }; } )( $.cleanData ); $.widget = function( name, base, prototype ) { var existingConstructor, constructor, basePrototype; // ProxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) var proxiedPrototype = {}; var namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; var fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } if ( $.isArray( prototype ) ) { prototype = $.extend.apply( null, [ {} ].concat( prototype ) ); } // Create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // Allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // Allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // Extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // Copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // Track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] } ); basePrototype = new base(); // We need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = ( function() { function _super() { return base.prototype[ prop ].apply( this, arguments ); } function _superApply( args ) { return base.prototype[ prop ].apply( this, args ); } return function() { var __super = this._super; var __superApply = this._superApply; var returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; } )(); } ); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName } ); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // Redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); } ); // Remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = widgetSlice.call( arguments, 1 ); var inputIndex = 0; var inputLength = input.length; var key; var value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string"; var args = widgetSlice.call( arguments, 1 ); var returnValue = this; if ( isMethodCall ) { // If this is an empty collection, we need to have the instance method // return undefined instead of the jQuery instance if ( !this.length && options === "instance" ) { returnValue = undefined; } else { this.each( function() { var methodValue; var instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } } ); } } else { // Allow multiple hashes to be passed on init if ( args.length ) { options = $.widget.extend.apply( null, [ options ].concat( args ) ); } this.each( function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} ); if ( instance._init ) { instance._init(); } } else { $.data( this, fullName, new object( options, this ) ); } } ); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { classes: {}, disabled: false, // Callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = widgetUuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.bindings = $(); this.hoverable = $(); this.focusable = $(); this.classesElementLookup = {}; if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } } ); this.document = $( element.style ? // Element within the document element.ownerDocument : // Element is window or document element.document || element ); this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow ); } this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this._create(); if ( this.options.disabled ) { this._setOptionDisabled( this.options.disabled ); } this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: function() { return {}; }, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { var that = this; this._destroy(); $.each( this.classesElementLookup, function( key, value ) { that._removeClass( value, key ); } ); // We can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .off( this.eventNamespace ) .removeData( this.widgetFullName ); this.widget() .off( this.eventNamespace ) .removeAttr( "aria-disabled" ); // Clean up events and states this.bindings.off( this.eventNamespace ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key; var parts; var curOption; var i; if ( arguments.length === 0 ) { // Don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( arguments.length === 1 ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( arguments.length === 1 ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { if ( key === "classes" ) { this._setOptionClasses( value ); } this.options[ key ] = value; if ( key === "disabled" ) { this._setOptionDisabled( value ); } return this; }, _setOptionClasses: function( value ) { var classKey, elements, currentElements; for ( classKey in value ) { currentElements = this.classesElementLookup[ classKey ]; if ( value[ classKey ] === this.options.classes[ classKey ] || !currentElements || !currentElements.length ) { continue; } // We are doing this to create a new jQuery object because the _removeClass() call // on the next line is going to destroy the reference to the current elements being // tracked. We need to save a copy of this collection so that we can add the new classes // below. elements = $( currentElements.get() ); this._removeClass( currentElements, classKey ); // We don't use _addClass() here, because that uses this.options.classes // for generating the string of classes. We want to use the value passed in from // _setOption(), this is the new value of the classes option which was passed to // _setOption(). We pass this value directly to _classes(). elements.addClass( this._classes( { element: elements, keys: classKey, classes: value, add: true } ) ); } }, _setOptionDisabled: function( value ) { this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value ); // If the widget is becoming disabled, then nothing is interactive if ( value ) { this._removeClass( this.hoverable, null, "ui-state-hover" ); this._removeClass( this.focusable, null, "ui-state-focus" ); } }, enable: function() { return this._setOptions( { disabled: false } ); }, disable: function() { return this._setOptions( { disabled: true } ); }, _classes: function( options ) { var full = []; var that = this; options = $.extend( { element: this.element, classes: this.options.classes || {} }, options ); function processClassString( classes, checkOption ) { var current, i; for ( i = 0; i < classes.length; i++ ) { current = that.classesElementLookup[ classes[ i ] ] || $(); if ( options.add ) { current = $( $.unique( current.get().concat( options.element.get() ) ) ); } else { current = $( current.not( options.element ).get() ); } that.classesElementLookup[ classes[ i ] ] = current; full.push( classes[ i ] ); if ( checkOption && options.classes[ classes[ i ] ] ) { full.push( options.classes[ classes[ i ] ] ); } } } this._on( options.element, { "remove": "_untrackClassesElement" } ); if ( options.keys ) { processClassString( options.keys.match( /\S+/g ) || [], true ); } if ( options.extra ) { processClassString( options.extra.match( /\S+/g ) || [] ); } return full.join( " " ); }, _untrackClassesElement: function( event ) { var that = this; $.each( that.classesElementLookup, function( key, value ) { if ( $.inArray( event.target, value ) !== -1 ) { that.classesElementLookup[ key ] = $( value.not( event.target ).get() ); } } ); }, _removeClass: function( element, keys, extra ) { return this._toggleClass( element, keys, extra, false ); }, _addClass: function( element, keys, extra ) { return this._toggleClass( element, keys, extra, true ); }, _toggleClass: function( element, keys, extra, add ) { add = ( typeof add === "boolean" ) ? add : extra; var shift = ( typeof element === "string" || element === null ), options = { extra: shift ? keys : extra, keys: shift ? element : keys, element: shift ? this.element : element, add: add }; options.element.toggleClass( this._classes( options ), add ); return this; }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement; var instance = this; // No suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // No element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // Allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // Copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^([\w:-]*)\s*(.*)$/ ); var eventName = match[ 1 ] + instance.eventNamespace; var selector = match[ 2 ]; if ( selector ) { delegateElement.on( eventName, selector, handlerProxy ); } else { element.on( eventName, handlerProxy ); } } ); }, _off: function( element, eventName ) { eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.off( eventName ).off( eventName ); // Clear the stack to avoid memory leaks (#10056) this.bindings = $( this.bindings.not( element ).get() ); this.focusable = $( this.focusable.not( element ).get() ); this.hoverable = $( this.hoverable.not( element ).get() ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { this._addClass( $( event.currentTarget ), null, "ui-state-hover" ); }, mouseleave: function( event ) { this._removeClass( $( event.currentTarget ), null, "ui-state-hover" ); } } ); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { this._addClass( $( event.currentTarget ), null, "ui-state-focus" ); }, focusout: function( event ) { this._removeClass( $( event.currentTarget ), null, "ui-state-focus" ); } } ); }, _trigger: function( type, event, data ) { var prop, orig; var callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // The original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // Copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions; var effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue( function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); } ); } }; } ); var widget = $.widget; /*! * jQuery UI Position 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/position/ */ //>>label: Position //>>group: Core //>>description: Positions elements relative to other elements. //>>docs: http://api.jqueryui.com/position/ //>>demos: http://jqueryui.com/position/ ( function() { var cachedScrollbarWidth, max = Math.max, abs = Math.abs, rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, roffset = /[\+\-]\d+(\.[\d]+)?%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } function getDimensions( elem ) { var raw = elem[ 0 ]; if ( raw.nodeType === 9 ) { return { width: elem.width(), height: elem.height(), offset: { top: 0, left: 0 } }; } if ( $.isWindow( raw ) ) { return { width: elem.width(), height: elem.height(), offset: { top: elem.scrollTop(), left: elem.scrollLeft() } }; } if ( raw.preventDefault ) { return { width: 0, height: 0, offset: { top: raw.pageY, left: raw.pageX } }; } return { width: elem.outerWidth(), height: elem.outerHeight(), offset: elem.offset() }; } $.position = { scrollbarWidth: function() { if ( cachedScrollbarWidth !== undefined ) { return cachedScrollbarWidth; } var w1, w2, div = $( "<div " + "style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'>" + "<div style='height:100px;width:auto;'></div></div>" ), innerDiv = div.children()[ 0 ]; $( "body" ).append( div ); w1 = innerDiv.offsetWidth; div.css( "overflow", "scroll" ); w2 = innerDiv.offsetWidth; if ( w1 === w2 ) { w2 = div[ 0 ].clientWidth; } div.remove(); return ( cachedScrollbarWidth = w1 - w2 ); }, getScrollInfo: function( within ) { var overflowX = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-x" ), overflowY = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-y" ), hasOverflowX = overflowX === "scroll" || ( overflowX === "auto" && within.width < within.element[ 0 ].scrollWidth ), hasOverflowY = overflowY === "scroll" || ( overflowY === "auto" && within.height < within.element[ 0 ].scrollHeight ); return { width: hasOverflowY ? $.position.scrollbarWidth() : 0, height: hasOverflowX ? $.position.scrollbarWidth() : 0 }; }, getWithinInfo: function( element ) { var withinElement = $( element || window ), isWindow = $.isWindow( withinElement[ 0 ] ), isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9, hasOffset = !isWindow && !isDocument; return { element: withinElement, isWindow: isWindow, isDocument: isDocument, offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), width: withinElement.outerWidth(), height: withinElement.outerHeight() }; } }; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // Make a copy, we don't want to modify arguments options = $.extend( {}, options ); var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), collision = ( options.collision || "flip" ).split( " " ), offsets = {}; dimensions = getDimensions( target ); if ( target[ 0 ].preventDefault ) { // Force left top to allow flipping options.at = "left top"; } targetWidth = dimensions.width; targetHeight = dimensions.height; targetOffset = dimensions.offset; // Clone to reuse original targetOffset later basePosition = $.extend( {}, targetOffset ); // Force my and at to have valid horizontal and vertical positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[ this ] || "" ).split( " " ), horizontalOffset, verticalOffset; if ( pos.length === 1 ) { pos = rhorizontal.test( pos[ 0 ] ) ? pos.concat( [ "center" ] ) : rvertical.test( pos[ 0 ] ) ? [ "center" ].concat( pos ) : [ "center", "center" ]; } pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; // Calculate offsets horizontalOffset = roffset.exec( pos[ 0 ] ); verticalOffset = roffset.exec( pos[ 1 ] ); offsets[ this ] = [ horizontalOffset ? horizontalOffset[ 0 ] : 0, verticalOffset ? verticalOffset[ 0 ] : 0 ]; // Reduce to just the positions without the offsets options[ this ] = [ rposition.exec( pos[ 0 ] )[ 0 ], rposition.exec( pos[ 1 ] )[ 0 ] ]; } ); // Normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } if ( options.at[ 0 ] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[ 0 ] === "center" ) { basePosition.left += targetWidth / 2; } if ( options.at[ 1 ] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[ 1 ] === "center" ) { basePosition.top += targetHeight / 2; } atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); basePosition.left += atOffset[ 0 ]; basePosition.top += atOffset[ 1 ]; return this.each( function() { var collisionPosition, using, elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseCss( this, "marginLeft" ), marginTop = parseCss( this, "marginTop" ), collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, position = $.extend( {}, basePosition ), myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); if ( options.my[ 0 ] === "right" ) { position.left -= elemWidth; } else if ( options.my[ 0 ] === "center" ) { position.left -= elemWidth / 2; } if ( options.my[ 1 ] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[ 1 ] === "center" ) { position.top -= elemHeight / 2; } position.left += myOffset[ 0 ]; position.top += myOffset[ 1 ]; collisionPosition = { marginLeft: marginLeft, marginTop: marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[ i ] ] ) { $.ui.position[ collision[ i ] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], my: options.my, at: options.at, within: within, elem: elem } ); } } ); if ( options.using ) { // Adds feedback as second argument to using callback, if present using = function( props ) { var left = targetOffset.left - position.left, right = left + targetWidth - elemWidth, top = targetOffset.top - position.top, bottom = top + targetHeight - elemHeight, feedback = { target: { element: target, left: targetOffset.left, top: targetOffset.top, width: targetWidth, height: targetHeight }, element: { element: elem, left: position.left, top: position.top, width: elemWidth, height: elemHeight }, horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" }; if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { feedback.horizontal = "center"; } if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { feedback.vertical = "middle"; } if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { feedback.important = "horizontal"; } else { feedback.important = "vertical"; } options.using.call( this, props, feedback ); }; } elem.offset( $.extend( position, { using: using } ) ); } ); }; $.ui.position = { fit: { left: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, outerWidth = within.width, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = withinOffset - collisionPosLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, newOverRight; // Element is wider than within if ( data.collisionWidth > outerWidth ) { // Element is initially over the left side of within if ( overLeft > 0 && overRight <= 0 ) { newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; position.left += overLeft - newOverRight; // Element is initially over right side of within } else if ( overRight > 0 && overLeft <= 0 ) { position.left = withinOffset; // Element is initially over both left and right sides of within } else { if ( overLeft > overRight ) { position.left = withinOffset + outerWidth - data.collisionWidth; } else { position.left = withinOffset; } } // Too far left -> align with left edge } else if ( overLeft > 0 ) { position.left += overLeft; // Too far right -> align with right edge } else if ( overRight > 0 ) { position.left -= overRight; // Adjust based on position and margin } else { position.left = max( position.left - collisionPosLeft, position.left ); } }, top: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollTop : within.offset.top, outerHeight = data.within.height, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = withinOffset - collisionPosTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, newOverBottom; // Element is taller than within if ( data.collisionHeight > outerHeight ) { // Element is initially over the top of within if ( overTop > 0 && overBottom <= 0 ) { newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; position.top += overTop - newOverBottom; // Element is initially over bottom of within } else if ( overBottom > 0 && overTop <= 0 ) { position.top = withinOffset; // Element is initially over both top and bottom of within } else { if ( overTop > overBottom ) { position.top = withinOffset + outerHeight - data.collisionHeight; } else { position.top = withinOffset; } } // Too far up -> align with top } else if ( overTop > 0 ) { position.top += overTop; // Too far down -> align with bottom edge } else if ( overBottom > 0 ) { position.top -= overBottom; // Adjust based on position and margin } else { position.top = max( position.top - collisionPosTop, position.top ); } } }, flip: { left: function( position, data ) { var within = data.within, withinOffset = within.offset.left + within.scrollLeft, outerWidth = within.width, offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = collisionPosLeft - offsetLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : data.at[ 0 ] === "right" ? -data.targetWidth : 0, offset = -2 * data.offset[ 0 ], newOverRight, newOverLeft; if ( overLeft < 0 ) { newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { position.left += myOffset + atOffset + offset; } } else if ( overRight > 0 ) { newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { position.left += myOffset + atOffset + offset; } } }, top: function( position, data ) { var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[ 1 ] === "top", myOffset = top ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : data.at[ 1 ] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[ 1 ], newOverTop, newOverBottom; if ( overTop < 0 ) { newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) { position.top += myOffset + atOffset + offset; } } else if ( overBottom > 0 ) { newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) { position.top += myOffset + atOffset + offset; } } } }, flipfit: { left: function() { $.ui.position.flip.left.apply( this, arguments ); $.ui.position.fit.left.apply( this, arguments ); }, top: function() { $.ui.position.flip.top.apply( this, arguments ); $.ui.position.fit.top.apply( this, arguments ); } } }; } )(); var position = $.ui.position; /*! * jQuery UI Keycode 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: Keycode //>>group: Core //>>description: Provide keycodes as keynames //>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/ var keycode = $.ui.keyCode = { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 }; /*! * jQuery UI Scroll Parent 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: scrollParent //>>group: Core //>>description: Get the closest ancestor element that is scrollable. //>>docs: http://api.jqueryui.com/scrollParent/ var scrollParent = $.fn.scrollParent = function( includeHidden ) { var position = this.css( "position" ), excludeStaticParent = position === "absolute", overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/, scrollParent = this.parents().filter( function() { var parent = $( this ); if ( excludeStaticParent && parent.css( "position" ) === "static" ) { return false; } return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) ); } ).eq( 0 ); return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }; /*! * jQuery UI Unique ID 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: uniqueId //>>group: Core //>>description: Functions to generate and remove uniqueId's //>>docs: http://api.jqueryui.com/uniqueId/ var uniqueId = $.fn.extend( { uniqueId: ( function() { var uuid = 0; return function() { return this.each( function() { if ( !this.id ) { this.id = "ui-id-" + ( ++uuid ); } } ); }; } )(), removeUniqueId: function() { return this.each( function() { if ( /^ui-id-\d+$/.test( this.id ) ) { $( this ).removeAttr( "id" ); } } ); } } ); // NOTE: Original jQuery UI wrapper was replaced. See README-Fancytree.md // })); })(jQuery); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }(function( $ ) { /*! Fancytree Core *//*! * jquery.fancytree.js * Tree view control with support for lazy loading and much more. * https://github.com/mar10/fancytree/ * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ /** Core Fancytree module. */ // UMD wrapper for the Fancytree core module (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery", "./jquery.fancytree.ui-deps"], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree.ui-deps"); module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { "use strict"; // prevent duplicate loading if ($.ui && $.ui.fancytree) { $.ui.fancytree.warn("Fancytree: ignored duplicate include"); return; } /****************************************************************************** * Private functions and variables */ var i, attr, FT = null, // initialized below TEST_IMG = new RegExp(/\.|\//), // strings are considered image urls if they contain '.' or '/' REX_HTML = /[&<>"'/]/g, // Escape those characters REX_TOOLTIP = /[<>"'/]/g, // Don't escape `&` in tooltips RECURSIVE_REQUEST_ERROR = "$recursive_request", // CLIPBOARD = null, ENTITY_MAP = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;", "/": "&#x2F;", }, IGNORE_KEYCODES = { 16: true, 17: true, 18: true }, SPECIAL_KEYCODES = { 8: "backspace", 9: "tab", 10: "return", 13: "return", // 16: null, 17: null, 18: null, // ignore shift, ctrl, alt 19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 59: ";", 61: "=", // 91: null, 93: null, // ignore left and right meta 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111: "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", }, MODIFIERS = { 16: "shift", 17: "ctrl", 18: "alt", 91: "meta", 93: "meta", }, MOUSE_BUTTONS = { 0: "", 1: "left", 2: "middle", 3: "right" }, // Boolean attributes that can be set with equivalent class names in the LI tags // Note: v2.23: checkbox and hideCheckbox are *not* in this list CLASS_ATTRS = "active expanded focus folder lazy radiogroup selected unselectable unselectableIgnore".split( " " ), CLASS_ATTR_MAP = {}, // Top-level Fancytree attributes, that can be set by dict TREE_ATTRS = "columns types".split(" "), // TREE_ATTR_MAP = {}, // Top-level FancytreeNode attributes, that can be set by dict NODE_ATTRS = "checkbox expanded extraClasses folder icon iconTooltip key lazy partsel radiogroup refKey selected statusNodeType title tooltip type unselectable unselectableIgnore unselectableStatus".split( " " ), NODE_ATTR_MAP = {}, // Mapping of lowercase -> real name (because HTML5 data-... attribute only supports lowercase) NODE_ATTR_LOWERCASE_MAP = {}, // Attribute names that should NOT be added to node.data NONE_NODE_DATA_MAP = { active: true, children: true, data: true, focus: true, }; for (i = 0; i < CLASS_ATTRS.length; i++) { CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true; } for (i = 0; i < NODE_ATTRS.length; i++) { attr = NODE_ATTRS[i]; NODE_ATTR_MAP[attr] = true; if (attr !== attr.toLowerCase()) { NODE_ATTR_LOWERCASE_MAP[attr.toLowerCase()] = attr; } } // for(i=0; i<TREE_ATTRS.length; i++) { // TREE_ATTR_MAP[TREE_ATTRS[i]] = true; // } function _assert(cond, msg) { // TODO: see qunit.js extractStacktrace() if (!cond) { msg = msg ? ": " + msg : ""; // consoleApply("assert", [!!cond, msg]); $.error("Fancytree assertion failed" + msg); } } _assert($.ui, "Fancytree requires jQuery UI (http://jqueryui.com)"); function consoleApply(method, args) { var i, s, fn = window.console ? window.console[method] : null; if (fn) { try { fn.apply(window.console, args); } catch (e) { // IE 8? s = ""; for (i = 0; i < args.length; i++) { s += args[i]; } fn(s); } } } /* support: IE8 Polyfil for Date.now() */ if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } /*Return true if x is a FancytreeNode.*/ function _isNode(x) { return !!(x.tree && x.statusNodeType !== undefined); } /** Return true if dotted version string is equal or higher than requested version. * * See http://jsfiddle.net/mar10/FjSAN/ */ function isVersionAtLeast(dottedVersion, major, minor, patch) { var i, v, t, verParts = $.map($.trim(dottedVersion).split("."), function(e) { return parseInt(e, 10); }), testParts = $.map( Array.prototype.slice.call(arguments, 1), function(e) { return parseInt(e, 10); } ); for (i = 0; i < testParts.length; i++) { v = verParts[i] || 0; t = testParts[i] || 0; if (v !== t) { return v > t; } } return true; } /** * Deep-merge a list of objects (but replace array-type options). * * jQuery's $.extend(true, ...) method does a deep merge, that also merges Arrays. * This variant is used to merge extension defaults with user options, and should * merge objects, but override arrays (for example the `triggerStart: [...]` option * of ext-edit). Also `null` values are copied over and not skipped. * * See issue #876 * * Example: * _simpleDeepMerge({}, o1, o2); */ function _simpleDeepMerge() { var options, name, src, copy, clone, target = arguments[0] || {}, i = 1, length = arguments.length; // Handle case when target is a string or something (possible in deep copy) if (typeof target !== "object" && !$.isFunction(target)) { target = {}; } if (i === length) { throw Error("need at least two args"); } for (; i < length; i++) { // Only deal with non-null/undefined values if ((options = arguments[i]) != null) { // Extend the base object for (name in options) { if (options.hasOwnProperty(name)) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging plain objects // (NOTE: unlike $.extend, we don't merge arrays, but replace them) if (copy && $.isPlainObject(copy)) { clone = src && $.isPlainObject(src) ? src : {}; // Never move original objects, clone them target[name] = _simpleDeepMerge(clone, copy); // Don't bring in undefined values } else if (copy !== undefined) { target[name] = copy; } } } } } // Return the modified object return target; } /** Return a wrapper that calls sub.methodName() and exposes * this : tree * this._local : tree.ext.EXTNAME * this._super : base.methodName.call() * this._superApply : base.methodName.apply() */ function _makeVirtualFunction(methodName, tree, base, extension, extName) { // $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName); // if(rexTestSuper && !rexTestSuper.test(func)){ // // extension.methodName() doesn't call _super(), so no wrapper required // return func; // } // Use an immediate function as closure var proxy = (function() { var prevFunc = tree[methodName], // org. tree method or prev. proxy baseFunc = extension[methodName], // _local = tree.ext[extName], _super = function() { return prevFunc.apply(tree, arguments); }, _superApply = function(args) { return prevFunc.apply(tree, args); }; // Return the wrapper function return function() { var prevLocal = tree._local, prevSuper = tree._super, prevSuperApply = tree._superApply; try { tree._local = _local; tree._super = _super; tree._superApply = _superApply; return baseFunc.apply(tree, arguments); } finally { tree._local = prevLocal; tree._super = prevSuper; tree._superApply = prevSuperApply; } }; })(); // end of Immediate Function return proxy; } /** * Subclass `base` by creating proxy functions */ function _subclassObject(tree, base, extension, extName) { // $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName); for (var attrName in extension) { if (typeof extension[attrName] === "function") { if (typeof tree[attrName] === "function") { // override existing method tree[attrName] = _makeVirtualFunction( attrName, tree, base, extension, extName ); } else if (attrName.charAt(0) === "_") { // Create private methods in tree.ext.EXTENSION namespace tree.ext[extName][attrName] = _makeVirtualFunction( attrName, tree, base, extension, extName ); } else { $.error( "Could not override tree." + attrName + ". Use prefix '_' to create tree." + extName + "._" + attrName ); } } else { // Create member variables in tree.ext.EXTENSION namespace if (attrName !== "options") { tree.ext[extName][attrName] = extension[attrName]; } } } } function _getResolvedPromise(context, argArray) { if (context === undefined) { return $.Deferred(function() { this.resolve(); }).promise(); } return $.Deferred(function() { this.resolveWith(context, argArray); }).promise(); } function _getRejectedPromise(context, argArray) { if (context === undefined) { return $.Deferred(function() { this.reject(); }).promise(); } return $.Deferred(function() { this.rejectWith(context, argArray); }).promise(); } function _makeResolveFunc(deferred, context) { return function() { deferred.resolveWith(context); }; } function _getElementDataAsDict($el) { // Evaluate 'data-NAME' attributes with special treatment for 'data-json'. var d = $.extend({}, $el.data()), json = d.json; delete d.fancytree; // added to container by widget factory (old jQuery UI) delete d.uiFancytree; // added to container by widget factory if (json) { delete d.json; // <li data-json='...'> is already returned as object (http://api.jquery.com/data/#data-html5) d = $.extend(d, json); } return d; } function _escapeTooltip(s) { return ("" + s).replace(REX_TOOLTIP, function(s) { return ENTITY_MAP[s]; }); } // TODO: use currying function _makeNodeTitleMatcher(s) { s = s.toLowerCase(); return function(node) { return node.title.toLowerCase().indexOf(s) >= 0; }; } function _makeNodeTitleStartMatcher(s) { var reMatch = new RegExp("^" + s, "i"); return function(node) { return reMatch.test(node.title); }; } /****************************************************************************** * FancytreeNode */ /** * Creates a new FancytreeNode * * @class FancytreeNode * @classdesc A FancytreeNode represents the hierarchical data model and operations. * * @param {FancytreeNode} parent * @param {NodeData} obj * * @property {Fancytree} tree The tree instance * @property {FancytreeNode} parent The parent node * @property {string} key Node id (must be unique inside the tree) * @property {string} title Display name (may contain HTML) * @property {object} data Contains all extra data that was passed on node creation * @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br> * For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array * to define a node that has no children. * @property {boolean} expanded Use isExpanded(), setExpanded() to access this property. * @property {string} extraClasses Additional CSS classes, added to the node's `<span>`.<br> * Note: use `node.add/remove/toggleClass()` to modify. * @property {boolean} folder Folder nodes have different default icons and click behavior.<br> * Note: Also non-folders may have children. * @property {string} statusNodeType null for standard nodes. Otherwise type of special system node: 'error', 'loading', 'nodata', or 'paging'. * @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion. * @property {boolean} selected Use isSelected(), setSelected() to access this property. * @property {string} tooltip Alternative description used as hover popup * @property {string} iconTooltip Description used as hover popup for icon. @since 2.27 * @property {string} type Node type, used with tree.types map. @since 2.27 */ function FancytreeNode(parent, obj) { var i, l, name, cl; this.parent = parent; this.tree = parent.tree; this.ul = null; this.li = null; // <li id='key' ftnode=this> tag this.statusNodeType = null; // if this is a temp. node to display the status of its parent this._isLoading = false; // if this node itself is loading this._error = null; // {message: '...'} if a load error occurred this.data = {}; // TODO: merge this code with node.toDict() // copy attributes from obj object for (i = 0, l = NODE_ATTRS.length; i < l; i++) { name = NODE_ATTRS[i]; this[name] = obj[name]; } // unselectableIgnore and unselectableStatus imply unselectable if ( this.unselectableIgnore != null || this.unselectableStatus != null ) { this.unselectable = true; } if (obj.hideCheckbox) { $.error( "'hideCheckbox' node option was removed in v2.23.0: use 'checkbox: false'" ); } // node.data += obj.data if (obj.data) { $.extend(this.data, obj.data); } // Copy all other attributes to this.data.NAME for (name in obj) { if ( !NODE_ATTR_MAP[name] && !$.isFunction(obj[name]) && !NONE_NODE_DATA_MAP[name] ) { // node.data.NAME = obj.NAME this.data[name] = obj[name]; } } // Fix missing key if (this.key == null) { // test for null OR undefined if (this.tree.options.defaultKey) { this.key = this.tree.options.defaultKey(this); _assert(this.key, "defaultKey() must return a unique key"); } else { this.key = "_" + FT._nextNodeKey++; } } else { this.key = "" + this.key; // Convert to string (#217) } // Fix tree.activeNode // TODO: not elegant: we use obj.active as marker to set tree.activeNode // when loading from a dictionary. if (obj.active) { _assert( this.tree.activeNode === null, "only one active node allowed" ); this.tree.activeNode = this; } if (obj.selected) { // #186 this.tree.lastSelectedNode = this; } // TODO: handle obj.focus = true // Create child nodes cl = obj.children; if (cl) { if (cl.length) { this._setChildren(cl); } else { // if an empty array was passed for a lazy node, keep it, in order to mark it 'loaded' this.children = this.lazy ? [] : null; } } else { this.children = null; } // Add to key/ref map (except for root node) // if( parent ) { this.tree._callHook("treeRegisterNode", this.tree, true, this); // } } FancytreeNode.prototype = /** @lends FancytreeNode# */ { /* Return the direct child FancytreeNode with a given key, index. */ _findDirectChild: function(ptr) { var i, l, cl = this.children; if (cl) { if (typeof ptr === "string") { for (i = 0, l = cl.length; i < l; i++) { if (cl[i].key === ptr) { return cl[i]; } } } else if (typeof ptr === "number") { return this.children[ptr]; } else if (ptr.parent === this) { return ptr; } } return null; }, // TODO: activate() // TODO: activateSilently() /* Internal helper called in recursive addChildren sequence.*/ _setChildren: function(children) { _assert( children && (!this.children || this.children.length === 0), "only init supported" ); this.children = []; for (var i = 0, l = children.length; i < l; i++) { this.children.push(new FancytreeNode(this, children[i])); } this.tree._callHook( "treeStructureChanged", this.tree, "setChildren" ); }, /** * Append (or insert) a list of child nodes. * * @param {NodeData[]} children array of child node definitions (also single child accepted) * @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such). * If omitted, the new children are appended. * @returns {FancytreeNode} first child added * * @see FancytreeNode#applyPatch */ addChildren: function(children, insertBefore) { var i, l, pos, origFirstChild = this.getFirstChild(), origLastChild = this.getLastChild(), firstNode = null, nodeList = []; if ($.isPlainObject(children)) { children = [children]; } if (!this.children) { this.children = []; } for (i = 0, l = children.length; i < l; i++) { nodeList.push(new FancytreeNode(this, children[i])); } firstNode = nodeList[0]; if (insertBefore == null) { this.children = this.children.concat(nodeList); } else { // Returns null if insertBefore is not a direct child: insertBefore = this._findDirectChild(insertBefore); pos = $.inArray(insertBefore, this.children); _assert(pos >= 0, "insertBefore must be an existing child"); // insert nodeList after children[pos] this.children.splice.apply( this.children, [pos, 0].concat(nodeList) ); } if (origFirstChild && !insertBefore) { // #708: Fast path -- don't render every child of root, just the new ones! // #723, #729: but only if it's appended to an existing child list for (i = 0, l = nodeList.length; i < l; i++) { nodeList[i].render(); // New nodes were never rendered before } // Adjust classes where status may have changed // Has a first child if (origFirstChild !== this.getFirstChild()) { // Different first child -- recompute classes origFirstChild.renderStatus(); } if (origLastChild !== this.getLastChild()) { // Different last child -- recompute classes origLastChild.renderStatus(); } } else if (!this.parent || this.parent.ul || this.tr) { // render if the parent was rendered (or this is a root node) this.render(); } if (this.tree.options.selectMode === 3) { this.fixSelection3FromEndNodes(); } this.triggerModifyChild( "add", nodeList.length === 1 ? nodeList[0] : null ); return firstNode; }, /** * Add class to node's span tag and to .extraClasses. * * @param {string} className class name * * @since 2.17 */ addClass: function(className) { return this.toggleClass(className, true); }, /** * Append or prepend a node, or append a child node. * * This a convenience function that calls addChildren() * * @param {NodeData} node node definition * @param {string} [mode=child] 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child') * @returns {FancytreeNode} new node */ addNode: function(node, mode) { if (mode === undefined || mode === "over") { mode = "child"; } switch (mode) { case "after": return this.getParent().addChildren( node, this.getNextSibling() ); case "before": return this.getParent().addChildren(node, this); case "firstChild": // Insert before the first child if any var insertBefore = this.children ? this.children[0] : null; return this.addChildren(node, insertBefore); case "child": case "over": return this.addChildren(node); } _assert(false, "Invalid mode: " + mode); }, /**Add child status nodes that indicate 'More...', etc. * * This also maintains the node's `partload` property. * @param {boolean|object} node optional node definition. Pass `false` to remove all paging nodes. * @param {string} [mode='child'] 'child'|firstChild' * @since 2.15 */ addPagingNode: function(node, mode) { var i, n; mode = mode || "child"; if (node === false) { for (i = this.children.length - 1; i >= 0; i--) { n = this.children[i]; if (n.statusNodeType === "paging") { this.removeChild(n); } } this.partload = false; return; } node = $.extend( { title: this.tree.options.strings.moreData, statusNodeType: "paging", icon: false, }, node ); this.partload = true; return this.addNode(node, mode); }, /** * Append new node after this. * * This a convenience function that calls addNode(node, 'after') * * @param {NodeData} node node definition * @returns {FancytreeNode} new node */ appendSibling: function(node) { return this.addNode(node, "after"); }, /** * (experimental) Apply a modification (or navigation) operation. * * @param {string} cmd * @param {object} [opts] * @see Fancytree#applyCommand * @since 2.32 */ applyCommand: function(cmd, opts) { return this.tree.applyCommand(cmd, this, opts); }, /** * Modify existing child nodes. * * @param {NodePatch} patch * @returns {$.Promise} * @see FancytreeNode#addChildren */ applyPatch: function(patch) { // patch [key, null] means 'remove' if (patch === null) { this.remove(); return _getResolvedPromise(this); } // TODO: make sure that root node is not collapsed or modified // copy (most) attributes to node.ATTR or node.data.ATTR var name, promise, v, IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global for (name in patch) { if (patch.hasOwnProperty(name)) { v = patch[name]; if (!IGNORE_MAP[name] && !$.isFunction(v)) { if (NODE_ATTR_MAP[name]) { this[name] = v; } else { this.data[name] = v; } } } } // Remove and/or create children if (patch.hasOwnProperty("children")) { this.removeChildren(); if (patch.children) { // only if not null and not empty list // TODO: addChildren instead? this._setChildren(patch.children); } // TODO: how can we APPEND or INSERT child nodes? } if (this.isVisible()) { this.renderTitle(); this.renderStatus(); } // Expand collapse (final step, since this may be async) if (patch.hasOwnProperty("expanded")) { promise = this.setExpanded(patch.expanded); } else { promise = _getResolvedPromise(this); } return promise; }, /** Collapse all sibling nodes. * @returns {$.Promise} */ collapseSiblings: function() { return this.tree._callHook("nodeCollapseSiblings", this); }, /** Copy this node as sibling or child of `node`. * * @param {FancytreeNode} node source node * @param {string} [mode=child] 'before' | 'after' | 'child' * @param {Function} [map] callback function(NodeData) that could modify the new node * @returns {FancytreeNode} new */ copyTo: function(node, mode, map) { return node.addNode(this.toDict(true, map), mode); }, /** Count direct and indirect children. * * @param {boolean} [deep=true] pass 'false' to only count direct children * @returns {int} number of child nodes */ countChildren: function(deep) { var cl = this.children, i, l, n; if (!cl) { return 0; } n = cl.length; if (deep !== false) { for (i = 0, l = n; i < l; i++) { n += cl[i].countChildren(); } } return n; }, // TODO: deactivate() /** Write to browser console if debugLevel >= 4 (prepending node info) * * @param {*} msg string or object or array of such */ debug: function(msg) { if (this.tree.options.debugLevel >= 4) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("log", arguments); } }, /** Deprecated. * @deprecated since 2014-02-16. Use resetLazy() instead. */ discard: function() { this.warn( "FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead." ); return this.resetLazy(); }, /** Remove DOM elements for all descendents. May be called on .collapse event * to keep the DOM small. * @param {boolean} [includeSelf=false] */ discardMarkup: function(includeSelf) { var fn = includeSelf ? "nodeRemoveMarkup" : "nodeRemoveChildMarkup"; this.tree._callHook(fn, this); }, /** Write error to browser console if debugLevel >= 1 (prepending tree info) * * @param {*} msg string or object or array of such */ error: function(msg) { if (this.tree.options.debugLevel >= 1) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("error", arguments); } }, /**Find all nodes that match condition (excluding self). * * @param {string | function(node)} match title string to search for, or a * callback function that returns `true` if a node is matched. * @returns {FancytreeNode[]} array of nodes (may be empty) */ findAll: function(match) { match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match); var res = []; this.visit(function(n) { if (match(n)) { res.push(n); } }); return res; }, /**Find first node that matches condition (excluding self). * * @param {string | function(node)} match title string to search for, or a * callback function that returns `true` if a node is matched. * @returns {FancytreeNode} matching node or null * @see FancytreeNode#findAll */ findFirst: function(match) { match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match); var res = null; this.visit(function(n) { if (match(n)) { res = n; return false; } }); return res; }, /** Find a node relative to self. * * @param {number|string} where The keyCode that would normally trigger this move, * or a keyword ('down', 'first', 'last', 'left', 'parent', 'right', 'up'). * @returns {FancytreeNode} * @since v2.31 */ findRelatedNode: function(where, includeHidden) { return this.tree.findRelatedNode(this, where, includeHidden); }, /* Apply selection state (internal use only) */ _changeSelectStatusAttrs: function(state) { var changed = false, opts = this.tree.options, unselectable = FT.evalOption( "unselectable", this, this, opts, false ), unselectableStatus = FT.evalOption( "unselectableStatus", this, this, opts, undefined ); if (unselectable && unselectableStatus != null) { state = unselectableStatus; } switch (state) { case false: changed = this.selected || this.partsel; this.selected = false; this.partsel = false; break; case true: changed = !this.selected || !this.partsel; this.selected = true; this.partsel = true; break; case undefined: changed = this.selected || !this.partsel; this.selected = false; this.partsel = true; break; default: _assert(false, "invalid state: " + state); } // this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed); if (changed) { this.renderStatus(); } return changed; }, /** * Fix selection status, after this node was (de)selected in multi-hier mode. * This includes (de)selecting all children. */ fixSelection3AfterClick: function(callOpts) { var flag = this.isSelected(); // this.debug("fixSelection3AfterClick()"); this.visit(function(node) { node._changeSelectStatusAttrs(flag); if (node.radiogroup) { // #931: don't (de)select this branch return "skip"; } }); this.fixSelection3FromEndNodes(callOpts); }, /** * Fix selection status for multi-hier mode. * Only end-nodes are considered to update the descendants branch and parents. * Should be called after this node has loaded new children or after * children have been modified using the API. */ fixSelection3FromEndNodes: function(callOpts) { var opts = this.tree.options; // this.debug("fixSelection3FromEndNodes()"); _assert(opts.selectMode === 3, "expected selectMode 3"); // Visit all end nodes and adjust their parent's `selected` and `partsel` // attributes. Return selection state true, false, or undefined. function _walk(node) { var i, l, child, s, state, allSelected, someSelected, unselIgnore, unselState, children = node.children; if (children && children.length) { // check all children recursively allSelected = true; someSelected = false; for (i = 0, l = children.length; i < l; i++) { child = children[i]; // the selection state of a node is not relevant; we need the end-nodes s = _walk(child); // if( !child.unselectableIgnore ) { unselIgnore = FT.evalOption( "unselectableIgnore", child, child, opts, false ); if (!unselIgnore) { if (s !== false) { someSelected = true; } if (s !== true) { allSelected = false; } } } // eslint-disable-next-line no-nested-ternary state = allSelected ? true : someSelected ? undefined : false; } else { // This is an end-node: simply report the status unselState = FT.evalOption( "unselectableStatus", node, node, opts, undefined ); state = unselState == null ? !!node.selected : !!unselState; } // #939: Keep a `partsel` flag that was explicitly set on a lazy node if ( node.partsel && !node.selected && node.lazy && node.children == null ) { state = undefined; } node._changeSelectStatusAttrs(state); return state; } _walk(this); // Update parent's state this.visitParents(function(node) { var i, l, child, state, unselIgnore, unselState, children = node.children, allSelected = true, someSelected = false; for (i = 0, l = children.length; i < l; i++) { child = children[i]; unselIgnore = FT.evalOption( "unselectableIgnore", child, child, opts, false ); if (!unselIgnore) { unselState = FT.evalOption( "unselectableStatus", child, child, opts, undefined ); state = unselState == null ? !!child.selected : !!unselState; // When fixing the parents, we trust the sibling status (i.e. // we don't recurse) if (state || child.partsel) { someSelected = true; } if (!state) { allSelected = false; } } } // eslint-disable-next-line no-nested-ternary state = allSelected ? true : someSelected ? undefined : false; node._changeSelectStatusAttrs(state); }); }, // TODO: focus() /** * Update node data. If dict contains 'children', then also replace * the hole sub tree. * @param {NodeData} dict * * @see FancytreeNode#addChildren * @see FancytreeNode#applyPatch */ fromDict: function(dict) { // copy all other attributes to this.data.xxx for (var name in dict) { if (NODE_ATTR_MAP[name]) { // node.NAME = dict.NAME this[name] = dict[name]; } else if (name === "data") { // node.data += dict.data $.extend(this.data, dict.data); } else if ( !$.isFunction(dict[name]) && !NONE_NODE_DATA_MAP[name] ) { // node.data.NAME = dict.NAME this.data[name] = dict[name]; } } if (dict.children) { // recursively set children and render this.removeChildren(); this.addChildren(dict.children); } this.renderTitle(); /* var children = dict.children; if(children === undefined){ this.data = $.extend(this.data, dict); this.render(); return; } dict = $.extend({}, dict); dict.children = undefined; this.data = $.extend(this.data, dict); this.removeChildren(); this.addChild(children); */ }, /** Return the list of child nodes (undefined for unexpanded lazy nodes). * @returns {FancytreeNode[] | undefined} */ getChildren: function() { if (this.hasChildren() === undefined) { // TODO: only required for lazy nodes? return undefined; // Lazy node: unloaded, currently loading, or load error } return this.children; }, /** Return the first child node or null. * @returns {FancytreeNode | null} */ getFirstChild: function() { return this.children ? this.children[0] : null; }, /** Return the 0-based child index. * @returns {int} */ getIndex: function() { // return this.parent.children.indexOf(this); return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7 }, /** Return the hierarchical child index (1-based, e.g. '3.2.4'). * @param {string} [separator="."] * @param {int} [digits=1] * @returns {string} */ getIndexHier: function(separator, digits) { separator = separator || "."; var s, res = []; $.each(this.getParentList(false, true), function(i, o) { s = "" + (o.getIndex() + 1); if (digits) { // prepend leading zeroes s = ("0000000" + s).substr(-digits); } res.push(s); }); return res.join(separator); }, /** Return the parent keys separated by options.keyPathSeparator, e.g. "/id_1/id_17/id_32". * * (Unlike `node.getPath()`, this method prepends a "/" and inverts the first argument.) * * @see FancytreeNode#getPath * @param {boolean} [excludeSelf=false] * @returns {string} */ getKeyPath: function(excludeSelf) { var sep = this.tree.options.keyPathSeparator; return sep + this.getPath(!excludeSelf, "key", sep); }, /** Return the last child of this node or null. * @returns {FancytreeNode | null} */ getLastChild: function() { return this.children ? this.children[this.children.length - 1] : null; }, /** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... . * @returns {int} */ getLevel: function() { var level = 0, dtn = this.parent; while (dtn) { level++; dtn = dtn.parent; } return level; }, /** Return the successor node (under the same parent) or null. * @returns {FancytreeNode | null} */ getNextSibling: function() { // TODO: use indexOf, if available: (not in IE6) if (this.parent) { var i, l, ac = this.parent.children; for (i = 0, l = ac.length - 1; i < l; i++) { // up to length-2, so next(last) = null if (ac[i] === this) { return ac[i + 1]; } } } return null; }, /** Return the parent node (null for the system root node). * @returns {FancytreeNode | null} */ getParent: function() { // TODO: return null for top-level nodes? return this.parent; }, /** Return an array of all parent nodes (top-down). * @param {boolean} [includeRoot=false] Include the invisible system root node. * @param {boolean} [includeSelf=false] Include the node itself. * @returns {FancytreeNode[]} */ getParentList: function(includeRoot, includeSelf) { var l = [], dtn = includeSelf ? this : this.parent; while (dtn) { if (includeRoot || dtn.parent) { l.unshift(dtn); } dtn = dtn.parent; } return l; }, /** Return a string representing the hierachical node path, e.g. "a/b/c". * @param {boolean} [includeSelf=true] * @param {string | function} [part="title"] node property name or callback * @param {string} [separator="/"] * @returns {string} * @since v2.31 */ getPath: function(includeSelf, part, separator) { includeSelf = includeSelf !== false; part = part || "title"; separator = separator || "/"; var val, path = [], isFunc = $.isFunction(part); this.visitParents(function(n) { if (n.parent) { val = isFunc ? part(n) : n[part]; path.unshift(val); } }, includeSelf); return path.join(separator); }, /** Return the predecessor node (under the same parent) or null. * @returns {FancytreeNode | null} */ getPrevSibling: function() { if (this.parent) { var i, l, ac = this.parent.children; for (i = 1, l = ac.length; i < l; i++) { // start with 1, so prev(first) = null if (ac[i] === this) { return ac[i - 1]; } } } return null; }, /** * Return an array of selected descendant nodes. * @param {boolean} [stopOnParents=false] only return the topmost selected * node (useful with selectMode 3) * @returns {FancytreeNode[]} */ getSelectedNodes: function(stopOnParents) { var nodeList = []; this.visit(function(node) { if (node.selected) { nodeList.push(node); if (stopOnParents === true) { return "skip"; // stop processing this branch } } }); return nodeList; }, /** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded). * @returns {boolean | undefined} */ hasChildren: function() { if (this.lazy) { if (this.children == null) { // null or undefined: Not yet loaded return undefined; } else if (this.children.length === 0) { // Loaded, but response was empty return false; } else if ( this.children.length === 1 && this.children[0].isStatusNode() ) { // Currently loading or load error return undefined; } return true; } return !!(this.children && this.children.length); }, /** * Return true if node has `className` defined in .extraClasses. * * @param {string} className class name (separate multiple classes by space) * @returns {boolean} * * @since 2.32 */ hasClass: function(className) { return ( (" " + (this.extraClasses || "") + " ").indexOf( " " + className + " " ) >= 0 ); }, /** Return true if node has keyboard focus. * @returns {boolean} */ hasFocus: function() { return this.tree.hasFocus() && this.tree.focusNode === this; }, /** Write to browser console if debugLevel >= 3 (prepending node info) * * @param {*} msg string or object or array of such */ info: function(msg) { if (this.tree.options.debugLevel >= 3) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("info", arguments); } }, /** Return true if node is active (see also FancytreeNode#isSelected). * @returns {boolean} */ isActive: function() { return this.tree.activeNode === this; }, /** Return true if node is vertically below `otherNode`, i.e. rendered in a subsequent row. * @param {FancytreeNode} otherNode * @returns {boolean} * @since 2.28 */ isBelowOf: function(otherNode) { return this.getIndexHier(".", 5) > otherNode.getIndexHier(".", 5); }, /** Return true if node is a direct child of otherNode. * @param {FancytreeNode} otherNode * @returns {boolean} */ isChildOf: function(otherNode) { return this.parent && this.parent === otherNode; }, /** Return true, if node is a direct or indirect sub node of otherNode. * @param {FancytreeNode} otherNode * @returns {boolean} */ isDescendantOf: function(otherNode) { if (!otherNode || otherNode.tree !== this.tree) { return false; } var p = this.parent; while (p) { if (p === otherNode) { return true; } if (p === p.parent) { $.error("Recursive parent link: " + p); } p = p.parent; } return false; }, /** Return true if node is expanded. * @returns {boolean} */ isExpanded: function() { return !!this.expanded; }, /** Return true if node is the first node of its parent's children. * @returns {boolean} */ isFirstSibling: function() { var p = this.parent; return !p || p.children[0] === this; }, /** Return true if node is a folder, i.e. has the node.folder attribute set. * @returns {boolean} */ isFolder: function() { return !!this.folder; }, /** Return true if node is the last node of its parent's children. * @returns {boolean} */ isLastSibling: function() { var p = this.parent; return !p || p.children[p.children.length - 1] === this; }, /** Return true if node is lazy (even if data was already loaded) * @returns {boolean} */ isLazy: function() { return !!this.lazy; }, /** Return true if node is lazy and loaded. For non-lazy nodes always return true. * @returns {boolean} */ isLoaded: function() { return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node }, /** Return true if children are currently beeing loaded, i.e. a Ajax request is pending. * @returns {boolean} */ isLoading: function() { return !!this._isLoading; }, /* * @deprecated since v2.4.0: Use isRootNode() instead */ isRoot: function() { return this.isRootNode(); }, /** Return true if node is partially selected (tri-state). * @returns {boolean} * @since 2.23 */ isPartsel: function() { return !this.selected && !!this.partsel; }, /** (experimental) Return true if this is partially loaded. * @returns {boolean} * @since 2.15 */ isPartload: function() { return !!this.partload; }, /** Return true if this is the (invisible) system root node. * @returns {boolean} * @since 2.4 */ isRootNode: function() { return this.tree.rootNode === this; }, /** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive). * @returns {boolean} */ isSelected: function() { return !!this.selected; }, /** Return true if this node is a temporarily generated system node like * 'loading', 'paging', or 'error' (node.statusNodeType contains the type). * @returns {boolean} */ isStatusNode: function() { return !!this.statusNodeType; }, /** Return true if this node is a status node of type 'paging'. * @returns {boolean} * @since 2.15 */ isPagingNode: function() { return this.statusNodeType === "paging"; }, /** Return true if this a top level node, i.e. a direct child of the (invisible) system root node. * @returns {boolean} * @since 2.4 */ isTopLevel: function() { return this.tree.rootNode === this.parent; }, /** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false. * @returns {boolean} */ isUndefined: function() { return this.hasChildren() === undefined; // also checks if the only child is a status node }, /** Return true if all parent nodes are expanded. Note: this does not check * whether the node is scrolled into the visible part of the screen. * @returns {boolean} */ isVisible: function() { var i, l, n, hasFilter = this.tree.enableFilter, parents = this.getParentList(false, false); // TODO: check $(n.span).is(":visible") // i.e. return false for nodes (but not parents) that are hidden // by a filter if (hasFilter && !this.match && !this.subMatchCount) { // this.debug( "isVisible: HIDDEN (" + hasFilter + ", " + this.match + ", " + this.match + ")" ); return false; } for (i = 0, l = parents.length; i < l; i++) { n = parents[i]; if (!n.expanded) { // this.debug("isVisible: HIDDEN (parent collapsed)"); return false; } // if (hasFilter && !n.match && !n.subMatchCount) { // this.debug("isVisible: HIDDEN (" + hasFilter + ", " + this.match + ", " + this.match + ")"); // return false; // } } // this.debug("isVisible: VISIBLE"); return true; }, /** Deprecated. * @deprecated since 2014-02-16: use load() instead. */ lazyLoad: function(discard) { this.warn( "FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead." ); return this.load(discard); }, /** * Load all children of a lazy node if neccessary. The <i>expanded</i> state is maintained. * @param {boolean} [forceReload=false] Pass true to discard any existing nodes before. Otherwise this method does nothing if the node was already loaded. * @returns {$.Promise} */ load: function(forceReload) { var res, source, self = this, wasExpanded = this.isExpanded(); _assert(this.isLazy(), "load() requires a lazy node"); // _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" ); if (!forceReload && !this.isUndefined()) { return _getResolvedPromise(this); } if (this.isLoaded()) { this.resetLazy(); // also collapses } // This method is also called by setExpanded() and loadKeyPath(), so we // have to avoid recursion. source = this.tree._triggerNodeEvent("lazyLoad", this); if (source === false) { // #69 return _getResolvedPromise(this); } _assert( typeof source !== "boolean", "lazyLoad event must return source in data.result" ); res = this.tree._callHook("nodeLoadChildren", this, source); if (wasExpanded) { this.expanded = true; res.always(function() { self.render(); }); } else { res.always(function() { self.renderStatus(); // fix expander icon to 'loaded' }); } return res; }, /** Expand all parents and optionally scroll into visible area as neccessary. * Promise is resolved, when lazy loading and animations are done. * @param {object} [opts] passed to `setExpanded()`. * Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true} * @returns {$.Promise} */ makeVisible: function(opts) { var i, self = this, deferreds = [], dfd = new $.Deferred(), parents = this.getParentList(false, false), len = parents.length, effects = !(opts && opts.noAnimation === true), scroll = !(opts && opts.scrollIntoView === false); // Expand bottom-up, so only the top node is animated for (i = len - 1; i >= 0; i--) { // self.debug("pushexpand" + parents[i]); deferreds.push(parents[i].setExpanded(true, opts)); } $.when.apply($, deferreds).done(function() { // All expands have finished // self.debug("expand DONE", scroll); if (scroll) { self.scrollIntoView(effects).done(function() { // self.debug("scroll DONE"); dfd.resolve(); }); } else { dfd.resolve(); } }); return dfd.promise(); }, /** Move this node to targetNode. * @param {FancytreeNode} targetNode * @param {string} mode <pre> * 'child': append this node as last child of targetNode. * This is the default. To be compatble with the D'n'd * hitMode, we also accept 'over'. * 'firstChild': add this node as first child of targetNode. * 'before': add this node as sibling before targetNode. * 'after': add this node as sibling after targetNode.</pre> * @param {function} [map] optional callback(FancytreeNode) to allow modifcations */ moveTo: function(targetNode, mode, map) { if (mode === undefined || mode === "over") { mode = "child"; } else if (mode === "firstChild") { if (targetNode.children && targetNode.children.length) { mode = "before"; targetNode = targetNode.children[0]; } else { mode = "child"; } } var pos, tree = this.tree, prevParent = this.parent, targetParent = mode === "child" ? targetNode : targetNode.parent; if (this === targetNode) { return; } else if (!this.parent) { $.error("Cannot move system root"); } else if (targetParent.isDescendantOf(this)) { $.error("Cannot move a node to its own descendant"); } if (targetParent !== prevParent) { prevParent.triggerModifyChild("remove", this); } // Unlink this node from current parent if (this.parent.children.length === 1) { if (this.parent === targetParent) { return; // #258 } this.parent.children = this.parent.lazy ? [] : null; this.parent.expanded = false; } else { pos = $.inArray(this, this.parent.children); _assert(pos >= 0, "invalid source parent"); this.parent.children.splice(pos, 1); } // Remove from source DOM parent // if(this.parent.ul){ // this.parent.ul.removeChild(this.li); // } // Insert this node to target parent's child list this.parent = targetParent; if (targetParent.hasChildren()) { switch (mode) { case "child": // Append to existing target children targetParent.children.push(this); break; case "before": // Insert this node before target node pos = $.inArray(targetNode, targetParent.children); _assert(pos >= 0, "invalid target parent"); targetParent.children.splice(pos, 0, this); break; case "after": // Insert this node after target node pos = $.inArray(targetNode, targetParent.children); _assert(pos >= 0, "invalid target parent"); targetParent.children.splice(pos + 1, 0, this); break; default: $.error("Invalid mode " + mode); } } else { targetParent.children = [this]; } // Parent has no <ul> tag yet: // if( !targetParent.ul ) { // // This is the parent's first child: create UL tag // // (Hidden, because it will be // targetParent.ul = document.createElement("ul"); // targetParent.ul.style.display = "none"; // targetParent.li.appendChild(targetParent.ul); // } // // Issue 319: Add to target DOM parent (only if node was already rendered(expanded)) // if(this.li){ // targetParent.ul.appendChild(this.li); // } // Let caller modify the nodes if (map) { targetNode.visit(map, true); } if (targetParent === prevParent) { targetParent.triggerModifyChild("move", this); } else { // prevParent.triggerModifyChild("remove", this); targetParent.triggerModifyChild("add", this); } // Handle cross-tree moves if (tree !== targetNode.tree) { // Fix node.tree for all source nodes // _assert(false, "Cross-tree move is not yet implemented."); this.warn("Cross-tree moveTo is experimental!"); this.visit(function(n) { // TODO: fix selection state and activation, ... n.tree = targetNode.tree; }, true); } // A collaposed node won't re-render children, so we have to remove it manually // if( !targetParent.expanded ){ // prevParent.ul.removeChild(this.li); // } tree._callHook("treeStructureChanged", tree, "moveTo"); // Update HTML markup if (!prevParent.isDescendantOf(targetParent)) { prevParent.render(); } if ( !targetParent.isDescendantOf(prevParent) && targetParent !== prevParent ) { targetParent.render(); } // TODO: fix selection state // TODO: fix active state /* var tree = this.tree; var opts = tree.options; var pers = tree.persistence; // Always expand, if it's below minExpandLevel // tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel()); if ( opts.minExpandLevel >= ftnode.getLevel() ) { // tree.logDebug ("Force expand for %o", ftnode); this.bExpanded = true; } // In multi-hier mode, update the parents selection state // DT issue #82: only if not initializing, because the children may not exist yet // if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing ) // ftnode._fixSelectionState(); // In multi-hier mode, update the parents selection state if( ftnode.bSelected && opts.selectMode==3 ) { var p = this; while( p ) { if( !p.hasSubSel ) p._setSubSel(true); p = p.parent; } } // render this node and the new child if ( tree.bEnableUpdate ) this.render(); return ftnode; */ }, /** Set focus relative to this node and optionally activate. * * 'left' collapses the node if it is expanded, or move to the parent * otherwise. * 'right' expands the node if it is collapsed, or move to the first * child otherwise. * * @param {string|number} where 'down', 'first', 'last', 'left', 'parent', 'right', or 'up'. * (Alternatively the keyCode that would normally trigger this move, * e.g. `$.ui.keyCode.LEFT` = 'left'. * @param {boolean} [activate=true] * @returns {$.Promise} */ navigate: function(where, activate) { var node, KC = $.ui.keyCode; // Handle optional expand/collapse action for LEFT/RIGHT switch (where) { case "left": case KC.LEFT: if (this.expanded) { return this.setExpanded(false); } break; case "right": case KC.RIGHT: if (!this.expanded && (this.children || this.lazy)) { return this.setExpanded(); } break; } // Otherwise activate or focus the related node node = this.findRelatedNode(where); if (node) { // setFocus/setActive will scroll later (if autoScroll is specified) try { node.makeVisible({ scrollIntoView: false }); } catch (e) {} // #272 if (activate === false) { node.setFocus(); return _getResolvedPromise(); } return node.setActive(); } this.warn("Could not find related node '" + where + "'."); return _getResolvedPromise(); }, /** * Remove this node (not allowed for system root). */ remove: function() { return this.parent.removeChild(this); }, /** * Remove childNode from list of direct children. * @param {FancytreeNode} childNode */ removeChild: function(childNode) { return this.tree._callHook("nodeRemoveChild", this, childNode); }, /** * Remove all child nodes and descendents. This converts the node into a leaf.<br> * If this was a lazy node, it is still considered 'loaded'; call node.resetLazy() * in order to trigger lazyLoad on next expand. */ removeChildren: function() { return this.tree._callHook("nodeRemoveChildren", this); }, /** * Remove class from node's span tag and .extraClasses. * * @param {string} className class name * * @since 2.17 */ removeClass: function(className) { return this.toggleClass(className, false); }, /** * This method renders and updates all HTML markup that is required * to display this node in its current state.<br> * Note: * <ul> * <li>It should only be neccessary to call this method after the node object * was modified by direct access to its properties, because the common * API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...) * already handle this. * <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus} * are implied. If changes are more local, calling only renderTitle() or * renderStatus() may be sufficient and faster. * </ul> * * @param {boolean} [force=false] re-render, even if html markup was already created * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed */ render: function(force, deep) { return this.tree._callHook("nodeRender", this, force, deep); }, /** Create HTML markup for the node's outer `<span>` (expander, checkbox, icon, and title). * Implies {@link FancytreeNode#renderStatus}. * @see Fancytree_Hooks#nodeRenderTitle */ renderTitle: function() { return this.tree._callHook("nodeRenderTitle", this); }, /** Update element's CSS classes according to node state. * @see Fancytree_Hooks#nodeRenderStatus */ renderStatus: function() { return this.tree._callHook("nodeRenderStatus", this); }, /** * (experimental) Replace this node with `source`. * (Currently only available for paging nodes.) * @param {NodeData[]} source List of child node definitions * @since 2.15 */ replaceWith: function(source) { var res, parent = this.parent, pos = $.inArray(this, parent.children), self = this; _assert( this.isPagingNode(), "replaceWith() currently requires a paging status node" ); res = this.tree._callHook("nodeLoadChildren", this, source); res.done(function(data) { // New nodes are currently children of `this`. var children = self.children; // Prepend newly loaded child nodes to `this` // Move new children after self for (i = 0; i < children.length; i++) { children[i].parent = parent; } parent.children.splice.apply( parent.children, [pos + 1, 0].concat(children) ); // Remove self self.children = null; self.remove(); // Redraw new nodes parent.render(); // TODO: set node.partload = false if this was tha last paging node? // parent.addPagingNode(false); }).fail(function() { self.setExpanded(); }); return res; // $.error("Not implemented: replaceWith()"); }, /** * Remove all children, collapse, and set the lazy-flag, so that the lazyLoad * event is triggered on next expand. */ resetLazy: function() { this.removeChildren(); this.expanded = false; this.lazy = true; this.children = undefined; this.renderStatus(); }, /** Schedule activity for delayed execution (cancel any pending request). * scheduleAction('cancel') will only cancel a pending request (if any). * @param {string} mode * @param {number} ms */ scheduleAction: function(mode, ms) { if (this.tree.timer) { clearTimeout(this.tree.timer); this.tree.debug("clearTimeout(%o)", this.tree.timer); } this.tree.timer = null; var self = this; // required for closures switch (mode) { case "cancel": // Simply made sure that timer was cleared break; case "expand": this.tree.timer = setTimeout(function() { self.tree.debug("setTimeout: trigger expand"); self.setExpanded(true); }, ms); break; case "activate": this.tree.timer = setTimeout(function() { self.tree.debug("setTimeout: trigger activate"); self.setActive(true); }, ms); break; default: $.error("Invalid mode " + mode); } // this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer); }, /** * * @param {boolean | PlainObject} [effects=false] animation options. * @param {object} [options=null] {topNode: null, effects: ..., parent: ...} this node will remain visible in * any case, even if `this` is outside the scroll pane. * @returns {$.Promise} */ scrollIntoView: function(effects, options) { if (options !== undefined && _isNode(options)) { throw Error( "scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead." ); } // The scroll parent is typically the plain tree's <UL> container. // For ext-table, we choose the nearest parent that has `position: relative` // and `overflow` set. // (This default can be overridden by the local or global `scrollParent` option.) var opts = $.extend( { effects: effects === true ? { duration: 200, queue: false } : effects, scrollOfs: this.tree.options.scrollOfs, scrollParent: this.tree.options.scrollParent, topNode: null, }, options ), $scrollParent = opts.scrollParent, $container = this.tree.$container, overflowY = $container.css("overflow-y"); if (!$scrollParent) { if (this.tree.tbody) { $scrollParent = $container.scrollParent(); } else if (overflowY === "scroll" || overflowY === "auto") { $scrollParent = $container; } else { // #922 plain tree in a non-fixed-sized UL scrolls inside its parent $scrollParent = $container.scrollParent(); } } else if (!$scrollParent.jquery) { // Make sure we have a jQuery object $scrollParent = $($scrollParent); } if ( $scrollParent[0] === document || $scrollParent[0] === document.body ) { // `document` may be returned by $().scrollParent(), if nothing is found, // but would not work: (see #894) this.debug( "scrollIntoView(): normalizing scrollParent to 'window':", $scrollParent[0] ); $scrollParent = $(window); } // eslint-disable-next-line one-var var topNodeY, nodeY, horzScrollbarHeight, containerOffsetTop, dfd = new $.Deferred(), self = this, nodeHeight = $(this.span).height(), topOfs = opts.scrollOfs.top || 0, bottomOfs = opts.scrollOfs.bottom || 0, containerHeight = $scrollParent.height(), scrollTop = $scrollParent.scrollTop(), $animateTarget = $scrollParent, isParentWindow = $scrollParent[0] === window, topNode = opts.topNode || null, newScrollTop = null; // this.debug("scrollIntoView(), scrollTop=" + scrollTop, opts.scrollOfs); // _assert($(this.span).is(":visible"), "scrollIntoView node is invisible"); // otherwise we cannot calc offsets if (!this.isVisible()) { // We cannot calc offsets for hidden elements this.warn("scrollIntoView(): node is invisible."); return _getResolvedPromise(); } if (isParentWindow) { nodeY = $(this.span).offset().top; topNodeY = topNode && topNode.span ? $(topNode.span).offset().top : 0; $animateTarget = $("html,body"); } else { _assert( $scrollParent[0] !== document && $scrollParent[0] !== document.body, "scrollParent should be a simple element or `window`, not document or body." ); containerOffsetTop = $scrollParent.offset().top; nodeY = $(this.span).offset().top - containerOffsetTop + scrollTop; // relative to scroll parent topNodeY = topNode ? $(topNode.span).offset().top - containerOffsetTop + scrollTop : 0; horzScrollbarHeight = Math.max( 0, $scrollParent.innerHeight() - $scrollParent[0].clientHeight ); containerHeight -= horzScrollbarHeight; } // this.debug(" scrollIntoView(), nodeY=" + nodeY + ", containerHeight=" + containerHeight); if (nodeY < scrollTop + topOfs) { // Node is above visible container area newScrollTop = nodeY - topOfs; // this.debug(" scrollIntoView(), UPPER newScrollTop=" + newScrollTop); } else if ( nodeY + nodeHeight > scrollTop + containerHeight - bottomOfs ) { newScrollTop = nodeY + nodeHeight - containerHeight + bottomOfs; // this.debug(" scrollIntoView(), LOWER newScrollTop=" + newScrollTop); // If a topNode was passed, make sure that it is never scrolled // outside the upper border if (topNode) { _assert( topNode.isRootNode() || topNode.isVisible(), "topNode must be visible" ); if (topNodeY < newScrollTop) { newScrollTop = topNodeY - topOfs; // this.debug(" scrollIntoView(), TOP newScrollTop=" + newScrollTop); } } } if (newScrollTop === null) { dfd.resolveWith(this); } else { // this.debug(" scrollIntoView(), SET newScrollTop=" + newScrollTop); if (opts.effects) { opts.effects.complete = function() { dfd.resolveWith(self); }; $animateTarget.stop(true).animate( { scrollTop: newScrollTop, }, opts.effects ); } else { $animateTarget[0].scrollTop = newScrollTop; dfd.resolveWith(this); } } return dfd.promise(); }, /**Activate this node. * * The `cell` option requires the ext-table and ext-ariagrid extensions. * * @param {boolean} [flag=true] pass false to deactivate * @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false, cell: null} * @returns {$.Promise} */ setActive: function(flag, opts) { return this.tree._callHook("nodeSetActive", this, flag, opts); }, /**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done. * @param {boolean} [flag=true] pass false to collapse * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false} * @returns {$.Promise} */ setExpanded: function(flag, opts) { return this.tree._callHook("nodeSetExpanded", this, flag, opts); }, /**Set keyboard focus to this node. * @param {boolean} [flag=true] pass false to blur * @see Fancytree#setFocus */ setFocus: function(flag) { return this.tree._callHook("nodeSetFocus", this, flag); }, /**Select this node, i.e. check the checkbox. * @param {boolean} [flag=true] pass false to deselect * @param {object} [opts] additional options. Defaults to {noEvents: false, p * propagateDown: null, propagateUp: null, callback: null } */ setSelected: function(flag, opts) { return this.tree._callHook("nodeSetSelected", this, flag, opts); }, /**Mark a lazy node as 'error', 'loading', 'nodata', or 'ok'. * @param {string} status 'error'|'empty'|'ok' * @param {string} [message] * @param {string} [details] */ setStatus: function(status, message, details) { return this.tree._callHook( "nodeSetStatus", this, status, message, details ); }, /**Rename this node. * @param {string} title */ setTitle: function(title) { this.title = title; this.renderTitle(); this.triggerModify("rename"); }, /**Sort child list by title. * @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title). * @param {boolean} [deep=false] pass true to sort all descendant nodes */ sortChildren: function(cmp, deep) { var i, l, cl = this.children; if (!cl) { return; } cmp = cmp || function(a, b) { var x = a.title.toLowerCase(), y = b.title.toLowerCase(); // eslint-disable-next-line no-nested-ternary return x === y ? 0 : x > y ? 1 : -1; }; cl.sort(cmp); if (deep) { for (i = 0, l = cl.length; i < l; i++) { if (cl[i].children) { cl[i].sortChildren(cmp, "$norender$"); } } } if (deep !== "$norender$") { this.render(); } this.triggerModifyChild("sort"); }, /** Convert node (or whole branch) into a plain object. * * The result is compatible with node.addChildren(). * * @param {boolean} [recursive=false] include child nodes * @param {function} [callback] callback(dict, node) is called for every node, in order to allow modifications. * Return `false` to ignore this node or "skip" to include this node without its children. * @returns {NodeData} */ toDict: function(recursive, callback) { var i, l, node, res, dict = {}, self = this; $.each(NODE_ATTRS, function(i, a) { if (self[a] || self[a] === false) { dict[a] = self[a]; } }); if (!$.isEmptyObject(this.data)) { dict.data = $.extend({}, this.data); if ($.isEmptyObject(dict.data)) { delete dict.data; } } if (callback) { res = callback(dict, self); if (res === false) { return false; // Don't include this node nor its children } if (res === "skip") { recursive = false; // Include this node, but not the children } } if (recursive) { if (this.hasChildren()) { dict.children = []; for (i = 0, l = this.children.length; i < l; i++) { node = this.children[i]; if (!node.isStatusNode()) { res = node.toDict(true, callback); if (res !== false) { dict.children.push(res); } } } } } return dict; }, /** * Set, clear, or toggle class of node's span tag and .extraClasses. * * @param {string} className class name (separate multiple classes by space) * @param {boolean} [flag] true/false to add/remove class. If omitted, class is toggled. * @returns {boolean} true if a class was added * * @since 2.17 */ toggleClass: function(value, flag) { var className, hasClass, rnotwhite = /\S+/g, classNames = value.match(rnotwhite) || [], i = 0, wasAdded = false, statusElem = this[this.tree.statusClassPropName], curClasses = " " + (this.extraClasses || "") + " "; // this.info("toggleClass('" + value + "', " + flag + ")", curClasses); // Modify DOM element directly if it already exists if (statusElem) { $(statusElem).toggleClass(value, flag); } // Modify node.extraClasses to make this change persistent // Toggle if flag was not passed while ((className = classNames[i++])) { hasClass = curClasses.indexOf(" " + className + " ") >= 0; flag = flag === undefined ? !hasClass : !!flag; if (flag) { if (!hasClass) { curClasses += className + " "; wasAdded = true; } } else { while (curClasses.indexOf(" " + className + " ") > -1) { curClasses = curClasses.replace( " " + className + " ", " " ); } } } this.extraClasses = $.trim(curClasses); // this.info("-> toggleClass('" + value + "', " + flag + "): '" + this.extraClasses + "'"); return wasAdded; }, /** Flip expanded status. */ toggleExpanded: function() { return this.tree._callHook("nodeToggleExpanded", this); }, /** Flip selection status. */ toggleSelected: function() { return this.tree._callHook("nodeToggleSelected", this); }, toString: function() { return "FancytreeNode@" + this.key + "[title='" + this.title + "']"; // return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>"; }, /** * Trigger `modifyChild` event on a parent to signal that a child was modified. * @param {string} operation Type of change: 'add', 'remove', 'rename', 'move', 'data', ... * @param {FancytreeNode} [childNode] * @param {object} [extra] */ triggerModifyChild: function(operation, childNode, extra) { var data, modifyChild = this.tree.options.modifyChild; if (modifyChild) { if (childNode && childNode.parent !== this) { $.error( "childNode " + childNode + " is not a child of " + this ); } data = { node: this, tree: this.tree, operation: operation, childNode: childNode || null, }; if (extra) { $.extend(data, extra); } modifyChild({ type: "modifyChild" }, data); } }, /** * Trigger `modifyChild` event on node.parent(!). * @param {string} operation Type of change: 'add', 'remove', 'rename', 'move', 'data', ... * @param {object} [extra] */ triggerModify: function(operation, extra) { this.parent.triggerModifyChild(operation, this, extra); }, /** Call fn(node) for all child nodes in hierarchical order (depth-first).<br> * Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and * its children only. * @param {boolean} [includeSelf=false] * @returns {boolean} */ visit: function(fn, includeSelf) { var i, l, res = true, children = this.children; if (includeSelf === true) { res = fn(this); if (res === false || res === "skip") { return res; } } if (children) { for (i = 0, l = children.length; i < l; i++) { res = children[i].visit(fn, true); if (res === false) { break; } } } return res; }, /** Call fn(node) for all child nodes and recursively load lazy children.<br> * <b>Note:</b> If you need this method, you probably should consider to review * your architecture! Recursivley loading nodes is a perfect way for lazy * programmers to flood the server with requests ;-) * * @param {function} [fn] optional callback function. * Return false to stop iteration, return "skip" to skip this node and * its children only. * @param {boolean} [includeSelf=false] * @returns {$.Promise} * @since 2.4 */ visitAndLoad: function(fn, includeSelf, _recursion) { var dfd, res, loaders, node = this; // node.debug("visitAndLoad"); if (fn && includeSelf === true) { res = fn(node); if (res === false || res === "skip") { return _recursion ? res : _getResolvedPromise(); } } if (!node.children && !node.lazy) { return _getResolvedPromise(); } dfd = new $.Deferred(); loaders = []; // node.debug("load()..."); node.load().done(function() { // node.debug("load()... done."); for (var i = 0, l = node.children.length; i < l; i++) { res = node.children[i].visitAndLoad(fn, true, true); if (res === false) { dfd.reject(); break; } else if (res !== "skip") { loaders.push(res); // Add promise to the list } } $.when.apply(this, loaders).then(function() { dfd.resolve(); }); }); return dfd.promise(); }, /** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br> * Stop iteration, if fn() returns false.<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and children only. * @param {boolean} [includeSelf=false] * @returns {boolean} */ visitParents: function(fn, includeSelf) { // Visit parent nodes (bottom up) if (includeSelf && fn(this) === false) { return false; } var p = this.parent; while (p) { if (fn(p) === false) { return false; } p = p.parent; } return true; }, /** Call fn(node) for all sibling nodes.<br> * Stop iteration, if fn() returns false.<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration. * @param {boolean} [includeSelf=false] * @returns {boolean} */ visitSiblings: function(fn, includeSelf) { var i, l, n, ac = this.parent.children; for (i = 0, l = ac.length; i < l; i++) { n = ac[i]; if (includeSelf || n !== this) { if (fn(n) === false) { return false; } } } return true; }, /** Write warning to browser console if debugLevel >= 2 (prepending node info) * * @param {*} msg string or object or array of such */ warn: function(msg) { if (this.tree.options.debugLevel >= 2) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("warn", arguments); } }, }; /****************************************************************************** * Fancytree */ /** * Construct a new tree object. * * @class Fancytree * @classdesc The controller behind a fancytree. * This class also contains 'hook methods': see {@link Fancytree_Hooks}. * * @param {Widget} widget * * @property {string} _id Automatically generated unique tree instance ID, e.g. "1". * @property {string} _ns Automatically generated unique tree namespace, e.g. ".fancytree-1". * @property {FancytreeNode} activeNode Currently active node or null. * @property {string} ariaPropName Property name of FancytreeNode that contains the element which will receive the aria attributes. * Typically "li", but "tr" for table extension. * @property {jQueryObject} $container Outer `<ul>` element (or `<table>` element for ext-table). * @property {jQueryObject} $div A jQuery object containing the element used to instantiate the tree widget (`widget.element`) * @property {object|array} columns Recommended place to store shared column meta data. @since 2.27 * @property {object} data Metadata, i.e. properties that may be passed to `source` in addition to a children array. * @property {object} ext Hash of all active plugin instances. * @property {FancytreeNode} focusNode Currently focused node or null. * @property {FancytreeNode} lastSelectedNode Used to implement selectMode 1 (single select) * @property {string} nodeContainerAttrName Property name of FancytreeNode that contains the outer element of single nodes. * Typically "li", but "tr" for table extension. * @property {FancytreeOptions} options Current options, i.e. default options + options passed to constructor. * @property {FancytreeNode} rootNode Invisible system root node. * @property {string} statusClassPropName Property name of FancytreeNode that contains the element which will receive the status classes. * Typically "span", but "tr" for table extension. * @property {object} types Map for shared type specific meta data, used with node.type attribute. @since 2.27 * @property {object} viewport See ext-vieport. @since v2.31 * @property {object} widget Base widget instance. */ function Fancytree(widget) { this.widget = widget; this.$div = widget.element; this.options = widget.options; if (this.options) { if (this.options.lazyload !== undefined) { $.error( "The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead." ); } if (this.options.loaderror !== undefined) { $.error( "The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead." ); } if (this.options.fx !== undefined) { $.error( "The 'fx' option was replaced by 'toggleEffect' since 2014-11-30." ); } if (this.options.removeNode !== undefined) { $.error( "The 'removeNode' event was replaced by 'modifyChild' since 2.20 (2016-09-10)." ); } } this.ext = {}; // Active extension instances this.types = {}; this.columns = {}; // allow to init tree.data.foo from <div data-foo=''> this.data = _getElementDataAsDict(this.$div); // TODO: use widget.uuid instead? this._id = "" + (this.options.treeId || $.ui.fancytree._nextId++); // TODO: use widget.eventNamespace instead? this._ns = ".fancytree-" + this._id; // append for namespaced events this.activeNode = null; this.focusNode = null; this._hasFocus = null; this._tempCache = {}; this._lastMousedownNode = null; this._enableUpdate = true; this.lastSelectedNode = null; this.systemFocusElement = null; this.lastQuicksearchTerm = ""; this.lastQuicksearchTime = 0; this.viewport = null; // ext-grid this.statusClassPropName = "span"; this.ariaPropName = "li"; this.nodeContainerAttrName = "li"; // Remove previous markup if any this.$div.find(">ul.fancytree-container").remove(); // Create a node without parent. var fakeParent = { tree: this }, $ul; this.rootNode = new FancytreeNode(fakeParent, { title: "root", key: "root_" + this._id, children: null, expanded: true, }); this.rootNode.parent = null; // Create root markup $ul = $("<ul>", { id: "ft-id-" + this._id, class: "ui-fancytree fancytree-container fancytree-plain", }).appendTo(this.$div); this.$container = $ul; this.rootNode.ul = $ul[0]; if (this.options.debugLevel == null) { this.options.debugLevel = FT.debugLevel; } // // Add container to the TAB chain // // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant // // #577: Allow to set tabindex to "0", "-1" and "" // this.$container.attr("tabindex", this.options.tabindex); // if( this.options.rtl ) { // this.$container.attr("DIR", "RTL").addClass("fancytree-rtl"); // // }else{ // // this.$container.attr("DIR", null).removeClass("fancytree-rtl"); // } // if(this.options.aria){ // this.$container.attr("role", "tree"); // if( this.options.selectMode !== 1 ) { // this.$container.attr("aria-multiselectable", true); // } // } } Fancytree.prototype = /** @lends Fancytree# */ { /* Return a context object that can be re-used for _callHook(). * @param {Fancytree | FancytreeNode | EventData} obj * @param {Event} originalEvent * @param {Object} extra * @returns {EventData} */ _makeHookContext: function(obj, originalEvent, extra) { var ctx, tree; if (obj.node !== undefined) { // obj is already a context object if (originalEvent && obj.originalEvent !== originalEvent) { $.error("invalid args"); } ctx = obj; } else if (obj.tree) { // obj is a FancytreeNode tree = obj.tree; ctx = { node: obj, tree: tree, widget: tree.widget, options: tree.widget.options, originalEvent: originalEvent, typeInfo: tree.types[obj.type] || {}, }; } else if (obj.widget) { // obj is a Fancytree ctx = { node: null, tree: obj, widget: obj.widget, options: obj.widget.options, originalEvent: originalEvent, }; } else { $.error("invalid args"); } if (extra) { $.extend(ctx, extra); } return ctx; }, /* Trigger a hook function: funcName(ctx, [...]). * * @param {string} funcName * @param {Fancytree|FancytreeNode|EventData} contextObject * @param {any} [_extraArgs] optional additional arguments * @returns {any} */ _callHook: function(funcName, contextObject, _extraArgs) { var ctx = this._makeHookContext(contextObject), fn = this[funcName], args = Array.prototype.slice.call(arguments, 2); if (!$.isFunction(fn)) { $.error("_callHook('" + funcName + "') is not a function"); } args.unshift(ctx); // this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args); return fn.apply(this, args); }, _setExpiringValue: function(key, value, ms) { this._tempCache[key] = { value: value, expire: Date.now() + (+ms || 50), }; }, _getExpiringValue: function(key) { var entry = this._tempCache[key]; if (entry && entry.expire > Date.now()) { return entry.value; } delete this._tempCache[key]; return null; }, /* Check if this tree has extension `name` enabled. * * @param {string} name name of the required extension */ _usesExtension: function(name) { return $.inArray(name, this.options.extensions) >= 0; }, /* Check if current extensions dependencies are met and throw an error if not. * * This method may be called inside the `treeInit` hook for custom extensions. * * @param {string} name name of the required extension * @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present * @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter) * @param {string} [message] optional error message (defaults to a descriptve error message) */ _requireExtension: function(name, required, before, message) { if (before != null) { before = !!before; } var thisName = this._local.name, extList = this.options.extensions, isBefore = $.inArray(name, extList) < $.inArray(thisName, extList), isMissing = required && this.ext[name] == null, badOrder = !isMissing && before != null && before !== isBefore; _assert( thisName && thisName !== name, "invalid or same name '" + thisName + "' (require yourself?)" ); if (isMissing || badOrder) { if (!message) { if (isMissing || required) { message = "'" + thisName + "' extension requires '" + name + "'"; if (badOrder) { message += " to be registered " + (before ? "before" : "after") + " itself"; } } else { message = "If used together, `" + name + "` must be registered " + (before ? "before" : "after") + " `" + thisName + "`"; } } $.error(message); return false; } return true; }, /** Activate node with a given key and fire focus and activate events. * * A previously activated node will be deactivated. * If activeVisible option is set, all parents will be expanded as necessary. * Pass key = false, to deactivate the current node only. * @param {string} key * @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false} * @returns {FancytreeNode} activated node (null, if not found) */ activateKey: function(key, opts) { var node = this.getNodeByKey(key); if (node) { node.setActive(true, opts); } else if (this.activeNode) { this.activeNode.setActive(false, opts); } return node; }, /** (experimental) Add child status nodes that indicate 'More...', .... * @param {boolean|object} node optional node definition. Pass `false` to remove all paging nodes. * @param {string} [mode='append'] 'child'|firstChild' * @since 2.15 */ addPagingNode: function(node, mode) { return this.rootNode.addPagingNode(node, mode); }, /** * (experimental) Apply a modification (or navigation) operation. * * Valid commands: * - 'moveUp', 'moveDown' * - 'indent', 'outdent' * - 'remove' * - 'edit', 'addChild', 'addSibling': (reqires ext-edit extension) * - 'cut', 'copy', 'paste': (use an internal singleton 'clipboard') * - 'down', 'first', 'last', 'left', 'parent', 'right', 'up': navigate * * @param {string} cmd * @param {FancytreeNode} [node=active_node] * @param {object} [opts] Currently unused * * @since 2.32 */ applyCommand: function(cmd, node, opts_) { var // clipboard, refNode; // opts = $.extend( // { setActive: true, clipboard: CLIPBOARD }, // opts_ // ); node = node || this.getActiveNode(); // clipboard = opts.clipboard; switch (cmd) { // Sorting and indentation: case "moveUp": refNode = node.getPrevSibling(); if (refNode) { node.moveTo(refNode, "before"); node.setActive(); } break; case "moveDown": refNode = node.getNextSibling(); if (refNode) { node.moveTo(refNode, "after"); node.setActive(); } break; case "indent": refNode = node.getPrevSibling(); if (refNode) { node.moveTo(refNode, "child"); refNode.setExpanded(); node.setActive(); } break; case "outdent": if (!node.isTopLevel()) { node.moveTo(node.getParent(), "after"); node.setActive(); } break; // Remove: case "remove": refNode = node.getPrevSibling() || node.getParent(); node.remove(); if (refNode) { refNode.setActive(); } break; // Add, edit (requires ext-edit): case "addChild": node.editCreateNode("child", ""); break; case "addSibling": node.editCreateNode("after", ""); break; case "rename": node.editStart(); break; // Simple clipboard simulation: // case "cut": // clipboard = { mode: cmd, data: node }; // break; // case "copy": // clipboard = { // mode: cmd, // data: node.toDict(function(n) { // delete n.key; // }), // }; // break; // case "clear": // clipboard = null; // break; // case "paste": // if (clipboard.mode === "cut") { // // refNode = node.getPrevSibling(); // clipboard.data.moveTo(node, "child"); // clipboard.data.setActive(); // } else if (clipboard.mode === "copy") { // node.addChildren(clipboard.data).setActive(); // } // break; // Navigation commands: case "down": case "first": case "last": case "left": case "parent": case "right": case "up": return node.navigate(cmd); default: $.error("Unhandled command: '" + cmd + "'"); } }, /** (experimental) Modify existing data model. * * @param {Array} patchList array of [key, NodePatch] arrays * @returns {$.Promise} resolved, when all patches have been applied * @see TreePatch */ applyPatch: function(patchList) { var dfd, i, p2, key, patch, node, patchCount = patchList.length, deferredList = []; for (i = 0; i < patchCount; i++) { p2 = patchList[i]; _assert( p2.length === 2, "patchList must be an array of length-2-arrays" ); key = p2[0]; patch = p2[1]; node = key === null ? this.rootNode : this.getNodeByKey(key); if (node) { dfd = new $.Deferred(); deferredList.push(dfd); node.applyPatch(patch).always(_makeResolveFunc(dfd, node)); } else { this.warn("could not find node with key '" + key + "'"); } } // Return a promise that is resolved, when ALL patches were applied return $.when.apply($, deferredList).promise(); }, /* TODO: implement in dnd extension cancelDrag: function() { var dd = $.ui.ddmanager.current; if(dd){ dd.cancel(); } }, */ /** Remove all nodes. * @since 2.14 */ clear: function(source) { this._callHook("treeClear", this); }, /** Return the number of nodes. * @returns {integer} */ count: function() { return this.rootNode.countChildren(); }, /** Write to browser console if debugLevel >= 4 (prepending tree name) * * @param {*} msg string or object or array of such */ debug: function(msg) { if (this.options.debugLevel >= 4) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("log", arguments); } }, /** Destroy this widget, restore previous markup and cleanup resources. * * @since 2.34 */ destroy: function() { this.widget.destroy(); }, /** Enable (or disable) the tree control. * * @param {boolean} [flag=true] pass false to disable * @since 2.30 */ enable: function(flag) { if (flag === false) { this.widget.disable(); } else { this.widget.enable(); } }, /** Temporarily suppress rendering to improve performance on bulk-updates. * * @param {boolean} flag * @returns {boolean} previous status * @since 2.19 */ enableUpdate: function(flag) { flag = flag !== false; if (!!this._enableUpdate === !!flag) { return flag; } this._enableUpdate = flag; if (flag) { this.debug("enableUpdate(true): redraw "); //, this._dirtyRoots); this._callHook("treeStructureChanged", this, "enableUpdate"); this.render(); } else { // this._dirtyRoots = null; this.debug("enableUpdate(false)..."); } return !flag; // return previous value }, /** Write error to browser console if debugLevel >= 1 (prepending tree info) * * @param {*} msg string or object or array of such */ error: function(msg) { if (this.options.debugLevel >= 1) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("error", arguments); } }, /** Expand (or collapse) all parent nodes. * * This convenience method uses `tree.visit()` and `tree.setExpanded()` * internally. * * @param {boolean} [flag=true] pass false to collapse * @param {object} [opts] passed to setExpanded() * @since 2.30 */ expandAll: function(flag, opts) { var prev = this.enableUpdate(false); flag = flag !== false; this.visit(function(node) { if ( node.hasChildren() !== false && node.isExpanded() !== flag ) { node.setExpanded(flag, opts); } }); this.enableUpdate(prev); }, /**Find all nodes that matches condition. * * @param {string | function(node)} match title string to search for, or a * callback function that returns `true` if a node is matched. * @returns {FancytreeNode[]} array of nodes (may be empty) * @see FancytreeNode#findAll * @since 2.12 */ findAll: function(match) { return this.rootNode.findAll(match); }, /**Find first node that matches condition. * * @param {string | function(node)} match title string to search for, or a * callback function that returns `true` if a node is matched. * @returns {FancytreeNode} matching node or null * @see FancytreeNode#findFirst * @since 2.12 */ findFirst: function(match) { return this.rootNode.findFirst(match); }, /** Find the next visible node that starts with `match`, starting at `startNode` * and wrap-around at the end. * * @param {string|function} match * @param {FancytreeNode} [startNode] defaults to first node * @returns {FancytreeNode} matching node or null */ findNextNode: function(match, startNode) { //, visibleOnly) { var res = null, firstNode = this.getFirstChild(); match = typeof match === "string" ? _makeNodeTitleStartMatcher(match) : match; startNode = startNode || firstNode; function _checkNode(n) { // console.log("_check " + n) if (match(n)) { res = n; } if (res || n === startNode) { return false; } } this.visitRows(_checkNode, { start: startNode, includeSelf: false, }); // Wrap around search if (!res && startNode !== firstNode) { this.visitRows(_checkNode, { start: firstNode, includeSelf: true, }); } return res; }, /** Find a node relative to another node. * * @param {FancytreeNode} node * @param {string|number} where 'down', 'first', 'last', 'left', 'parent', 'right', or 'up'. * (Alternatively the keyCode that would normally trigger this move, * e.g. `$.ui.keyCode.LEFT` = 'left'. * @param {boolean} [includeHidden=false] Not yet implemented * @returns {FancytreeNode|null} * @since v2.31 */ findRelatedNode: function(node, where, includeHidden) { var res = null, KC = $.ui.keyCode; switch (where) { case "parent": case KC.BACKSPACE: if (node.parent && node.parent.parent) { res = node.parent; } break; case "first": case KC.HOME: // First visible node this.visit(function(n) { if (n.isVisible()) { res = n; return false; } }); break; case "last": case KC.END: this.visit(function(n) { // last visible node if (n.isVisible()) { res = n; } }); break; case "left": case KC.LEFT: if (node.expanded) { node.setExpanded(false); } else if (node.parent && node.parent.parent) { res = node.parent; } break; case "right": case KC.RIGHT: if (!node.expanded && (node.children || node.lazy)) { node.setExpanded(); res = node; } else if (node.children && node.children.length) { res = node.children[0]; } break; case "up": case KC.UP: this.visitRows( function(n) { res = n; return false; }, { start: node, reverse: true, includeSelf: false } ); break; case "down": case KC.DOWN: this.visitRows( function(n) { res = n; return false; }, { start: node, includeSelf: false } ); break; default: this.tree.warn("Unknown relation '" + where + "'."); } return res; }, // TODO: fromDict /** * Generate INPUT elements that can be submitted with html forms. * * In selectMode 3 only the topmost selected nodes are considered, unless * `opts.stopOnParents: false` is passed. * * @example * // Generate input elements for active and selected nodes * tree.generateFormElements(); * // Generate input elements selected nodes, using a custom `name` attribute * tree.generateFormElements("cust_sel", false); * // Generate input elements using a custom filter * tree.generateFormElements(true, true, { filter: function(node) { * return node.isSelected() && node.data.yes; * }}); * * @param {boolean | string} [selected=true] Pass false to disable, pass a string to override the field name (default: 'ft_ID[]') * @param {boolean | string} [active=true] Pass false to disable, pass a string to override the field name (default: 'ft_ID_active') * @param {object} [opts] default { filter: null, stopOnParents: true } */ generateFormElements: function(selected, active, opts) { opts = opts || {}; var nodeList, selectedName = typeof selected === "string" ? selected : "ft_" + this._id + "[]", activeName = typeof active === "string" ? active : "ft_" + this._id + "_active", id = "fancytree_result_" + this._id, $result = $("#" + id), stopOnParents = this.options.selectMode === 3 && opts.stopOnParents !== false; if ($result.length) { $result.empty(); } else { $result = $("<div>", { id: id, }) .hide() .insertAfter(this.$container); } if (active !== false && this.activeNode) { $result.append( $("<input>", { type: "radio", name: activeName, value: this.activeNode.key, checked: true, }) ); } function _appender(node) { $result.append( $("<input>", { type: "checkbox", name: selectedName, value: node.key, checked: true, }) ); } if (opts.filter) { this.visit(function(node) { var res = opts.filter(node); if (res === "skip") { return res; } if (res !== false) { _appender(node); } }); } else if (selected !== false) { nodeList = this.getSelectedNodes(stopOnParents); $.each(nodeList, function(idx, node) { _appender(node); }); } }, /** * Return the currently active node or null. * @returns {FancytreeNode} */ getActiveNode: function() { return this.activeNode; }, /** Return the first top level node if any (not the invisible root node). * @returns {FancytreeNode | null} */ getFirstChild: function() { return this.rootNode.getFirstChild(); }, /** * Return node that has keyboard focus or null. * @returns {FancytreeNode} */ getFocusNode: function() { return this.focusNode; }, /** * Return current option value. * (Note: this is the preferred variant of `$().fancytree("option", "KEY")`) * * @param {string} name option name (may contain '.') * @returns {any} */ getOption: function(optionName) { return this.widget.option(optionName); }, /** * Return node with a given key or null if not found. * * @param {string} key * @param {FancytreeNode} [searchRoot] only search below this node * @returns {FancytreeNode | null} */ getNodeByKey: function(key, searchRoot) { // Search the DOM by element ID (assuming this is faster than traversing all nodes). var el, match; // TODO: use tree.keyMap if available // TODO: check opts.generateIds === true if (!searchRoot) { el = document.getElementById(this.options.idPrefix + key); if (el) { return el.ftnode ? el.ftnode : null; } } // Not found in the DOM, but still may be in an unrendered part of tree searchRoot = searchRoot || this.rootNode; match = null; searchRoot.visit(function(node) { if (node.key === key) { match = node; return false; // Stop iteration } }, true); return match; }, /** Return the invisible system root node. * @returns {FancytreeNode} */ getRootNode: function() { return this.rootNode; }, /** * Return an array of selected nodes. * * Note: you cannot send this result via Ajax directly. Instead the * node object need to be converted to plain objects, for example * by using `$.map()` and `node.toDict()`. * @param {boolean} [stopOnParents=false] only return the topmost selected * node (useful with selectMode 3) * @returns {FancytreeNode[]} */ getSelectedNodes: function(stopOnParents) { return this.rootNode.getSelectedNodes(stopOnParents); }, /** Return true if the tree control has keyboard focus * @returns {boolean} */ hasFocus: function() { // var ae = document.activeElement, // hasFocus = !!( // ae && $(ae).closest(".fancytree-container").length // ); // if (hasFocus !== !!this._hasFocus) { // this.warn( // "hasFocus(): fix inconsistent container state, now: " + // hasFocus // ); // this._hasFocus = hasFocus; // this.$container.toggleClass("fancytree-treefocus", hasFocus); // } // return hasFocus; return !!this._hasFocus; }, /** Write to browser console if debugLevel >= 3 (prepending tree name) * @param {*} msg string or object or array of such */ info: function(msg) { if (this.options.debugLevel >= 3) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("info", arguments); } }, /** Return true if any node is currently beeing loaded, i.e. a Ajax request is pending. * @returns {boolean} * @since 2.32 */ isLoading: function() { var res = false; this.rootNode.visit(function(n) { // also visit rootNode if (n._isLoading || n._requestId) { res = true; return false; } }, true); return res; }, /* TODO: isInitializing: function() { return ( this.phase=="init" || this.phase=="postInit" ); }, TODO: isReloading: function() { return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound; }, TODO: isUserEvent: function() { return ( this.phase=="userEvent" ); }, */ /** * Make sure that a node with a given ID is loaded, by traversing - and * loading - its parents. This method is meant for lazy hierarchies. * A callback is executed for every node as we go. * @example * // Resolve using node.key: * tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){ * if(status === "loaded") { * console.log("loaded intermediate node " + node); * }else if(status === "ok") { * node.activate(); * } * }); * // Use deferred promise: * tree.loadKeyPath("/_3/_23/_26/_27").progress(function(data){ * if(data.status === "loaded") { * console.log("loaded intermediate node " + data.node); * }else if(data.status === "ok") { * node.activate(); * } * }).done(function(){ * ... * }); * // Custom path segment resolver: * tree.loadKeyPath("/321/431/21/2", { * matchKey: function(node, key){ * return node.data.refKey === key; * }, * callback: function(node, status){ * if(status === "loaded") { * console.log("loaded intermediate node " + node); * }else if(status === "ok") { * node.activate(); * } * } * }); * @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7') * @param {function | object} optsOrCallback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error'). * Pass an object to define custom key matchers for the path segments: {callback: function, matchKey: function}. * @returns {$.Promise} */ loadKeyPath: function(keyPathList, optsOrCallback) { var callback, i, path, self = this, dfd = new $.Deferred(), parent = this.getRootNode(), sep = this.options.keyPathSeparator, pathSegList = [], opts = $.extend({}, optsOrCallback); // Prepare options if (typeof optsOrCallback === "function") { callback = optsOrCallback; } else if (optsOrCallback && optsOrCallback.callback) { callback = optsOrCallback.callback; } opts.callback = function(ctx, node, status) { if (callback) { callback.call(ctx, node, status); } dfd.notifyWith(ctx, [{ node: node, status: status }]); }; if (opts.matchKey == null) { opts.matchKey = function(node, key) { return node.key === key; }; } // Convert array of path strings to array of segment arrays if (!$.isArray(keyPathList)) { keyPathList = [keyPathList]; } for (i = 0; i < keyPathList.length; i++) { path = keyPathList[i]; // strip leading slash if (path.charAt(0) === sep) { path = path.substr(1); } // segListMap[path] = { parent: parent, segList: path.split(sep) }; pathSegList.push(path.split(sep)); // targetList.push({ parent: parent, segList: path.split(sep)/* , path: path*/}); } // The timeout forces async behavior always (even if nodes are all loaded) // This way a potential progress() event will fire. setTimeout(function() { self._loadKeyPathImpl(dfd, opts, parent, pathSegList).done( function() { dfd.resolve(); } ); }, 0); return dfd.promise(); }, /* * Resolve a list of paths, relative to one parent node. */ _loadKeyPathImpl: function(dfd, opts, parent, pathSegList) { var deferredList, i, key, node, nodeKey, remain, remainMap, tmpParent, segList, subDfd, self = this; function __findChild(parent, key) { // console.log("__findChild", key, parent); var i, l, cl = parent.children; if (cl) { for (i = 0, l = cl.length; i < l; i++) { if (opts.matchKey(cl[i], key)) { return cl[i]; } } } return null; } // console.log("_loadKeyPathImpl, parent=", parent, ", pathSegList=", pathSegList); // Pass 1: // Handle all path segments for nodes that are already loaded. // Collect distinct top-most lazy nodes in a map. // Note that we can use node.key to de-dupe entries, even if a custom matcher would // look for other node attributes. // map[node.key] => {node: node, pathList: [list of remaining rest-paths]} remainMap = {}; for (i = 0; i < pathSegList.length; i++) { segList = pathSegList[i]; // target = targetList[i]; // Traverse and pop path segments (i.e. keys), until we hit a lazy, unloaded node tmpParent = parent; while (segList.length) { key = segList.shift(); node = __findChild(tmpParent, key); if (!node) { this.warn( "loadKeyPath: key not found: " + key + " (parent: " + tmpParent + ")" ); opts.callback(this, key, "error"); break; } else if (segList.length === 0) { opts.callback(this, node, "ok"); break; } else if (!node.lazy || node.hasChildren() !== undefined) { opts.callback(this, node, "loaded"); tmpParent = node; } else { opts.callback(this, node, "loaded"); key = node.key; //target.segList.join(sep); if (remainMap[key]) { remainMap[key].pathSegList.push(segList); } else { remainMap[key] = { parent: node, pathSegList: [segList], }; } break; } } } // console.log("_loadKeyPathImpl AFTER pass 1, remainMap=", remainMap); // Now load all lazy nodes and continue iteration for remaining paths deferredList = []; // Avoid jshint warning 'Don't make functions within a loop.': function __lazyload(dfd, parent, pathSegList) { // console.log("__lazyload", parent, "pathSegList=", pathSegList); opts.callback(self, parent, "loading"); parent .load() .done(function() { self._loadKeyPathImpl .call(self, dfd, opts, parent, pathSegList) .always(_makeResolveFunc(dfd, self)); }) .fail(function(errMsg) { self.warn("loadKeyPath: error loading lazy " + parent); opts.callback(self, node, "error"); dfd.rejectWith(self); }); } // remainMap contains parent nodes, each with a list of relative sub-paths. // We start loading all of them now, and pass the the list to each loader. for (nodeKey in remainMap) { if (remainMap.hasOwnProperty(nodeKey)) { remain = remainMap[nodeKey]; // console.log("for(): remain=", remain, "remainMap=", remainMap); // key = remain.segList.shift(); // node = __findChild(remain.parent, key); // if (node == null) { // #576 // // Issue #576, refactored for v2.27: // // The root cause was, that sometimes the wrong parent was used here // // to find the next segment. // // Falling back to getNodeByKey() was a hack that no longer works if a custom // // matcher is used, because we cannot assume that a single segment-key is unique // // throughout the tree. // self.error("loadKeyPath: error loading child by key '" + key + "' (parent: " + target.parent + ")", target); // // node = self.getNodeByKey(key); // continue; // } subDfd = new $.Deferred(); deferredList.push(subDfd); __lazyload(subDfd, remain.parent, remain.pathSegList); } } // Return a promise that is resolved, when ALL paths were loaded return $.when.apply($, deferredList).promise(); }, /** Re-fire beforeActivate, activate, and (optional) focus events. * Calling this method in the `init` event, will activate the node that * was marked 'active' in the source data, and optionally set the keyboard * focus. * @param [setFocus=false] */ reactivate: function(setFocus) { var res, node = this.activeNode; if (!node) { return _getResolvedPromise(); } this.activeNode = null; // Force re-activating res = node.setActive(true, { noFocus: true }); if (setFocus) { node.setFocus(); } return res; }, /** Reload tree from source and return a promise. * @param [source] optional new source (defaults to initial source data) * @returns {$.Promise} */ reload: function(source) { this._callHook("treeClear", this); return this._callHook("treeLoad", this, source); }, /**Render tree (i.e. create DOM elements for all top-level nodes). * @param {boolean} [force=false] create DOM elemnts, even if parent is collapsed * @param {boolean} [deep=false] */ render: function(force, deep) { return this.rootNode.render(force, deep); }, /**(De)select all nodes. * @param {boolean} [flag=true] * @since 2.28 */ selectAll: function(flag) { this.visit(function(node) { node.setSelected(flag); }); }, // TODO: selectKey: function(key, select) // TODO: serializeArray: function(stopOnParents) /** * @param {boolean} [flag=true] */ setFocus: function(flag) { return this._callHook("treeSetFocus", this, flag); }, /** * Set current option value. * (Note: this is the preferred variant of `$().fancytree("option", "KEY", VALUE)`) * @param {string} name option name (may contain '.') * @param {any} new value */ setOption: function(optionName, value) { return this.widget.option(optionName, value); }, /** * Call console.time() when in debug mode (verbose >= 4). * * @param {string} label */ debugTime: function(label) { if (this.options.debugLevel >= 4) { window.console.time(this + " - " + label); } }, /** * Call console.timeEnd() when in debug mode (verbose >= 4). * * @param {string} label */ debugTimeEnd: function(label) { if (this.options.debugLevel >= 4) { window.console.timeEnd(this + " - " + label); } }, /** * Return all nodes as nested list of {@link NodeData}. * * @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children) * @param {function} [callback] callback(dict, node) is called for every node, in order to allow modifications. * Return `false` to ignore this node or "skip" to include this node without its children. * @returns {Array | object} * @see FancytreeNode#toDict */ toDict: function(includeRoot, callback) { var res = this.rootNode.toDict(true, callback); return includeRoot ? res : res.children; }, /* Implicitly called for string conversions. * @returns {string} */ toString: function() { return "Fancytree@" + this._id; // return "<Fancytree(#" + this._id + ")>"; }, /* _trigger a widget event with additional node ctx. * @see EventData */ _triggerNodeEvent: function(type, node, originalEvent, extra) { // this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx); var ctx = this._makeHookContext(node, originalEvent, extra), res = this.widget._trigger(type, originalEvent, ctx); if (res !== false && ctx.result !== undefined) { return ctx.result; } return res; }, /* _trigger a widget event with additional tree data. */ _triggerTreeEvent: function(type, originalEvent, extra) { // this.debug("_trigger(" + type + ")", ctx); var ctx = this._makeHookContext(this, originalEvent, extra), res = this.widget._trigger(type, originalEvent, ctx); if (res !== false && ctx.result !== undefined) { return ctx.result; } return res; }, /** Call fn(node) for all nodes in hierarchical order (depth-first). * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and children only. * @returns {boolean} false, if the iterator was stopped. */ visit: function(fn) { return this.rootNode.visit(fn, false); }, /** Call fn(node) for all nodes in vertical order, top down (or bottom up).<br> * Stop iteration, if fn() returns false.<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and children only. * @param {object} [options] * Defaults: * {start: First top node, reverse: false, includeSelf: true, includeHidden: false} * @returns {boolean} false if iteration was cancelled * @since 2.28 */ visitRows: function(fn, opts) { if (!this.rootNode.hasChildren()) { return false; } if (opts && opts.reverse) { delete opts.reverse; return this._visitRowsUp(fn, opts); } opts = opts || {}; var i, nextIdx, parent, res, siblings, siblingOfs = 0, skipFirstNode = opts.includeSelf === false, includeHidden = !!opts.includeHidden, checkFilter = !includeHidden && this.enableFilter, node = opts.start || this.rootNode.children[0]; parent = node.parent; while (parent) { // visit siblings siblings = parent.children; nextIdx = siblings.indexOf(node) + siblingOfs; for (i = nextIdx; i < siblings.length; i++) { node = siblings[i]; if (checkFilter && !node.match && !node.subMatchCount) { continue; } if (!skipFirstNode && fn(node) === false) { return false; } skipFirstNode = false; // Dive into node's child nodes if ( node.children && node.children.length && (includeHidden || node.expanded) ) { // Disable warning: Functions declared within loops referencing an outer // scoped variable may lead to confusing semantics: /*jshint -W083 */ res = node.visit(function(n) { if (checkFilter && !n.match && !n.subMatchCount) { return "skip"; } if (fn(n) === false) { return false; } if (!includeHidden && n.children && !n.expanded) { return "skip"; } }, false); /*jshint +W083 */ if (res === false) { return false; } } } // Visit parent nodes (bottom up) node = parent; parent = parent.parent; siblingOfs = 1; // } return true; }, /* Call fn(node) for all nodes in vertical order, bottom up. */ _visitRowsUp: function(fn, opts) { var children, idx, parent, includeHidden = !!opts.includeHidden, node = opts.start || this.rootNode.children[0]; while (true) { parent = node.parent; children = parent.children; if (children[0] === node) { // If this is already the first sibling, goto parent node = parent; if (!node.parent) { break; // first node of the tree } children = parent.children; } else { // Otherwise, goto prev. sibling idx = children.indexOf(node); node = children[idx - 1]; // If the prev. sibling has children, follow down to last descendant while ( // See: https://github.com/eslint/eslint/issues/11302 // eslint-disable-next-line no-unmodified-loop-condition (includeHidden || node.expanded) && node.children && node.children.length ) { children = node.children; parent = node; node = children[children.length - 1]; } } // Skip invisible if (!includeHidden && !node.isVisible()) { continue; } if (fn(node) === false) { return false; } } }, /** Write warning to browser console if debugLevel >= 2 (prepending tree info) * * @param {*} msg string or object or array of such */ warn: function(msg) { if (this.options.debugLevel >= 2) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("warn", arguments); } }, }; /** * These additional methods of the {@link Fancytree} class are 'hook functions' * that can be used and overloaded by extensions. * * @see [writing extensions](https://github.com/mar10/fancytree/wiki/TutorialExtensions) * @mixin Fancytree_Hooks */ $.extend( Fancytree.prototype, /** @lends Fancytree_Hooks# */ { /** Default handling for mouse click events. * * @param {EventData} ctx */ nodeClick: function(ctx) { var activate, expand, // event = ctx.originalEvent, targetType = ctx.targetType, node = ctx.node; // this.debug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which, ctx); // TODO: use switch // TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample) if (targetType === "expander") { if (node.isLoading()) { // #495: we probably got a click event while a lazy load is pending. // The 'expanded' state is not yet set, so 'toggle' would expand // and trigger lazyLoad again. // It would be better to allow to collapse/expand the status node // while loading (instead of ignoring), but that would require some // more work. node.debug("Got 2nd click while loading: ignored"); return; } // Clicking the expander icon always expands/collapses this._callHook("nodeToggleExpanded", ctx); } else if (targetType === "checkbox") { // Clicking the checkbox always (de)selects this._callHook("nodeToggleSelected", ctx); if (ctx.options.focusOnSelect) { // #358 this._callHook("nodeSetFocus", ctx, true); } } else { // Honor `clickFolderMode` for expand = false; activate = true; if (node.folder) { switch (ctx.options.clickFolderMode) { case 2: // expand only expand = true; activate = false; break; case 3: // expand and activate activate = true; expand = true; //!node.isExpanded(); break; // else 1 or 4: just activate } } if (activate) { this.nodeSetFocus(ctx); this._callHook("nodeSetActive", ctx, true); } if (expand) { if (!activate) { // this._callHook("nodeSetFocus", ctx); } // this._callHook("nodeSetExpanded", ctx, true); this._callHook("nodeToggleExpanded", ctx); } } // Make sure that clicks stop, otherwise <a href='#'> jumps to the top // if(event.target.localName === "a" && event.target.className === "fancytree-title"){ // event.preventDefault(); // } // TODO: return promise? }, /** Collapse all other children of same parent. * * @param {EventData} ctx * @param {object} callOpts */ nodeCollapseSiblings: function(ctx, callOpts) { // TODO: return promise? var ac, i, l, node = ctx.node; if (node.parent) { ac = node.parent.children; for (i = 0, l = ac.length; i < l; i++) { if (ac[i] !== node && ac[i].expanded) { this._callHook( "nodeSetExpanded", ac[i], false, callOpts ); } } } }, /** Default handling for mouse douleclick events. * @param {EventData} ctx */ nodeDblclick: function(ctx) { // TODO: return promise? if ( ctx.targetType === "title" && ctx.options.clickFolderMode === 4 ) { // this.nodeSetFocus(ctx); // this._callHook("nodeSetActive", ctx, true); this._callHook("nodeToggleExpanded", ctx); } // TODO: prevent text selection on dblclicks if (ctx.targetType === "title") { ctx.originalEvent.preventDefault(); } }, /** Default handling for mouse keydown events. * * NOTE: this may be called with node == null if tree (but no node) has focus. * @param {EventData} ctx */ nodeKeydown: function(ctx) { // TODO: return promise? var matchNode, stamp, _res, focusNode, event = ctx.originalEvent, node = ctx.node, tree = ctx.tree, opts = ctx.options, which = event.which, // #909: Use event.key, to get unicode characters. // We can't use `/\w/.test(key)`, because that would // only detect plain ascii alpha-numerics. But we still need // to ignore modifier-only, whitespace, cursor-keys, etc. key = event.key || String.fromCharCode(which), specialModifiers = !!( event.altKey || event.ctrlKey || event.metaKey ), isAlnum = !MODIFIERS[which] && !SPECIAL_KEYCODES[which] && !specialModifiers, $target = $(event.target), handled = true, activate = !(event.ctrlKey || !opts.autoActivate); // (node || FT).debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which); // FT.debug( "eventToString(): " + FT.eventToString(event) + ", key='" + key + "', isAlnum: " + isAlnum ); // Set focus to active (or first node) if no other node has the focus yet if (!node) { focusNode = this.getActiveNode() || this.getFirstChild(); if (focusNode) { focusNode.setFocus(); node = ctx.node = this.focusNode; node.debug("Keydown force focus on active node"); } } if ( opts.quicksearch && isAlnum && !$target.is(":input:enabled") ) { // Allow to search for longer streaks if typed in quickly stamp = Date.now(); if (stamp - tree.lastQuicksearchTime > 500) { tree.lastQuicksearchTerm = ""; } tree.lastQuicksearchTime = stamp; tree.lastQuicksearchTerm += key; // tree.debug("quicksearch find", tree.lastQuicksearchTerm); matchNode = tree.findNextNode( tree.lastQuicksearchTerm, tree.getActiveNode() ); if (matchNode) { matchNode.setActive(); } event.preventDefault(); return; } switch (FT.eventToString(event)) { case "+": case "=": // 187: '+' @ Chrome, Safari tree.nodeSetExpanded(ctx, true); break; case "-": tree.nodeSetExpanded(ctx, false); break; case "space": if (node.isPagingNode()) { tree._triggerNodeEvent("clickPaging", ctx, event); } else if ( FT.evalOption("checkbox", node, node, opts, false) ) { // #768 tree.nodeToggleSelected(ctx); } else { tree.nodeSetActive(ctx, true); } break; case "return": tree.nodeSetActive(ctx, true); break; case "home": case "end": case "backspace": case "left": case "right": case "up": case "down": _res = node.navigate(event.which, activate); break; default: handled = false; } if (handled) { event.preventDefault(); } }, // /** Default handling for mouse keypress events. */ // nodeKeypress: function(ctx) { // var event = ctx.originalEvent; // }, // /** Trigger lazyLoad event (async). */ // nodeLazyLoad: function(ctx) { // var node = ctx.node; // if(this._triggerNodeEvent()) // }, /** Load child nodes (async). * * @param {EventData} ctx * @param {object[]|object|string|$.Promise|function} source * @returns {$.Promise} The deferred will be resolved as soon as the (ajax) * data was rendered. */ nodeLoadChildren: function(ctx, source) { var ajax, delay, dfd, res, tree = ctx.tree, node = ctx.node, requestId = Date.now(); if ($.isFunction(source)) { source = source.call(tree, { type: "source" }, ctx); _assert( !$.isFunction(source), "source callback must not return another function" ); } if (source.url) { if (node._requestId) { node.warn( "Recursive load request #" + requestId + " while #" + node._requestId + " is pending." ); // } else { // node.debug("Send load request #" + requestId); } // `source` is an Ajax options object ajax = $.extend({}, ctx.options.ajax, source); node._requestId = requestId; if (ajax.debugDelay) { // simulate a slow server delay = ajax.debugDelay; delete ajax.debugDelay; // remove debug option if ($.isArray(delay)) { // random delay range [min..max] delay = delay[0] + Math.random() * (delay[1] - delay[0]); } node.warn( "nodeLoadChildren waiting debugDelay " + Math.round(delay) + " ms ..." ); dfd = $.Deferred(function(dfd) { setTimeout(function() { $.ajax(ajax) .done(function() { dfd.resolveWith(this, arguments); }) .fail(function() { dfd.rejectWith(this, arguments); }); }, delay); }); } else { dfd = $.ajax(ajax); } // Defer the deferred: we want to be able to reject, even if ajax // resolved ok. source = new $.Deferred(); dfd.done(function(data, textStatus, jqXHR) { var errorObj, res; if ( (this.dataType === "json" || this.dataType === "jsonp") && typeof data === "string" ) { $.error( "Ajax request returned a string (did you get the JSON dataType wrong?)." ); } if (node._requestId && node._requestId > requestId) { // The expected request time stamp is later than `requestId` // (which was kept as as closure variable to this handler function) // node.warn("Ignored load response for obsolete request #" + requestId + " (expected #" + node._requestId + ")"); source.rejectWith(this, [RECURSIVE_REQUEST_ERROR]); return; // } else { // node.debug("Response returned for load request #" + requestId); } // postProcess is similar to the standard ajax dataFilter hook, // but it is also called for JSONP if (ctx.options.postProcess) { try { // The handler may either // - modify `ctx.response` in-place (and leave `ctx.result` undefined) // => res = undefined // - return a replacement in `ctx.result` // => res = <new data> // If res contains an `error` property, an error status is displayed res = tree._triggerNodeEvent( "postProcess", ctx, ctx.originalEvent, { response: data, error: null, dataType: this.dataType, } ); } catch (e) { res = { error: e, message: "" + e, details: "postProcess failed", }; } if (res.error) { errorObj = $.isPlainObject(res.error) ? res.error : { message: res.error }; errorObj = tree._makeHookContext( node, null, errorObj ); source.rejectWith(this, [errorObj]); return; } if ( $.isArray(res) || ($.isPlainObject(res) && $.isArray(res.children)) ) { // Use `ctx.result` if valid // (otherwise use existing data, which may have been modified in-place) data = res; } } else if ( data && data.hasOwnProperty("d") && ctx.options.enableAspx ) { // Process ASPX WebMethod JSON object inside "d" property data = typeof data.d === "string" ? $.parseJSON(data.d) : data.d; } source.resolveWith(this, [data]); }).fail(function(jqXHR, textStatus, errorThrown) { var errorObj = tree._makeHookContext(node, null, { error: jqXHR, args: Array.prototype.slice.call(arguments), message: errorThrown, details: jqXHR.status + ": " + errorThrown, }); source.rejectWith(this, [errorObj]); }); } // #383: accept and convert ECMAScript 6 Promise if ($.isFunction(source.then) && $.isFunction(source.catch)) { dfd = source; source = new $.Deferred(); dfd.then( function(value) { source.resolve(value); }, function(reason) { source.reject(reason); } ); } if ($.isFunction(source.promise)) { // `source` is a deferred, i.e. ajax request // _assert(!node.isLoading(), "recursive load"); tree.nodeSetStatus(ctx, "loading"); source .done(function(children) { tree.nodeSetStatus(ctx, "ok"); node._requestId = null; }) .fail(function(error) { var ctxErr; if (error === RECURSIVE_REQUEST_ERROR) { node.warn( "Ignored response for obsolete load request #" + requestId + " (expected #" + node._requestId + ")" ); return; } else if ( error.node && error.error && error.message ) { // error is already a context object ctxErr = error; } else { ctxErr = tree._makeHookContext(node, null, { error: error, // it can be jqXHR or any custom error args: Array.prototype.slice.call(arguments), message: error ? error.message || error.toString() : "", }); if (ctxErr.message === "[object Object]") { ctxErr.message = ""; } } node.warn( "Load children failed (" + ctxErr.message + ")", ctxErr ); if ( tree._triggerNodeEvent( "loadError", ctxErr, null ) !== false ) { tree.nodeSetStatus( ctx, "error", ctxErr.message, ctxErr.details ); } }); } else { if (ctx.options.postProcess) { // #792: Call postProcess for non-deferred source res = tree._triggerNodeEvent( "postProcess", ctx, ctx.originalEvent, { response: source, error: null, dataType: typeof source, } ); if ( $.isArray(res) || ($.isPlainObject(res) && $.isArray(res.children)) ) { // Use `ctx.result` if valid // (otherwise use existing data, which may have been modified in-place) source = res; } } } // $.when(source) resolves also for non-deferreds return $.when(source).done(function(children) { var metaData, noDataRes; if ($.isPlainObject(children)) { // We got {foo: 'abc', children: [...]} // Copy extra properties to tree.data.foo _assert( node.isRootNode(), "source may only be an object for root nodes (expecting an array of child objects otherwise)" ); _assert( $.isArray(children.children), "if an object is passed as source, it must contain a 'children' array (all other properties are added to 'tree.data')" ); metaData = children; children = children.children; delete metaData.children; // Copy some attributes to tree.data $.each(TREE_ATTRS, function(i, attr) { if (metaData[attr] !== undefined) { tree[attr] = metaData[attr]; delete metaData[attr]; } }); // Copy all other attributes to tree.data.NAME $.extend(tree.data, metaData); } _assert($.isArray(children), "expected array of children"); node._setChildren(children); if (tree.options.nodata && children.length === 0) { if ($.isFunction(tree.options.nodata)) { noDataRes = tree.options.nodata.call( tree, { type: "nodata" }, ctx ); } else if ( tree.options.nodata === true && node.isRootNode() ) { noDataRes = tree.options.strings.nodata; } else if ( typeof tree.options.nodata === "string" && node.isRootNode() ) { noDataRes = tree.options.nodata; } if (noDataRes) { node.setStatus("nodata", noDataRes); } } // trigger fancytreeloadchildren tree._triggerNodeEvent("loadChildren", node); }); }, /** [Not Implemented] */ nodeLoadKeyPath: function(ctx, keyPathList) { // TODO: implement and improve // http://code.google.com/p/dynatree/issues/detail?id=222 }, /** * Remove a single direct child of ctx.node. * @param {EventData} ctx * @param {FancytreeNode} childNode dircect child of ctx.node */ nodeRemoveChild: function(ctx, childNode) { var idx, node = ctx.node, // opts = ctx.options, subCtx = $.extend({}, ctx, { node: childNode }), children = node.children; // FT.debug("nodeRemoveChild()", node.toString(), childNode.toString()); if (children.length === 1) { _assert(childNode === children[0], "invalid single child"); return this.nodeRemoveChildren(ctx); } if ( this.activeNode && (childNode === this.activeNode || this.activeNode.isDescendantOf(childNode)) ) { this.activeNode.setActive(false); // TODO: don't fire events } if ( this.focusNode && (childNode === this.focusNode || this.focusNode.isDescendantOf(childNode)) ) { this.focusNode = null; } // TODO: persist must take care to clear select and expand cookies this.nodeRemoveMarkup(subCtx); this.nodeRemoveChildren(subCtx); idx = $.inArray(childNode, children); _assert(idx >= 0, "invalid child"); // Notify listeners node.triggerModifyChild("remove", childNode); // Unlink to support GC childNode.visit(function(n) { n.parent = null; }, true); this._callHook("treeRegisterNode", this, false, childNode); // remove from child list children.splice(idx, 1); }, /**Remove HTML markup for all descendents of ctx.node. * @param {EventData} ctx */ nodeRemoveChildMarkup: function(ctx) { var node = ctx.node; // FT.debug("nodeRemoveChildMarkup()", node.toString()); // TODO: Unlink attr.ftnode to support GC if (node.ul) { if (node.isRootNode()) { $(node.ul).empty(); } else { $(node.ul).remove(); node.ul = null; } node.visit(function(n) { n.li = n.ul = null; }); } }, /**Remove all descendants of ctx.node. * @param {EventData} ctx */ nodeRemoveChildren: function(ctx) { var //subCtx, tree = ctx.tree, node = ctx.node, children = node.children; // opts = ctx.options; // FT.debug("nodeRemoveChildren()", node.toString()); if (!children) { return; } if (this.activeNode && this.activeNode.isDescendantOf(node)) { this.activeNode.setActive(false); // TODO: don't fire events } if (this.focusNode && this.focusNode.isDescendantOf(node)) { this.focusNode = null; } // TODO: persist must take care to clear select and expand cookies this.nodeRemoveChildMarkup(ctx); // Unlink children to support GC // TODO: also delete this.children (not possible using visit()) // subCtx = $.extend({}, ctx); node.triggerModifyChild("remove", null); node.visit(function(n) { n.parent = null; tree._callHook("treeRegisterNode", tree, false, n); }); if (node.lazy) { // 'undefined' would be interpreted as 'not yet loaded' for lazy nodes node.children = []; } else { node.children = null; } if (!node.isRootNode()) { node.expanded = false; // #449, #459 } this.nodeRenderStatus(ctx); }, /**Remove HTML markup for ctx.node and all its descendents. * @param {EventData} ctx */ nodeRemoveMarkup: function(ctx) { var node = ctx.node; // FT.debug("nodeRemoveMarkup()", node.toString()); // TODO: Unlink attr.ftnode to support GC if (node.li) { $(node.li).remove(); node.li = null; } this.nodeRemoveChildMarkup(ctx); }, /** * Create `<li><span>..</span> .. </li>` tags for this node. * * This method takes care that all HTML markup is created that is required * to display this node in its current state. * * Call this method to create new nodes, or after the strucuture * was changed (e.g. after moving this node or adding/removing children) * nodeRenderTitle() and nodeRenderStatus() are implied. * * ```html * <li id='KEY' ftnode=NODE> * <span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'> * <span class="fancytree-expander"></span> * <span class="fancytree-checkbox"></span> // only present in checkbox mode * <span class="fancytree-icon"></span> * <a href="#" class="fancytree-title"> Node 1 </a> * </span> * <ul> // only present if node has children * <li id='KEY' ftnode=NODE> child1 ... </li> * <li id='KEY' ftnode=NODE> child2 ... </li> * </ul> * </li> * ``` * * @param {EventData} ctx * @param {boolean} [force=false] re-render, even if html markup was already created * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed * @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later */ nodeRender: function(ctx, force, deep, collapsed, _recursive) { /* This method must take care of all cases where the current data mode * (i.e. node hierarchy) does not match the current markup. * * - node was not yet rendered: * create markup * - node was rendered: exit fast * - children have been added * - children have been removed */ var childLI, childNode1, childNode2, i, l, next, subCtx, node = ctx.node, tree = ctx.tree, opts = ctx.options, aria = opts.aria, firstTime = false, parent = node.parent, isRootNode = !parent, children = node.children, successorLi = null; // FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString()); if (tree._enableUpdate === false) { // tree.debug("no render", tree._enableUpdate); return; } if (!isRootNode && !parent.ul) { // Calling node.collapse on a deep, unrendered node return; } _assert(isRootNode || parent.ul, "parent UL must exist"); // Render the node if (!isRootNode) { // Discard markup on force-mode, or if it is not linked to parent <ul> if ( node.li && (force || node.li.parentNode !== node.parent.ul) ) { if (node.li.parentNode === node.parent.ul) { // #486: store following node, so we can insert the new markup there later successorLi = node.li.nextSibling; } else { // May happen, when a top-level node was dropped over another this.debug( "Unlinking " + node + " (must be child of " + node.parent + ")" ); } // this.debug("nodeRemoveMarkup..."); this.nodeRemoveMarkup(ctx); } // Create <li><span /> </li> // node.debug("render..."); if (node.li) { // this.nodeRenderTitle(ctx); this.nodeRenderStatus(ctx); } else { // node.debug("render... really"); firstTime = true; node.li = document.createElement("li"); node.li.ftnode = node; if (node.key && opts.generateIds) { node.li.id = opts.idPrefix + node.key; } node.span = document.createElement("span"); node.span.className = "fancytree-node"; if (aria && !node.tr) { $(node.li).attr("role", "treeitem"); } node.li.appendChild(node.span); // Create inner HTML for the <span> (expander, checkbox, icon, and title) this.nodeRenderTitle(ctx); // Allow tweaking and binding, after node was created for the first time if (opts.createNode) { opts.createNode.call( tree, { type: "createNode" }, ctx ); } } // Allow tweaking after node state was rendered if (opts.renderNode) { opts.renderNode.call(tree, { type: "renderNode" }, ctx); } } // Visit child nodes if (children) { if (isRootNode || node.expanded || deep === true) { // Create a UL to hold the children if (!node.ul) { node.ul = document.createElement("ul"); if ( (collapsed === true && !_recursive) || !node.expanded ) { // hide top UL, so we can use an animation to show it later node.ul.style.display = "none"; } if (aria) { $(node.ul).attr("role", "group"); } if (node.li) { // issue #67 node.li.appendChild(node.ul); } else { node.tree.$div.append(node.ul); } } // Add child markup for (i = 0, l = children.length; i < l; i++) { subCtx = $.extend({}, ctx, { node: children[i] }); this.nodeRender(subCtx, force, deep, false, true); } // Remove <li> if nodes have moved to another parent childLI = node.ul.firstChild; while (childLI) { childNode2 = childLI.ftnode; if (childNode2 && childNode2.parent !== node) { node.debug( "_fixParent: remove missing " + childNode2, childLI ); next = childLI.nextSibling; childLI.parentNode.removeChild(childLI); childLI = next; } else { childLI = childLI.nextSibling; } } // Make sure, that <li> order matches node.children order. childLI = node.ul.firstChild; for (i = 0, l = children.length - 1; i < l; i++) { childNode1 = children[i]; childNode2 = childLI.ftnode; if (childNode1 === childNode2) { childLI = childLI.nextSibling; } else { // node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2); node.ul.insertBefore( childNode1.li, childNode2.li ); } } } } else { // No children: remove markup if any if (node.ul) { // alert("remove child markup for " + node); this.warn("remove child markup for " + node); this.nodeRemoveChildMarkup(ctx); } } if (!isRootNode) { // Update element classes according to node state // this.nodeRenderStatus(ctx); // Finally add the whole structure to the DOM, so the browser can render if (firstTime) { // #486: successorLi is set, if we re-rendered (i.e. discarded) // existing markup, which we want to insert at the same position. // (null is equivalent to append) // parent.ul.appendChild(node.li); parent.ul.insertBefore(node.li, successorLi); } } }, /** Create HTML inside the node's outer `<span>` (i.e. expander, checkbox, * icon, and title). * * nodeRenderStatus() is implied. * @param {EventData} ctx * @param {string} [title] optinal new title */ nodeRenderTitle: function(ctx, title) { // set node connector images, links and text var checkbox, className, icon, nodeTitle, role, tabindex, tooltip, iconTooltip, node = ctx.node, tree = ctx.tree, opts = ctx.options, aria = opts.aria, level = node.getLevel(), ares = []; if (title !== undefined) { node.title = title; } if (!node.span || tree._enableUpdate === false) { // Silently bail out if node was not rendered yet, assuming // node.render() will be called as the node becomes visible return; } // Connector (expanded, expandable or simple) role = aria && node.hasChildren() !== false ? " role='button'" : ""; if (level < opts.minExpandLevel) { if (!node.lazy) { node.expanded = true; } if (level > 1) { ares.push( "<span " + role + " class='fancytree-expander fancytree-expander-fixed'></span>" ); } // .. else (i.e. for root level) skip expander/connector alltogether } else { ares.push( "<span " + role + " class='fancytree-expander'></span>" ); } // Checkbox mode checkbox = FT.evalOption("checkbox", node, node, opts, false); if (checkbox && !node.isStatusNode()) { role = aria ? " role='checkbox'" : ""; className = "fancytree-checkbox"; if ( checkbox === "radio" || (node.parent && node.parent.radiogroup) ) { className += " fancytree-radio"; } ares.push( "<span " + role + " class='" + className + "'></span>" ); } // Folder or doctype icon if (node.data.iconClass !== undefined) { // 2015-11-16 // Handle / warn about backward compatibility if (node.icon) { $.error( "'iconClass' node option is deprecated since v2.14.0: use 'icon' only instead" ); } else { node.warn( "'iconClass' node option is deprecated since v2.14.0: use 'icon' instead" ); node.icon = node.data.iconClass; } } // If opts.icon is a callback and returns something other than undefined, use that // else if node.icon is a boolean or string, use that // else if opts.icon is a boolean or string, use that // else show standard icon (which may be different for folders or documents) icon = FT.evalOption("icon", node, node, opts, true); // if( typeof icon !== "boolean" ) { // // icon is defined, but not true/false: must be a string // icon = "" + icon; // } if (icon !== false) { role = aria ? " role='presentation'" : ""; iconTooltip = FT.evalOption( "iconTooltip", node, node, opts, null ); iconTooltip = iconTooltip ? " title='" + _escapeTooltip(iconTooltip) + "'" : ""; if (typeof icon === "string") { if (TEST_IMG.test(icon)) { // node.icon is an image url. Prepend imagePath icon = icon.charAt(0) === "/" ? icon : (opts.imagePath || "") + icon; ares.push( "<img src='" + icon + "' class='fancytree-icon'" + iconTooltip + " alt='' />" ); } else { ares.push( "<span " + role + " class='fancytree-custom-icon " + icon + "'" + iconTooltip + "></span>" ); } } else if (icon.text) { ares.push( "<span " + role + " class='fancytree-custom-icon " + (icon.addClass || "") + "'" + iconTooltip + ">" + FT.escapeHtml(icon.text) + "</span>" ); } else if (icon.html) { ares.push( "<span " + role + " class='fancytree-custom-icon " + (icon.addClass || "") + "'" + iconTooltip + ">" + icon.html + "</span>" ); } else { // standard icon: theme css will take care of this ares.push( "<span " + role + " class='fancytree-icon'" + iconTooltip + "></span>" ); } } // Node title nodeTitle = ""; if (opts.renderTitle) { nodeTitle = opts.renderTitle.call( tree, { type: "renderTitle" }, ctx ) || ""; } if (!nodeTitle) { tooltip = FT.evalOption("tooltip", node, node, opts, null); if (tooltip === true) { tooltip = node.title; } // if( node.tooltip ) { // tooltip = node.tooltip; // } else if ( opts.tooltip ) { // tooltip = opts.tooltip === true ? node.title : opts.tooltip.call(tree, node); // } tooltip = tooltip ? " title='" + _escapeTooltip(tooltip) + "'" : ""; tabindex = opts.titlesTabbable ? " tabindex='0'" : ""; nodeTitle = "<span class='fancytree-title'" + tooltip + tabindex + ">" + (opts.escapeTitles ? FT.escapeHtml(node.title) : node.title) + "</span>"; } ares.push(nodeTitle); // Note: this will trigger focusout, if node had the focus //$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly node.span.innerHTML = ares.join(""); // Update CSS classes this.nodeRenderStatus(ctx); if (opts.enhanceTitle) { ctx.$title = $(">span.fancytree-title", node.span); nodeTitle = opts.enhanceTitle.call( tree, { type: "enhanceTitle" }, ctx ) || ""; } }, /** Update element classes according to node state. * @param {EventData} ctx */ nodeRenderStatus: function(ctx) { // Set classes for current status var $ariaElem, node = ctx.node, tree = ctx.tree, opts = ctx.options, // nodeContainer = node[tree.nodeContainerAttrName], hasChildren = node.hasChildren(), isLastSib = node.isLastSibling(), aria = opts.aria, cn = opts._classNames, cnList = [], statusElem = node[tree.statusClassPropName]; if (!statusElem || tree._enableUpdate === false) { // if this function is called for an unrendered node, ignore it (will be updated on nect render anyway) return; } if (aria) { $ariaElem = $(node.tr || node.li); } // Build a list of class names that we will add to the node <span> cnList.push(cn.node); if (tree.activeNode === node) { cnList.push(cn.active); // $(">span.fancytree-title", statusElem).attr("tabindex", "0"); // tree.$container.removeAttr("tabindex"); // }else{ // $(">span.fancytree-title", statusElem).removeAttr("tabindex"); // tree.$container.attr("tabindex", "0"); } if (tree.focusNode === node) { cnList.push(cn.focused); } if (node.expanded) { cnList.push(cn.expanded); } if (aria) { if (hasChildren === false) { $ariaElem.removeAttr("aria-expanded"); } else { $ariaElem.attr("aria-expanded", Boolean(node.expanded)); } } if (node.folder) { cnList.push(cn.folder); } if (hasChildren !== false) { cnList.push(cn.hasChildren); } // TODO: required? if (isLastSib) { cnList.push(cn.lastsib); } if (node.lazy && node.children == null) { cnList.push(cn.lazy); } if (node.partload) { cnList.push(cn.partload); } if (node.partsel) { cnList.push(cn.partsel); } if (FT.evalOption("unselectable", node, node, opts, false)) { cnList.push(cn.unselectable); } if (node._isLoading) { cnList.push(cn.loading); } if (node._error) { cnList.push(cn.error); } if (node.statusNodeType) { cnList.push(cn.statusNodePrefix + node.statusNodeType); } if (node.selected) { cnList.push(cn.selected); if (aria) { $ariaElem.attr("aria-selected", true); } } else if (aria) { $ariaElem.attr("aria-selected", false); } if (node.extraClasses) { cnList.push(node.extraClasses); } // IE6 doesn't correctly evaluate multiple class names, // so we create combined class names that can be used in the CSS if (hasChildren === false) { cnList.push( cn.combinedExpanderPrefix + "n" + (isLastSib ? "l" : "") ); } else { cnList.push( cn.combinedExpanderPrefix + (node.expanded ? "e" : "c") + (node.lazy && node.children == null ? "d" : "") + (isLastSib ? "l" : "") ); } cnList.push( cn.combinedIconPrefix + (node.expanded ? "e" : "c") + (node.folder ? "f" : "") ); // node.span.className = cnList.join(" "); statusElem.className = cnList.join(" "); // TODO: we should not set this in the <span> tag also, if we set it here: // Maybe most (all) of the classes should be set in LI instead of SPAN? if (node.li) { // #719: we have to consider that there may be already other classes: $(node.li).toggleClass(cn.lastsib, isLastSib); } }, /** Activate node. * flag defaults to true. * If flag is true, the node is activated (must be a synchronous operation) * If flag is false, the node is deactivated (must be a synchronous operation) * @param {EventData} ctx * @param {boolean} [flag=true] * @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false} * @returns {$.Promise} */ nodeSetActive: function(ctx, flag, callOpts) { // Handle user click / [space] / [enter], according to clickFolderMode. callOpts = callOpts || {}; var subCtx, node = ctx.node, tree = ctx.tree, opts = ctx.options, noEvents = callOpts.noEvents === true, noFocus = callOpts.noFocus === true, scroll = callOpts.scrollIntoView !== false, isActive = node === tree.activeNode; // flag defaults to true flag = flag !== false; // node.debug("nodeSetActive", flag); if (isActive === flag) { // Nothing to do return _getResolvedPromise(node); } else if ( flag && !noEvents && this._triggerNodeEvent( "beforeActivate", node, ctx.originalEvent ) === false ) { // Callback returned false return _getRejectedPromise(node, ["rejected"]); } if (flag) { if (tree.activeNode) { _assert( tree.activeNode !== node, "node was active (inconsistency)" ); subCtx = $.extend({}, ctx, { node: tree.activeNode }); tree.nodeSetActive(subCtx, false); _assert( tree.activeNode === null, "deactivate was out of sync?" ); } if (opts.activeVisible) { // If no focus is set (noFocus: true) and there is no focused node, this node is made visible. // scroll = noFocus && tree.focusNode == null; // #863: scroll by default (unless `scrollIntoView: false` was passed) node.makeVisible({ scrollIntoView: scroll }); } tree.activeNode = node; tree.nodeRenderStatus(ctx); if (!noFocus) { tree.nodeSetFocus(ctx); } if (!noEvents) { tree._triggerNodeEvent( "activate", node, ctx.originalEvent ); } } else { _assert( tree.activeNode === node, "node was not active (inconsistency)" ); tree.activeNode = null; this.nodeRenderStatus(ctx); if (!noEvents) { ctx.tree._triggerNodeEvent( "deactivate", node, ctx.originalEvent ); } } return _getResolvedPromise(node); }, /** Expand or collapse node, return Deferred.promise. * * @param {EventData} ctx * @param {boolean} [flag=true] * @param {object} [opts] additional options. Defaults to `{noAnimation: false, noEvents: false}` * @returns {$.Promise} The deferred will be resolved as soon as the (lazy) * data was retrieved, rendered, and the expand animation finished. */ nodeSetExpanded: function(ctx, flag, callOpts) { callOpts = callOpts || {}; var _afterLoad, dfd, i, l, parents, prevAC, node = ctx.node, tree = ctx.tree, opts = ctx.options, noAnimation = callOpts.noAnimation === true, noEvents = callOpts.noEvents === true; // flag defaults to true flag = flag !== false; // node.debug("nodeSetExpanded(" + flag + ")"); if ((node.expanded && flag) || (!node.expanded && !flag)) { // Nothing to do // node.debug("nodeSetExpanded(" + flag + "): nothing to do"); return _getResolvedPromise(node); } else if (flag && !node.lazy && !node.hasChildren()) { // Prevent expanding of empty nodes // return _getRejectedPromise(node, ["empty"]); return _getResolvedPromise(node); } else if (!flag && node.getLevel() < opts.minExpandLevel) { // Prevent collapsing locked levels return _getRejectedPromise(node, ["locked"]); } else if ( !noEvents && this._triggerNodeEvent( "beforeExpand", node, ctx.originalEvent ) === false ) { // Callback returned false return _getRejectedPromise(node, ["rejected"]); } // If this node inside a collpased node, no animation and scrolling is needed if (!noAnimation && !node.isVisible()) { noAnimation = callOpts.noAnimation = true; } dfd = new $.Deferred(); // Auto-collapse mode: collapse all siblings if (flag && !node.expanded && opts.autoCollapse) { parents = node.getParentList(false, true); prevAC = opts.autoCollapse; try { opts.autoCollapse = false; for (i = 0, l = parents.length; i < l; i++) { // TODO: should return promise? this._callHook( "nodeCollapseSiblings", parents[i], callOpts ); } } finally { opts.autoCollapse = prevAC; } } // Trigger expand/collapse after expanding dfd.done(function() { var lastChild = node.getLastChild(); if ( flag && opts.autoScroll && !noAnimation && lastChild && tree._enableUpdate ) { // Scroll down to last child, but keep current node visible lastChild .scrollIntoView(true, { topNode: node }) .always(function() { if (!noEvents) { ctx.tree._triggerNodeEvent( flag ? "expand" : "collapse", ctx ); } }); } else { if (!noEvents) { ctx.tree._triggerNodeEvent( flag ? "expand" : "collapse", ctx ); } } }); // vvv Code below is executed after loading finished: _afterLoad = function(callback) { var cn = opts._classNames, isVisible, isExpanded, effect = opts.toggleEffect; node.expanded = flag; tree._callHook( "treeStructureChanged", ctx, flag ? "expand" : "collapse" ); // Create required markup, but make sure the top UL is hidden, so we // can animate later tree._callHook("nodeRender", ctx, false, false, true); // Hide children, if node is collapsed if (node.ul) { isVisible = node.ul.style.display !== "none"; isExpanded = !!node.expanded; if (isVisible === isExpanded) { node.warn( "nodeSetExpanded: UL.style.display already set" ); } else if (!effect || noAnimation) { node.ul.style.display = node.expanded || !parent ? "" : "none"; } else { // The UI toggle() effect works with the ext-wide extension, // while jQuery.animate() has problems when the title span // has position: absolute. // Since jQuery UI 1.12, the blind effect requires the parent // element to have 'position: relative'. // See #716, #717 $(node.li).addClass(cn.animating); // #717 if ($.isFunction($(node.ul)[effect.effect])) { // tree.debug( "use jquery." + effect.effect + " method" ); $(node.ul)[effect.effect]({ duration: effect.duration, always: function() { // node.debug("fancytree-animating end: " + node.li.className); $(this).removeClass(cn.animating); // #716 $(node.li).removeClass(cn.animating); // #717 callback(); }, }); } else { // The UI toggle() effect works with the ext-wide extension, // while jQuery.animate() has problems when the title span // has positon: absolute. // Since jQuery UI 1.12, the blind effect requires the parent // element to have 'position: relative'. // See #716, #717 // tree.debug("use specified effect (" + effect.effect + ") with the jqueryui.toggle method"); // try to stop an animation that might be already in progress $(node.ul).stop(true, true); //< does not work after resetLazy has been called for a node whose animation wasn't complete and effect was "blind" // dirty fix to remove a defunct animation (effect: "blind") after resetLazy has been called $(node.ul) .parent() .find(".ui-effects-placeholder") .remove(); $(node.ul).toggle( effect.effect, effect.options, effect.duration, function() { // node.debug("fancytree-animating end: " + node.li.className); $(this).removeClass(cn.animating); // #716 $(node.li).removeClass(cn.animating); // #717 callback(); } ); } return; } } callback(); }; // ^^^ Code above is executed after loading finshed. // Load lazy nodes, if any. Then continue with _afterLoad() if (flag && node.lazy && node.hasChildren() === undefined) { // node.debug("nodeSetExpanded: load start..."); node.load() .done(function() { // node.debug("nodeSetExpanded: load done"); if (dfd.notifyWith) { // requires jQuery 1.6+ dfd.notifyWith(node, ["loaded"]); } _afterLoad(function() { dfd.resolveWith(node); }); }) .fail(function(errMsg) { _afterLoad(function() { dfd.rejectWith(node, [ "load failed (" + errMsg + ")", ]); }); }); /* var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent); _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result"); node.debug("nodeSetExpanded: load start..."); this._callHook("nodeLoadChildren", ctx, source).done(function(){ node.debug("nodeSetExpanded: load done"); if(dfd.notifyWith){ // requires jQuery 1.6+ dfd.notifyWith(node, ["loaded"]); } _afterLoad.call(tree); }).fail(function(errMsg){ dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); }); */ } else { _afterLoad(function() { dfd.resolveWith(node); }); } // node.debug("nodeSetExpanded: returns"); return dfd.promise(); }, /** Focus or blur this node. * @param {EventData} ctx * @param {boolean} [flag=true] */ nodeSetFocus: function(ctx, flag) { // ctx.node.debug("nodeSetFocus(" + flag + ")"); var ctx2, tree = ctx.tree, node = ctx.node, opts = tree.options, // et = ctx.originalEvent && ctx.originalEvent.type, isInput = ctx.originalEvent ? $(ctx.originalEvent.target).is(":input") : false; flag = flag !== false; // (node || tree).debug("nodeSetFocus(" + flag + "), event: " + et + ", isInput: "+ isInput); // Blur previous node if any if (tree.focusNode) { if (tree.focusNode === node && flag) { // node.debug("nodeSetFocus(" + flag + "): nothing to do"); return; } ctx2 = $.extend({}, ctx, { node: tree.focusNode }); tree.focusNode = null; this._triggerNodeEvent("blur", ctx2); this._callHook("nodeRenderStatus", ctx2); } // Set focus to container and node if (flag) { if (!this.hasFocus()) { node.debug("nodeSetFocus: forcing container focus"); this._callHook("treeSetFocus", ctx, true, { calledByNode: true, }); } node.makeVisible({ scrollIntoView: false }); tree.focusNode = node; if (opts.titlesTabbable) { if (!isInput) { // #621 $(node.span) .find(".fancytree-title") .focus(); } } if (opts.aria) { // Set active descendant to node's span ID (create one, if needed) $(tree.$container).attr( "aria-activedescendant", $(node.tr || node.li) .uniqueId() .attr("id") ); // "ftal_" + opts.idPrefix + node.key); } // $(node.span).find(".fancytree-title").focus(); this._triggerNodeEvent("focus", ctx); // determine if we have focus on or inside tree container var hasFancytreeFocus = document.activeElement === tree.$container.get(0) || $(document.activeElement, tree.$container).length >= 1; if (!hasFancytreeFocus) { // We cannot set KB focus to a node, so use the tree container // #563, #570: IE scrolls on every call to .focus(), if the container // is partially outside the viewport. So do it only, when absolutely // necessary. $(tree.$container).focus(); } // if( opts.autoActivate ){ // tree.nodeSetActive(ctx, true); // } if (opts.autoScroll) { node.scrollIntoView(); } this._callHook("nodeRenderStatus", ctx); } }, /** (De)Select node, return new status (sync). * * @param {EventData} ctx * @param {boolean} [flag=true] * @param {object} [opts] additional options. Defaults to {noEvents: false, * propagateDown: null, propagateUp: null, * callback: null, * } * @returns {boolean} previous status */ nodeSetSelected: function(ctx, flag, callOpts) { callOpts = callOpts || {}; var node = ctx.node, tree = ctx.tree, opts = ctx.options, noEvents = callOpts.noEvents === true, parent = node.parent; // flag defaults to true flag = flag !== false; // node.debug("nodeSetSelected(" + flag + ")", ctx); // Cannot (de)select unselectable nodes directly (only by propagation or // by setting the `.selected` property) if (FT.evalOption("unselectable", node, node, opts, false)) { return; } // Remember the user's intent, in case down -> up propagation prevents // applying it to node.selected node._lastSelectIntent = flag; // Confusing use of '!' // Nothing to do? if (!!node.selected === flag) { if (opts.selectMode === 3 && node.partsel && !flag) { // If propagation prevented selecting this node last time, we still // want to allow to apply setSelected(false) now } else { return flag; } } if ( !noEvents && this._triggerNodeEvent( "beforeSelect", node, ctx.originalEvent ) === false ) { return !!node.selected; } if (flag && opts.selectMode === 1) { // single selection mode (we don't uncheck all tree nodes, for performance reasons) if (tree.lastSelectedNode) { tree.lastSelectedNode.setSelected(false); } node.selected = flag; } else if ( opts.selectMode === 3 && parent && !parent.radiogroup && !node.radiogroup ) { // multi-hierarchical selection mode node.selected = flag; node.fixSelection3AfterClick(callOpts); } else if (parent && parent.radiogroup) { node.visitSiblings(function(n) { n._changeSelectStatusAttrs(flag && n === node); }, true); } else { // default: selectMode: 2, multi selection mode node.selected = flag; } this.nodeRenderStatus(ctx); tree.lastSelectedNode = flag ? node : null; if (!noEvents) { tree._triggerNodeEvent("select", ctx); } }, /** Show node status (ok, loading, error, nodata) using styles and a dummy child node. * * @param {EventData} ctx * @param status * @param message * @param details * @since 2.3 */ nodeSetStatus: function(ctx, status, message, details) { var node = ctx.node, tree = ctx.tree; function _clearStatusNode() { // Remove dedicated dummy node, if any var firstChild = node.children ? node.children[0] : null; if (firstChild && firstChild.isStatusNode()) { try { // I've seen exceptions here with loadKeyPath... if (node.ul) { node.ul.removeChild(firstChild.li); firstChild.li = null; // avoid leaks (DT issue 215) } } catch (e) {} if (node.children.length === 1) { node.children = []; } else { node.children.shift(); } tree._callHook( "treeStructureChanged", ctx, "clearStatusNode" ); } } function _setStatusNode(data, type) { // Create/modify the dedicated dummy node for 'loading...' or // 'error!' status. (only called for direct child of the invisible // system root) var firstChild = node.children ? node.children[0] : null; if (firstChild && firstChild.isStatusNode()) { $.extend(firstChild, data); firstChild.statusNodeType = type; tree._callHook("nodeRenderTitle", firstChild); } else { node._setChildren([data]); tree._callHook( "treeStructureChanged", ctx, "setStatusNode" ); node.children[0].statusNodeType = type; tree.render(); } return node.children[0]; } switch (status) { case "ok": _clearStatusNode(); node._isLoading = false; node._error = null; node.renderStatus(); break; case "loading": if (!node.parent) { _setStatusNode( { title: tree.options.strings.loading + (message ? " (" + message + ")" : ""), // icon: true, // needed for 'loding' icon checkbox: false, tooltip: details, }, status ); } node._isLoading = true; node._error = null; node.renderStatus(); break; case "error": _setStatusNode( { title: tree.options.strings.loadError + (message ? " (" + message + ")" : ""), // icon: false, checkbox: false, tooltip: details, }, status ); node._isLoading = false; node._error = { message: message, details: details }; node.renderStatus(); break; case "nodata": _setStatusNode( { title: message || tree.options.strings.noData, // icon: false, checkbox: false, tooltip: details, }, status ); node._isLoading = false; node._error = null; node.renderStatus(); break; default: $.error("invalid node status " + status); } }, /** * * @param {EventData} ctx */ nodeToggleExpanded: function(ctx) { return this.nodeSetExpanded(ctx, !ctx.node.expanded); }, /** * @param {EventData} ctx */ nodeToggleSelected: function(ctx) { var node = ctx.node, flag = !node.selected; // In selectMode: 3 this node may be unselected+partsel, even if // setSelected(true) was called before, due to `unselectable` children. // In this case, we now toggle as `setSelected(false)` if ( node.partsel && !node.selected && node._lastSelectIntent === true ) { flag = false; node.selected = true; // so it is not considered 'nothing to do' } node._lastSelectIntent = flag; return this.nodeSetSelected(ctx, flag); }, /** Remove all nodes. * @param {EventData} ctx */ treeClear: function(ctx) { var tree = ctx.tree; tree.activeNode = null; tree.focusNode = null; tree.$div.find(">ul.fancytree-container").empty(); // TODO: call destructors and remove reference loops tree.rootNode.children = null; tree._callHook("treeStructureChanged", ctx, "clear"); }, /** Widget was created (called only once, even it re-initialized). * @param {EventData} ctx */ treeCreate: function(ctx) {}, /** Widget was destroyed. * @param {EventData} ctx */ treeDestroy: function(ctx) { this.$div.find(">ul.fancytree-container").remove(); if (this.$source) { this.$source.removeClass("fancytree-helper-hidden"); } }, /** Widget was (re-)initialized. * @param {EventData} ctx */ treeInit: function(ctx) { var tree = ctx.tree, opts = tree.options; //this.debug("Fancytree.treeInit()"); // Add container to the TAB chain // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant // #577: Allow to set tabindex to "0", "-1" and "" tree.$container.attr("tabindex", opts.tabindex); // Copy some attributes to tree.data $.each(TREE_ATTRS, function(i, attr) { if (opts[attr] !== undefined) { tree.info("Move option " + attr + " to tree"); tree[attr] = opts[attr]; delete opts[attr]; } }); if (opts.checkboxAutoHide) { tree.$container.addClass("fancytree-checkbox-auto-hide"); } if (opts.rtl) { tree.$container .attr("DIR", "RTL") .addClass("fancytree-rtl"); } else { tree.$container .removeAttr("DIR") .removeClass("fancytree-rtl"); } if (opts.aria) { tree.$container.attr("role", "tree"); if (opts.selectMode !== 1) { tree.$container.attr("aria-multiselectable", true); } } this.treeLoad(ctx); }, /** Parse Fancytree from source, as configured in the options. * @param {EventData} ctx * @param {object} [source] optional new source (use last data otherwise) */ treeLoad: function(ctx, source) { var metaData, type, $ul, tree = ctx.tree, $container = ctx.widget.element, dfd, // calling context for root node rootCtx = $.extend({}, ctx, { node: this.rootNode }); if (tree.rootNode.children) { this.treeClear(ctx); } source = source || this.options.source; if (!source) { type = $container.data("type") || "html"; switch (type) { case "html": // There should be an embedded `<ul>` with initial nodes, // but another `<ul class='fancytree-container'>` is appended // to the tree's <div> on startup anyway. $ul = $container .find(">ul") .not(".fancytree-container") .first(); if ($ul.length) { $ul.addClass( "ui-fancytree-source fancytree-helper-hidden" ); source = $.ui.fancytree.parseHtml($ul); // allow to init tree.data.foo from <ul data-foo=''> this.data = $.extend( this.data, _getElementDataAsDict($ul) ); } else { FT.warn( "No `source` option was passed and container does not contain `<ul>`: assuming `source: []`." ); source = []; } break; case "json": source = $.parseJSON($container.text()); // $container already contains the <ul>, but we remove the plain (json) text // $container.empty(); $container .contents() .filter(function() { return this.nodeType === 3; }) .remove(); if ($.isPlainObject(source)) { // We got {foo: 'abc', children: [...]} _assert( $.isArray(source.children), "if an object is passed as source, it must contain a 'children' array (all other properties are added to 'tree.data')" ); metaData = source; source = source.children; delete metaData.children; // Copy some attributes to tree.data $.each(TREE_ATTRS, function(i, attr) { if (metaData[attr] !== undefined) { tree[attr] = metaData[attr]; delete metaData[attr]; } }); // Copy extra properties to tree.data.foo $.extend(tree.data, metaData); } break; default: $.error("Invalid data-type: " + type); } } else if (typeof source === "string") { // TODO: source is an element ID $.error("Not implemented"); } // preInit is fired when the widget markup is created, but nodes // not yet loaded tree._triggerTreeEvent("preInit", null); // Trigger fancytreeinit after nodes have been loaded dfd = this.nodeLoadChildren(rootCtx, source) .done(function() { tree._callHook( "treeStructureChanged", ctx, "loadChildren" ); tree.render(); if (ctx.options.selectMode === 3) { tree.rootNode.fixSelection3FromEndNodes(); } if (tree.activeNode && tree.options.activeVisible) { tree.activeNode.makeVisible(); } tree._triggerTreeEvent("init", null, { status: true }); }) .fail(function() { tree.render(); tree._triggerTreeEvent("init", null, { status: false }); }); return dfd; }, /** Node was inserted into or removed from the tree. * @param {EventData} ctx * @param {boolean} add * @param {FancytreeNode} node */ treeRegisterNode: function(ctx, add, node) { ctx.tree._callHook( "treeStructureChanged", ctx, add ? "addNode" : "removeNode" ); }, /** Widget got focus. * @param {EventData} ctx * @param {boolean} [flag=true] */ treeSetFocus: function(ctx, flag, callOpts) { var targetNode; flag = flag !== false; // this.debug("treeSetFocus(" + flag + "), callOpts: ", callOpts, this.hasFocus()); // this.debug(" focusNode: " + this.focusNode); // this.debug(" activeNode: " + this.activeNode); if (flag !== this.hasFocus()) { this._hasFocus = flag; if (!flag && this.focusNode) { // Node also looses focus if widget blurs this.focusNode.setFocus(false); } else if (flag && (!callOpts || !callOpts.calledByNode)) { $(this.$container).focus(); } this.$container.toggleClass("fancytree-treefocus", flag); this._triggerTreeEvent(flag ? "focusTree" : "blurTree"); if (flag && !this.activeNode) { // #712: Use last mousedowned node ('click' event fires after focusin) targetNode = this._lastMousedownNode || this.getFirstChild(); if (targetNode) { targetNode.setFocus(); } } } }, /** Widget option was set using `$().fancytree("option", "KEY", VALUE)`. * * Note: `key` may reference a nested option, e.g. 'dnd5.scroll'. * In this case `value`contains the complete, modified `dnd5` option hash. * We can check for changed values like * if( value.scroll !== tree.options.dnd5.scroll ) {...} * * @param {EventData} ctx * @param {string} key option name * @param {any} value option value */ treeSetOption: function(ctx, key, value) { var tree = ctx.tree, callDefault = true, callCreate = false, callRender = false; switch (key) { case "aria": case "checkbox": case "icon": case "minExpandLevel": case "tabindex": // tree._callHook("treeCreate", tree); callCreate = true; callRender = true; break; case "checkboxAutoHide": tree.$container.toggleClass( "fancytree-checkbox-auto-hide", !!value ); break; case "escapeTitles": case "tooltip": callRender = true; break; case "rtl": if (value === false) { tree.$container .removeAttr("DIR") .removeClass("fancytree-rtl"); } else { tree.$container .attr("DIR", "RTL") .addClass("fancytree-rtl"); } callRender = true; break; case "source": callDefault = false; tree._callHook("treeLoad", tree, value); callRender = true; break; } tree.debug( "set option " + key + "=" + value + " <" + typeof value + ">" ); if (callDefault) { if (this.widget._super) { // jQuery UI 1.9+ this.widget._super.call(this.widget, key, value); } else { // jQuery UI <= 1.8, we have to manually invoke the _setOption method from the base widget $.Widget.prototype._setOption.call( this.widget, key, value ); } } if (callCreate) { tree._callHook("treeCreate", tree); } if (callRender) { tree.render(true, false); // force, not-deep } }, /** A Node was added, removed, moved, or it's visibility changed. * @param {EventData} ctx */ treeStructureChanged: function(ctx, type) {}, } ); /******************************************************************************* * jQuery UI widget boilerplate */ /** * The plugin (derrived from [jQuery.Widget](http://api.jqueryui.com/jQuery.widget/)). * * **Note:** * These methods implement the standard jQuery UI widget API. * It is recommended to use methods of the {Fancytree} instance instead * * @example * // DEPRECATED: Access jQuery UI widget methods and members: * var tree = $("#tree").fancytree("getTree", "#myTree"); * var node = $.ui.fancytree.getTree("#tree").getActiveNode(); * * // RECOMMENDED: Use the Fancytree object API * var tree = $.ui.fancytree.getTree("#myTree"); * var node = tree.getActiveNode(); * * // or you may already have stored the tree instance upon creation: * import {createTree, version} from 'jquery.fancytree' * const tree = createTree('#tree', { ... }); * var node = tree.getActiveNode(); * * @see {Fancytree_Static#getTree} * @deprecated Use methods of the {Fancytree} instance instead * @mixin Fancytree_Widget */ $.widget( "ui.fancytree", /** @lends Fancytree_Widget# */ { /**These options will be used as defaults * @type {FancytreeOptions} */ options: { activeVisible: true, ajax: { type: "GET", cache: false, // false: Append random '_' argument to the request url to prevent caching. // timeout: 0, // >0: Make sure we get an ajax error if server is unreachable dataType: "json", // Expect json format and pass json object to callbacks. }, aria: true, autoActivate: true, autoCollapse: false, autoScroll: false, checkbox: false, clickFolderMode: 4, debugLevel: null, // 0..4 (null: use global setting $.ui.fancytree.debugLevel) disabled: false, // TODO: required anymore? enableAspx: true, escapeTitles: false, extensions: [], // fx: { height: "toggle", duration: 200 }, // toggleEffect: { effect: "drop", options: {direction: "left"}, duration: 200 }, // toggleEffect: { effect: "slide", options: {direction: "up"}, duration: 200 }, //toggleEffect: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 }, toggleEffect: { effect: "slideToggle", duration: 200 }, //< "toggle" or "slideToggle" to use jQuery instead of jQueryUI for toggleEffect animation generateIds: false, icon: true, idPrefix: "ft_", focusOnSelect: false, keyboard: true, keyPathSeparator: "/", minExpandLevel: 1, nodata: true, // (bool, string, or callback) display message, when no data available quicksearch: false, rtl: false, scrollOfs: { top: 0, bottom: 0 }, scrollParent: null, selectMode: 2, strings: { loading: "Loading...", // &#8230; would be escaped when escapeTitles is true loadError: "Load error!", moreData: "More...", noData: "No data.", }, tabindex: "0", titlesTabbable: false, tooltip: false, treeId: null, _classNames: { node: "fancytree-node", folder: "fancytree-folder", animating: "fancytree-animating", combinedExpanderPrefix: "fancytree-exp-", combinedIconPrefix: "fancytree-ico-", hasChildren: "fancytree-has-children", active: "fancytree-active", selected: "fancytree-selected", expanded: "fancytree-expanded", lazy: "fancytree-lazy", focused: "fancytree-focused", partload: "fancytree-partload", partsel: "fancytree-partsel", radio: "fancytree-radio", // radiogroup: "fancytree-radiogroup", unselectable: "fancytree-unselectable", lastsib: "fancytree-lastsib", loading: "fancytree-loading", error: "fancytree-error", statusNodePrefix: "fancytree-statusnode-", }, // events lazyLoad: null, postProcess: null, }, _deprecationWarning: function(name) { var tree = this.tree; if (tree && tree.options.debugLevel >= 3) { tree.warn( "$().fancytree('" + name + "') is deprecated (see https://wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree_Widget.html" ); } }, /* Set up the widget, Called on first $().fancytree() */ _create: function() { this.tree = new Fancytree(this); this.$source = this.source || this.element.data("type") === "json" ? this.element : this.element.find(">ul").first(); // Subclass Fancytree instance with all enabled extensions var extension, extName, i, opts = this.options, extensions = opts.extensions, base = this.tree; for (i = 0; i < extensions.length; i++) { extName = extensions[i]; extension = $.ui.fancytree._extensions[extName]; if (!extension) { $.error( "Could not apply extension '" + extName + "' (it is not registered, did you forget to include it?)" ); } // Add extension options as tree.options.EXTENSION // _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName); // console.info("extend " + extName, extension.options, this.tree.options[extName]) // issue #876: we want to replace custom array-options, not merge them this.tree.options[extName] = _simpleDeepMerge( {}, extension.options, this.tree.options[extName] ); // this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]); // console.info("extend " + extName + " =>", this.tree.options[extName]) // console.info("extend " + extName + " org default =>", extension.options) // Add a namespace tree.ext.EXTENSION, to hold instance data _assert( this.tree.ext[extName] === undefined, "Extension name must not exist as Fancytree.ext attribute: '" + extName + "'" ); // this.tree[extName] = extension; this.tree.ext[extName] = {}; // Subclass Fancytree methods using proxies. _subclassObject(this.tree, base, extension, extName); // current extension becomes base for the next extension base = extension; } // if (opts.icons !== undefined) { // 2015-11-16 if (opts.icon === true) { this.tree.warn( "'icons' tree option is deprecated since v2.14.0: use 'icon' instead" ); opts.icon = opts.icons; } else { $.error( "'icons' tree option is deprecated since v2.14.0: use 'icon' only instead" ); } } if (opts.iconClass !== undefined) { // 2015-11-16 if (opts.icon) { $.error( "'iconClass' tree option is deprecated since v2.14.0: use 'icon' only instead" ); } else { this.tree.warn( "'iconClass' tree option is deprecated since v2.14.0: use 'icon' instead" ); opts.icon = opts.iconClass; } } if (opts.tabbable !== undefined) { // 2016-04-04 opts.tabindex = opts.tabbable ? "0" : "-1"; this.tree.warn( "'tabbable' tree option is deprecated since v2.17.0: use 'tabindex='" + opts.tabindex + "' instead" ); } // this.tree._callHook("treeCreate", this.tree); // Note: 'fancytreecreate' event is fired by widget base class // this.tree._triggerTreeEvent("create"); }, /* Called on every $().fancytree() */ _init: function() { this.tree._callHook("treeInit", this.tree); // TODO: currently we call bind after treeInit, because treeInit // might change tree.$container. // It would be better, to move event binding into hooks altogether this._bind(); }, /* Use the _setOption method to respond to changes to options. */ _setOption: function(key, value) { return this.tree._callHook( "treeSetOption", this.tree, key, value ); }, /** Use the destroy method to clean up any modifications your widget has made to the DOM */ _destroy: function() { this._unbind(); this.tree._callHook("treeDestroy", this.tree); // In jQuery UI 1.8, you must invoke the destroy method from the base widget // $.Widget.prototype.destroy.call(this); // TODO: delete tree and nodes to make garbage collect easier? // TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method }, // ------------------------------------------------------------------------- /* Remove all event handlers for our namespace */ _unbind: function() { var ns = this.tree._ns; this.element.off(ns); this.tree.$container.off(ns); $(document).off(ns); }, /* Add mouse and kyboard handlers to the container */ _bind: function() { var self = this, opts = this.options, tree = this.tree, ns = tree._ns; // selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" ) // Remove all previuous handlers for this tree this._unbind(); //alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container); // tree.debug("bind events; container: ", tree.$container); tree.$container .on("focusin" + ns + " focusout" + ns, function(event) { var node = FT.getNode(event), flag = event.type === "focusin"; if (!flag && node && $(event.target).is("a")) { // #764 node.debug( "Ignored focusout on embedded <a> element." ); return; } // tree.treeOnFocusInOut.call(tree, event); // tree.debug("Tree container got event " + event.type, node, event, FT.getEventTarget(event)); if (flag) { if (tree._getExpiringValue("focusin")) { // #789: IE 11 may send duplicate focusin events tree.debug("Ignored double focusin."); return; } tree._setExpiringValue("focusin", true, 50); if (!node) { // #789: IE 11 may send focusin before mousdown(?) node = tree._getExpiringValue("mouseDownNode"); if (node) { tree.debug( "Reconstruct mouse target for focusin from recent event." ); } } } if (node) { // For example clicking into an <input> that is part of a node tree._callHook( "nodeSetFocus", tree._makeHookContext(node, event), flag ); } else { if ( tree.tbody && $(event.target).parents( "table.fancytree-container > thead" ).length ) { // #767: ignore events in the table's header tree.debug( "Ignore focus event outside table body.", event ); } else { tree._callHook("treeSetFocus", tree, flag); } } }) .on("selectstart" + ns, "span.fancytree-title", function( event ) { // prevent mouse-drags to select text ranges // tree.debug("<span title> got event " + event.type); event.preventDefault(); }) .on("keydown" + ns, function(event) { // TODO: also bind keyup and keypress // tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus()); // if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){ if (opts.disabled || opts.keyboard === false) { return true; } var res, node = tree.focusNode, // node may be null ctx = tree._makeHookContext(node || tree, event), prevPhase = tree.phase; try { tree.phase = "userEvent"; // If a 'fancytreekeydown' handler returns false, skip the default // handling (implemented by tree.nodeKeydown()). if (node) { res = tree._triggerNodeEvent( "keydown", node, event ); } else { res = tree._triggerTreeEvent("keydown", event); } if (res === "preventNav") { res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls } else if (res !== false) { res = tree._callHook("nodeKeydown", ctx); } return res; } finally { tree.phase = prevPhase; } }) .on("mousedown" + ns, function(event) { var et = FT.getEventTarget(event); // self.tree.debug("event(" + event.type + "): node: ", et.node); // #712: Store the clicked node, so we can use it when we get a focusin event // ('click' event fires after focusin) // tree.debug("event(" + event.type + "): node: ", et.node); tree._lastMousedownNode = et ? et.node : null; // #789: Store the node also for a short period, so we can use it // in a *resulting* focusin event tree._setExpiringValue( "mouseDownNode", tree._lastMousedownNode ); }) .on("click" + ns + " dblclick" + ns, function(event) { if (opts.disabled) { return true; } var ctx, et = FT.getEventTarget(event), node = et.node, tree = self.tree, prevPhase = tree.phase; // self.tree.debug("event(" + event.type + "): node: ", node); if (!node) { return true; // Allow bubbling of other events } ctx = tree._makeHookContext(node, event); // self.tree.debug("event(" + event.type + "): node: ", node); try { tree.phase = "userEvent"; switch (event.type) { case "click": ctx.targetType = et.type; if (node.isPagingNode()) { return ( tree._triggerNodeEvent( "clickPaging", ctx, event ) === true ); } return tree._triggerNodeEvent( "click", ctx, event ) === false ? false : tree._callHook("nodeClick", ctx); case "dblclick": ctx.targetType = et.type; return tree._triggerNodeEvent( "dblclick", ctx, event ) === false ? false : tree._callHook("nodeDblclick", ctx); } } finally { tree.phase = prevPhase; } }); }, /** Return the active node or null. * @returns {FancytreeNode} * @deprecated Use methods of the Fancytree instance instead (<a href="Fancytree_Widget.html">example above</a>). */ getActiveNode: function() { this._deprecationWarning("getActiveNode"); return this.tree.activeNode; }, /** Return the matching node or null. * @param {string} key * @returns {FancytreeNode} * @deprecated Use methods of the Fancytree instance instead (<a href="Fancytree_Widget.html">example above</a>). */ getNodeByKey: function(key) { this._deprecationWarning("getNodeByKey"); return this.tree.getNodeByKey(key); }, /** Return the invisible system root node. * @returns {FancytreeNode} * @deprecated Use methods of the Fancytree instance instead (<a href="Fancytree_Widget.html">example above</a>). */ getRootNode: function() { this._deprecationWarning("getRootNode"); return this.tree.rootNode; }, /** Return the current tree instance. * @returns {Fancytree} * @deprecated Use `$.ui.fancytree.getTree()` instead (<a href="Fancytree_Widget.html">example above</a>). */ getTree: function() { this._deprecationWarning("getTree"); return this.tree; }, } ); // $.ui.fancytree was created by the widget factory. Create a local shortcut: FT = $.ui.fancytree; /** * Static members in the `$.ui.fancytree` namespace. * This properties and methods can be accessed without instantiating a concrete * Fancytree instance. * * @example * // Access static members: * var node = $.ui.fancytree.getNode(element); * alert($.ui.fancytree.version); * * @mixin Fancytree_Static */ $.extend( $.ui.fancytree, /** @lends Fancytree_Static# */ { /** Version number `"MAJOR.MINOR.PATCH"` * @type {string} */ version: "2.34.0", // Set to semver by 'grunt release' /** @type {string} * @description `"production" for release builds` */ buildType: "production", // Set to 'production' by 'grunt build' /** @type {int} * @description 0: silent .. 5: verbose (default: 3 for release builds). */ debugLevel: 3, // Set to 3 by 'grunt build' // Used by $.ui.fancytree.debug() and as default for tree.options.debugLevel _nextId: 1, _nextNodeKey: 1, _extensions: {}, // focusTree: null, /** Expose class object as `$.ui.fancytree._FancytreeClass`. * Useful to extend `$.ui.fancytree._FancytreeClass.prototype`. * @type {Fancytree} */ _FancytreeClass: Fancytree, /** Expose class object as $.ui.fancytree._FancytreeNodeClass * Useful to extend `$.ui.fancytree._FancytreeNodeClass.prototype`. * @type {FancytreeNode} */ _FancytreeNodeClass: FancytreeNode, /* Feature checks to provide backwards compatibility */ jquerySupports: { // http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at positionMyOfs: isVersionAtLeast($.ui.version, 1, 9), }, /** Throw an error if condition fails (debug method). * @param {boolean} cond * @param {string} msg */ assert: function(cond, msg) { return _assert(cond, msg); }, /** Create a new Fancytree instance on a target element. * * @param {Element | jQueryObject | string} el Target DOM element or selector * @param {FancytreeOptions} [opts] Fancytree options * @returns {Fancytree} new tree instance * @example * var tree = $.ui.fancytree.createTree("#tree", { * source: {url: "my/webservice"} * }); // Create tree for this matching element * * @since 2.25 */ createTree: function(el, opts) { var $tree = $(el).fancytree(opts); return FT.getTree($tree); }, /** Return a function that executes *fn* at most every *timeout* ms. * @param {integer} timeout * @param {function} fn * @param {boolean} [invokeAsap=false] * @param {any} [ctx] */ debounce: function(timeout, fn, invokeAsap, ctx) { var timer; if (arguments.length === 3 && typeof invokeAsap !== "boolean") { ctx = invokeAsap; invokeAsap = false; } return function() { var args = arguments; ctx = ctx || this; // eslint-disable-next-line no-unused-expressions invokeAsap && !timer && fn.apply(ctx, args); clearTimeout(timer); timer = setTimeout(function() { // eslint-disable-next-line no-unused-expressions invokeAsap || fn.apply(ctx, args); timer = null; }, timeout); }; }, /** Write message to console if debugLevel >= 4 * @param {string} msg */ debug: function(msg) { if ($.ui.fancytree.debugLevel >= 4) { consoleApply("log", arguments); } }, /** Write error message to console if debugLevel >= 1. * @param {string} msg */ error: function(msg) { if ($.ui.fancytree.debugLevel >= 1) { consoleApply("error", arguments); } }, /** Convert `<`, `>`, `&`, `"`, `'`, and `/` to the equivalent entities. * * @param {string} s * @returns {string} */ escapeHtml: function(s) { return ("" + s).replace(REX_HTML, function(s) { return ENTITY_MAP[s]; }); }, /** Make jQuery.position() arguments backwards compatible, i.e. if * jQuery UI version <= 1.8, convert * { my: "left+3 center", at: "left bottom", of: $target } * to * { my: "left center", at: "left bottom", of: $target, offset: "3 0" } * * See http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at * and http://jsfiddle.net/mar10/6xtu9a4e/ * * @param {object} opts * @returns {object} the (potentially modified) original opts hash object */ fixPositionOptions: function(opts) { if (opts.offset || ("" + opts.my + opts.at).indexOf("%") >= 0) { $.error( "expected new position syntax (but '%' is not supported)" ); } if (!$.ui.fancytree.jquerySupports.positionMyOfs) { var // parse 'left+3 center' into ['left+3 center', 'left', '+3', 'center', undefined] myParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec( opts.my ), atParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec( opts.at ), // convert to numbers dx = (myParts[2] ? +myParts[2] : 0) + (atParts[2] ? +atParts[2] : 0), dy = (myParts[4] ? +myParts[4] : 0) + (atParts[4] ? +atParts[4] : 0); opts = $.extend({}, opts, { // make a copy and overwrite my: myParts[1] + " " + myParts[3], at: atParts[1] + " " + atParts[3], }); if (dx || dy) { opts.offset = "" + dx + " " + dy; } } return opts; }, /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event. * * @param {Event} event Mouse event, e.g. click, ... * @returns {object} Return a {node: FancytreeNode, type: TYPE} object * TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined */ getEventTarget: function(event) { var $target, tree, tcn = event && event.target ? event.target.className : "", res = { node: this.getNode(event.target), type: undefined }; // We use a fast version of $(res.node).hasClass() // See http://jsperf.com/test-for-classname/2 if (/\bfancytree-title\b/.test(tcn)) { res.type = "title"; } else if (/\bfancytree-expander\b/.test(tcn)) { res.type = res.node.hasChildren() === false ? "prefix" : "expander"; // }else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){ } else if (/\bfancytree-checkbox\b/.test(tcn)) { res.type = "checkbox"; } else if (/\bfancytree(-custom)?-icon\b/.test(tcn)) { res.type = "icon"; } else if (/\bfancytree-node\b/.test(tcn)) { // Somewhere near the title res.type = "title"; } else if (event && event.target) { $target = $(event.target); if ($target.is("ul[role=group]")) { // #nnn: Clicking right to a node may hit the surrounding UL tree = res.node && res.node.tree; (tree || FT).debug("Ignoring click on outer UL."); res.node = null; } else if ($target.closest(".fancytree-title").length) { // #228: clicking an embedded element inside a title res.type = "title"; } else if ($target.closest(".fancytree-checkbox").length) { // E.g. <svg> inside checkbox span res.type = "checkbox"; } else if ($target.closest(".fancytree-expander").length) { res.type = "expander"; } } return res; }, /** Return a string describing the affected node region for a mouse event. * * @param {Event} event Mouse event, e.g. click, mousemove, ... * @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined */ getEventTargetType: function(event) { return this.getEventTarget(event).type; }, /** Return a FancytreeNode instance from element, event, or jQuery object. * * @param {Element | jQueryObject | Event} el * @returns {FancytreeNode} matching node or null */ getNode: function(el) { if (el instanceof FancytreeNode) { return el; // el already was a FancytreeNode } else if (el instanceof $) { el = el[0]; // el was a jQuery object: use the DOM element } else if (el.originalEvent !== undefined) { el = el.target; // el was an Event } while (el) { if (el.ftnode) { return el.ftnode; } el = el.parentNode; } return null; }, /** Return a Fancytree instance, from element, index, event, or jQueryObject. * * @param {Element | jQueryObject | Event | integer | string} [el] * @returns {Fancytree} matching tree or null * @example * $.ui.fancytree.getTree(); // Get first Fancytree instance on page * $.ui.fancytree.getTree(1); // Get second Fancytree instance on page * $.ui.fancytree.getTree(event); // Get tree for this mouse- or keyboard event * $.ui.fancytree.getTree("foo"); // Get tree for this `opts.treeId` * $.ui.fancytree.getTree("#tree"); // Get tree for this matching element * * @since 2.13 */ getTree: function(el) { var widget, orgEl = el; if (el instanceof Fancytree) { return el; // el already was a Fancytree } if (el === undefined) { el = 0; // get first tree } if (typeof el === "number") { el = $(".fancytree-container").eq(el); // el was an integer: return nth instance } else if (typeof el === "string") { // `el` may be a treeId or a selector: el = $("#ft-id-" + orgEl).eq(0); if (!el.length) { el = $(orgEl).eq(0); // el was a selector: use first match } } else if ( el instanceof Element || el instanceof HTMLDocument ) { el = $(el); } else if (el instanceof $) { el = el.eq(0); // el was a jQuery object: use the first } else if (el.originalEvent !== undefined) { el = $(el.target); // el was an Event } // el is a jQuery object wit one element here el = el.closest(":ui-fancytree"); widget = el.data("ui-fancytree") || el.data("fancytree"); // the latter is required by jQuery <= 1.8 return widget ? widget.tree : null; }, /** Return an option value that has a default, but may be overridden by a * callback or a node instance attribute. * * Evaluation sequence: * * If `tree.options.<optionName>` is a callback that returns something, use that. * Else if `node.<optionName>` is defined, use that. * Else if `tree.options.<optionName>` is a value, use that. * Else use `defaultValue`. * * @param {string} optionName name of the option property (on node and tree) * @param {FancytreeNode} node passed to the callback * @param {object} nodeObject where to look for the local option property, e.g. `node` or `node.data` * @param {object} treeOption where to look for the tree option, e.g. `tree.options` or `tree.options.dnd5` * @param {any} [defaultValue] * @returns {any} * * @example * // Check for node.foo, tree,options.foo(), and tree.options.foo: * $.ui.fancytree.evalOption("foo", node, node, tree.options); * // Check for node.data.bar, tree,options.qux.bar(), and tree.options.qux.bar: * $.ui.fancytree.evalOption("bar", node, node.data, tree.options.qux); * * @since 2.22 */ evalOption: function( optionName, node, nodeObject, treeOptions, defaultValue ) { var ctx, res, tree = node.tree, treeOpt = treeOptions[optionName], nodeOpt = nodeObject[optionName]; if ($.isFunction(treeOpt)) { ctx = { node: node, tree: tree, widget: tree.widget, options: tree.widget.options, typeInfo: tree.types[node.type] || {}, }; res = treeOpt.call(tree, { type: optionName }, ctx); if (res == null) { res = nodeOpt; } } else { res = nodeOpt == null ? treeOpt : nodeOpt; } if (res == null) { res = defaultValue; // no option set at all: return default } return res; }, /** Set expander, checkbox, or node icon, supporting string and object format. * * @param {Element | jQueryObject} span * @param {string} baseClass * @param {string | object} icon * @since 2.27 */ setSpanIcon: function(span, baseClass, icon) { var $span = $(span); if (typeof icon === "string") { $span.attr("class", baseClass + " " + icon); } else { // support object syntax: { text: ligature, addClasse: classname } if (icon.text) { $span.text("" + icon.text); } else if (icon.html) { span.innerHTML = icon.html; } $span.attr( "class", baseClass + " " + (icon.addClass || "") ); } }, /** Convert a keydown or mouse event to a canonical string like 'ctrl+a', * 'ctrl+shift+f2', 'shift+leftdblclick'. * * This is especially handy for switch-statements in event handlers. * * @param {event} * @returns {string} * * @example switch( $.ui.fancytree.eventToString(event) ) { case "-": tree.nodeSetExpanded(ctx, false); break; case "shift+return": tree.nodeSetActive(ctx, true); break; case "down": res = node.navigate(event.which, activate); break; default: handled = false; } if( handled ){ event.preventDefault(); } */ eventToString: function(event) { // Poor-man's hotkeys. See here for a complete implementation: // https://github.com/jeresig/jquery.hotkeys var which = event.which, et = event.type, s = []; if (event.altKey) { s.push("alt"); } if (event.ctrlKey) { s.push("ctrl"); } if (event.metaKey) { s.push("meta"); } if (event.shiftKey) { s.push("shift"); } if (et === "click" || et === "dblclick") { s.push(MOUSE_BUTTONS[event.button] + et); } else if (et === "wheel") { s.push(et); } else if (!IGNORE_KEYCODES[which]) { s.push( SPECIAL_KEYCODES[which] || String.fromCharCode(which).toLowerCase() ); } return s.join("+"); }, /** Write message to console if debugLevel >= 3 * @param {string} msg */ info: function(msg) { if ($.ui.fancytree.debugLevel >= 3) { consoleApply("info", arguments); } }, /* @deprecated: use eventToString(event) instead. */ keyEventToString: function(event) { this.warn( "keyEventToString() is deprecated: use eventToString()" ); return this.eventToString(event); }, /** Return a wrapped handler method, that provides `this._super`. * * @example // Implement `opts.createNode` event to add the 'draggable' attribute $.ui.fancytree.overrideMethod(ctx.options, "createNode", function(event, data) { // Default processing if any this._super.apply(this, arguments); // Add 'draggable' attribute data.node.span.draggable = true; }); * * @param {object} instance * @param {string} methodName * @param {function} handler * @param {object} [context] optional context */ overrideMethod: function(instance, methodName, handler, context) { var prevSuper, _super = instance[methodName] || $.noop; instance[methodName] = function() { var self = context || this; try { prevSuper = self._super; self._super = _super; return handler.apply(self, arguments); } finally { self._super = prevSuper; } }; }, /** * Parse tree data from HTML <ul> markup * * @param {jQueryObject} $ul * @returns {NodeData[]} */ parseHtml: function($ul) { var classes, className, extraClasses, i, iPos, l, tmp, tmp2, $children = $ul.find(">li"), children = []; $children.each(function() { var allData, lowerCaseAttr, $li = $(this), $liSpan = $li.find(">span", this).first(), $liA = $liSpan.length ? null : $li.find(">a").first(), d = { tooltip: null, data: {} }; if ($liSpan.length) { d.title = $liSpan.html(); } else if ($liA && $liA.length) { // If a <li><a> tag is specified, use it literally and extract href/target. d.title = $liA.html(); d.data.href = $liA.attr("href"); d.data.target = $liA.attr("target"); d.tooltip = $liA.attr("title"); } else { // If only a <li> tag is specified, use the trimmed string up to // the next child <ul> tag. d.title = $li.html(); iPos = d.title.search(/<ul/i); if (iPos >= 0) { d.title = d.title.substring(0, iPos); } } d.title = $.trim(d.title); // Make sure all fields exist for (i = 0, l = CLASS_ATTRS.length; i < l; i++) { d[CLASS_ATTRS[i]] = undefined; } // Initialize to `true`, if class is set and collect extraClasses classes = this.className.split(" "); extraClasses = []; for (i = 0, l = classes.length; i < l; i++) { className = classes[i]; if (CLASS_ATTR_MAP[className]) { d[className] = true; } else { extraClasses.push(className); } } d.extraClasses = extraClasses.join(" "); // Parse node options from ID, title and class attributes tmp = $li.attr("title"); if (tmp) { d.tooltip = tmp; // overrides <a title='...'> } tmp = $li.attr("id"); if (tmp) { d.key = tmp; } // Translate hideCheckbox -> checkbox:false if ($li.attr("hideCheckbox")) { d.checkbox = false; } // Add <li data-NAME='...'> as node.data.NAME allData = _getElementDataAsDict($li); if (allData && !$.isEmptyObject(allData)) { // #507: convert data-hidecheckbox (lower case) to hideCheckbox for (lowerCaseAttr in NODE_ATTR_LOWERCASE_MAP) { if (allData.hasOwnProperty(lowerCaseAttr)) { allData[ NODE_ATTR_LOWERCASE_MAP[lowerCaseAttr] ] = allData[lowerCaseAttr]; delete allData[lowerCaseAttr]; } } // #56: Allow to set special node.attributes from data-... for (i = 0, l = NODE_ATTRS.length; i < l; i++) { tmp = NODE_ATTRS[i]; tmp2 = allData[tmp]; if (tmp2 != null) { delete allData[tmp]; d[tmp] = tmp2; } } // All other data-... goes to node.data... $.extend(d.data, allData); } // Recursive reading of child nodes, if LI tag contains an UL tag $ul = $li.find(">ul").first(); if ($ul.length) { d.children = $.ui.fancytree.parseHtml($ul); } else { d.children = d.lazy ? undefined : null; } children.push(d); // FT.debug("parse ", d, children); }); return children; }, /** Add Fancytree extension definition to the list of globally available extensions. * * @param {object} definition */ registerExtension: function(definition) { _assert( definition.name != null, "extensions must have a `name` property." ); _assert( definition.version != null, "extensions must have a `version` property." ); $.ui.fancytree._extensions[definition.name] = definition; }, /** Inverse of escapeHtml(). * * @param {string} s * @returns {string} */ unescapeHtml: function(s) { var e = document.createElement("div"); e.innerHTML = s; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; }, /** Write warning message to console if debugLevel >= 2. * @param {string} msg */ warn: function(msg) { if ($.ui.fancytree.debugLevel >= 2) { consoleApply("warn", arguments); } }, } ); // Value returned by `require('jquery.fancytree')` return $.ui.fancytree; }); // End of closure /*! Extension 'jquery.fancytree.childcounter.js' */// Extending Fancytree // =================== // // See also the [live demo](https://wwWendt.de/tech/fancytree/demo/sample-ext-childcounter.html) of this code. // // Every extension should have a comment header containing some information // about the author, copyright and licensing. Also a pointer to the latest // source code. // Prefix with `/*!` so the comment is not removed by the minifier. /*! * jquery.fancytree.childcounter.js * * Add a child counter bubble to tree nodes. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ // To keep the global namespace clean, we wrap everything in a closure. // The UMD wrapper pattern defines the dependencies on jQuery and the // Fancytree core module, and makes sure that we can use the `require()` // syntax with package loaders. (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery", "./jquery.fancytree"], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { // Consider to use [strict mode](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/) "use strict"; // The [coding guidelines](http://contribute.jquery.org/style-guide/js/) // require jshint /eslint compliance. // But for this sample, we want to allow unused variables for demonstration purpose. /*eslint-disable no-unused-vars */ // Adding methods // -------------- // New member functions can be added to the `Fancytree` class. // This function will be available for every tree instance: // // var tree = $.ui.fancytree.getTree("#tree"); // tree.countSelected(false); $.ui.fancytree._FancytreeClass.prototype.countSelected = function(topOnly) { var tree = this, treeOptions = tree.options; return tree.getSelectedNodes(topOnly).length; }; // The `FancytreeNode` class can also be easily extended. This would be called // like // node.updateCounters(); // // It is also good practice to add a docstring comment. /** * [ext-childcounter] Update counter badges for `node` and its parents. * May be called in the `loadChildren` event, to update parents of lazy loaded * nodes. * @alias FancytreeNode#updateCounters * @requires jquery.fancytree.childcounters.js */ $.ui.fancytree._FancytreeNodeClass.prototype.updateCounters = function() { var node = this, $badge = $("span.fancytree-childcounter", node.span), extOpts = node.tree.options.childcounter, count = node.countChildren(extOpts.deep); node.data.childCounter = count; if ( (count || !extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ) { if (!$badge.length) { $badge = $("<span class='fancytree-childcounter'/>").appendTo( $( "span.fancytree-icon,span.fancytree-custom-icon", node.span ) ); } $badge.text(count); } else { $badge.remove(); } if (extOpts.deep && !node.isTopLevel() && !node.isRoot()) { node.parent.updateCounters(); } }; // Finally, we can extend the widget API and create functions that are called // like so: // // $("#tree").fancytree("widgetMethod1", "abc"); $.ui.fancytree.prototype.widgetMethod1 = function(arg1) { var tree = this.tree; return arg1; }; // Register a Fancytree extension // ------------------------------ // A full blown extension, extension is available for all trees and can be // enabled like so (see also the [live demo](https://wwWendt.de/tech/fancytree/demo/sample-ext-childcounter.html)): // // <script src="../src/jquery.fancytree.js"></script> // <script src="../src/jquery.fancytree.childcounter.js"></script> // ... // // $("#tree").fancytree({ // extensions: ["childcounter"], // childcounter: { // hideExpanded: true // }, // ... // }); // /* 'childcounter' extension */ $.ui.fancytree.registerExtension({ // Every extension must be registered by a unique name. name: "childcounter", // Version information should be compliant with [semver](http://semver.org) version: "2.34.0", // Extension specific options and their defaults. // This options will be available as `tree.options.childcounter.hideExpanded` options: { deep: true, hideZeros: true, hideExpanded: false, }, // Attributes other than `options` (or functions) can be defined here, and // will be added to the tree.ext.EXTNAME namespace, in this case `tree.ext.childcounter.foo`. // They can also be accessed as `this._local.foo` from within the extension // methods. foo: 42, // Local functions are prefixed with an underscore '_'. // Callable as `this._local._appendCounter()`. _appendCounter: function(bar) { var tree = this; }, // **Override virtual methods for this extension.** // // Fancytree implements a number of 'hook methods', prefixed by 'node...' or 'tree...'. // with a `ctx` argument (see [EventData](https://wwWendt.de/tech/fancytree/doc/jsdoc/global.html#EventData) // for details) and an extended calling context:<br> // `this` : the Fancytree instance<br> // `this._local`: the namespace that contains extension attributes and private methods (same as this.ext.EXTNAME)<br> // `this._super`: the virtual function that was overridden (member of previous extension or Fancytree) // // See also the [complete list of available hook functions](https://wwWendt.de/tech/fancytree/doc/jsdoc/Fancytree_Hooks.html). /* Init */ // `treeInit` is triggered when a tree is initalized. We can set up classes or // bind event handlers here... treeInit: function(ctx) { var tree = this, // same as ctx.tree, opts = ctx.options, extOpts = ctx.options.childcounter; // Optionally check for dependencies with other extensions /* this._requireExtension("glyph", false, false); */ // Call the base implementation this._superApply(arguments); // Add a class to the tree container this.$container.addClass("fancytree-ext-childcounter"); }, // Destroy this tree instance (we only call the default implementation, so // this method could as well be omitted). treeDestroy: function(ctx) { this._superApply(arguments); }, // Overload the `renderTitle` hook, to append a counter badge nodeRenderTitle: function(ctx, title) { var node = ctx.node, extOpts = ctx.options.childcounter, count = node.data.childCounter == null ? node.countChildren(extOpts.deep) : +node.data.childCounter; // Let the base implementation render the title // We use `_super()` instead of `_superApply()` here, since it is a little bit // more performant when called often this._super(ctx, title); // Append a counter badge if ( (count || !extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ) { $( "span.fancytree-icon,span.fancytree-custom-icon", node.span ).append( $("<span class='fancytree-childcounter'/>").text(count) ); } }, // Overload the `setExpanded` hook, so the counters are updated nodeSetExpanded: function(ctx, flag, callOpts) { var tree = ctx.tree, node = ctx.node; // Let the base implementation expand/collapse the node, then redraw the title // after the animation has finished return this._superApply(arguments).always(function() { tree.nodeRenderTitle(ctx); }); }, // End of extension definition }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; }); // End of closure /*! Extension 'jquery.fancytree.clones.js' *//*! * * jquery.fancytree.clones.js * Support faster lookup of nodes by key and shared ref-ids. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery", "./jquery.fancytree"], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { "use strict"; /******************************************************************************* * Private functions and variables */ function _assert(cond, msg) { // TODO: see qunit.js extractStacktrace() if (!cond) { msg = msg ? ": " + msg : ""; $.error("Assertion failed" + msg); } } /* Return first occurrence of member from array. */ function _removeArrayMember(arr, elem) { // TODO: use Array.indexOf for IE >= 9 var i; for (i = arr.length - 1; i >= 0; i--) { if (arr[i] === elem) { arr.splice(i, 1); return true; } } return false; } /** * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) * * @author <a href="mailto:[email protected]">Gary Court</a> * @see http://github.com/garycourt/murmurhash-js * @author <a href="mailto:[email protected]">Austin Appleby</a> * @see http://sites.google.com/site/murmurhash/ * * @param {string} key ASCII only * @param {boolean} [asString=false] * @param {number} seed Positive integer only * @return {number} 32-bit positive integer hash */ function hashMurmur3(key, asString, seed) { /*eslint-disable no-bitwise */ var h1b, k1, remainder = key.length & 3, bytes = key.length - remainder, h1 = seed, c1 = 0xcc9e2d51, c2 = 0x1b873593, i = 0; while (i < bytes) { k1 = (key.charCodeAt(i) & 0xff) | ((key.charCodeAt(++i) & 0xff) << 8) | ((key.charCodeAt(++i) & 0xff) << 16) | ((key.charCodeAt(++i) & 0xff) << 24); ++i; k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); h1b = ((h1 & 0xffff) * 5 + ((((h1 >>> 16) * 5) & 0xffff) << 16)) & 0xffffffff; h1 = (h1b & 0xffff) + 0x6b64 + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16); } k1 = 0; switch (remainder) { case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; // fall through case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; // fall through case 1: k1 ^= key.charCodeAt(i) & 0xff; k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; h1 ^= k1; } h1 ^= key.length; h1 ^= h1 >>> 16; h1 = ((h1 & 0xffff) * 0x85ebca6b + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; h1 ^= h1 >>> 13; h1 = ((h1 & 0xffff) * 0xc2b2ae35 + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16)) & 0xffffffff; h1 ^= h1 >>> 16; if (asString) { // Convert to 8 digit hex string return ("0000000" + (h1 >>> 0).toString(16)).substr(-8); } return h1 >>> 0; /*eslint-enable no-bitwise */ } /* * Return a unique key for node by calculating the hash of the parents refKey-list. */ function calcUniqueKey(node) { var key, h1, path = $.map(node.getParentList(false, true), function(e) { return e.refKey || e.key; }); path = path.join("/"); // 32-bit has a high probability of collisions, so we pump up to 64-bit // https://security.stackexchange.com/q/209882/207588 h1 = hashMurmur3(path, true); key = "id_" + h1 + hashMurmur3(h1 + path, true); return key; } /** * [ext-clones] Return a list of clone-nodes (i.e. same refKey) or null. * @param {boolean} [includeSelf=false] * @returns {FancytreeNode[] | null} * * @alias FancytreeNode#getCloneList * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.getCloneList = function( includeSelf ) { var key, tree = this.tree, refList = tree.refMap[this.refKey] || null, keyMap = tree.keyMap; if (refList) { key = this.key; // Convert key list to node list if (includeSelf) { refList = $.map(refList, function(val) { return keyMap[val]; }); } else { refList = $.map(refList, function(val) { return val === key ? null : keyMap[val]; }); if (refList.length < 1) { refList = null; } } } return refList; }; /** * [ext-clones] Return true if this node has at least another clone with same refKey. * @returns {boolean} * * @alias FancytreeNode#isClone * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.isClone = function() { var refKey = this.refKey || null, refList = (refKey && this.tree.refMap[refKey]) || null; return !!(refList && refList.length > 1); }; /** * [ext-clones] Update key and/or refKey for an existing node. * @param {string} key * @param {string} refKey * @returns {boolean} * * @alias FancytreeNode#reRegister * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.reRegister = function( key, refKey ) { key = key == null ? null : "" + key; refKey = refKey == null ? null : "" + refKey; // this.debug("reRegister", key, refKey); var tree = this.tree, prevKey = this.key, prevRefKey = this.refKey, keyMap = tree.keyMap, refMap = tree.refMap, refList = refMap[prevRefKey] || null, // curCloneKeys = refList ? node.getCloneList(true), modified = false; // Key has changed: update all references if (key != null && key !== this.key) { if (keyMap[key]) { $.error( "[ext-clones] reRegister(" + key + "): already exists: " + this ); } // Update keyMap delete keyMap[prevKey]; keyMap[key] = this; // Update refMap if (refList) { refMap[prevRefKey] = $.map(refList, function(e) { return e === prevKey ? key : e; }); } this.key = key; modified = true; } // refKey has changed if (refKey != null && refKey !== this.refKey) { // Remove previous refKeys if (refList) { if (refList.length === 1) { delete refMap[prevRefKey]; } else { refMap[prevRefKey] = $.map(refList, function(e) { return e === prevKey ? null : e; }); } } // Add refKey if (refMap[refKey]) { refMap[refKey].append(key); } else { refMap[refKey] = [this.key]; } this.refKey = refKey; modified = true; } return modified; }; /** * [ext-clones] Define a refKey for an existing node. * @param {string} refKey * @returns {boolean} * * @alias FancytreeNode#setRefKey * @requires jquery.fancytree.clones.js * @since 2.16 */ $.ui.fancytree._FancytreeNodeClass.prototype.setRefKey = function(refKey) { return this.reRegister(null, refKey); }; /** * [ext-clones] Return all nodes with a given refKey (null if not found). * @param {string} refKey * @param {FancytreeNode} [rootNode] optionally restrict results to descendants of this node * @returns {FancytreeNode[] | null} * @alias Fancytree#getNodesByRef * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeClass.prototype.getNodesByRef = function( refKey, rootNode ) { var keyMap = this.keyMap, refList = this.refMap[refKey] || null; if (refList) { // Convert key list to node list if (rootNode) { refList = $.map(refList, function(val) { var node = keyMap[val]; return node.isDescendantOf(rootNode) ? node : null; }); } else { refList = $.map(refList, function(val) { return keyMap[val]; }); } if (refList.length < 1) { refList = null; } } return refList; }; /** * [ext-clones] Replace a refKey with a new one. * @param {string} oldRefKey * @param {string} newRefKey * @alias Fancytree#changeRefKey * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeClass.prototype.changeRefKey = function( oldRefKey, newRefKey ) { var i, node, keyMap = this.keyMap, refList = this.refMap[oldRefKey] || null; if (refList) { for (i = 0; i < refList.length; i++) { node = keyMap[refList[i]]; node.refKey = newRefKey; } delete this.refMap[oldRefKey]; this.refMap[newRefKey] = refList; } }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "clones", version: "2.34.0", // Default options for this extension. options: { highlightActiveClones: true, // set 'fancytree-active-clone' on active clones and all peers highlightClones: false, // set 'fancytree-clone' class on any node that has at least one clone }, treeCreate: function(ctx) { this._superApply(arguments); ctx.tree.refMap = {}; ctx.tree.keyMap = {}; }, treeInit: function(ctx) { this.$container.addClass("fancytree-ext-clones"); _assert(ctx.options.defaultKey == null); // Generate unique / reproducible default keys ctx.options.defaultKey = function(node) { return calcUniqueKey(node); }; // The default implementation loads initial data this._superApply(arguments); }, treeClear: function(ctx) { ctx.tree.refMap = {}; ctx.tree.keyMap = {}; return this._superApply(arguments); }, treeRegisterNode: function(ctx, add, node) { var refList, len, tree = ctx.tree, keyMap = tree.keyMap, refMap = tree.refMap, key = node.key, refKey = node && node.refKey != null ? "" + node.refKey : null; // ctx.tree.debug("clones.treeRegisterNode", add, node); if (node.isStatusNode()) { return this._super(ctx, add, node); } if (add) { if (keyMap[node.key] != null) { var other = keyMap[node.key], msg = "clones.treeRegisterNode: duplicate key '" + node.key + "': /" + node.getPath(true) + " => " + other.getPath(true); // Sometimes this exception is not visible in the console, // so we also write it: tree.error(msg); $.error(msg); } keyMap[key] = node; if (refKey) { refList = refMap[refKey]; if (refList) { refList.push(key); if ( refList.length === 2 && ctx.options.clones.highlightClones ) { // Mark peer node, if it just became a clone (no need to // mark current node, since it will be rendered later anyway) keyMap[refList[0]].renderStatus(); } } else { refMap[refKey] = [key]; } // node.debug("clones.treeRegisterNode: add clone =>", refMap[refKey]); } } else { if (keyMap[key] == null) { $.error( "clones.treeRegisterNode: node.key not registered: " + node.key ); } delete keyMap[key]; if (refKey) { refList = refMap[refKey]; // node.debug("clones.treeRegisterNode: remove clone BEFORE =>", refMap[refKey]); if (refList) { len = refList.length; if (len <= 1) { _assert(len === 1); _assert(refList[0] === key); delete refMap[refKey]; } else { _removeArrayMember(refList, key); // Unmark peer node, if this was the only clone if ( len === 2 && ctx.options.clones.highlightClones ) { // node.debug("clones.treeRegisterNode: last =>", node.getCloneList()); keyMap[refList[0]].renderStatus(); } } // node.debug("clones.treeRegisterNode: remove clone =>", refMap[refKey]); } } } return this._super(ctx, add, node); }, nodeRenderStatus: function(ctx) { var $span, res, node = ctx.node; res = this._super(ctx); if (ctx.options.clones.highlightClones) { $span = $(node[ctx.tree.statusClassPropName]); // Only if span already exists if ($span.length && node.isClone()) { // node.debug("clones.nodeRenderStatus: ", ctx.options.clones.highlightClones); $span.addClass("fancytree-clone"); } } return res; }, nodeSetActive: function(ctx, flag, callOpts) { var res, scpn = ctx.tree.statusClassPropName, node = ctx.node; res = this._superApply(arguments); if (ctx.options.clones.highlightActiveClones && node.isClone()) { $.each(node.getCloneList(true), function(idx, n) { // n.debug("clones.nodeSetActive: ", flag !== false); $(n[scpn]).toggleClass( "fancytree-active-clone", flag !== false ); }); } return res; }, }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; }); // End of closure /*! Extension 'jquery.fancytree.dnd5.js' *//*! * jquery.fancytree.dnd5.js * * Drag-and-drop support (native HTML5). * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ /* #TODO Compatiblity when dragging between *separate* windows: Drag from Chrome Edge FF IE11 Safari To Chrome ok ok ok NO ? Edge ok ok ok NO ? FF ok ok ok NO ? IE 11 ok ok ok ok ? Safari ? ? ? ? ok */ (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery", "./jquery.fancytree"], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { "use strict"; /****************************************************************************** * Private functions and variables */ var FT = $.ui.fancytree, isMac = /Mac/.test(navigator.platform), classDragSource = "fancytree-drag-source", classDragRemove = "fancytree-drag-remove", classDropAccept = "fancytree-drop-accept", classDropAfter = "fancytree-drop-after", classDropBefore = "fancytree-drop-before", classDropOver = "fancytree-drop-over", classDropReject = "fancytree-drop-reject", classDropTarget = "fancytree-drop-target", nodeMimeType = "application/x-fancytree-node", $dropMarker = null, $dragImage, $extraHelper, SOURCE_NODE = null, SOURCE_NODE_LIST = null, $sourceList = null, DRAG_ENTER_RESPONSE = null, // SESSION_DATA = null, // plain object passed to events as `data` SUGGESTED_DROP_EFFECT = null, REQUESTED_DROP_EFFECT = null, REQUESTED_EFFECT_ALLOWED = null, LAST_HIT_MODE = null, DRAG_OVER_STAMP = null; // Time when a node entered the 'over' hitmode /* */ function _clearGlobals() { DRAG_ENTER_RESPONSE = null; DRAG_OVER_STAMP = null; REQUESTED_DROP_EFFECT = null; REQUESTED_EFFECT_ALLOWED = null; SUGGESTED_DROP_EFFECT = null; SOURCE_NODE = null; SOURCE_NODE_LIST = null; if ($sourceList) { $sourceList.removeClass(classDragSource + " " + classDragRemove); } $sourceList = null; if ($dropMarker) { $dropMarker.hide(); } // Take this badge off of me - I can't use it anymore: if ($extraHelper) { $extraHelper.remove(); $extraHelper = null; } } /* Convert number to string and prepend +/-; return empty string for 0.*/ function offsetString(n) { // eslint-disable-next-line no-nested-ternary return n === 0 ? "" : n > 0 ? "+" + n : "" + n; } /* Convert a dragEnter() or dragOver() response to a canonical form. * Return false or plain object * @param {string|object|boolean} r * @return {object|false} */ function normalizeDragEnterResponse(r) { var res; if (!r) { return false; } if ($.isPlainObject(r)) { res = { over: !!r.over, before: !!r.before, after: !!r.after, }; } else if ($.isArray(r)) { res = { over: $.inArray("over", r) >= 0, before: $.inArray("before", r) >= 0, after: $.inArray("after", r) >= 0, }; } else { res = { over: r === true || r === "over", before: r === true || r === "before", after: r === true || r === "after", }; } if (Object.keys(res).length === 0) { return false; } // if( Object.keys(res).length === 1 ) { // res.unique = res[0]; // } return res; } /* Convert a dataTransfer.effectAllowed to a canonical form. * Return false or plain object * @param {string|boolean} r * @return {object|false} */ // function normalizeEffectAllowed(r) { // if (!r || r === "none") { // return false; // } // var all = r === "all", // res = { // copy: all || /copy/i.test(r), // link: all || /link/i.test(r), // move: all || /move/i.test(r), // }; // return res; // } /* Implement auto scrolling when drag cursor is in top/bottom area of scroll parent. */ function autoScroll(tree, event) { var spOfs, scrollTop, delta, dndOpts = tree.options.dnd5, sp = tree.$scrollParent[0], sensitivity = dndOpts.scrollSensitivity, speed = dndOpts.scrollSpeed, scrolled = 0; if (sp !== document && sp.tagName !== "HTML") { spOfs = tree.$scrollParent.offset(); scrollTop = sp.scrollTop; if (spOfs.top + sp.offsetHeight - event.pageY < sensitivity) { delta = sp.scrollHeight - tree.$scrollParent.innerHeight() - scrollTop; // console.log ("sp.offsetHeight: " + sp.offsetHeight // + ", spOfs.top: " + spOfs.top // + ", scrollTop: " + scrollTop // + ", innerHeight: " + tree.$scrollParent.innerHeight() // + ", scrollHeight: " + sp.scrollHeight // + ", delta: " + delta // ); if (delta > 0) { sp.scrollTop = scrolled = scrollTop + speed; } } else if (scrollTop > 0 && event.pageY - spOfs.top < sensitivity) { sp.scrollTop = scrolled = scrollTop - speed; } } else { scrollTop = $(document).scrollTop(); if (scrollTop > 0 && event.pageY - scrollTop < sensitivity) { scrolled = scrollTop - speed; $(document).scrollTop(scrolled); } else if ( $(window).height() - (event.pageY - scrollTop) < sensitivity ) { scrolled = scrollTop + speed; $(document).scrollTop(scrolled); } } if (scrolled) { tree.debug("autoScroll: " + scrolled + "px"); } return scrolled; } /* Guess dropEffect from modifier keys. * Using rules suggested here: * https://ux.stackexchange.com/a/83769 * @returns * 'copy', 'link', 'move', or 'none' */ function evalEffectModifiers(tree, event, effectDefault) { var res = effectDefault; if (isMac) { if (event.metaKey && event.altKey) { // Mac: [Control] + [Option] res = "link"; } else if (event.ctrlKey) { // Chrome on Mac: [Control] res = "link"; } else if (event.metaKey) { // Mac: [Command] res = "move"; } else if (event.altKey) { // Mac: [Option] res = "copy"; } } else { if (event.ctrlKey) { // Windows: [Ctrl] res = "copy"; } else if (event.shiftKey) { // Windows: [Shift] res = "move"; } else if (event.altKey) { // Windows: [Alt] res = "link"; } } if (res !== SUGGESTED_DROP_EFFECT) { tree.info( "evalEffectModifiers: " + event.type + " - evalEffectModifiers(): " + SUGGESTED_DROP_EFFECT + " -> " + res ); } SUGGESTED_DROP_EFFECT = res; // tree.debug("evalEffectModifiers: " + res); return res; } /* * Check if the previous callback (dragEnter, dragOver, ...) has changed * the `data` object and apply those settings. * * Safari: * It seems that `dataTransfer.dropEffect` can only be set on dragStart, and will remain * even if the cursor changes when [Alt] or [Ctrl] are pressed (?) * Using rules suggested here: * https://ux.stackexchange.com/a/83769 * @returns * 'copy', 'link', 'move', or 'none' */ function prepareDropEffectCallback(event, data) { var tree = data.tree, dataTransfer = data.dataTransfer; if (event.type === "dragstart") { data.effectAllowed = tree.options.dnd5.effectAllowed; data.dropEffect = tree.options.dnd5.dropEffectDefault; } else { data.effectAllowed = REQUESTED_EFFECT_ALLOWED; data.dropEffect = REQUESTED_DROP_EFFECT; } data.dropEffectSuggested = evalEffectModifiers( tree, event, tree.options.dnd5.dropEffectDefault ); data.isMove = data.dropEffect === "move"; data.files = dataTransfer.files || []; // if (REQUESTED_EFFECT_ALLOWED !== dataTransfer.effectAllowed) { // tree.warn( // "prepareDropEffectCallback(" + // event.type + // "): dataTransfer.effectAllowed changed from " + // REQUESTED_EFFECT_ALLOWED + // " -> " + // dataTransfer.effectAllowed // ); // } // if (REQUESTED_DROP_EFFECT !== dataTransfer.dropEffect) { // tree.warn( // "prepareDropEffectCallback(" + // event.type + // "): dataTransfer.dropEffect changed from requested " + // REQUESTED_DROP_EFFECT + // " to " + // dataTransfer.dropEffect // ); // } } function applyDropEffectCallback(event, data, allowDrop) { var tree = data.tree, dataTransfer = data.dataTransfer; if ( event.type !== "dragstart" && REQUESTED_EFFECT_ALLOWED !== data.effectAllowed ) { tree.warn( "effectAllowed should only be changed in dragstart event: " + event.type + ": data.effectAllowed changed from " + REQUESTED_EFFECT_ALLOWED + " -> " + data.effectAllowed ); } if (allowDrop === false) { tree.info("applyDropEffectCallback: allowDrop === false"); data.effectAllowed = "none"; data.dropEffect = "none"; } // if (REQUESTED_DROP_EFFECT !== data.dropEffect) { // tree.debug( // "applyDropEffectCallback(" + // event.type + // "): data.dropEffect changed from previous " + // REQUESTED_DROP_EFFECT + // " to " + // data.dropEffect // ); // } data.isMove = data.dropEffect === "move"; // data.isMove = data.dropEffectSuggested === "move"; REQUESTED_EFFECT_ALLOWED = data.effectAllowed; REQUESTED_DROP_EFFECT = data.dropEffect; // if (REQUESTED_DROP_EFFECT !== dataTransfer.dropEffect) { // data.tree.info( // "applyDropEffectCallback(" + // event.type + // "): dataTransfer.dropEffect changed from " + // REQUESTED_DROP_EFFECT + // " -> " + // dataTransfer.dropEffect // ); // } dataTransfer.effectAllowed = REQUESTED_EFFECT_ALLOWED; dataTransfer.dropEffect = REQUESTED_DROP_EFFECT; // tree.debug( // "applyDropEffectCallback(" + // event.type + // "): set " + // dataTransfer.dropEffect + // "/" + // dataTransfer.effectAllowed // ); // if (REQUESTED_DROP_EFFECT !== dataTransfer.dropEffect) { // data.tree.warn( // "applyDropEffectCallback(" + // event.type + // "): could not set dataTransfer.dropEffect to " + // REQUESTED_DROP_EFFECT + // ": got " + // dataTransfer.dropEffect // ); // } return REQUESTED_DROP_EFFECT; } /* Handle dragover event (fired every x ms) on valid drop targets. * * - Auto-scroll when cursor is in border regions * - Apply restrictioan like 'preventVoidMoves' * - Calculate hit mode * - Calculate drop effect * - Trigger dragOver() callback to let user modify hit mode and drop effect * - Adjust the drop marker accordingly * * @returns hitMode */ function handleDragOver(event, data) { // Implement auto-scrolling if (data.options.dnd5.scroll) { autoScroll(data.tree, event); } // Bail out with previous response if we get an invalid dragover if (!data.node) { data.tree.warn("Ignored dragover for non-node"); //, event, data); return LAST_HIT_MODE; } var markerOffsetX, nodeOfs, pos, relPosY, hitMode = null, tree = data.tree, options = tree.options, dndOpts = options.dnd5, targetNode = data.node, sourceNode = data.otherNode, markerAt = "center", $target = $(targetNode.span), $targetTitle = $target.find("span.fancytree-title"); if (DRAG_ENTER_RESPONSE === false) { tree.debug("Ignored dragover, since dragenter returned false."); return false; } else if (typeof DRAG_ENTER_RESPONSE === "string") { $.error("assert failed: dragenter returned string"); } // Calculate hitMode from relative cursor position. nodeOfs = $target.offset(); relPosY = (event.pageY - nodeOfs.top) / $target.height(); if (DRAG_ENTER_RESPONSE.after && relPosY > 0.75) { hitMode = "after"; } else if ( !DRAG_ENTER_RESPONSE.over && DRAG_ENTER_RESPONSE.after && relPosY > 0.5 ) { hitMode = "after"; } else if (DRAG_ENTER_RESPONSE.before && relPosY <= 0.25) { hitMode = "before"; } else if ( !DRAG_ENTER_RESPONSE.over && DRAG_ENTER_RESPONSE.before && relPosY <= 0.5 ) { hitMode = "before"; } else if (DRAG_ENTER_RESPONSE.over) { hitMode = "over"; } // Prevent no-ops like 'before source node' // TODO: these are no-ops when moving nodes, but not in copy mode if (dndOpts.preventVoidMoves && data.dropEffect === "move") { if (targetNode === sourceNode) { targetNode.debug("Drop over source node prevented."); hitMode = null; } else if ( hitMode === "before" && sourceNode && targetNode === sourceNode.getNextSibling() ) { targetNode.debug("Drop after source node prevented."); hitMode = null; } else if ( hitMode === "after" && sourceNode && targetNode === sourceNode.getPrevSibling() ) { targetNode.debug("Drop before source node prevented."); hitMode = null; } else if ( hitMode === "over" && sourceNode && sourceNode.parent === targetNode && sourceNode.isLastSibling() ) { targetNode.debug("Drop last child over own parent prevented."); hitMode = null; } } // Let callback modify the calculated hitMode data.hitMode = hitMode; if (hitMode && dndOpts.dragOver) { prepareDropEffectCallback(event, data); dndOpts.dragOver(targetNode, data); var allowDrop = !!hitMode; applyDropEffectCallback(event, data, allowDrop); hitMode = data.hitMode; } LAST_HIT_MODE = hitMode; // if (hitMode === "after" || hitMode === "before" || hitMode === "over") { markerOffsetX = dndOpts.dropMarkerOffsetX || 0; switch (hitMode) { case "before": markerAt = "top"; markerOffsetX += dndOpts.dropMarkerInsertOffsetX || 0; break; case "after": markerAt = "bottom"; markerOffsetX += dndOpts.dropMarkerInsertOffsetX || 0; break; } pos = { my: "left" + offsetString(markerOffsetX) + " center", at: "left " + markerAt, of: $targetTitle, }; if (options.rtl) { pos.my = "right" + offsetString(-markerOffsetX) + " center"; pos.at = "right " + markerAt; // console.log("rtl", pos); } $dropMarker .toggleClass(classDropAfter, hitMode === "after") .toggleClass(classDropOver, hitMode === "over") .toggleClass(classDropBefore, hitMode === "before") .show() .position(FT.fixPositionOptions(pos)); } else { $dropMarker.hide(); // console.log("hide dropmarker") } $(targetNode.span) .toggleClass( classDropTarget, hitMode === "after" || hitMode === "before" || hitMode === "over" ) .toggleClass(classDropAfter, hitMode === "after") .toggleClass(classDropBefore, hitMode === "before") .toggleClass(classDropAccept, hitMode === "over") .toggleClass(classDropReject, hitMode === false); return hitMode; } /* * Handle dragstart drag dragend events on the container */ function onDragEvent(event) { var json, tree = this, dndOpts = tree.options.dnd5, node = FT.getNode(event), dataTransfer = event.dataTransfer || event.originalEvent.dataTransfer, data = { tree: tree, node: node, options: tree.options, originalEvent: event.originalEvent, widget: tree.widget, dataTransfer: dataTransfer, useDefaultImage: true, dropEffect: undefined, dropEffectSuggested: undefined, effectAllowed: undefined, // set by dragstart files: undefined, // only for drop events isCancelled: undefined, // set by dragend isMove: undefined, }; switch (event.type) { case "dragstart": if (!node) { tree.info("Ignored dragstart on a non-node."); return false; } // Store current source node in different formats SOURCE_NODE = node; // Also optionally store selected nodes if (dndOpts.multiSource === false) { SOURCE_NODE_LIST = [node]; } else if (dndOpts.multiSource === true) { SOURCE_NODE_LIST = tree.getSelectedNodes(); if (!node.isSelected()) { SOURCE_NODE_LIST.unshift(node); } } else { SOURCE_NODE_LIST = dndOpts.multiSource(node, data); } // Cache as array of jQuery objects for faster access: $sourceList = $( $.map(SOURCE_NODE_LIST, function(n) { return n.span; }) ); // Set visual feedback $sourceList.addClass(classDragSource); // Set payload // Note: // Transfer data is only accessible on dragstart and drop! // For all other events the formats and kinds in the drag // data store list of items representing dragged data can be // enumerated, but the data itself is unavailable and no new // data can be added. var nodeData = node.toDict(); nodeData.treeId = node.tree._id; json = JSON.stringify(nodeData); try { dataTransfer.setData(nodeMimeType, json); dataTransfer.setData("text/html", $(node.span).html()); dataTransfer.setData("text/plain", node.title); } catch (ex) { // IE only accepts 'text' type tree.warn( "Could not set data (IE only accepts 'text') - " + ex ); } // We always need to set the 'text' type if we want to drag // Because IE 11 only accepts this single type. // If we pass JSON here, IE can can access all node properties, // even when the source lives in another window. (D'n'd inside // the same window will always work.) // The drawback is, that in this case ALL browsers will see // the JSON representation as 'text', so dragging // to a text field will insert the JSON string instead of // the node title. if (dndOpts.setTextTypeJson) { dataTransfer.setData("text", json); } else { dataTransfer.setData("text", node.title); } // Set the allowed drag modes (combinations of move, copy, and link) // (effectAllowed can only be set in the dragstart event.) // This can be overridden in the dragStart() callback prepareDropEffectCallback(event, data); // Let user cancel or modify above settings // Realize potential changes by previous callback if (dndOpts.dragStart(node, data) === false) { // Cancel dragging // dataTransfer.dropEffect = "none"; _clearGlobals(); return false; } applyDropEffectCallback(event, data); // Unless user set `data.useDefaultImage` to false in dragStart, // generata a default drag image now: $extraHelper = null; if (data.useDefaultImage) { // Set the title as drag image (otherwise it would contain the expander) $dragImage = $(node.span).find(".fancytree-title"); if (SOURCE_NODE_LIST && SOURCE_NODE_LIST.length > 1) { // Add a counter badge to node title if dragging more than one node. // We want this, because the element that is used as drag image // must be *visible* in the DOM, so we cannot create some hidden // custom markup. // See https://kryogenix.org/code/browser/custom-drag-image.html // Also, since IE 11 and Edge don't support setDragImage() alltogether, // it gives som feedback to the user. // The badge will be removed later on drag end. $extraHelper = $( "<span class='fancytree-childcounter'/>" ) .text("+" + (SOURCE_NODE_LIST.length - 1)) .appendTo($dragImage); } if (dataTransfer.setDragImage) { // IE 11 and Edge do not support this dataTransfer.setDragImage($dragImage[0], -10, -10); } } return true; case "drag": // Called every few milliseconds (no matter if the // cursor is over a valid drop target) // data.tree.info("drag", SOURCE_NODE) prepareDropEffectCallback(event, data); dndOpts.dragDrag(node, data); applyDropEffectCallback(event, data); $sourceList.toggleClass(classDragRemove, data.isMove); break; case "dragend": // Called at the end of a d'n'd process (after drop) // Note caveat: If drop removed the dragged source element, // we may not get this event, since the target does not exist // anymore prepareDropEffectCallback(event, data); _clearGlobals(); data.isCancelled = !LAST_HIT_MODE; dndOpts.dragEnd(node, data, !LAST_HIT_MODE); // applyDropEffectCallback(event, data); break; } } /* * Handle dragenter dragover dragleave drop events on the container */ function onDropEvent(event) { var json, allowAutoExpand, nodeData, isSourceFtNode, r, res, tree = this, dndOpts = tree.options.dnd5, allowDrop = null, node = FT.getNode(event), dataTransfer = event.dataTransfer || event.originalEvent.dataTransfer, data = { tree: tree, node: node, options: tree.options, originalEvent: event.originalEvent, widget: tree.widget, hitMode: DRAG_ENTER_RESPONSE, dataTransfer: dataTransfer, otherNode: SOURCE_NODE || null, otherNodeList: SOURCE_NODE_LIST || null, otherNodeData: null, // set by drop event useDefaultImage: true, dropEffect: undefined, dropEffectSuggested: undefined, effectAllowed: undefined, // set by dragstart files: null, // list of File objects (may be []) isCancelled: undefined, // set by drop event isMove: undefined, }; // data.isMove = dropEffect === "move"; switch (event.type) { case "dragenter": // The dragenter event is fired when a dragged element or // text selection enters a valid drop target. DRAG_OVER_STAMP = null; if (!node) { // Sometimes we get dragenter for the container element tree.debug( "Ignore non-node " + event.type + ": " + event.target.tagName + "." + event.target.className ); DRAG_ENTER_RESPONSE = false; break; } $(node.span) .addClass(classDropOver) .removeClass(classDropAccept + " " + classDropReject); // Data is only readable in the dragstart and drop event, // but we can check for the type: isSourceFtNode = $.inArray(nodeMimeType, dataTransfer.types) >= 0; if (dndOpts.preventNonNodes && !isSourceFtNode) { node.debug("Reject dropping a non-node."); DRAG_ENTER_RESPONSE = false; break; } else if ( dndOpts.preventForeignNodes && (!SOURCE_NODE || SOURCE_NODE.tree !== node.tree) ) { node.debug("Reject dropping a foreign node."); DRAG_ENTER_RESPONSE = false; break; } else if ( dndOpts.preventSameParent && data.otherNode && data.otherNode.tree === node.tree && node.parent === data.otherNode.parent ) { node.debug("Reject dropping as sibling (same parent)."); DRAG_ENTER_RESPONSE = false; break; } else if ( dndOpts.preventRecursion && data.otherNode && data.otherNode.tree === node.tree && node.isDescendantOf(data.otherNode) ) { node.debug("Reject dropping below own ancestor."); DRAG_ENTER_RESPONSE = false; break; } $dropMarker.show(); // Call dragEnter() to figure out if (and where) dropping is allowed prepareDropEffectCallback(event, data); r = dndOpts.dragEnter(node, data); res = normalizeDragEnterResponse(r); DRAG_ENTER_RESPONSE = res; allowDrop = res && (res.over || res.before || res.after); applyDropEffectCallback(event, data, allowDrop); break; case "dragover": if (!node) { tree.debug( "Ignore non-node " + event.type + ": " + event.target.tagName + "." + event.target.className ); break; } // The dragover event is fired when an element or text // selection is being dragged over a valid drop target // (every few hundred milliseconds). // tree.debug( // event.type + // ": dropEffect: " + // dataTransfer.dropEffect // ); prepareDropEffectCallback(event, data); LAST_HIT_MODE = handleDragOver(event, data); // The flag controls the preventDefault() below: allowDrop = !!LAST_HIT_MODE; allowAutoExpand = LAST_HIT_MODE === "over" || LAST_HIT_MODE === false; if ( allowAutoExpand && !node.expanded && node.hasChildren() !== false ) { if (!DRAG_OVER_STAMP) { DRAG_OVER_STAMP = Date.now(); } else if ( dndOpts.autoExpandMS && Date.now() - DRAG_OVER_STAMP > dndOpts.autoExpandMS && (!dndOpts.dragExpand || dndOpts.dragExpand(node, data) !== false) ) { node.setExpanded(); } } else { DRAG_OVER_STAMP = null; } break; case "dragleave": // NOTE: dragleave is fired AFTER the dragenter event of the // FOLLOWING element. if (!node) { tree.debug( "Ignore non-node " + event.type + ": " + event.target.tagName + "." + event.target.className ); break; } if (!$(node.span).hasClass(classDropOver)) { node.debug("Ignore dragleave (multi)."); break; } $(node.span).removeClass( classDropOver + " " + classDropAccept + " " + classDropReject ); node.scheduleAction("cancel"); dndOpts.dragLeave(node, data); $dropMarker.hide(); break; case "drop": // Data is only readable in the (dragstart and) drop event: if ($.inArray(nodeMimeType, dataTransfer.types) >= 0) { nodeData = dataTransfer.getData(nodeMimeType); tree.info( event.type + ": getData('application/x-fancytree-node'): '" + nodeData + "'" ); } if (!nodeData) { // 1. Source is not a Fancytree node, or // 2. If the FT mime type was set, but returns '', this // is probably IE 11 (which only supports 'text') nodeData = dataTransfer.getData("text"); tree.info( event.type + ": getData('text'): '" + nodeData + "'" ); } if (nodeData) { try { // 'text' type may contain JSON if IE is involved // and setTextTypeJson option was set json = JSON.parse(nodeData); if (json.title !== undefined) { data.otherNodeData = json; } } catch (ex) { // assume 'text' type contains plain text, so `otherNodeData` // should not be set } } tree.debug( event.type + ": nodeData: '" + nodeData + "', otherNodeData: ", data.otherNodeData ); $(node.span).removeClass( classDropOver + " " + classDropAccept + " " + classDropReject ); // Let user implement the actual drop operation data.hitMode = LAST_HIT_MODE; prepareDropEffectCallback(event, data, !LAST_HIT_MODE); data.isCancelled = !LAST_HIT_MODE; var orgSourceElem = SOURCE_NODE && SOURCE_NODE.span, orgSourceTree = SOURCE_NODE && SOURCE_NODE.tree; dndOpts.dragDrop(node, data); // applyDropEffectCallback(event, data); // Prevent browser's default drop handling, i.e. open as link, ... event.preventDefault(); if (orgSourceElem && !document.body.contains(orgSourceElem)) { // The drop handler removed the original drag source from // the DOM, so the dragend event will probaly not fire. if (orgSourceTree === tree) { tree.debug( "Drop handler removed source element: generating dragEnd." ); dndOpts.dragEnd(SOURCE_NODE, data); } else { tree.warn( "Drop handler removed source element: dragend event may be lost." ); } } _clearGlobals(); break; } // Dnd API madness: we must PREVENT default handling to enable dropping if (allowDrop) { event.preventDefault(); return false; } } /** [ext-dnd5] Return a Fancytree instance, from element, index, event, or jQueryObject. * * @returns {FancytreeNode[]} List of nodes (empty if no drag operation) * @example * $.ui.fancytree.getDragNodeList(); * * @alias Fancytree_Static#getDragNodeList * @requires jquery.fancytree.dnd5.js * @since 2.31 */ $.ui.fancytree.getDragNodeList = function() { return SOURCE_NODE_LIST || []; }; /** [ext-dnd5] Return the FancytreeNode that is currently being dragged. * * If multiple nodes are dragged, only the first is returned. * * @returns {FancytreeNode | null} dragged nodes or null if no drag operation * @example * $.ui.fancytree.getDragNode(); * * @alias Fancytree_Static#getDragNode * @requires jquery.fancytree.dnd5.js * @since 2.31 */ $.ui.fancytree.getDragNode = function() { return SOURCE_NODE; }; /****************************************************************************** * */ $.ui.fancytree.registerExtension({ name: "dnd5", version: "2.34.0", // Default options for this extension. options: { autoExpandMS: 1500, // Expand nodes after n milliseconds of hovering dropMarkerInsertOffsetX: -16, // Additional offset for drop-marker with hitMode = "before"/"after" dropMarkerOffsetX: -24, // Absolute position offset for .fancytree-drop-marker relatively to ..fancytree-title (icon/img near a node accepting drop) multiSource: false, // true: Drag multiple (i.e. selected) nodes. Also a callback() is allowed effectAllowed: "all", // Restrict the possible cursor shapes and modifier operations (can also be set in the dragStart event) // dropEffect: "auto", // 'copy'|'link'|'move'|'auto'(calculate from `effectAllowed`+modifier keys) or callback(node, data) that returns such string. dropEffectDefault: "move", // Default dropEffect ('copy', 'link', or 'move') when no modifier is pressed (overide in dragDrag, dragOver). preventForeignNodes: false, // Prevent dropping nodes from different Fancytrees preventNonNodes: false, // Prevent dropping items other than Fancytree nodes preventRecursion: true, // Prevent dropping nodes on own descendants preventSameParent: false, // Prevent dropping nodes under same direct parent preventVoidMoves: true, // Prevent dropping nodes 'before self', etc. scroll: true, // Enable auto-scrolling while dragging scrollSensitivity: 20, // Active top/bottom margin in pixel scrollSpeed: 5, // Pixel per event setTextTypeJson: false, // Allow dragging of nodes to different IE windows // Events (drag support) dragStart: null, // Callback(sourceNode, data), return true, to enable dnd drag dragDrag: $.noop, // Callback(sourceNode, data) dragEnd: $.noop, // Callback(sourceNode, data) // Events (drop support) dragEnter: null, // Callback(targetNode, data), return true, to enable dnd drop dragOver: $.noop, // Callback(targetNode, data) dragExpand: $.noop, // Callback(targetNode, data), return false to prevent autoExpand dragDrop: $.noop, // Callback(targetNode, data) dragLeave: $.noop, // Callback(targetNode, data) }, treeInit: function(ctx) { var $temp, tree = ctx.tree, opts = ctx.options, glyph = opts.glyph || null, dndOpts = opts.dnd5; if ($.inArray("dnd", opts.extensions) >= 0) { $.error("Extensions 'dnd' and 'dnd5' are mutually exclusive."); } if (dndOpts.dragStop) { $.error( "dragStop is not used by ext-dnd5. Use dragEnd instead." ); } if (dndOpts.preventRecursiveMoves != null) { $.error( "preventRecursiveMoves was renamed to preventRecursion." ); } // Implement `opts.createNode` event to add the 'draggable' attribute // #680: this must happen before calling super.treeInit() if (dndOpts.dragStart) { FT.overrideMethod(ctx.options, "createNode", function( event, data ) { // Default processing if any this._super.apply(this, arguments); if (data.node.span) { data.node.span.draggable = true; } else { data.node.warn("Cannot add `draggable`: no span tag"); } }); } this._superApply(arguments); this.$container.addClass("fancytree-ext-dnd5"); // Store the current scroll parent, which may be the tree // container, any enclosing div, or the document. // #761: scrollParent() always needs a container child $temp = $("<span>").appendTo(this.$container); this.$scrollParent = $temp.scrollParent(); $temp.remove(); $dropMarker = $("#fancytree-drop-marker"); if (!$dropMarker.length) { $dropMarker = $("<div id='fancytree-drop-marker'></div>") .hide() .css({ "z-index": 1000, // Drop marker should not steal dragenter/dragover events: "pointer-events": "none", }) .prependTo("body"); if (glyph) { FT.setSpanIcon( $dropMarker[0], glyph.map._addClass, glyph.map.dropMarker ); } } $dropMarker.toggleClass("fancytree-rtl", !!opts.rtl); // Enable drag support if dragStart() is specified: if (dndOpts.dragStart) { // Bind drag event handlers tree.$container.on( "dragstart drag dragend", onDragEvent.bind(tree) ); } // Enable drop support if dragEnter() is specified: if (dndOpts.dragEnter) { // Bind drop event handlers tree.$container.on( "dragenter dragover dragleave drop", onDropEvent.bind(tree) ); } }, }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; }); // End of closure /*! Extension 'jquery.fancytree.edit.js' *//*! * jquery.fancytree.edit.js * * Make node titles editable. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery", "./jquery.fancytree"], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { "use strict"; /******************************************************************************* * Private functions and variables */ var isMac = /Mac/.test(navigator.platform), escapeHtml = $.ui.fancytree.escapeHtml, unescapeHtml = $.ui.fancytree.unescapeHtml; /** * [ext-edit] Start inline editing of current node title. * * @alias FancytreeNode#editStart * @requires Fancytree */ $.ui.fancytree._FancytreeNodeClass.prototype.editStart = function() { var $input, node = this, tree = this.tree, local = tree.ext.edit, instOpts = tree.options.edit, $title = $(".fancytree-title", node.span), eventData = { node: node, tree: tree, options: tree.options, isNew: $(node[tree.statusClassPropName]).hasClass( "fancytree-edit-new" ), orgTitle: node.title, input: null, dirty: false, }; // beforeEdit may want to modify the title before editing if ( instOpts.beforeEdit.call( node, { type: "beforeEdit" }, eventData ) === false ) { return false; } $.ui.fancytree.assert(!local.currentNode, "recursive edit"); local.currentNode = this; local.eventData = eventData; // Disable standard Fancytree mouse- and key handling tree.widget._unbind(); local.lastDraggableAttrValue = node.span.draggable; if (local.lastDraggableAttrValue) { node.span.draggable = false; } // #116: ext-dnd prevents the blur event, so we have to catch outer clicks $(document).on("mousedown.fancytree-edit", function(event) { if (!$(event.target).hasClass("fancytree-edit-input")) { node.editEnd(true, event); } }); // Replace node with <input> $input = $("<input />", { class: "fancytree-edit-input", type: "text", value: tree.options.escapeTitles ? eventData.orgTitle : unescapeHtml(eventData.orgTitle), }); local.eventData.input = $input; if (instOpts.adjustWidthOfs != null) { $input.width($title.width() + instOpts.adjustWidthOfs); } if (instOpts.inputCss != null) { $input.css(instOpts.inputCss); } $title.html($input); // Focus <input> and bind keyboard handler $input .focus() .change(function(event) { $input.addClass("fancytree-edit-dirty"); }) .on("keydown", function(event) { switch (event.which) { case $.ui.keyCode.ESCAPE: node.editEnd(false, event); break; case $.ui.keyCode.ENTER: node.editEnd(true, event); return false; // so we don't start editmode on Mac } event.stopPropagation(); }) .blur(function(event) { return node.editEnd(true, event); }); instOpts.edit.call(node, { type: "edit" }, eventData); }; /** * [ext-edit] Stop inline editing. * @param {Boolean} [applyChanges=false] false: cancel edit, true: save (if modified) * @alias FancytreeNode#editEnd * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function( applyChanges, _event ) { var newVal, node = this, tree = this.tree, local = tree.ext.edit, eventData = local.eventData, instOpts = tree.options.edit, $title = $(".fancytree-title", node.span), $input = $title.find("input.fancytree-edit-input"); if (instOpts.trim) { $input.val($.trim($input.val())); } newVal = $input.val(); eventData.dirty = newVal !== node.title; eventData.originalEvent = _event; // Find out, if saving is required if (applyChanges === false) { // If true/false was passed, honor this (except in rename mode, if unchanged) eventData.save = false; } else if (eventData.isNew) { // In create mode, we save everything, except for empty text eventData.save = newVal !== ""; } else { // In rename mode, we save everyting, except for empty or unchanged text eventData.save = eventData.dirty && newVal !== ""; } // Allow to break (keep editor open), modify input, or re-define data.save if ( instOpts.beforeClose.call( node, { type: "beforeClose" }, eventData ) === false ) { return false; } if ( eventData.save && instOpts.save.call(node, { type: "save" }, eventData) === false ) { return false; } $input.removeClass("fancytree-edit-dirty").off(); // Unbind outer-click handler $(document).off(".fancytree-edit"); if (eventData.save) { // # 171: escape user input (not required if global escaping is on) node.setTitle( tree.options.escapeTitles ? newVal : escapeHtml(newVal) ); node.setFocus(); } else { if (eventData.isNew) { node.remove(); node = eventData.node = null; local.relatedNode.setFocus(); } else { node.renderTitle(); node.setFocus(); } } local.eventData = null; local.currentNode = null; local.relatedNode = null; // Re-enable mouse and keyboard handling tree.widget._bind(); if (local.lastDraggableAttrValue) { node.span.draggable = true; } // Set keyboard focus, even if setFocus() claims 'nothing to do' $(tree.$container).focus(); eventData.input = null; instOpts.close.call(node, { type: "close" }, eventData); return true; }; /** * [ext-edit] Create a new child or sibling node and start edit mode. * * @param {String} [mode='child'] 'before', 'after', or 'child' * @param {Object} [init] NodeData (or simple title string) * @alias FancytreeNode#editCreateNode * @requires jquery.fancytree.edit.js * @since 2.4 */ $.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function( mode, init ) { var newNode, tree = this.tree, self = this; mode = mode || "child"; if (init == null) { init = { title: "" }; } else if (typeof init === "string") { init = { title: init }; } else { $.ui.fancytree.assert($.isPlainObject(init)); } // Make sure node is expanded (and loaded) in 'child' mode if ( mode === "child" && !this.isExpanded() && this.hasChildren() !== false ) { this.setExpanded().done(function() { self.editCreateNode(mode, init); }); return; } newNode = this.addNode(init, mode); // #644: Don't filter new nodes. newNode.match = true; $(newNode[tree.statusClassPropName]) .removeClass("fancytree-hide") .addClass("fancytree-match"); newNode.makeVisible(/*{noAnimation: true}*/).done(function() { $(newNode[tree.statusClassPropName]).addClass("fancytree-edit-new"); self.tree.ext.edit.relatedNode = self; newNode.editStart(); }); }; /** * [ext-edit] Check if any node in this tree in edit mode. * * @returns {FancytreeNode | null} * @alias Fancytree#isEditing * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeClass.prototype.isEditing = function() { return this.ext.edit ? this.ext.edit.currentNode : null; }; /** * [ext-edit] Check if this node is in edit mode. * @returns {Boolean} true if node is currently beeing edited * @alias FancytreeNode#isEditing * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function() { return this.tree.ext.edit ? this.tree.ext.edit.currentNode === this : false; }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "edit", version: "2.34.0", // Default options for this extension. options: { adjustWidthOfs: 4, // null: don't adjust input size to content allowEmpty: false, // Prevent empty input inputCss: { minWidth: "3em" }, // triggerCancel: ["esc", "tab", "click"], triggerStart: ["f2", "mac+enter", "shift+click"], trim: true, // Trim whitespace before save // Events: beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available) beforeEdit: $.noop, // Return false to prevent edit mode close: $.noop, // Editor was removed edit: $.noop, // Editor was opened (available as data.input) // keypress: $.noop, // Not yet implemented save: $.noop, // Save data.input.val() or return false to keep editor open }, // Local attributes currentNode: null, treeInit: function(ctx) { var tree = ctx.tree; this._superApply(arguments); this.$container .addClass("fancytree-ext-edit") .on("fancytreebeforeupdateviewport", function(event, data) { var editNode = tree.isEditing(); // When scrolling, the TR may be re-used by another node, so the // active cell marker an if (editNode) { editNode.info("Cancel edit due to scroll event."); editNode.editEnd(false, event); } }); }, nodeClick: function(ctx) { var eventStr = $.ui.fancytree.eventToString(ctx.originalEvent), triggerStart = ctx.options.edit.triggerStart; if ( eventStr === "shift+click" && $.inArray("shift+click", triggerStart) >= 0 ) { if (ctx.originalEvent.shiftKey) { ctx.node.editStart(); return false; } } if ( eventStr === "click" && $.inArray("clickActive", triggerStart) >= 0 ) { // Only when click was inside title text (not aynwhere else in the row) if ( ctx.node.isActive() && !ctx.node.isEditing() && $(ctx.originalEvent.target).hasClass("fancytree-title") ) { ctx.node.editStart(); return false; } } return this._superApply(arguments); }, nodeDblclick: function(ctx) { if ($.inArray("dblclick", ctx.options.edit.triggerStart) >= 0) { ctx.node.editStart(); return false; } return this._superApply(arguments); }, nodeKeydown: function(ctx) { switch (ctx.originalEvent.which) { case 113: // [F2] if ($.inArray("f2", ctx.options.edit.triggerStart) >= 0) { ctx.node.editStart(); return false; } break; case $.ui.keyCode.ENTER: if ( $.inArray("mac+enter", ctx.options.edit.triggerStart) >= 0 && isMac ) { ctx.node.editStart(); return false; } break; } return this._superApply(arguments); }, }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; }); // End of closure /*! Extension 'jquery.fancytree.filter.js' *//*! * jquery.fancytree.filter.js * * Remove or highlight tree nodes, based on a filter. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery", "./jquery.fancytree"], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { "use strict"; /******************************************************************************* * Private functions and variables */ var KeyNoData = "__not_found__", escapeHtml = $.ui.fancytree.escapeHtml; function _escapeRegex(str) { return (str + "").replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); } function extractHtmlText(s) { if (s.indexOf(">") >= 0) { return $("<div/>") .html(s) .text(); } return s; } $.ui.fancytree._FancytreeClass.prototype._applyFilterImpl = function( filter, branchMode, _opts ) { var match, statusNode, re, reHighlight, temp, prevEnableUpdate, count = 0, treeOpts = this.options, escapeTitles = treeOpts.escapeTitles, prevAutoCollapse = treeOpts.autoCollapse, opts = $.extend({}, treeOpts.filter, _opts), hideMode = opts.mode === "hide", leavesOnly = !!opts.leavesOnly && !branchMode; // Default to 'match title substring (not case sensitive)' if (typeof filter === "string") { if (filter === "") { this.warn( "Fancytree passing an empty string as a filter is handled as clearFilter()." ); this.clearFilter(); return; } if (opts.fuzzy) { // See https://codereview.stackexchange.com/questions/23899/faster-javascript-fuzzy-string-matching-function/23905#23905 // and http://www.quora.com/How-is-the-fuzzy-search-algorithm-in-Sublime-Text-designed // and http://www.dustindiaz.com/autocomplete-fuzzy-matching match = filter.split("").reduce(function(a, b) { return a + "[^" + b + "]*" + b; }); } else { match = _escapeRegex(filter); // make sure a '.' is treated literally } re = new RegExp(".*" + match + ".*", "i"); reHighlight = new RegExp(_escapeRegex(filter), "gi"); filter = function(node) { if (!node.title) { return false; } var text = escapeTitles ? node.title : extractHtmlText(node.title), res = !!re.test(text); if (res && opts.highlight) { if (escapeTitles) { // #740: we must not apply the marks to escaped entity names, e.g. `&quot;` // Use some exotic characters to mark matches: temp = text.replace(reHighlight, function(s) { return "\uFFF7" + s + "\uFFF8"; }); // now we can escape the title... node.titleWithHighlight = escapeHtml(temp) // ... and finally insert the desired `<mark>` tags .replace(/\uFFF7/g, "<mark>") .replace(/\uFFF8/g, "</mark>"); } else { node.titleWithHighlight = text.replace( reHighlight, function(s) { return "<mark>" + s + "</mark>"; } ); } // node.debug("filter", escapeTitles, text, node.titleWithHighlight); } return res; }; } this.enableFilter = true; this.lastFilterArgs = arguments; prevEnableUpdate = this.enableUpdate(false); this.$div.addClass("fancytree-ext-filter"); if (hideMode) { this.$div.addClass("fancytree-ext-filter-hide"); } else { this.$div.addClass("fancytree-ext-filter-dimm"); } this.$div.toggleClass( "fancytree-ext-filter-hide-expanders", !!opts.hideExpanders ); // Reset current filter this.rootNode.subMatchCount = 0; this.visit(function(node) { delete node.match; delete node.titleWithHighlight; node.subMatchCount = 0; }); statusNode = this.getRootNode()._findDirectChild(KeyNoData); if (statusNode) { statusNode.remove(); } // Adjust node.hide, .match, and .subMatchCount properties treeOpts.autoCollapse = false; // #528 this.visit(function(node) { if (leavesOnly && node.children != null) { return; } var res = filter(node), matchedByBranch = false; if (res === "skip") { node.visit(function(c) { c.match = false; }, true); return "skip"; } if (!res && (branchMode || res === "branch") && node.parent.match) { res = true; matchedByBranch = true; } if (res) { count++; node.match = true; node.visitParents(function(p) { if (p !== node) { p.subMatchCount += 1; } // Expand match (unless this is no real match, but only a node in a matched branch) if (opts.autoExpand && !matchedByBranch && !p.expanded) { p.setExpanded(true, { noAnimation: true, noEvents: true, scrollIntoView: false, }); p._filterAutoExpanded = true; } }, true); } }); treeOpts.autoCollapse = prevAutoCollapse; if (count === 0 && opts.nodata && hideMode) { statusNode = opts.nodata; if ($.isFunction(statusNode)) { statusNode = statusNode(); } if (statusNode === true) { statusNode = {}; } else if (typeof statusNode === "string") { statusNode = { title: statusNode }; } statusNode = $.extend( { statusNodeType: "nodata", key: KeyNoData, title: this.options.strings.noData, }, statusNode ); this.getRootNode().addNode(statusNode).match = true; } // Redraw whole tree this._callHook("treeStructureChanged", this, "applyFilter"); // this.render(); this.enableUpdate(prevEnableUpdate); return count; }; /** * [ext-filter] Dimm or hide nodes. * * @param {function | string} filter * @param {boolean} [opts={autoExpand: false, leavesOnly: false}] * @returns {integer} count * @alias Fancytree#filterNodes * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.filterNodes = function( filter, opts ) { if (typeof opts === "boolean") { opts = { leavesOnly: opts }; this.warn( "Fancytree.filterNodes() leavesOnly option is deprecated since 2.9.0 / 2015-04-19. Use opts.leavesOnly instead." ); } return this._applyFilterImpl(filter, false, opts); }; /** * [ext-filter] Dimm or hide whole branches. * * @param {function | string} filter * @param {boolean} [opts={autoExpand: false}] * @returns {integer} count * @alias Fancytree#filterBranches * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.filterBranches = function( filter, opts ) { return this._applyFilterImpl(filter, true, opts); }; /** * [ext-filter] Reset the filter. * * @alias Fancytree#clearFilter * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.clearFilter = function() { var $title, statusNode = this.getRootNode()._findDirectChild(KeyNoData), escapeTitles = this.options.escapeTitles, enhanceTitle = this.options.enhanceTitle, prevEnableUpdate = this.enableUpdate(false); if (statusNode) { statusNode.remove(); } // we also counted root node's subMatchCount delete this.rootNode.match; delete this.rootNode.subMatchCount; this.visit(function(node) { if (node.match && node.span) { // #491, #601 $title = $(node.span).find(">span.fancytree-title"); if (escapeTitles) { $title.text(node.title); } else { $title.html(node.title); } if (enhanceTitle) { enhanceTitle( { type: "enhanceTitle" }, { node: node, $title: $title } ); } } delete node.match; delete node.subMatchCount; delete node.titleWithHighlight; if (node.$subMatchBadge) { node.$subMatchBadge.remove(); delete node.$subMatchBadge; } if (node._filterAutoExpanded && node.expanded) { node.setExpanded(false, { noAnimation: true, noEvents: true, scrollIntoView: false, }); } delete node._filterAutoExpanded; }); this.enableFilter = false; this.lastFilterArgs = null; this.$div.removeClass( "fancytree-ext-filter fancytree-ext-filter-dimm fancytree-ext-filter-hide" ); this._callHook("treeStructureChanged", this, "clearFilter"); // this.render(); this.enableUpdate(prevEnableUpdate); }; /** * [ext-filter] Return true if a filter is currently applied. * * @returns {Boolean} * @alias Fancytree#isFilterActive * @requires jquery.fancytree.filter.js * @since 2.13 */ $.ui.fancytree._FancytreeClass.prototype.isFilterActive = function() { return !!this.enableFilter; }; /** * [ext-filter] Return true if this node is matched by current filter (or no filter is active). * * @returns {Boolean} * @alias FancytreeNode#isMatched * @requires jquery.fancytree.filter.js * @since 2.13 */ $.ui.fancytree._FancytreeNodeClass.prototype.isMatched = function() { return !(this.tree.enableFilter && !this.match); }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "filter", version: "2.34.0", // Default options for this extension. options: { autoApply: true, // Re-apply last filter if lazy data is loaded autoExpand: false, // Expand all branches that contain matches while filtered counter: true, // Show a badge with number of matching child nodes near parent icons fuzzy: false, // Match single characters in order, e.g. 'fb' will match 'FooBar' hideExpandedCounter: true, // Hide counter badge if parent is expanded hideExpanders: false, // Hide expanders if all child nodes are hidden by filter highlight: true, // Highlight matches by wrapping inside <mark> tags leavesOnly: false, // Match end nodes only nodata: true, // Display a 'no data' status node if result is empty mode: "dimm", // Grayout unmatched nodes (pass "hide" to remove unmatched node instead) }, nodeLoadChildren: function(ctx, source) { var tree = ctx.tree; return this._superApply(arguments).done(function() { if ( tree.enableFilter && tree.lastFilterArgs && ctx.options.filter.autoApply ) { tree._applyFilterImpl.apply(tree, tree.lastFilterArgs); } }); }, nodeSetExpanded: function(ctx, flag, callOpts) { var node = ctx.node; delete node._filterAutoExpanded; // Make sure counter badge is displayed again, when node is beeing collapsed if ( !flag && ctx.options.filter.hideExpandedCounter && node.$subMatchBadge ) { node.$subMatchBadge.show(); } return this._superApply(arguments); }, nodeRenderStatus: function(ctx) { // Set classes for current status var res, node = ctx.node, tree = ctx.tree, opts = ctx.options.filter, $title = $(node.span).find("span.fancytree-title"), $span = $(node[tree.statusClassPropName]), enhanceTitle = ctx.options.enhanceTitle, escapeTitles = ctx.options.escapeTitles; res = this._super(ctx); // nothing to do, if node was not yet rendered if (!$span.length || !tree.enableFilter) { return res; } $span .toggleClass("fancytree-match", !!node.match) .toggleClass("fancytree-submatch", !!node.subMatchCount) .toggleClass( "fancytree-hide", !(node.match || node.subMatchCount) ); // Add/update counter badge if ( opts.counter && node.subMatchCount && (!node.isExpanded() || !opts.hideExpandedCounter) ) { if (!node.$subMatchBadge) { node.$subMatchBadge = $( "<span class='fancytree-childcounter'/>" ); $( "span.fancytree-icon, span.fancytree-custom-icon", node.span ).append(node.$subMatchBadge); } node.$subMatchBadge.show().text(node.subMatchCount); } else if (node.$subMatchBadge) { node.$subMatchBadge.hide(); } // node.debug("nodeRenderStatus", node.titleWithHighlight, node.title) // #601: also check for $title.length, because we don't need to render // if node.span is null (i.e. not rendered) if (node.span && (!node.isEditing || !node.isEditing.call(node))) { if (node.titleWithHighlight) { $title.html(node.titleWithHighlight); } else if (escapeTitles) { $title.text(node.title); } else { $title.html(node.title); } if (enhanceTitle) { enhanceTitle( { type: "enhanceTitle" }, { node: node, $title: $title } ); } } return res; }, }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; }); // End of closure /*! Extension 'jquery.fancytree.glyph.js' *//*! * jquery.fancytree.glyph.js * * Use glyph-fonts, ligature-fonts, or SVG icons instead of icon sprites. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery", "./jquery.fancytree"], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { "use strict"; /****************************************************************************** * Private functions and variables */ var FT = $.ui.fancytree, PRESETS = { awesome3: { // Outdated! _addClass: "", checkbox: "icon-check-empty", checkboxSelected: "icon-check", checkboxUnknown: "icon-check icon-muted", dragHelper: "icon-caret-right", dropMarker: "icon-caret-right", error: "icon-exclamation-sign", expanderClosed: "icon-caret-right", expanderLazy: "icon-angle-right", expanderOpen: "icon-caret-down", loading: "icon-refresh icon-spin", nodata: "icon-meh", noExpander: "", radio: "icon-circle-blank", radioSelected: "icon-circle", // radioUnknown: "icon-circle icon-muted", // Default node icons. // (Use tree.options.icon callback to define custom icons based on node data) doc: "icon-file-alt", docOpen: "icon-file-alt", folder: "icon-folder-close-alt", folderOpen: "icon-folder-open-alt", }, awesome4: { _addClass: "fa", checkbox: "fa-square-o", checkboxSelected: "fa-check-square-o", checkboxUnknown: "fa-square fancytree-helper-indeterminate-cb", dragHelper: "fa-arrow-right", dropMarker: "fa-long-arrow-right", error: "fa-warning", expanderClosed: "fa-caret-right", expanderLazy: "fa-angle-right", expanderOpen: "fa-caret-down", // We may prevent wobbling rotations on FF by creating a separate sub element: loading: { html: "<span class='fa fa-spinner fa-pulse' />" }, nodata: "fa-meh-o", noExpander: "", radio: "fa-circle-thin", // "fa-circle-o" radioSelected: "fa-circle", // radioUnknown: "fa-dot-circle-o", // Default node icons. // (Use tree.options.icon callback to define custom icons based on node data) doc: "fa-file-o", docOpen: "fa-file-o", folder: "fa-folder-o", folderOpen: "fa-folder-open-o", }, awesome5: { // fontawesome 5 have several different base classes // "far, fas, fal and fab" The rendered svg puts that prefix // in a different location so we have to keep them separate here _addClass: "", checkbox: "far fa-square", checkboxSelected: "far fa-check-square", // checkboxUnknown: "far fa-window-close", checkboxUnknown: "fas fa-square fancytree-helper-indeterminate-cb", radio: "far fa-circle", radioSelected: "fas fa-circle", radioUnknown: "far fa-dot-circle", dragHelper: "fas fa-arrow-right", dropMarker: "fas fa-long-arrow-alt-right", error: "fas fa-exclamation-triangle", expanderClosed: "fas fa-caret-right", expanderLazy: "fas fa-angle-right", expanderOpen: "fas fa-caret-down", loading: "fas fa-spinner fa-pulse", nodata: "far fa-meh", noExpander: "", // Default node icons. // (Use tree.options.icon callback to define custom icons based on node data) doc: "far fa-file", docOpen: "far fa-file", folder: "far fa-folder", folderOpen: "far fa-folder-open", }, bootstrap3: { _addClass: "glyphicon", checkbox: "glyphicon-unchecked", checkboxSelected: "glyphicon-check", checkboxUnknown: "glyphicon-expand fancytree-helper-indeterminate-cb", // "glyphicon-share", dragHelper: "glyphicon-play", dropMarker: "glyphicon-arrow-right", error: "glyphicon-warning-sign", expanderClosed: "glyphicon-menu-right", // glyphicon-plus-sign expanderLazy: "glyphicon-menu-right", // glyphicon-plus-sign expanderOpen: "glyphicon-menu-down", // glyphicon-minus-sign loading: "glyphicon-refresh fancytree-helper-spin", nodata: "glyphicon-info-sign", noExpander: "", radio: "glyphicon-remove-circle", // "glyphicon-unchecked", radioSelected: "glyphicon-ok-circle", // "glyphicon-check", // radioUnknown: "glyphicon-ban-circle", // Default node icons. // (Use tree.options.icon callback to define custom icons based on node data) doc: "glyphicon-file", docOpen: "glyphicon-file", folder: "glyphicon-folder-close", folderOpen: "glyphicon-folder-open", }, material: { _addClass: "material-icons", checkbox: { text: "check_box_outline_blank" }, checkboxSelected: { text: "check_box" }, checkboxUnknown: { text: "indeterminate_check_box" }, dragHelper: { text: "play_arrow" }, dropMarker: { text: "arrow-forward" }, error: { text: "warning" }, expanderClosed: { text: "chevron_right" }, expanderLazy: { text: "last_page" }, expanderOpen: { text: "expand_more" }, loading: { text: "autorenew", addClass: "fancytree-helper-spin", }, nodata: { text: "info" }, noExpander: { text: "" }, radio: { text: "radio_button_unchecked" }, radioSelected: { text: "radio_button_checked" }, // Default node icons. // (Use tree.options.icon callback to define custom icons based on node data) doc: { text: "insert_drive_file" }, docOpen: { text: "insert_drive_file" }, folder: { text: "folder" }, folderOpen: { text: "folder_open" }, }, }; function setIcon(span, baseClass, opts, type) { var map = opts.map, icon = map[type], $span = $(span), $counter = $span.find(".fancytree-childcounter"), setClass = baseClass + " " + (map._addClass || ""); if (typeof icon === "string") { // #883: remove inner html that may be added by prev. mode span.innerHTML = ""; $span.attr("class", setClass + " " + icon).append($counter); } else if (icon) { if (icon.text) { span.textContent = "" + icon.text; } else if (icon.html) { span.innerHTML = icon.html; } else { span.innerHTML = ""; } $span .attr("class", setClass + " " + (icon.addClass || "")) .append($counter); } } $.ui.fancytree.registerExtension({ name: "glyph", version: "2.34.0", // Default options for this extension. options: { preset: null, // 'awesome3', 'awesome4', 'bootstrap3', 'material' map: {}, }, treeInit: function(ctx) { var tree = ctx.tree, opts = ctx.options.glyph; if (opts.preset) { FT.assert( !!PRESETS[opts.preset], "Invalid value for `options.glyph.preset`: " + opts.preset ); opts.map = $.extend({}, PRESETS[opts.preset], opts.map); } else { tree.warn("ext-glyph: missing `preset` option."); } this._superApply(arguments); tree.$container.addClass("fancytree-ext-glyph"); }, nodeRenderStatus: function(ctx) { var checkbox, icon, res, span, node = ctx.node, $span = $(node.span), opts = ctx.options.glyph; res = this._super(ctx); if (node.isRoot()) { return res; } span = $span.children("span.fancytree-expander").get(0); if (span) { // if( node.isLoading() ){ // icon = "loading"; if (node.expanded && node.hasChildren()) { icon = "expanderOpen"; } else if (node.isUndefined()) { icon = "expanderLazy"; } else if (node.hasChildren()) { icon = "expanderClosed"; } else { icon = "noExpander"; } // span.className = "fancytree-expander " + map[icon]; setIcon(span, "fancytree-expander", opts, icon); } if (node.tr) { span = $("td", node.tr) .find("span.fancytree-checkbox") .get(0); } else { span = $span.children("span.fancytree-checkbox").get(0); } if (span) { checkbox = FT.evalOption("checkbox", node, node, opts, false); if ( (node.parent && node.parent.radiogroup) || checkbox === "radio" ) { icon = node.selected ? "radioSelected" : "radio"; setIcon( span, "fancytree-checkbox fancytree-radio", opts, icon ); } else { // eslint-disable-next-line no-nested-ternary icon = node.selected ? "checkboxSelected" : node.partsel ? "checkboxUnknown" : "checkbox"; // span.className = "fancytree-checkbox " + map[icon]; setIcon(span, "fancytree-checkbox", opts, icon); } } // Standard icon (note that this does not match .fancytree-custom-icon, // that might be set by opts.icon callbacks) span = $span.children("span.fancytree-icon").get(0); if (span) { if (node.statusNodeType) { icon = node.statusNodeType; // loading, error } else if (node.folder) { icon = node.expanded && node.hasChildren() ? "folderOpen" : "folder"; } else { icon = node.expanded ? "docOpen" : "doc"; } setIcon(span, "fancytree-icon", opts, icon); } return res; }, nodeSetStatus: function(ctx, status, message, details) { var res, span, opts = ctx.options.glyph, node = ctx.node; res = this._superApply(arguments); if ( status === "error" || status === "loading" || status === "nodata" ) { if (node.parent) { span = $("span.fancytree-expander", node.span).get(0); if (span) { setIcon(span, "fancytree-expander", opts, status); } } else { // span = $( ".fancytree-statusnode-" + status, node[this.nodeContainerAttrName] ) .find("span.fancytree-icon") .get(0); if (span) { setIcon(span, "fancytree-icon", opts, status); } } } return res; }, }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; }); // End of closure /*! Extension 'jquery.fancytree.gridnav.js' *//*! * jquery.fancytree.gridnav.js * * Support keyboard navigation for trees with embedded input controls. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define([ "jquery", "./jquery.fancytree", "./jquery.fancytree.table", ], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree.table"); // core + table module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { "use strict"; /******************************************************************************* * Private functions and variables */ // Allow these navigation keys even when input controls are focused var KC = $.ui.keyCode, // which keys are *not* handled by embedded control, but passed to tree // navigation handler: NAV_KEYS = { text: [KC.UP, KC.DOWN], checkbox: [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT], link: [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT], radiobutton: [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT], "select-one": [KC.LEFT, KC.RIGHT], "select-multiple": [KC.LEFT, KC.RIGHT], }; /* Calculate TD column index (considering colspans).*/ function getColIdx($tr, $td) { var colspan, td = $td.get(0), idx = 0; $tr.children().each(function() { if (this === td) { return false; } colspan = $(this).prop("colspan"); idx += colspan ? colspan : 1; }); return idx; } /* Find TD at given column index (considering colspans).*/ function findTdAtColIdx($tr, colIdx) { var colspan, res = null, idx = 0; $tr.children().each(function() { if (idx >= colIdx) { res = $(this); return false; } colspan = $(this).prop("colspan"); idx += colspan ? colspan : 1; }); return res; } /* Find adjacent cell for a given direction. Skip empty cells and consider merged cells */ function findNeighbourTd($target, keyCode) { var $tr, colIdx, $td = $target.closest("td"), $tdNext = null; switch (keyCode) { case KC.LEFT: $tdNext = $td.prev(); break; case KC.RIGHT: $tdNext = $td.next(); break; case KC.UP: case KC.DOWN: $tr = $td.parent(); colIdx = getColIdx($tr, $td); while (true) { $tr = keyCode === KC.UP ? $tr.prev() : $tr.next(); if (!$tr.length) { break; } // Skip hidden rows if ($tr.is(":hidden")) { continue; } // Find adjacent cell in the same column $tdNext = findTdAtColIdx($tr, colIdx); // Skip cells that don't conatain a focusable element if ($tdNext && $tdNext.find(":input,a").length) { break; } } break; } return $tdNext; } /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "gridnav", version: "2.34.0", // Default options for this extension. options: { autofocusInput: false, // Focus first embedded input if node gets activated handleCursorKeys: true, // Allow UP/DOWN in inputs to move to prev/next node }, treeInit: function(ctx) { // gridnav requires the table extension to be loaded before itself this._requireExtension("table", true, true); this._superApply(arguments); this.$container.addClass("fancytree-ext-gridnav"); // Activate node if embedded input gets focus (due to a click) this.$container.on("focusin", function(event) { var ctx2, node = $.ui.fancytree.getNode(event.target); if (node && !node.isActive()) { // Call node.setActive(), but also pass the event ctx2 = ctx.tree._makeHookContext(node, event); ctx.tree._callHook("nodeSetActive", ctx2, true); } }); }, nodeSetActive: function(ctx, flag, callOpts) { var $outer, opts = ctx.options.gridnav, node = ctx.node, event = ctx.originalEvent || {}, triggeredByInput = $(event.target).is(":input"); flag = flag !== false; this._superApply(arguments); if (flag) { if (ctx.options.titlesTabbable) { if (!triggeredByInput) { $(node.span) .find("span.fancytree-title") .focus(); node.setFocus(); } // If one node is tabbable, the container no longer needs to be ctx.tree.$container.attr("tabindex", "-1"); // ctx.tree.$container.removeAttr("tabindex"); } else if (opts.autofocusInput && !triggeredByInput) { // Set focus to input sub input (if node was clicked, but not // when TAB was pressed ) $outer = $(node.tr || node.span); $outer .find(":input:enabled") .first() .focus(); } } }, nodeKeydown: function(ctx) { var inputType, handleKeys, $td, opts = ctx.options.gridnav, event = ctx.originalEvent, $target = $(event.target); if ($target.is(":input:enabled")) { inputType = $target.prop("type"); } else if ($target.is("a")) { inputType = "link"; } // ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType); if (inputType && opts.handleCursorKeys) { handleKeys = NAV_KEYS[inputType]; if (handleKeys && $.inArray(event.which, handleKeys) >= 0) { $td = findNeighbourTd($target, event.which); if ($td && $td.length) { // ctx.node.debug("ignore keydown in input", event.which, handleKeys); $td.find(":input:enabled,a").focus(); // Prevent Fancytree default navigation return false; } } return true; } // ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType); return this._superApply(arguments); }, }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; }); // End of closure /*! Extension 'jquery.fancytree.multi.js' *//*! * jquery.fancytree.multi.js * * Allow multiple selection of nodes by mouse or keyboard. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery", "./jquery.fancytree"], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { "use strict"; /******************************************************************************* * Private functions and variables */ // var isMac = /Mac/.test(navigator.platform); /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "multi", version: "2.34.0", // Default options for this extension. options: { allowNoSelect: false, // mode: "sameParent", // // Events: // beforeSelect: $.noop // Return false to prevent cancel/save (data.input is available) }, treeInit: function(ctx) { this._superApply(arguments); this.$container.addClass("fancytree-ext-multi"); if (ctx.options.selectMode === 1) { $.error( "Fancytree ext-multi: selectMode: 1 (single) is not compatible." ); } }, nodeClick: function(ctx) { var //pluginOpts = ctx.options.multi, tree = ctx.tree, node = ctx.node, activeNode = tree.getActiveNode() || tree.getFirstChild(), isCbClick = ctx.targetType === "checkbox", isExpanderClick = ctx.targetType === "expander", eventStr = $.ui.fancytree.eventToString(ctx.originalEvent); switch (eventStr) { case "click": if (isExpanderClick) { break; } // Default handler will expand/collapse if (!isCbClick) { tree.selectAll(false); // Select clicked node (radio-button mode) node.setSelected(); } // Default handler will toggle checkbox clicks and activate break; case "shift+click": // node.debug("click") tree.visitRows( function(n) { // n.debug("click2", n===node, node) n.setSelected(); if (n === node) { return false; } }, { start: activeNode, reverse: activeNode.isBelowOf(node), } ); break; case "ctrl+click": case "meta+click": // Mac: [Command] node.toggleSelected(); return; } return this._superApply(arguments); }, nodeKeydown: function(ctx) { var tree = ctx.tree, node = ctx.node, event = ctx.originalEvent, eventStr = $.ui.fancytree.eventToString(event); switch (eventStr) { case "up": case "down": tree.selectAll(false); node.navigate(event.which, true); tree.getActiveNode().setSelected(); break; case "shift+up": case "shift+down": node.navigate(event.which, true); tree.getActiveNode().setSelected(); break; } return this._superApply(arguments); }, }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; }); // End of closure /*! Extension 'jquery.fancytree.persist.js' *//*! * jquery.fancytree.persist.js * * Persist tree status in cookiesRemove or highlight tree nodes, based on a filter. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * @depends: js-cookie or jquery-cookie * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery", "./jquery.fancytree"], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { "use strict"; /* global Cookies:false */ /******************************************************************************* * Private functions and variables */ var cookieStore = null, localStorageStore = window.localStorage ? { get: function(key) { return window.localStorage.getItem(key); }, set: function(key, value) { window.localStorage.setItem(key, value); }, remove: function(key) { window.localStorage.removeItem(key); }, } : null, sessionStorageStore = window.sessionStorage ? { get: function(key) { return window.sessionStorage.getItem(key); }, set: function(key, value) { window.sessionStorage.setItem(key, value); }, remove: function(key) { window.sessionStorage.removeItem(key); }, } : null, _assert = $.ui.fancytree.assert, ACTIVE = "active", EXPANDED = "expanded", FOCUS = "focus", SELECTED = "selected"; if (typeof Cookies === "function") { // Assume https://github.com/js-cookie/js-cookie cookieStore = { get: Cookies.get, set: function(key, value) { Cookies.set(key, value, this.options.persist.cookie); }, remove: Cookies.remove, }; } else if ($ && typeof $.cookie === "function") { // Fall back to https://github.com/carhartl/jquery-cookie cookieStore = { get: $.cookie, set: function(key, value) { $.cookie.set(key, value, this.options.persist.cookie); }, remove: $.removeCookie, }; } /* Recursively load lazy nodes * @param {string} mode 'load', 'expand', false */ function _loadLazyNodes(tree, local, keyList, mode, dfd) { var i, key, l, node, foundOne = false, expandOpts = tree.options.persist.expandOpts, deferredList = [], missingKeyList = []; keyList = keyList || []; dfd = dfd || $.Deferred(); for (i = 0, l = keyList.length; i < l; i++) { key = keyList[i]; node = tree.getNodeByKey(key); if (node) { if (mode && node.isUndefined()) { foundOne = true; tree.debug( "_loadLazyNodes: " + node + " is lazy: loading..." ); if (mode === "expand") { deferredList.push(node.setExpanded(true, expandOpts)); } else { deferredList.push(node.load()); } } else { tree.debug("_loadLazyNodes: " + node + " already loaded."); node.setExpanded(true, expandOpts); } } else { missingKeyList.push(key); tree.debug("_loadLazyNodes: " + node + " was not yet found."); } } $.when.apply($, deferredList).always(function() { // All lazy-expands have finished if (foundOne && missingKeyList.length > 0) { // If we read new nodes from server, try to resolve yet-missing keys _loadLazyNodes(tree, local, missingKeyList, mode, dfd); } else { if (missingKeyList.length) { tree.warn( "_loadLazyNodes: could not load those keys: ", missingKeyList ); for (i = 0, l = missingKeyList.length; i < l; i++) { key = keyList[i]; local._appendKey(EXPANDED, keyList[i], false); } } dfd.resolve(); } }); return dfd; } /** * [ext-persist] Remove persistence data of the given type(s). * Called like * $.ui.fancytree.getTree("#tree").clearCookies("active expanded focus selected"); * * @alias Fancytree#clearPersistData * @requires jquery.fancytree.persist.js */ $.ui.fancytree._FancytreeClass.prototype.clearPersistData = function( types ) { var local = this.ext.persist, prefix = local.cookiePrefix; types = types || "active expanded focus selected"; if (types.indexOf(ACTIVE) >= 0) { local._data(prefix + ACTIVE, null); } if (types.indexOf(EXPANDED) >= 0) { local._data(prefix + EXPANDED, null); } if (types.indexOf(FOCUS) >= 0) { local._data(prefix + FOCUS, null); } if (types.indexOf(SELECTED) >= 0) { local._data(prefix + SELECTED, null); } }; $.ui.fancytree._FancytreeClass.prototype.clearCookies = function(types) { this.warn( "'tree.clearCookies()' is deprecated since v2.27.0: use 'clearPersistData()' instead." ); return this.clearPersistData(types); }; /** * [ext-persist] Return persistence information from cookies * * Called like * $.ui.fancytree.getTree("#tree").getPersistData(); * * @alias Fancytree#getPersistData * @requires jquery.fancytree.persist.js */ $.ui.fancytree._FancytreeClass.prototype.getPersistData = function() { var local = this.ext.persist, prefix = local.cookiePrefix, delim = local.cookieDelimiter, res = {}; res[ACTIVE] = local._data(prefix + ACTIVE); res[EXPANDED] = (local._data(prefix + EXPANDED) || "").split(delim); res[SELECTED] = (local._data(prefix + SELECTED) || "").split(delim); res[FOCUS] = local._data(prefix + FOCUS); return res; }; /****************************************************************************** * Extension code */ $.ui.fancytree.registerExtension({ name: "persist", version: "2.34.0", // Default options for this extension. options: { cookieDelimiter: "~", cookiePrefix: undefined, // 'fancytree-<treeId>-' by default cookie: { raw: false, expires: "", path: "", domain: "", secure: false, }, expandLazy: false, // true: recursively expand and load lazy nodes expandOpts: undefined, // optional `opts` argument passed to setExpanded() fireActivate: true, // false: suppress `activate` event after active node was restored overrideSource: true, // true: cookie takes precedence over `source` data attributes. store: "auto", // 'cookie': force cookie, 'local': force localStore, 'session': force sessionStore types: "active expanded focus selected", }, /* Generic read/write string data to cookie, sessionStorage or localStorage. */ _data: function(key, value) { var store = this._local.store; if (value === undefined) { return store.get.call(this, key); } else if (value === null) { store.remove.call(this, key); } else { store.set.call(this, key, value); } }, /* Append `key` to a cookie. */ _appendKey: function(type, key, flag) { key = "" + key; // #90 var local = this._local, instOpts = this.options.persist, delim = instOpts.cookieDelimiter, cookieName = local.cookiePrefix + type, data = local._data(cookieName), keyList = data ? data.split(delim) : [], idx = $.inArray(key, keyList); // Remove, even if we add a key, so the key is always the last entry if (idx >= 0) { keyList.splice(idx, 1); } // Append key to cookie if (flag) { keyList.push(key); } local._data(cookieName, keyList.join(delim)); }, treeInit: function(ctx) { var tree = ctx.tree, opts = ctx.options, local = this._local, instOpts = this.options.persist; // // For 'auto' or 'cookie' mode, the cookie plugin must be available // _assert((instOpts.store !== "auto" && instOpts.store !== "cookie") || cookieStore, // "Missing required plugin for 'persist' extension: js.cookie.js or jquery.cookie.js"); local.cookiePrefix = instOpts.cookiePrefix || "fancytree-" + tree._id + "-"; local.storeActive = instOpts.types.indexOf(ACTIVE) >= 0; local.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0; local.storeSelected = instOpts.types.indexOf(SELECTED) >= 0; local.storeFocus = instOpts.types.indexOf(FOCUS) >= 0; local.store = null; if (instOpts.store === "auto") { instOpts.store = localStorageStore ? "local" : "cookie"; } if ($.isPlainObject(instOpts.store)) { local.store = instOpts.store; } else if (instOpts.store === "cookie") { local.store = cookieStore; } else if (instOpts.store === "local") { local.store = instOpts.store === "local" ? localStorageStore : sessionStorageStore; } else if (instOpts.store === "session") { local.store = instOpts.store === "local" ? localStorageStore : sessionStorageStore; } _assert(local.store, "Need a valid store."); // Bind init-handler to apply cookie state tree.$div.on("fancytreeinit", function(event) { if ( tree._triggerTreeEvent("beforeRestore", null, {}) === false ) { return; } var cookie, dfd, i, keyList, node, prevFocus = local._data(local.cookiePrefix + FOCUS), // record this before node.setActive() overrides it; noEvents = instOpts.fireActivate === false; // tree.debug("document.cookie:", document.cookie); cookie = local._data(local.cookiePrefix + EXPANDED); keyList = cookie && cookie.split(instOpts.cookieDelimiter); if (local.storeExpanded) { // Recursively load nested lazy nodes if expandLazy is 'expand' or 'load' // Also remove expand-cookies for unmatched nodes dfd = _loadLazyNodes( tree, local, keyList, instOpts.expandLazy ? "expand" : false, null ); } else { // nothing to do dfd = new $.Deferred().resolve(); } dfd.done(function() { if (local.storeSelected) { cookie = local._data(local.cookiePrefix + SELECTED); if (cookie) { keyList = cookie.split(instOpts.cookieDelimiter); for (i = 0; i < keyList.length; i++) { node = tree.getNodeByKey(keyList[i]); if (node) { if ( node.selected === undefined || (instOpts.overrideSource && node.selected === false) ) { // node.setSelected(); node.selected = true; node.renderStatus(); } } else { // node is no longer member of the tree: remove from cookie also local._appendKey( SELECTED, keyList[i], false ); } } } // In selectMode 3 we have to fix the child nodes, since we // only stored the selected *top* nodes if (tree.options.selectMode === 3) { tree.visit(function(n) { if (n.selected) { n.fixSelection3AfterClick(); return "skip"; } }); } } if (local.storeActive) { cookie = local._data(local.cookiePrefix + ACTIVE); if ( cookie && (opts.persist.overrideSource || !tree.activeNode) ) { node = tree.getNodeByKey(cookie); if (node) { node.debug("persist: set active", cookie); // We only want to set the focus if the container // had the keyboard focus before node.setActive(true, { noFocus: true, noEvents: noEvents, }); } } } if (local.storeFocus && prevFocus) { node = tree.getNodeByKey(prevFocus); if (node) { // node.debug("persist: set focus", cookie); if (tree.options.titlesTabbable) { $(node.span) .find(".fancytree-title") .focus(); } else { $(tree.$container).focus(); } // node.setFocus(); } } tree._triggerTreeEvent("restore", null, {}); }); }); // Init the tree return this._superApply(arguments); }, nodeSetActive: function(ctx, flag, callOpts) { var res, local = this._local; flag = flag !== false; res = this._superApply(arguments); if (local.storeActive) { local._data( local.cookiePrefix + ACTIVE, this.activeNode ? this.activeNode.key : null ); } return res; }, nodeSetExpanded: function(ctx, flag, callOpts) { var res, node = ctx.node, local = this._local; flag = flag !== false; res = this._superApply(arguments); if (local.storeExpanded) { local._appendKey(EXPANDED, node.key, flag); } return res; }, nodeSetFocus: function(ctx, flag) { var res, local = this._local; flag = flag !== false; res = this._superApply(arguments); if (local.storeFocus) { local._data( local.cookiePrefix + FOCUS, this.focusNode ? this.focusNode.key : null ); } return res; }, nodeSetSelected: function(ctx, flag, callOpts) { var res, selNodes, tree = ctx.tree, node = ctx.node, local = this._local; flag = flag !== false; res = this._superApply(arguments); if (local.storeSelected) { if (tree.options.selectMode === 3) { // In selectMode 3 we only store the the selected *top* nodes. // De-selecting a node may also de-select some parents, so we // calculate the current status again selNodes = $.map(tree.getSelectedNodes(true), function(n) { return n.key; }); selNodes = selNodes.join( ctx.options.persist.cookieDelimiter ); local._data(local.cookiePrefix + SELECTED, selNodes); } else { // beforeSelect can prevent the change - flag doesn't reflect the node.selected state local._appendKey(SELECTED, node.key, node.selected); } } return res; }, }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; }); // End of closure /*! Extension 'jquery.fancytree.table.js' *//*! * jquery.fancytree.table.js * * Render tree as table (aka 'tree grid', 'table tree'). * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery", "./jquery.fancytree"], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { "use strict"; /****************************************************************************** * Private functions and variables */ function _assert(cond, msg) { msg = msg || ""; if (!cond) { $.error("Assertion failed " + msg); } } function insertFirstChild(referenceNode, newNode) { referenceNode.insertBefore(newNode, referenceNode.firstChild); } function insertSiblingAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling ); } /* Show/hide all rows that are structural descendants of `parent`. */ function setChildRowVisibility(parent, flag) { parent.visit(function(node) { var tr = node.tr; // currentFlag = node.hide ? false : flag; // fix for ext-filter if (tr) { tr.style.display = node.hide || !flag ? "none" : ""; } if (!node.expanded) { return "skip"; } }); } /* Find node that is rendered in previous row. */ function findPrevRowNode(node) { var i, last, prev, parent = node.parent, siblings = parent ? parent.children : null; if (siblings && siblings.length > 1 && siblings[0] !== node) { // use the lowest descendant of the preceeding sibling i = $.inArray(node, siblings); prev = siblings[i - 1]; _assert(prev.tr); // descend to lowest child (with a <tr> tag) while (prev.children && prev.children.length) { last = prev.children[prev.children.length - 1]; if (!last.tr) { break; } prev = last; } } else { // if there is no preceding sibling, use the direct parent prev = parent; } return prev; } $.ui.fancytree.registerExtension({ name: "table", version: "2.34.0", // Default options for this extension. options: { checkboxColumnIdx: null, // render the checkboxes into the this column index (default: nodeColumnIdx) indentation: 16, // indent every node level by 16px mergeStatusColumns: true, // display 'nodata', 'loading', 'error' centered in a single, merged TR nodeColumnIdx: 0, // render node expander, icon, and title to this column (default: #0) }, // Overide virtual methods for this extension. // `this` : is this extension object // `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree) treeInit: function(ctx) { var i, n, $row, $tbody, tree = ctx.tree, opts = ctx.options, tableOpts = opts.table, $table = tree.widget.element; if (tableOpts.customStatus != null) { if (opts.renderStatusColumns == null) { tree.warn( "The 'customStatus' option is deprecated since v2.15.0. Use 'renderStatusColumns' instead." ); opts.renderStatusColumns = tableOpts.customStatus; } else { $.error( "The 'customStatus' option is deprecated since v2.15.0. Use 'renderStatusColumns' only instead." ); } } if (opts.renderStatusColumns) { if (opts.renderStatusColumns === true) { opts.renderStatusColumns = opts.renderColumns; // } else if( opts.renderStatusColumns === "wide" ) { // opts.renderStatusColumns = _renderStatusNodeWide; } } $table.addClass("fancytree-container fancytree-ext-table"); $tbody = $table.find(">tbody"); if (!$tbody.length) { // TODO: not sure if we can rely on browsers to insert missing <tbody> before <tr>s: if ($table.find(">tr").length) { $.error( "Expected table > tbody > tr. If you see this please open an issue." ); } $tbody = $("<tbody>").appendTo($table); } tree.tbody = $tbody[0]; // Prepare row templates: // Determine column count from table header if any tree.columnCount = $("thead >tr", $table) .last() .find(">th", $table).length; // Read TR templates from tbody if any $row = $tbody.children("tr").first(); if ($row.length) { n = $row.children("td").length; if (tree.columnCount && n !== tree.columnCount) { tree.warn( "Column count mismatch between thead (" + tree.columnCount + ") and tbody (" + n + "): using tbody." ); tree.columnCount = n; } $row = $row.clone(); } else { // Only thead is defined: create default row markup _assert( tree.columnCount >= 1, "Need either <thead> or <tbody> with <td> elements to determine column count." ); $row = $("<tr />"); for (i = 0; i < tree.columnCount; i++) { $row.append("<td />"); } } $row.find(">td") .eq(tableOpts.nodeColumnIdx) .html("<span class='fancytree-node' />"); if (opts.aria) { $row.attr("role", "row"); $row.find("td").attr("role", "gridcell"); } tree.rowFragment = document.createDocumentFragment(); tree.rowFragment.appendChild($row.get(0)); // // If tbody contains a second row, use this as status node template // $row = $tbody.children("tr").eq(1); // if( $row.length === 0 ) { // tree.statusRowFragment = tree.rowFragment; // } else { // $row = $row.clone(); // tree.statusRowFragment = document.createDocumentFragment(); // tree.statusRowFragment.appendChild($row.get(0)); // } // $tbody.empty(); // Make sure that status classes are set on the node's <tr> elements tree.statusClassPropName = "tr"; tree.ariaPropName = "tr"; this.nodeContainerAttrName = "tr"; // #489: make sure $container is set to <table>, even if ext-dnd is listed before ext-table tree.$container = $table; this._superApply(arguments); // standard Fancytree created a root UL $(tree.rootNode.ul).remove(); tree.rootNode.ul = null; // Add container to the TAB chain // #577: Allow to set tabindex to "0", "-1" and "" this.$container.attr("tabindex", opts.tabindex); // this.$container.attr("tabindex", opts.tabbable ? "0" : "-1"); if (opts.aria) { tree.$container .attr("role", "treegrid") .attr("aria-readonly", true); } }, nodeRemoveChildMarkup: function(ctx) { var node = ctx.node; // node.debug("nodeRemoveChildMarkup()"); node.visit(function(n) { if (n.tr) { $(n.tr).remove(); n.tr = null; } }); }, nodeRemoveMarkup: function(ctx) { var node = ctx.node; // node.debug("nodeRemoveMarkup()"); if (node.tr) { $(node.tr).remove(); node.tr = null; } this.nodeRemoveChildMarkup(ctx); }, /* Override standard render. */ nodeRender: function(ctx, force, deep, collapsed, _recursive) { var children, firstTr, i, l, newRow, prevNode, prevTr, subCtx, tree = ctx.tree, node = ctx.node, opts = ctx.options, isRootNode = !node.parent; if (tree._enableUpdate === false) { // $.ui.fancytree.debug("*** nodeRender _enableUpdate: false"); return; } if (!_recursive) { ctx.hasCollapsedParents = node.parent && !node.parent.expanded; } // $.ui.fancytree.debug("*** nodeRender " + node + ", isRoot=" + isRootNode, "tr=" + node.tr, "hcp=" + ctx.hasCollapsedParents, "parent.tr=" + (node.parent && node.parent.tr)); if (!isRootNode) { if (node.tr && force) { this.nodeRemoveMarkup(ctx); } if (node.tr) { if (force) { // Set icon, link, and title (normally this is only required on initial render) this.nodeRenderTitle(ctx); // triggers renderColumns() } else { // Update element classes according to node state this.nodeRenderStatus(ctx); } } else { if (ctx.hasCollapsedParents && !deep) { // #166: we assume that the parent will be (recursively) rendered // later anyway. // node.debug("nodeRender ignored due to unrendered parent"); return; } // Create new <tr> after previous row // if( node.isStatusNode() ) { // newRow = tree.statusRowFragment.firstChild.cloneNode(true); // } else { newRow = tree.rowFragment.firstChild.cloneNode(true); // } prevNode = findPrevRowNode(node); // $.ui.fancytree.debug("*** nodeRender " + node + ": prev: " + prevNode.key); _assert(prevNode); if (collapsed === true && _recursive) { // hide all child rows, so we can use an animation to show it later newRow.style.display = "none"; } else if (deep && ctx.hasCollapsedParents) { // also hide this row if deep === true but any parent is collapsed newRow.style.display = "none"; // newRow.style.color = "red"; } if (prevNode.tr) { insertSiblingAfter(prevNode.tr, newRow); } else { _assert( !prevNode.parent, "prev. row must have a tr, or be system root" ); // tree.tbody.appendChild(newRow); insertFirstChild(tree.tbody, newRow); // #675 } node.tr = newRow; if (node.key && opts.generateIds) { node.tr.id = opts.idPrefix + node.key; } node.tr.ftnode = node; // if(opts.aria){ // $(node.tr).attr("aria-labelledby", "ftal_" + opts.idPrefix + node.key); // } node.span = $("span.fancytree-node", node.tr).get(0); // Set icon, link, and title (normally this is only required on initial render) this.nodeRenderTitle(ctx); // Allow tweaking, binding, after node was created for the first time // tree._triggerNodeEvent("createNode", ctx); if (opts.createNode) { opts.createNode.call(tree, { type: "createNode" }, ctx); } } } // Allow tweaking after node state was rendered // tree._triggerNodeEvent("renderNode", ctx); if (opts.renderNode) { opts.renderNode.call(tree, { type: "renderNode" }, ctx); } // Visit child nodes // Add child markup children = node.children; if (children && (isRootNode || deep || node.expanded)) { for (i = 0, l = children.length; i < l; i++) { subCtx = $.extend({}, ctx, { node: children[i] }); subCtx.hasCollapsedParents = subCtx.hasCollapsedParents || !node.expanded; this.nodeRender(subCtx, force, deep, collapsed, true); } } // Make sure, that <tr> order matches node.children order. if (children && !_recursive) { // we only have to do it once, for the root branch prevTr = node.tr || null; firstTr = tree.tbody.firstChild; // Iterate over all descendants node.visit(function(n) { if (n.tr) { if ( !n.parent.expanded && n.tr.style.display !== "none" ) { // fix after a node was dropped over a collapsed n.tr.style.display = "none"; setChildRowVisibility(n, false); } if (n.tr.previousSibling !== prevTr) { node.debug("_fixOrder: mismatch at node: " + n); var nextTr = prevTr ? prevTr.nextSibling : firstTr; tree.tbody.insertBefore(n.tr, nextTr); } prevTr = n.tr; } }); } // Update element classes according to node state // if(!isRootNode){ // this.nodeRenderStatus(ctx); // } }, nodeRenderTitle: function(ctx, title) { var $cb, res, tree = ctx.tree, node = ctx.node, opts = ctx.options, isStatusNode = node.isStatusNode(); res = this._super(ctx, title); if (node.isRootNode()) { return res; } // Move checkbox to custom column if ( opts.checkbox && !isStatusNode && opts.table.checkboxColumnIdx != null ) { $cb = $("span.fancytree-checkbox", node.span); //.detach(); $(node.tr) .find("td") .eq(+opts.table.checkboxColumnIdx) .html($cb); } // Update element classes according to node state this.nodeRenderStatus(ctx); if (isStatusNode) { if (opts.renderStatusColumns) { // Let user code write column content opts.renderStatusColumns.call( tree, { type: "renderStatusColumns" }, ctx ); } else if (opts.table.mergeStatusColumns && node.isTopLevel()) { $(node.tr) .find(">td") .eq(0) .prop("colspan", tree.columnCount) .text(node.title) .addClass("fancytree-status-merged") .nextAll() .remove(); } // else: default rendering for status node: leave other cells empty } else if (opts.renderColumns) { opts.renderColumns.call(tree, { type: "renderColumns" }, ctx); } return res; }, nodeRenderStatus: function(ctx) { var indent, node = ctx.node, opts = ctx.options; this._super(ctx); $(node.tr).removeClass("fancytree-node"); // indent indent = (node.getLevel() - 1) * opts.table.indentation; if (opts.rtl) { $(node.span).css({ paddingRight: indent + "px" }); } else { $(node.span).css({ paddingLeft: indent + "px" }); } }, /* Expand node, return Deferred.promise. */ nodeSetExpanded: function(ctx, flag, callOpts) { // flag defaults to true flag = flag !== false; if ((ctx.node.expanded && flag) || (!ctx.node.expanded && !flag)) { // Expanded state isn't changed - just call base implementation return this._superApply(arguments); } var dfd = new $.Deferred(), subOpts = $.extend({}, callOpts, { noEvents: true, noAnimation: true, }); callOpts = callOpts || {}; function _afterExpand(ok) { setChildRowVisibility(ctx.node, flag); if (ok) { if ( flag && ctx.options.autoScroll && !callOpts.noAnimation && ctx.node.hasChildren() ) { // Scroll down to last child, but keep current node visible ctx.node .getLastChild() .scrollIntoView(true, { topNode: ctx.node }) .always(function() { if (!callOpts.noEvents) { ctx.tree._triggerNodeEvent( flag ? "expand" : "collapse", ctx ); } dfd.resolveWith(ctx.node); }); } else { if (!callOpts.noEvents) { ctx.tree._triggerNodeEvent( flag ? "expand" : "collapse", ctx ); } dfd.resolveWith(ctx.node); } } else { if (!callOpts.noEvents) { ctx.tree._triggerNodeEvent( flag ? "expand" : "collapse", ctx ); } dfd.rejectWith(ctx.node); } } // Call base-expand with disabled events and animation this._super(ctx, flag, subOpts) .done(function() { _afterExpand(true); }) .fail(function() { _afterExpand(false); }); return dfd.promise(); }, nodeSetStatus: function(ctx, status, message, details) { if (status === "ok") { var node = ctx.node, firstChild = node.children ? node.children[0] : null; if (firstChild && firstChild.isStatusNode()) { $(firstChild.tr).remove(); } } return this._superApply(arguments); }, treeClear: function(ctx) { this.nodeRemoveChildMarkup(this._makeHookContext(this.rootNode)); return this._superApply(arguments); }, treeDestroy: function(ctx) { this.$container.find("tbody").empty(); if (this.$source) { this.$source.removeClass("fancytree-helper-hidden"); } return this._superApply(arguments); }, /*, treeSetFocus: function(ctx, flag) { // alert("treeSetFocus" + ctx.tree.$container); ctx.tree.$container.focus(); $.ui.fancytree.focusTree = ctx.tree; }*/ }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; }); // End of closure /*! Extension 'jquery.fancytree.themeroller.js' *//*! * jquery.fancytree.themeroller.js * * Enable jQuery UI ThemeRoller styles. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * @see http://jqueryui.com/themeroller/ * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery", "./jquery.fancytree"], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { "use strict"; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "themeroller", version: "2.34.0", // Default options for this extension. options: { activeClass: "ui-state-active", // Class added to active node // activeClass: "ui-state-highlight", addClass: "ui-corner-all", // Class added to all nodes focusClass: "ui-state-focus", // Class added to focused node hoverClass: "ui-state-hover", // Class added to hovered node selectedClass: "ui-state-highlight", // Class added to selected nodes // selectedClass: "ui-state-active" }, treeInit: function(ctx) { var $el = ctx.widget.element, opts = ctx.options.themeroller; this._superApply(arguments); if ($el[0].nodeName === "TABLE") { $el.addClass("ui-widget ui-corner-all"); $el.find(">thead tr").addClass("ui-widget-header"); $el.find(">tbody").addClass("ui-widget-conent"); } else { $el.addClass("ui-widget ui-widget-content ui-corner-all"); } $el.on("mouseenter mouseleave", ".fancytree-node", function(event) { var node = $.ui.fancytree.getNode(event.target), flag = event.type === "mouseenter"; $(node.tr ? node.tr : node.span).toggleClass( opts.hoverClass + " " + opts.addClass, flag ); }); }, treeDestroy: function(ctx) { this._superApply(arguments); ctx.widget.element.removeClass( "ui-widget ui-widget-content ui-corner-all" ); }, nodeRenderStatus: function(ctx) { var classes = {}, node = ctx.node, $el = $(node.tr ? node.tr : node.span), opts = ctx.options.themeroller; this._super(ctx); /* .ui-state-highlight: Class to be applied to highlighted or selected elements. Applies "highlight" container styles to an element and its child text, links, and icons. .ui-state-error: Class to be applied to error messaging container elements. Applies "error" container styles to an element and its child text, links, and icons. .ui-state-error-text: An additional class that applies just the error text color without background. Can be used on form labels for instance. Also applies error icon color to child icons. .ui-state-default: Class to be applied to clickable button-like elements. Applies "clickable default" container styles to an element and its child text, links, and icons. .ui-state-hover: Class to be applied on mouseover to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons. .ui-state-focus: Class to be applied on keyboard focus to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons. .ui-state-active: Class to be applied on mousedown to clickable button-like elements. Applies "clickable active" container styles to an element and its child text, links, and icons. */ // Set ui-state-* class (handle the case that the same class is assigned // to different states) classes[opts.activeClass] = false; classes[opts.focusClass] = false; classes[opts.selectedClass] = false; if (node.isActive()) { classes[opts.activeClass] = true; } if (node.hasFocus()) { classes[opts.focusClass] = true; } // activeClass takes precedence before selectedClass: if (node.isSelected() && !node.isActive()) { classes[opts.selectedClass] = true; } $el.toggleClass(opts.activeClass, classes[opts.activeClass]); $el.toggleClass(opts.focusClass, classes[opts.focusClass]); $el.toggleClass(opts.selectedClass, classes[opts.selectedClass]); // Additional classes (e.g. 'ui-corner-all') $el.addClass(opts.addClass); }, }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; }); // End of closure /*! Extension 'jquery.fancytree.wide.js' *//*! * jquery.fancytree.wide.js * Support for 100% wide selection bars. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2019, Martin Wendt (https://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.34.0 * @date 2019-12-26T14:16:19Z */ (function(factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery", "./jquery.fancytree"], factory); } else if (typeof module === "object" && module.exports) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } })(function($) { "use strict"; var reNumUnit = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/; // split "1.5em" to ["1.5", "em"] /******************************************************************************* * Private functions and variables */ // var _assert = $.ui.fancytree.assert; /* Calculate inner width without scrollbar */ // function realInnerWidth($el) { // // http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/ // // inst.contWidth = parseFloat(this.$container.css("width"), 10); // // 'Client width without scrollbar' - 'padding' // return $el[0].clientWidth - ($el.innerWidth() - parseFloat($el.css("width"), 10)); // } /* Create a global embedded CSS style for the tree. */ function defineHeadStyleElement(id, cssText) { id = "fancytree-style-" + id; var $headStyle = $("#" + id); if (!cssText) { $headStyle.remove(); return null; } if (!$headStyle.length) { $headStyle = $("<style />") .attr("id", id) .addClass("fancytree-style") .prop("type", "text/css") .appendTo("head"); } try { $headStyle.html(cssText); } catch (e) { // fix for IE 6-8 $headStyle[0].styleSheet.cssText = cssText; } return $headStyle; } /* Calculate the CSS rules that indent title spans. */ function renderLevelCss( containerId, depth, levelOfs, lineOfs, labelOfs, measureUnit ) { var i, prefix = "#" + containerId + " span.fancytree-level-", rules = []; for (i = 0; i < depth; i++) { rules.push( prefix + (i + 1) + " span.fancytree-title { padding-left: " + (i * levelOfs + lineOfs) + measureUnit + "; }" ); } // Some UI animations wrap the UL inside a DIV and set position:relative on both. // This breaks the left:0 and padding-left:nn settings of the title rules.push( "#" + containerId + " div.ui-effects-wrapper ul li span.fancytree-title, " + "#" + containerId + " li.fancytree-animating span.fancytree-title " + // #716 "{ padding-left: " + labelOfs + measureUnit + "; position: static; width: auto; }" ); return rules.join("\n"); } // /** // * [ext-wide] Recalculate the width of the selection bar after the tree container // * was resized.<br> // * May be called explicitly on container resize, since there is no resize event // * for DIV tags. // * // * @alias Fancytree#wideUpdate // * @requires jquery.fancytree.wide.js // */ // $.ui.fancytree._FancytreeClass.prototype.wideUpdate = function(){ // var inst = this.ext.wide, // prevCw = inst.contWidth, // prevLo = inst.lineOfs; // inst.contWidth = realInnerWidth(this.$container); // // Each title is precceeded by 2 or 3 icons (16px + 3 margin) // // + 1px title border and 3px title padding // // TODO: use code from treeInit() below // inst.lineOfs = (this.options.checkbox ? 3 : 2) * 19; // if( prevCw !== inst.contWidth || prevLo !== inst.lineOfs ) { // this.debug("wideUpdate: " + inst.contWidth); // this.visit(function(node){ // node.tree._callHook("nodeRenderTitle", node); // }); // } // }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "wide", version: "2.34.0", // Default options for this extension. options: { iconWidth: null, // Adjust this if @fancy-icon-width != "16px" iconSpacing: null, // Adjust this if @fancy-icon-spacing != "3px" labelSpacing: null, // Adjust this if padding between icon and label != "3px" levelOfs: null, // Adjust this if ul padding != "16px" }, treeCreate: function(ctx) { this._superApply(arguments); this.$container.addClass("fancytree-ext-wide"); var containerId, cssText, iconSpacingUnit, labelSpacingUnit, iconWidthUnit, levelOfsUnit, instOpts = ctx.options.wide, // css sniffing $dummyLI = $( "<li id='fancytreeTemp'><span class='fancytree-node'><span class='fancytree-icon' /><span class='fancytree-title' /></span><ul />" ).appendTo(ctx.tree.$container), $dummyIcon = $dummyLI.find(".fancytree-icon"), $dummyUL = $dummyLI.find("ul"), // $dummyTitle = $dummyLI.find(".fancytree-title"), iconSpacing = instOpts.iconSpacing || $dummyIcon.css("margin-left"), iconWidth = instOpts.iconWidth || $dummyIcon.css("width"), labelSpacing = instOpts.labelSpacing || "3px", levelOfs = instOpts.levelOfs || $dummyUL.css("padding-left"); $dummyLI.remove(); iconSpacingUnit = iconSpacing.match(reNumUnit)[2]; iconSpacing = parseFloat(iconSpacing, 10); labelSpacingUnit = labelSpacing.match(reNumUnit)[2]; labelSpacing = parseFloat(labelSpacing, 10); iconWidthUnit = iconWidth.match(reNumUnit)[2]; iconWidth = parseFloat(iconWidth, 10); levelOfsUnit = levelOfs.match(reNumUnit)[2]; if ( iconSpacingUnit !== iconWidthUnit || levelOfsUnit !== iconWidthUnit || labelSpacingUnit !== iconWidthUnit ) { $.error( "iconWidth, iconSpacing, and levelOfs must have the same css measure unit" ); } this._local.measureUnit = iconWidthUnit; this._local.levelOfs = parseFloat(levelOfs); this._local.lineOfs = (1 + (ctx.options.checkbox ? 1 : 0) + (ctx.options.icon === false ? 0 : 1)) * (iconWidth + iconSpacing) + iconSpacing; this._local.labelOfs = labelSpacing; this._local.maxDepth = 10; // Get/Set a unique Id on the container (if not already exists) containerId = this.$container.uniqueId().attr("id"); // Generated css rules for some levels (extended on demand) cssText = renderLevelCss( containerId, this._local.maxDepth, this._local.levelOfs, this._local.lineOfs, this._local.labelOfs, this._local.measureUnit ); defineHeadStyleElement(containerId, cssText); }, treeDestroy: function(ctx) { // Remove generated css rules defineHeadStyleElement(this.$container.attr("id"), null); return this._superApply(arguments); }, nodeRenderStatus: function(ctx) { var containerId, cssText, res, node = ctx.node, level = node.getLevel(); res = this._super(ctx); // Generate some more level-n rules if required if (level > this._local.maxDepth) { containerId = this.$container.attr("id"); this._local.maxDepth *= 2; node.debug( "Define global ext-wide css up to level " + this._local.maxDepth ); cssText = renderLevelCss( containerId, this._local.maxDepth, this._local.levelOfs, this._local.lineOfs, this._local.labelSpacing, this._local.measureUnit ); defineHeadStyleElement(containerId, cssText); } // Add level-n class to apply indentation padding. // (Setting element style would not work, since it cannot easily be // overriden while animations run) $(node.span).addClass("fancytree-level-" + level); return res; }, }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; }); // End of closure // Value returned by `require('jquery.fancytree')` return $.ui.fancytree; })); // End of closure
let handler = async(m) => { let donasi = `${ucapan()}... Have a great day ╭━━•›ꪶ ཻུ۪۪ꦽꦼ̷⸙ ━ ━ ━ ━ ꪶ ཻུ۪۪ꦽꦼ̷⸙‹•━━╮ ┃╭┈─────────────⩵꙰ཱི࿐ ┃╰──*DONATE*──➤ ↶↷* ╰•͙✩̣̣ ${namabot} ⁙┃ ુོ DANA : 0888-2611-841 ⁙┃ ુོ OVO : 0888-2611-841 ⁙┃ ⁙┃ ુོ SAWERIA : https://saweria.co/irwanxyans ⁙┃ ⁙╰•°°°🕊°°°°°🕊°°°°°°🕊°°°°°°°°` await sock.sendTemplateButtonLoc(m.chat, donasi, wm, await(await require('node-fetch')(fla + 'Donasi')).buffer(), 'Owner', '#owner', m) } handler.help = ['donasi'] handler.tags = ['info'] handler.command = /^dona(te|si)$/i module.exports = handler function ucapan() { const time = require('moment-timezone').tz('Asia/Jakarta').format('HH') res = "Selamat dinihari" if (time >= 4) { res = "Selamat pagi" } if (time > 10) { res = "Selamat siang" } if (time >= 15) { res = "Selamat sore" } if (time >= 18) { res = "Selamat malam" } return res }
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/App'; import HomePage from './components/home/HomePage'; import AboutPage from './components/about/AboutPage'; import CoursesPage from './components/course/CoursesPage'; export default ( <Route path="/" component={App}> <IndexRoute component={HomePage} /> <Route path="about" component={AboutPage} /> <Route path="courses" component={CoursesPage} /> </Route> );
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.messages = exports.ruleName = undefined; exports.default = function (actual) { return function (root, result) { var validOptions = (0, _utils.validateOptions)(result, ruleName, { actual: actual }); if (!validOptions) { return; } root.walkRules(function (rule) { if (!(0, _utils.isStandardSyntaxRule)(rule)) { return; } var selector = rule.selector; if (!(0, _utils.isStandardSyntaxSelector)(selector)) { return; } (0, _utils.parseSelector)(selector, result, rule, function (selectorAST) { selectorAST.walkUniversals(function (universal) { (0, _utils.report)({ message: messages.rejected, node: rule, index: universal.sourceIndex, ruleName: ruleName, result: result }); }); }); }); }; }; var _utils = require("../../utils"); var ruleName = exports.ruleName = "selector-no-universal"; var messages = exports.messages = (0, _utils.ruleMessages)(ruleName, { rejected: "Unexpected universal selector" });
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; 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; }; var BABYLON; (function (BABYLON) { var Rectangle2DRenderCache = (function (_super) { __extends(Rectangle2DRenderCache, _super); function Rectangle2DRenderCache(engine, modelKey) { _super.call(this, engine, modelKey); this.effectsReady = false; this.fillVB = null; this.fillIB = null; this.fillIndicesCount = 0; this.instancingFillAttributes = null; this.effectFill = null; this.effectFillInstanced = null; this.borderVB = null; this.borderIB = null; this.borderIndicesCount = 0; this.instancingBorderAttributes = null; this.effectBorder = null; this.effectBorderInstanced = null; } Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) { // Do nothing if the shader is still loading/preparing if (!this.effectsReady) { if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) || (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) { return false; } this.effectsReady = true; } var canvas = instanceInfo.owner.owner; var engine = canvas.engine; var depthFunction = 0; if (this.effectFill && this.effectBorder) { depthFunction = engine.getDepthFunction(); engine.setDepthFunctionToLessOrEqual(); } var curAlphaMode = engine.getAlphaMode(); if (this.effectFill) { var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString()); var pid = context.groupInfoPartData[partIndex]; if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) { engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true); } var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill; engine.enableEffect(effect); engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect); if (context.useInstancing) { if (!this.instancingFillAttributes) { this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect); } var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer; var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount; canvas._addDrawCallCount(1, context.renderMode); engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes); engine.draw(true, 0, this.fillIndicesCount, count); engine.unbindInstanceAttributes(); } else { canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode); for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) { this.setupUniforms(effect, partIndex, pid._partData, i); engine.draw(true, 0, this.fillIndicesCount); } } } if (this.effectBorder) { var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString()); var pid = context.groupInfoPartData[partIndex]; if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) { engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true); } var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder; engine.enableEffect(effect); engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect); if (context.useInstancing) { if (!this.instancingBorderAttributes) { this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect); } var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer; var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount; canvas._addDrawCallCount(1, context.renderMode); engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes); engine.draw(true, 0, this.borderIndicesCount, count); engine.unbindInstanceAttributes(); } else { canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode); for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) { this.setupUniforms(effect, partIndex, pid._partData, i); engine.draw(true, 0, this.borderIndicesCount); } } } engine.setAlphaMode(curAlphaMode, true); if (this.effectFill && this.effectBorder) { engine.setDepthFunction(depthFunction); } return true; }; Rectangle2DRenderCache.prototype.dispose = function () { if (!_super.prototype.dispose.call(this)) { return false; } if (this.fillVB) { this._engine._releaseBuffer(this.fillVB); this.fillVB = null; } if (this.fillIB) { this._engine._releaseBuffer(this.fillIB); this.fillIB = null; } this.effectFill = null; this.effectFillInstanced = null; this.effectBorder = null; this.effectBorderInstanced = null; if (this.borderVB) { this._engine._releaseBuffer(this.borderVB); this.borderVB = null; } if (this.borderIB) { this._engine._releaseBuffer(this.borderIB); this.borderIB = null; } return true; }; return Rectangle2DRenderCache; })(BABYLON.ModelRenderCache); BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache; var Rectangle2DInstanceData = (function (_super) { __extends(Rectangle2DInstanceData, _super); function Rectangle2DInstanceData(partId) { _super.call(this, partId, 1); } Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", { get: function () { return null; }, enumerable: true, configurable: true }); __decorate([ BABYLON.instanceData() ], Rectangle2DInstanceData.prototype, "properties", null); return Rectangle2DInstanceData; })(BABYLON.Shape2DInstanceData); BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData; var Rectangle2D = (function (_super) { __extends(Rectangle2D, _super); /** * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one. * @param settings a combination of settings, possible ones are * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting) * - children: an array of direct children * - id a text identifier, for information purpose * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0] * - rotation: the initial rotation (in radian) of the primitive. default is 0 * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent. * - zOrder: override the zOrder with the specified value * - origin: define the normalized origin point location, default [0.5;0.5] * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10]. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle). * - fill: the brush used to draw the fill content of the rectangle, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString) * - border: the brush used to draw the border of the rectangle, you can set null to draw nothing (but you will have to set a fill brush), default is null. can also be a string value (see Canvas2D.GetBrushFromString) * - borderThickness: the thickness of the drawn border, default is 1. * - isVisible: true if the primitive must be visible, false for hidden. Default is true. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED! * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString) * - marginHAlignment: one value of the PrimitiveAlignment type's static properties * - marginVAlignment: one value of the PrimitiveAlignment type's static properties * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString) * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString) */ function Rectangle2D(settings) { // Avoid checking every time if the object exists if (settings == null) { settings = {}; } _super.call(this, settings); if (settings.size != null) { this.size = settings.size; } else if (settings.width || settings.height) { var size = new BABYLON.Size(settings.width, settings.height); this.size = size; } //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10))); var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius; var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness; //this.size = size; this.roundRadius = roundRadius; this.borderThickness = borderThickness; } Object.defineProperty(Rectangle2D.prototype, "actualSize", { get: function () { if (this._actualSize) { return this._actualSize; } return this.size; }, set: function (value) { this._actualSize = value; }, enumerable: true, configurable: true }); Object.defineProperty(Rectangle2D.prototype, "notRounded", { get: function () { return this._notRounded; }, set: function (value) { this._notRounded = value; }, enumerable: true, configurable: true }); Object.defineProperty(Rectangle2D.prototype, "roundRadius", { get: function () { return this._roundRadius; }, set: function (value) { this._roundRadius = value; this.notRounded = value === 0; this._positioningDirty(); }, enumerable: true, configurable: true }); Rectangle2D.prototype.levelIntersect = function (intersectInfo) { // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed! if (this.notRounded) { return true; } // If we got so far it means the bounding box at least passed, so we know it's inside the bounding rectangle, but it can be outside the roundedRectangle. // The easiest way is to check if the point is inside on of the four corners area (a little square of roundRadius size at the four corners) // If it's the case for one, check if the mouse is located in the quarter that we care about (the one who is visible) then finally make a distance check with the roundRadius radius to see if it's inside the circle quarter or outside. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left var size = this.size; Rectangle2D._i0.x = intersectInfo._localPickPosition.x; Rectangle2D._i0.y = intersectInfo._localPickPosition.y; var rr = this.roundRadius; var rrs = rr * rr; // Check if the point is in the bottom/left quarter area Rectangle2D._i1.x = rr; Rectangle2D._i1.y = rr; if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) { // Compute the intersection point in the quarter local space Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x; Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y; // It's a hit if the squared distance is less/equal to the squared radius of the round circle return Rectangle2D._i2.lengthSquared() <= rrs; } // Check if the point is in the top/left quarter area Rectangle2D._i1.x = rr; Rectangle2D._i1.y = size.height - rr; if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) { // Compute the intersection point in the quarter local space Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x; Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y; // It's a hit if the squared distance is less/equal to the squared radius of the round circle return Rectangle2D._i2.lengthSquared() <= rrs; } // Check if the point is in the top/right quarter area Rectangle2D._i1.x = size.width - rr; Rectangle2D._i1.y = size.height - rr; if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) { // Compute the intersection point in the quarter local space Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x; Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y; // It's a hit if the squared distance is less/equal to the squared radius of the round circle return Rectangle2D._i2.lengthSquared() <= rrs; } // Check if the point is in the bottom/right quarter area Rectangle2D._i1.x = size.width - rr; Rectangle2D._i1.y = rr; if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) { // Compute the intersection point in the quarter local space Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x; Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y; // It's a hit if the squared distance is less/equal to the squared radius of the round circle return Rectangle2D._i2.lengthSquared() <= rrs; } // At any other locations the point is guarantied to be inside return true; }; Rectangle2D.prototype.updateLevelBoundingInfo = function () { BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo); }; Rectangle2D.prototype.createModelRenderCache = function (modelKey) { var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey); return renderCache; }; Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) { var renderCache = modelRenderCache; var engine = this.owner.engine; // Need to create WebGL resources for fill part? if (this.fill) { var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1; var vb = new Float32Array(vbSize); for (var i = 0; i < vbSize; i++) { vb[i] = i; } renderCache.fillVB = engine.createVertexBuffer(vb); var triCount = vbSize - 1; var ib = new Float32Array(triCount * 3); for (var i = 0; i < triCount; i++) { ib[i * 3 + 0] = 0; ib[i * 3 + 2] = i + 1; ib[i * 3 + 1] = i + 2; } ib[triCount * 3 - 2] = 1; renderCache.fillIB = engine.createIndexBuffer(ib); renderCache.fillIndicesCount = triCount * 3; // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true); if (ei) { renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null); } // Get the non instanced version ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false); renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null); } // Need to create WebGL resource for border part? if (this.border) { var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2; var vb = new Float32Array(vbSize); for (var i = 0; i < vbSize; i++) { vb[i] = i; } renderCache.borderVB = engine.createVertexBuffer(vb); var triCount = vbSize; var rs = triCount / 2; var ib = new Float32Array(triCount * 3); for (var i = 0; i < rs; i++) { var r0 = i; var r1 = (i + 1) % rs; ib[i * 6 + 0] = rs + r1; ib[i * 6 + 1] = rs + r0; ib[i * 6 + 2] = r0; ib[i * 6 + 3] = r1; ib[i * 6 + 4] = rs + r1; ib[i * 6 + 5] = r0; } renderCache.borderIB = engine.createIndexBuffer(ib); renderCache.borderIndicesCount = triCount * 3; // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true); if (ei) { renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null); } // Get the non instanced version ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false); renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null); } return renderCache; }; // We override this method because if there's a roundRadius set, we will reduce the initial Content Area to make sure the computed area won't intersect with the shape contour. The formula is simple: we shrink the incoming size by the amount of the roundRadius Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) { // Fall back to default implementation if there's no round Radius if (this._notRounded) { _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea); } else { var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3); initialContentPosition.x = initialContentPosition.y = rr; initialContentArea.width = Math.max(0, primSize.width - (rr * 2)); initialContentArea.height = Math.max(0, primSize.height - (rr * 2)); } }; Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) { // Fall back to default implementation if there's no round Radius if (this._notRounded) { _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize); } else { var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3); newPrimSize.copyFrom(primSize); newPrimSize.width += rr * 2; newPrimSize.height += rr * 2; } }; Rectangle2D.prototype.createInstanceDataParts = function () { var res = new Array(); if (this.border) { res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID)); } if (this.fill) { res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID)); } return res; }; Rectangle2D.prototype.refreshInstanceDataPart = function (part) { if (!_super.prototype.refreshInstanceDataPart.call(this, part)) { return false; } if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) { var d = part; var size = this.actualSize; var s = this.actualScale; d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0); } else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) { var d = part; var size = this.actualSize; var s = this.actualScale; d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0); } return true; }; Rectangle2D._i0 = BABYLON.Vector2.Zero(); Rectangle2D._i1 = BABYLON.Vector2.Zero(); Rectangle2D._i2 = BABYLON.Vector2.Zero(); Rectangle2D.roundSubdivisions = 16; __decorate([ BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true) ], Rectangle2D.prototype, "actualSize", null); __decorate([ BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; }) ], Rectangle2D.prototype, "notRounded", null); __decorate([ BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; }) ], Rectangle2D.prototype, "roundRadius", null); Rectangle2D = __decorate([ BABYLON.className("Rectangle2D") ], Rectangle2D); return Rectangle2D; })(BABYLON.Shape2D); BABYLON.Rectangle2D = Rectangle2D; })(BABYLON || (BABYLON = {}));
import React from 'react'; import {createPortal} from 'react-dom'; import {propTypes, defaultProps} from './PopoverPropTypes'; import CONST from '../../CONST'; import Modal from '../Modal'; import withWindowDimensions from '../withWindowDimensions'; /* * This is a convenience wrapper around the Modal component for a responsive Popover. * On small screen widths, it uses BottomDocked modal type, and a Popover type on wide screen widths. */ const Popover = (props) => { if (!props.fullscreen && !props.isSmallScreenWidth) { return createPortal( <Modal type={CONST.MODAL.MODAL_TYPE.POPOVER} popoverAnchorPosition={props.anchorPosition} // eslint-disable-next-line react/jsx-props-no-spreading {...props} animationIn={props.isSmallScreenWidth ? undefined : props.animationIn} animationOut={props.isSmallScreenWidth ? undefined : props.animationOut} shouldCloseOnOutsideClick />, document.body, ); } return ( <Modal type={props.isSmallScreenWidth ? CONST.MODAL.MODAL_TYPE.BOTTOM_DOCKED : CONST.MODAL.MODAL_TYPE.POPOVER} popoverAnchorPosition={props.isSmallScreenWidth ? undefined : props.anchorPosition} // eslint-disable-next-line react/jsx-props-no-spreading {...props} fullscreen={props.isSmallScreenWidth ? true : props.fullscreen} animationIn={props.isSmallScreenWidth ? undefined : props.animationIn} animationOut={props.isSmallScreenWidth ? undefined : props.animationOut} /> ); }; Popover.propTypes = propTypes; Popover.defaultProps = defaultProps; Popover.displayName = 'Popover'; export default withWindowDimensions(Popover);
/*global QUnit*/ sap.ui.define([ "sap/gantt/shape/Text", "sap/gantt/config/Shape", "sap/gantt/config/TimeHorizon", "sap/gantt/GanttChart" ], function (Text, ShapeConfig, TimeHorizon, GanttChart) { "use strict"; QUnit.module("Create Shape by GanttChart without properties configured.", { beforeEach: function () { // shape configuration object this.oShapeConfig = new ShapeConfig({ key: "ut", shapeClassName: "sap.gantt.shape.Text", shapeProperties: { time: "{startTime}", endTime: "{endTime}" } }); // GanttChart object which creates shape instance var oTimeAxisConfig = new sap.gantt.config.TimeAxis({ planHorizon: new TimeHorizon({ startTime: "20140901000000", endTime: "20141031000000" }) }); this.oGanttChart = new GanttChart({ timeAxis: oTimeAxisConfig, shapes: [this.oShapeConfig] }); // text instance created by GanttChart this.oText = this.oGanttChart.getShapeInstance("ut"); // call back parameter this.oData = { startTime: "20140919000000", endTime: "20141012000000" }; // call back parameter this.oRowInfo = { rowHeight: 32, y: 0, uid: "PATH:0000|SCHEME:ac_main[0]", data: { ut: [this.oData] } }; }, afterEach: function () { this.oText = undefined; this.oShapeConfig = undefined; this.oData = undefined; this.oRowInfo = undefined; this.oGanttChart.destroy(); } }); QUnit.test("Test default value of get<Property>() methods.", function (assert) { assert.strictEqual(this.oText.getText(this.oData, this.oRowInfo), undefined); assert.strictEqual(this.oText.getX(this.oData, this.oRowInfo), 405.0187369882027); assert.strictEqual(this.oText.getY(this.oData, this.oRowInfo), 21); assert.strictEqual(this.oText.getFontSize(this.oData, this.oRowInfo), 10); assert.strictEqual(this.oText.getFontFamily(this.oData, this.oRowInfo), undefined); assert.strictEqual(this.oText.getTextAnchor(this.oData, this.oRowInfo), "start"); assert.strictEqual(this.oText.getWrapWidth(this.oData, this.oRowInfo), -1); assert.strictEqual(this.oText.getWrapDy(this.oData, this.oRowInfo), 20); assert.strictEqual(this.oText.getTruncateWidth(this.oData, this.oRowInfo), -1); assert.strictEqual(this.oText.getEllipsisWidth(this.oData, this.oRowInfo), 12); }); // this test make sure every newly defined properties other than parent is added with config first logic. QUnit.module("Create Shape by GanttChart with properties configured.", { beforeEach: function () { // shape configuration object this.oShapeConfig = new ShapeConfig({ key: "ut", shapeClassName: "sap.gantt.shape.Text", shapeProperties: { text: "text", fontSize: 12, textAnchor: "end", fontFamily: "Arial", wrapWidth: 2, wrapDy: 30, truncateWidth: 20, ellipsisWidth: 10, time: "{startTime}", x: 1, y: 3 } }); // GanttChart object which creates shape instance var oTimeAxisConfig = new sap.gantt.config.TimeAxis({ planHorizon: new TimeHorizon({ startTime: "20140901000000", endTime: "20141031000000" }) }); this.oGanttChart = new GanttChart({ timeAxis: oTimeAxisConfig, shapes: [this.oShapeConfig] }); // text instance created by GanttChart this.oText = this.oGanttChart.getShapeInstance("ut"); // call back parameter this.oData = { startTime: "20140919000000", endTime: "20141012000000" }; // call back parameter this.oRowInfo = { rowHeight: 32, y: 0, uid: "PATH:0000|SCHEME:ac_main[0]", data: { ut: [this.oData] } }; }, afterEach: function () { this.oText = undefined; this.oShapeConfig = undefined; this.oData = undefined; this.oRowInfo = undefined; this.oGanttChart.destroy(); } }); QUnit.test("Test configured value of get<Property>() methods.", function (assert) { assert.strictEqual(this.oText.getText(this.oData, this.oRowInfo), "text"); assert.strictEqual(this.oText.getX(this.oData, this.oRowInfo), 1); assert.strictEqual(this.oText.getY(this.oData, this.oRowInfo), 3); assert.strictEqual(this.oText.getFontSize(this.oData, this.oRowInfo), 12); assert.strictEqual(this.oText.getFontFamily(this.oData, this.oRowInfo), "Arial"); assert.strictEqual(this.oText.getTextAnchor(this.oData, this.oRowInfo), "end"); assert.strictEqual(this.oText.getWrapWidth(this.oData, this.oRowInfo), 2); assert.strictEqual(this.oText.getWrapDy(this.oData, this.oRowInfo), 30); assert.strictEqual(this.oText.getTruncateWidth(this.oData, this.oRowInfo), 20); assert.strictEqual(this.oText.getEllipsisWidth(this.oData, this.oRowInfo), 10); }); QUnit.module("Text.getStyle module", { beforeEach: function () { this.oShape = new Text({ fontSize: 13, fontFamily: "Arial", fill: "gray" }); this.oShape.mShapeConfig = new ShapeConfig({ key: "ut", shapeClassName: "sap.gantt.shape.Text" }); }, afterEach: function () { this.oShape = null; } }); QUnit.test("Text.getStyle default value", function (assert) { var expectedResult = "stroke-width:0; font-size:13px;; fill:gray; fill-opacity:1; font-family:Arial; "; assert.strictEqual(this.oShape.getStyle(), expectedResult, "default style is correct"); }); });
const express = require('express') const google = require('googleapis').google const youtube = google.youtube({ version: 'v3' }) const OAuth2 = google.auth.OAuth2 const state = require('./state.js') const fs = require('fs') async function robot() { console.log('> [youtube-robot] Starting...') const content = state.load() await authenticateWithOAuth() const videoInformation = await uploadVideo(content) await uploadThumbnail(videoInformation) async function authenticateWithOAuth() { const webServer = await startWebServer() const OAuthClient = await createOAuthClient() requestUserConsent(OAuthClient) const authorizationToken = await waitForGoogleCallback(webServer) await requestGoogleForAccessTokens(OAuthClient, authorizationToken) await setGlobalGoogleAuthentication(OAuthClient) await stopWebServer(webServer) async function startWebServer() { return new Promise((resolve, reject) => { const port = 5000 const app = express() const server = app.listen(port, () => { console.log(`> [youtube-robot] Listening on http://localhost:${port}`) resolve({ app, server }) }) }) } async function createOAuthClient() { const credentials = require('../credentials/google-youtube.json') const OAuthClient = new OAuth2( credentials.web.client_id, credentials.web.client_secret, credentials.web.redirect_uris[0] ) return OAuthClient } function requestUserConsent(OAuthClient) { const consentUrl = OAuthClient.generateAuthUrl({ acess_type: 'offline', scope: ['https://www.googleapis.com/auth/youtube'] }) console.log(`> [youtube-robot] Please give your consent: ${consentUrl}`) } async function waitForGoogleCallback(webServer) { return new Promise((resolve, reject) => { console.log(`> [youtube-robot] Waiting for user consent...`) webServer.app.get('/oauth2callback', (req, res) => { const authCode = req.query.code console.log(`> [youtube-robot] Consent given: ${authCode}`) res.send('<h1>Thank you!</h1><p>Now close this tab.</p>') resolve(authCode) }) }) } async function requestGoogleForAccessTokens(OAuthClient, authorizationToken) { return new Promise((resolve, reject) => { OAuthClient.getToken(authorizationToken, (err, tokens) => { if (err) { return reject(err) } console.log('> [youtube-robot] Access tokens received!') OAuthClient.setCredentials(tokens) resolve() }) }) } async function setGlobalGoogleAuthentication(OAuthClient) { google.options({ auth: OAuthClient }) } async function stopWebServer(webServer) { return new Promise((resolve, reject) => { webServer.server.close(() => { resolve() }) }) } } async function uploadVideo(content) { const videoFilePath = './content/video-maker.mp4' const videoFileSize = fs.statSync(videoFilePath).size const videoTitle = `${content.prefix} ${content.searchTerm}` const videoTags = [content.searchTerm, ...content.sentences[0].keywords] const videoDescription = content.sentences.map((sentence) => { return sentence.text }).join('\n\n') const requestParameters = { part: 'snippet, status', requestBody: { snippet: { title: videoTitle, description: videoDescription, tags: videoTags }, status: { privacyStatus: 'unlisted' } }, media: { body: fs.createReadStream(videoFilePath) } } console.log('> [youtube-robot] Starting to upload the video to YouTube') const youtubeResponse = await youtube.videos.insert(requestParameters, { onUploadProgress: onUploadProgress }) console.log(`> [youtube-robot] Video available at: https://youtu.be/${youtubeResponse.data.id}`) return youtubeResponse.data function onUploadProgress(event) { const progress = Math.round((event.bytesRead / videoFileSize) * 100) console.log(`> [youtube-robot] ${progress}% completed`) } } async function uploadThumbnail(videoInformation) { const videoId = videoInformation.id const videoThumbnailFilePath = './content/youtube-thumbnail.jpg' const requestParameters = { videoId: videoId, media: { mimeType: 'image/jpeg', body: fs.createReadStream(videoThumbnailFilePath) } } const youtubeResponse = await youtube.thumbnails.set(requestParameters) console.log(`> [youtube-robot] Thumbnail uploaded!`) } } module.exports = robot
'use strict'; var Alexa = require('alexa-sdk'); var GoogleMapsAPI = require('googlemaps'); // json files var cities = require('cities.json'); var promptPhrases = require('promptPhrases.json'); var GOOGLE_API_KEY = 'AIzaSyCXNeYsacckhQ5e3Kp5f-4ZJez_si5gQYY'; var APP_ID = "amzn1.ask.skill.bdb46a77-6e06-4e5e-8e7f-5f67d148a287"; var SKILL_NAME = "How Many Steps"; var publicConfig = { key: GOOGLE_API_KEY, stagger_time: 100, // for elevationPath encode_polylines: false, secure: true, // use https }; var gmAPI = new GoogleMapsAPI(publicConfig); var stepsPerKm = 1320; exports.handler = function(event, context, callback) { var alexa = Alexa.handler(event, context); alexa.appId = APP_ID; alexa.registerHandlers(handlers); alexa.execute(); }; var cityArray = cities.name; var city1; var city2; function random_item(items) { return items[Math.floor(Math.random()*items.length)]; } function getTwoCities() { city1 = random_item(cityArray); do { city2 = random_item(cityArray); console.log(city1 + " " + city2); } while(city1 == city2); } var handlers = { 'LaunchRequest': function () { getTwoCities(); this.attributes["speechOutput"] = "Welcome to " + SKILL_NAME + ". You can ask me a question like, how many steps does it take from " + city1 + " to " + city2 + ". Or try saying, tell me a fact to find out."; this.emit(':ask', this.attributes['speechOutput'], this.attributes['repromptSpeech']); }, 'HowManyStepsIntent': function () { var USplaceOne = this.event.request.intent.slots.USplaceOne.value; var USplaceTwo = this.event.request.intent.slots.USplaceTwo.value; var EUplaceOne = this.event.request.intent.slots.EUplaceOne.value; var EUplaceTwo = this.event.request.intent.slots.EUplaceTwo.value; var self = this; if (USplaceOne!=undefined && USplaceTwo!=undefined) { checkCities(USplaceOne, USplaceTwo, self); } else if (EUplaceOne!=undefined && EUplaceTwo!=undefined) { checkCities(EUplaceOne, EUplaceTwo, self); } else { self.emit('DiffRegionError'); } function checkCities(origin, destination, self) { if (origin==undefined || destination==undefined) { self.emit('Unhandled'); } else if (origin == destination) { self.emit('SameCitiesError'); } else { var params = { origins: origin, destinations: destination, units: 'metric' }; gmAPI.distance(params, function(err, result){ console.log("err: "+err); console.log("result: "+result); console.log("is result ok: "+result.status); var arry = result.rows[0].elements; if(arry[0].distance==undefined || arry[0].duration==undefined){ self.emit('CantTravelError'); } else { var distance = arry[0].distance.value; var divideDistance = distance / 1000; var roundedDistance = Math.round(divideDistance); var totalSteps = roundedDistance * stepsPerKm; console.log("Steps is: " + totalSteps); var totalResult = "It takes an average of " + totalSteps.toString() + " steps from " + params.origins + " to " + params.destinations + "."; console.log(totalResult); var phrase = random_item(promptPhrases.phrase); self.emit(':tell',totalResult + " " + phrase); } }); } } }, 'TellFactIntent': function () { getTwoCities(); var self = this; function tellFact(origin, destination, self) { if (origin==undefined || destination==undefined) { self.emit('Unhandled'); } else { var params = { origins: origin + ", USA", destinations: destination + ", USA", units: 'metric' }; gmAPI.distance(params, function(err, result){ console.log("err: "+err); console.log("result: "+result); console.log("is result ok: "+result.status); var arry = result.rows[0].elements; if(arry[0].distance==undefined || arry[0].duration==undefined){ self.emit('CantTravelError'); } else { var distance = arry[0].distance.value; var divideDistance = distance / 1000; var roundedDistance = Math.round(divideDistance); var totalSteps = roundedDistance * stepsPerKm; console.log("Steps is: " + totalSteps); var totalResult = "It takes an average of " + totalSteps.toString() + " steps from " + params.origins + " to " + params.destinations + "."; console.log(totalResult); var phrase = random_item(promptPhrases.phrase); self.emit(':tell',totalResult + " " + phrase); } }); } } tellFact(city1, city2, self); }, 'SupportedCitiesIntent': function () { this.emit(':tell', "Currently I can tell you the number of steps between cities or places in Europe or the United States of America."); }, 'AMAZON.HelpIntent': function () { getTwoCities(); this.emit(':ask', "Just tell me two places or cities such as " + city1 + " and " + city2 + " to get the average number of steps between them."); }, 'AMAZON.CancelIntent': function () { this.emit(':tell', "Goodbye!"); this.emit('SessionEndedRequest'); }, 'AMAZON.StopIntent': function () { this.emit(':tell', "Goodbye!"); this.emit('SessionEndedRequest'); }, 'DiffRegionError': function () { getTwoCities(); this.emit(':tell', "Please try two places in the same region or country. Say something like how many steps between " + city1 + " and " + city2 + "?"); }, 'SameCitiesError': function () { this.emit(':tell', "Sorry, but you can\'t walk to the same place!, Please try again."); }, 'CantTravelError': function() { this.emit(':tell', 'Sorry, I don\'t know if you can walk between those cities. Please try again.'); }, 'Unhandled': function() { this.emit(':tell', 'Sorry, I don\'t understand. Please try again.'); } };
<!doctype html> <!--[if IE 9]><html class="lt-ie10" lang="en" > <![endif]--> <!--[if IE 10]><html class="ie10" lang="en" > <![endif]--> <html class="no-js" lang="en" data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>Foundation</title> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,700italic,400,300,700"/> <link rel="icon" href="http://foundation.zurb.com/assets/img/icons/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://foundation.zurb.com/assets/img/icons/apple-touch-icon-144x144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://foundation.zurb.com/assets/img/icons/apple-touch-icon-114x114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://foundation.zurb.com/assets/img/icons/apple-touch-icon-72x72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="http://foundation.zurb.com/assets/img/icons/apple-touch-icon-precomposed.png"> <meta name="description" content="Documentation and reference library for ZURB Foundation. JavaScript, CSS, components, grid and more."/> <meta name="author" content="ZURB, inc. ZURB network also includes zurb.com"/> <meta name="copyright" content="ZURB, inc. Copyright (c) 2015"/> <link type="text/css" rel="stylesheet" href="http://foundation.zurb.com/assets/css/marketing.css"/> <script src="http://foundation.zurb.com/assets/js/modernizr.js"></script> </head> <body> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=257781267581967"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="off-canvas-wrap"> <div class="inner-wrap"> <aside class="left-off-canvas-menu"> <ul class="off-canvas-list"> <li><label class="first">Foundation</label></li> <li><a href="index.html">Home</a></li> </ul> <hr> <ul class="off-canvas-list"> <li><label class="first">Learn</label></li> <li><a href="learn/features.html">Features</a></li> <li><a href="learn/case-washington-post.html">Case Studies</a></li> <li><a href="learn/brands.html">Brands</a></li> <li><a href="learn/video-started-with-foundation.html">Tutorials</a></li> <li><a href="learn/classes.html">Classes</a></li> <li><a href="learn/about.html">About Foundation</a></li> </ul> <hr> <ul class="off-canvas-list"> <li><label>Develop</label></li> <li><a href="develop/getting-started.html">Getting Started</a></li> <li><a href="develop/download.html">Download</a></li> <li><a href="http://foundation.zurb.com/docs/">Documentation</a></li> <li><a href="develop/resources.html">Resources</a></li> <li><a href="templates.html">Templates</a></li> <li><a href="develop/contribute.html">Contribute</a></li> </ul> <hr> <ul class="off-canvas-list"> <li><label>Support</label></li> <li><a href="support/support.html">Support Channels</a></li> <li><a href="/forum">Foundation Forum</a></li> <li><a href="support/images-and-badges.html">Images &amp; Badges</a></li> </ul> <hr> <ul class="off-canvas-list"> <li><label>Business</label></li> <li><a href="business/services.html" class="">Services</a></li> <li><a href="business/certification.html" class="">Certification</a></li> <li><a href="business/business-support.html" class="">Business Support</a></li> <li><a href="business/engineering-studios.html" class="">Engineering Studios</a></li> <li><a href="business/training.html" class="">Business Training</a></li> <li><a href="business/design-apps.html" class="">Design Apps</a></li> </ul> <hr> <ul class="off-canvas-list"> <li><label>Docs</label></li> <li><a href="docs" class="">Docs</a></li> </ul> <hr> <ul class="off-canvas-list"> <li><label>Getting Started</label></li> <li class="gs" id="gs"><p><a href="docs" class="button">Getting Started</a></p></li> </ul> <hr> <ul class="off-canvas-list"> <li><label>More ZURB Goodness</label></li> <li><a href="http://zurb.com/studios/our-work" class="">Foundation Training</a></li> <li><a href="http://zurb.com/studios/our-work" class="">Our Work</a></li> <li><a href="http://zurb.com/notable" class="">Notable</a></li> </ul> <hr> <div class="zurb-links"> <ul class="top"> <li class="logo"><a href="http://zurb.com"></a></li> <li><a href="http://zurb.com/about">About</a></li> <li><a href="http://zurb.com/blog">Blog</a></li> <li><a href="http://zurb.com/contact">Contact</a></li> </ul> <ul class="pillars"> <li> <a href="http://www.zurb.com/studios" class="footer-link-block services"> <span class="title">Studios</span> <span>Helping startups win since '98.</span> </a> </li> <li> <a href="http://foundation.zurb.com/" class="footer-link-block foundation"> <span class="title">Foundation</span> <span>World's most advanced responsive framework.</span> </a> </li> <li> <a href="http://zurb.com/notable" class="footer-link-block apps"> <span class="title">Notable</span> <span>Tools to rapidly prototype and iterate.</span> </a> </li> <li> <a href="http://zurb.com/university" class="footer-link-block expo"> <span class="title">University</span> <span>Online training for smarter product design.</span> </a> </li> </ul> </div> </aside> <title>Foundation: The Most Advanced Responsive Front-end Framework from ZURB</title><meta name="description" content="Foundation from ZURB is the most advanced responsive front-end framework in the world."/> <nav class="tab-bar"> <a class="left-off-canvas-toggle menu-icon sidebar-button"> <img alt="Menu grey" src="assets/img/offcanvas/menu-wht.png"> <h1><a href="index.html"><img class="zurb-logo-mobile" src="assets/img/zurb-logo.svg"></a></h1> </a> </nav> <nav class="top-bar" data-topbar> <ul class="title-area"> <li class="name"> <h1><a href="index.html"><img class="zurb-logo" src="assets/img/zurb-logo.svg"><span>Foundation</span></a></h1> </li> </ul> <section class="top-bar-section"> <ul class="right"> <li class="divider"></li> <li class="has-dropdown"> <a href="learn/features.html" class="">Learn</a> <ul class="dropdown"> <li><a href="learn/features.html">Features</a></li> <li><a href="learn/case-studies.html">Case Studies</a></li> <li><a href="learn/brands.html">Brands</a></li> <li><a href="learn/tutorials.html">Tutorials</a></li> <li><a href="learn/classes.html">Classes</a></li> <li><a href="learn/about.html">About Foundation</a></li> </ul> </li> <li class="divider"></li> <li class="has-dropdown"> <a href="develop/getting-started.html" class="">Develop</a> <ul class="dropdown"> <li><a href="develop/getting-started.html">Getting Started</a></li> <li><a href="develop/download.html">Download</a></li> <li><a href="http://foundation.zurb.com/docs/">Documentation</a></li> <li><a href="develop/resources.html">Resources</a></li> <li><a href="templates.html">HTML Templates</a></li> <li><a href="develop/contribute.html">Contribute</a></li> <li><a href="http://foundation.zurb.com/apps/">Foundation for Apps</a></li> <li><a href="http://zurb.com/ink/">Foundation for Emails</a></li> </ul> </li> <li class="divider"></li> <li class="has-dropdown"> <a href="support/support.html" class="">Support</a> <ul class="dropdown"> <li><a href="support/support.html">Support Channels</a></li> <li><a href="/forum">Foundation Forum</a></li> <li><a href="support/faq.html">FAQs</a></li> </ul> </li> <li class="divider"></li> <li class="has-dropdown"> <a href="business/services.html" class="">Business</a> <ul class="dropdown"> <li><a href="business/services.html">Services</a></li> <li><a href="business/business-support.html">Business Support</a></li> <li><a href="business/engineering-studios.html">Engineering Studios</a></li> <li><a href="business/training.html">Business Training</a></li> <li><a href="business/design-apps.html">Hosted Prototypes</a></li> </ul> </li> <li class="divider"></li> <li> <a href="/docs" class="">Docs</a> </li> <li class="divider"></li> <li class="has-form"> <a href="develop/getting-started.html" class="small button">Getting Started</a> </ul> </section> </nav> <section id="oops"> <div class="row"> <div class="large-9 medium-9 small-12 columns small-centered"> <h5>404: Page Not Found</h5> <h1 class="oversized">Keep on looking...</h1> <p class="lead bottom40">Double check the URL or head back to the <a href="http://foundation.zurb.com/index.html">homepage.</a> If you continue to get this page, email us at <a href="/cdn-cgi/l/email-protection#a3c5ccd6cdc7c2d7cacccde3d9d6d1c18dc0ccce"><span class="__cf_email__" data-cfemail="3f59504a515b5e4b5650517f454a4d5d115c505211">[email&#160;protected]</span><script data-cfhash='f9e31' type="text/javascript"> /* <![CDATA[ */!function(){try{var t="currentScript"in document?document.currentScript:function(){for(var t=document.getElementsByTagName("script"),e=t.length;e--;)if(t[e].getAttribute("data-cfhash"))return t[e]}();if(t&&t.previousSibling){var e,r,n,i,c=t.previousSibling,a=c.getAttribute("data-cfemail");if(a){for(e="",r=parseInt(a.substr(0,2),16),n=2;a.length-n;n+=2)i=parseInt(a.substr(n,2),16)^r,e+=String.fromCharCode(i);e=document.createTextNode(e),c.parentNode.replaceChild(e,c)}t.parentNode.removeChild(t);}}catch(u){}}()/* ]]> */</script></a></p> <h3>Or try one of these:</h3> <ul> <li><a href="http://foundation.zurb.com/learn/features.html" class="">What's new in Foundation 5</a></li> <li><a href="http://foundation.zurb.com/learn/training.html">Foundation Training</a></li> <li><a href="http://foundation.zurb.com/templates.html">HTML Templates for Foundation</a></li> <li><a href="http://foundation.zurb.com/support/support.html" class="">Foundation Support</a></li> <li><a href="http://foundation.zurb.com/business/services.html" class="">Foundation Business</a></li> </ul> </div> </div> </section> <div id="newsletter"> <div class="row"> <div class="medium-8 columns"> <h5>Stay on top of what&rsquo;s happening in <a href="http://zurb.com/responsive">responsive design</a>.</h5> <p>Sign up to receive monthly <a href="http://zurb.com/responsive/reading">Responsive Reading</a> highlights.</p> </div> <div class="medium-4 columns"> <form action="http://zurb.createsend.com/t/y/s/xlitlu/" method="post"> <div class="row collapse margintop-20px"> <div class="small-8 medium-8 columns"> <input id="fieldEmail" name="cm-xlitlu-xlitlu" type="text" placeholder="[email protected]"> </div> <div class="small-4 medium-4 columns"> <input type="submit" href="#" class="postfix small button expand" value="Sign Up"> </div> </div> </form> </div> </div> </div> <div class="zurb-footer-top bg-fblue"> <div class="row property"> <div class="medium-4 columns"> <div class="property-info"> <h3>Foundation for Sites</h3> <p>Foundation is a responsive front-end framework made by <a href="http://zurb.com">ZURB</a>, a product design company in Campbell, CA. This framework is the result of building web products &amp; services since 1998. </p> </div> </div> <div class="medium-8 columns"> <div class="row collapse"> <div class="medium-4 columns"> <div class="learn-links"> <h4 class="hide-for-small">Want more?</h4> <ul> <li><a href="http://foundation.zurb.com/apps">Foundation for Apps</a></li> <li><a href="http://zurb.com/ink/">Ink Responsive Emails</a></li> <li><a href="http://zurb.com/notable">Notable Design Apps</a></li> <li><a href="http://zurb.com/university/courses">Training</a></li> <li><a href="http://zurb.com/library">Design Resources</a></li> </ul> </div> </div> <div class="medium-4 columns"> <div class="support-links"> <h4 class="hide-for-small">Talk to us</h4> <p>Tweet us at <br> <a href="https://twitter.com/zurbfoundation">@ZURBfoundation</a></p> <p><a href="business/services.html">Business Support</a></p> <p>Or check our <a href="support/support.html">support page</a></p> </div> </div> <div class="medium-4 columns"> <div class="connect-links"> <h4 class="hide-for-small">Stay Updated</h4> <p>Keep up with the latest on Foundation. Find us on <a href="https://github.com/zurb/foundation">Github</a>.</p> <a href="http://foundation.zurb.com/foundation-news.html" class="small button">Stay Connected</a> </div> </div> </div> </div> </div> <div class="row global"> <div class="medium-3 small-6 columns"> <a href="http://zurb.com/studios" class="footer-link-block services"> <span class="title">Studios</span> <span>Helping more than 200 startups succeed since 1998.</span> </a> </div> <div class="medium-3 small-6 columns"> <a href="http://foundation.zurb.com/" class="footer-link-block foundation"> <span class="title">Foundation</span> <span>The most advanced front-end framework in the world.</span> </a> </div> <div class="medium-3 small-6 columns"> <a href="http://zurb.com/notable" class="footer-link-block apps"> <span class="title">Notable Design Apps</span> <span>Prototype, iterate and collect feedback on your products.</span> </a> </div> <div class="medium-3 small-6 columns"> <a href="http://zurb.com/university" class="footer-link-block expo"> <span class="title">University</span> <span>Ideas, thoughts and design resources shared with you.</span> </a> </div> </div> </div> <div class="zurb-footer-bottom"> <div class="row"> <div class="medium-4 medium-4 push-8 columns"> <ul class="home-social"> <li><a href="http://www.twitter.com/ZURB" class="twitter"></a></li> <li><a href="http://www.facebook.com/ZURB" class="facebook"></a></li> <li><a href="http://zurb.com/contact" class="mail"></a></li> </ul> </div> <div class="medium-8 medium-8 pull-4 columns"> <a href="http://www.zurb.com" class="zurb-logo regular"></a> <ul class="zurb-links"> <li><a href="http://zurb.com/about">About</a></li> <li><a href="http://zurb.com/blog">Blog</a></li> <li><a href="http://zurb.com/news">News<span class="show-for-medium-up"> &amp; Events</span></a></li> <li><a href="http://zurb.com/contact">Contact</a></li> <li><a href="http://zurb.com/sitemap">Sitemap</a></li> </ul> <p class="copyright">© 1998–2015 ZURB, Inc. All rights reserved.</p> </div> </div> </div> <a class="exit-off-canvas"></a> </div> </div> <script src="http://foundation.zurb.com/assets/js/templates.js"></script> <script src="http://foundation.zurb.com/assets/js/marketing.js"></script> <script type="text/javascript"> /* <![CDATA[ */ (function(){try{var s,a,i,j,r,c,l=document.getElementsByTagName("a"),t=document.createElement("textarea");for(i=0;l.length-i;i++){try{a=l[i].getAttribute("href");if(a&&a.indexOf("/cdn-cgi/l/email-protection") > -1 && (a.length > 28)){s='';j=27+ 1 + a.indexOf("/cdn-cgi/l/email-protection");if (a.length > j) {r=parseInt(a.substr(j,2),16);for(j+=2;a.length>j&&a.substr(j,1)!='X';j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}j+=1;s+=a.substr(j,a.length-j);}t.innerHTML=s.replace(/</g,"&lt;").replace(/>/g,"&gt;");l[i].setAttribute("href","mailto:"+t.value);}}catch(e){}}}catch(e){}})(); /* ]]> */ </script> </body> </html>
from ..call_rest import call_rest from .get_folder import get_folder def create_folder(path, auth={}): headers = { 'Content-Type': 'application/vnd.sas.content.folder+json', 'Accept': 'application/vnd.sas.content.folder+json' } folder_structure = path.split("/") folder_structure.pop(0) current_level = "" for folder_name in folder_structure: parent_level = current_level current_level = '/'.join([current_level, folder_name]) data = { "name": folder_name, "type": "folder" } folder = get_folder(current_level, auth=auth) if folder['json'] == {}: print("Folder '{0}' doesn't exist. Creating it!".format(current_level)) parent_folder = get_folder(parent_level, auth=auth) endpoint = "/folders/folders" params = {"parentFolderUri": "/folders/folders/{0}".format(parent_folder["json"]["id"])} call_rest( endpoint, "post", params=params, auth=auth, headers=headers, data=data) folder = get_folder(current_level, auth=auth) return folder