text
stringlengths
2
1.05M
export default class { constructor() { this.videoContainer = document.querySelector('.videoContainer'); } goToProducts() { console.log('clicked'); window.scrollTo(0, this.videoContainer.getBoundingClientRect().y + this.videoContainer.clientHeight); } }
var searchData= [ ['savecontroller',['SaveController',['../class_l_i_d_l_1_1_controller_1_1_save_controller.html',1,'LIDL::Controller']]], ['savedtabschangelistener',['SavedTabsChangeListener',['../interfaceorg_1_1schabi_1_1newpipe_1_1settings_1_1tabs_1_1_tabs_manager_1_1_saved_tabs_change_listener.html',1,'org::schabi::newpipe::settings::tabs::TabsManager']]], ['searchfragment',['SearchFragment',['../classorg_1_1schabi_1_1newpipe_1_1fragments_1_1list_1_1search_1_1_search_fragment.html',1,'org::schabi::newpipe::fragments::list::search']]], ['searchhistorydao',['SearchHistoryDAO',['../interfaceorg_1_1schabi_1_1newpipe_1_1database_1_1history_1_1dao_1_1_search_history_d_a_o.html',1,'org::schabi::newpipe::database::history::dao']]], ['searchhistoryentry',['SearchHistoryEntry',['../classorg_1_1schabi_1_1newpipe_1_1database_1_1history_1_1model_1_1_search_history_entry.html',1,'org::schabi::newpipe::database::history::model']]], ['secondarystreamhelper',['SecondaryStreamHelper',['../classorg_1_1schabi_1_1newpipe_1_1util_1_1_secondary_stream_helper.html',1,'org::schabi::newpipe::util']]], ['sectionspageradapter',['SectionsPagerAdapter',['../classorg_1_1schabi_1_1newpipe_1_1about_1_1_about_activity_1_1_sections_pager_adapter.html',1,'org::schabi::newpipe::about::AboutActivity']]], ['segment',['Segment',['../classorg_1_1schabi_1_1newpipe_1_1streams_1_1_web_m_reader_1_1_segment.html',1,'org::schabi::newpipe::streams::WebMReader']]], ['selectchannelfragment',['SelectChannelFragment',['../classorg_1_1schabi_1_1newpipe_1_1settings_1_1_select_channel_fragment.html',1,'org::schabi::newpipe::settings']]], ['selectchannelitemholder',['SelectChannelItemHolder',['../classorg_1_1schabi_1_1newpipe_1_1settings_1_1_select_channel_fragment_1_1_select_channel_adapter_1_1_select_channel_item_holder.html',1,'org::schabi::newpipe::settings::SelectChannelFragment::SelectChannelAdapter']]], ['selectevent',['SelectEvent',['../classorg_1_1schabi_1_1newpipe_1_1player_1_1playqueue_1_1events_1_1_select_event.html',1,'org::schabi::newpipe::player::playqueue::events']]], ['selectkioskfragment',['SelectKioskFragment',['../classorg_1_1schabi_1_1newpipe_1_1settings_1_1_select_kiosk_fragment.html',1,'org::schabi::newpipe::settings']]], ['selectkioskitemholder',['SelectKioskItemHolder',['../classorg_1_1schabi_1_1newpipe_1_1settings_1_1_select_kiosk_fragment_1_1_select_kiosk_adapter_1_1_select_kiosk_item_holder.html',1,'org::schabi::newpipe::settings::SelectKioskFragment::SelectKioskAdapter']]], ['serializedcache',['SerializedCache',['../classorg_1_1schabi_1_1newpipe_1_1util_1_1_serialized_cache.html',1,'org::schabi::newpipe::util']]], ['servicehelper',['ServiceHelper',['../classorg_1_1schabi_1_1newpipe_1_1util_1_1_service_helper.html',1,'org::schabi::newpipe::util']]], ['serviceplayeractivity',['ServicePlayerActivity',['../classorg_1_1schabi_1_1newpipe_1_1player_1_1_service_player_activity.html',1,'org::schabi::newpipe::player']]], ['settingsactivity',['SettingsActivity',['../classorg_1_1schabi_1_1newpipe_1_1settings_1_1_settings_activity.html',1,'org::schabi::newpipe::settings']]], ['settingscontroller',['SettingsController',['../class_l_i_d_l_1_1_controller_1_1_settings_controller.html',1,'LIDL::Controller']]], ['sfx',['SFX',['../struct_l_i_d_l_1_1_s_f_x.html',1,'LIDL']]], ['sfxsettingswidget',['SfxSettingsWidget',['../class_sfx_settings_widget.html',1,'']]], ['sharpinputstream',['SharpInputStream',['../classus_1_1shandian_1_1giga_1_1postprocessing_1_1io_1_1_sharp_input_stream.html',1,'us::shandian::giga::postprocessing::io']]], ['sharpstream',['SharpStream',['../classorg_1_1schabi_1_1newpipe_1_1streams_1_1io_1_1_sharp_stream.html',1,'org::schabi::newpipe::streams::io']]], ['simpleblock',['SimpleBlock',['../classorg_1_1schabi_1_1newpipe_1_1streams_1_1_web_m_reader_1_1_simple_block.html',1,'org::schabi::newpipe::streams::WebMReader']]], ['singleplayqueue',['SinglePlayQueue',['../classorg_1_1schabi_1_1newpipe_1_1player_1_1playqueue_1_1_single_play_queue.html',1,'org::schabi::newpipe::player::playqueue']]], ['sliderspin',['SliderSpin',['../class_slider_spin.html',1,'']]], ['sliderstrategy',['SliderStrategy',['../interfaceorg_1_1schabi_1_1newpipe_1_1util_1_1_slider_strategy.html',1,'org::schabi::newpipe::util']]], ['softwarecomponent',['SoftwareComponent',['../classorg_1_1schabi_1_1newpipe_1_1about_1_1_software_component.html',1,'org::schabi::newpipe::about']]], ['soundboardmainui',['SoundboardMainUI',['../class_soundboard_main_u_i.html',1,'']]], ['soundfile',['SoundFile',['../class_l_i_d_l_1_1_sound_file.html',1,'LIDL']]], ['soundwrapper',['SoundWrapper',['../class_sound_wrapper.html',1,'']]], ['spoiler',['Spoiler',['../class_spoiler.html',1,'']]], ['standardlicenses',['StandardLicenses',['../classorg_1_1schabi_1_1newpipe_1_1about_1_1_standard_licenses.html',1,'org::schabi::newpipe::about']]], ['statelistener',['StateListener',['../interfaceorg_1_1schabi_1_1newpipe_1_1views_1_1_collapsible_view_1_1_state_listener.html',1,'org::schabi::newpipe::views::CollapsibleView']]], ['statesaver',['StateSaver',['../classorg_1_1schabi_1_1newpipe_1_1util_1_1_state_saver.html',1,'org::schabi::newpipe::util']]], ['statisticsplaylistfragment',['StatisticsPlaylistFragment',['../classorg_1_1schabi_1_1newpipe_1_1local_1_1history_1_1_statistics_playlist_fragment.html',1,'org::schabi::newpipe::local::history']]], ['streamdao',['StreamDAO',['../classorg_1_1schabi_1_1newpipe_1_1database_1_1stream_1_1dao_1_1_stream_d_a_o.html',1,'org::schabi::newpipe::database::stream::dao']]], ['streamentity',['StreamEntity',['../classorg_1_1schabi_1_1newpipe_1_1database_1_1stream_1_1model_1_1_stream_entity.html',1,'org::schabi::newpipe::database::stream::model']]], ['streamgridinfoitemholder',['StreamGridInfoItemHolder',['../classorg_1_1schabi_1_1newpipe_1_1info__list_1_1holder_1_1_stream_grid_info_item_holder.html',1,'org::schabi::newpipe::info_list::holder']]], ['streamhistorydao',['StreamHistoryDAO',['../classorg_1_1schabi_1_1newpipe_1_1database_1_1history_1_1dao_1_1_stream_history_d_a_o.html',1,'org::schabi::newpipe::database::history::dao']]], ['streamhistoryentity',['StreamHistoryEntity',['../classorg_1_1schabi_1_1newpipe_1_1database_1_1history_1_1model_1_1_stream_history_entity.html',1,'org::schabi::newpipe::database::history::model']]], ['streamhistoryentry',['StreamHistoryEntry',['../classorg_1_1schabi_1_1newpipe_1_1database_1_1history_1_1model_1_1_stream_history_entry.html',1,'org::schabi::newpipe::database::history::model']]], ['streaminfoitemholder',['StreamInfoItemHolder',['../classorg_1_1schabi_1_1newpipe_1_1info__list_1_1holder_1_1_stream_info_item_holder.html',1,'org::schabi::newpipe::info_list::holder']]], ['streamitemadapter',['StreamItemAdapter',['../classorg_1_1schabi_1_1newpipe_1_1util_1_1_stream_item_adapter.html',1,'org::schabi::newpipe::util']]], ['streamitemadapter_3c_20audiostream_2c_20stream_20_3e',['StreamItemAdapter< AudioStream, Stream >',['../classorg_1_1schabi_1_1newpipe_1_1util_1_1_stream_item_adapter.html',1,'org::schabi::newpipe::util']]], ['streamitemadapter_3c_20subtitlesstream_2c_20stream_20_3e',['StreamItemAdapter< SubtitlesStream, Stream >',['../classorg_1_1schabi_1_1newpipe_1_1util_1_1_stream_item_adapter.html',1,'org::schabi::newpipe::util']]], ['streamitemadapter_3c_20videostream_2c_20audiostream_20_3e',['StreamItemAdapter< VideoStream, AudioStream >',['../classorg_1_1schabi_1_1newpipe_1_1util_1_1_stream_item_adapter.html',1,'org::schabi::newpipe::util']]], ['streamminiinfoitemholder',['StreamMiniInfoItemHolder',['../classorg_1_1schabi_1_1newpipe_1_1info__list_1_1holder_1_1_stream_mini_info_item_holder.html',1,'org::schabi::newpipe::info_list::holder']]], ['streamstatedao',['StreamStateDAO',['../classorg_1_1schabi_1_1newpipe_1_1database_1_1stream_1_1dao_1_1_stream_state_d_a_o.html',1,'org::schabi::newpipe::database::stream::dao']]], ['streamstateentity',['StreamStateEntity',['../classorg_1_1schabi_1_1newpipe_1_1database_1_1stream_1_1model_1_1_stream_state_entity.html',1,'org::schabi::newpipe::database::stream::model']]], ['streamstatisticsentry',['StreamStatisticsEntry',['../classorg_1_1schabi_1_1newpipe_1_1database_1_1stream_1_1_stream_statistics_entry.html',1,'org::schabi::newpipe::database::stream']]], ['styleddelegate',['StyledDelegate',['../class_styled_delegate.html',1,'']]], ['subscriptiondao',['SubscriptionDAO',['../classorg_1_1schabi_1_1newpipe_1_1database_1_1subscription_1_1_subscription_d_a_o.html',1,'org::schabi::newpipe::database::subscription']]], ['subscriptionentity',['SubscriptionEntity',['../classorg_1_1schabi_1_1newpipe_1_1database_1_1subscription_1_1_subscription_entity.html',1,'org::schabi::newpipe::database::subscription']]], ['subscriptionfragment',['SubscriptionFragment',['../classorg_1_1schabi_1_1newpipe_1_1local_1_1subscription_1_1_subscription_fragment.html',1,'org::schabi::newpipe::local::subscription']]], ['subscriptionservice',['SubscriptionService',['../classorg_1_1schabi_1_1newpipe_1_1local_1_1subscription_1_1_subscription_service.html',1,'org::schabi::newpipe::local::subscription']]], ['subscriptionsexportservice',['SubscriptionsExportService',['../classorg_1_1schabi_1_1newpipe_1_1local_1_1subscription_1_1services_1_1_subscriptions_export_service.html',1,'org::schabi::newpipe::local::subscription::services']]], ['subscriptionsimportservice',['SubscriptionsImportService',['../classorg_1_1schabi_1_1newpipe_1_1local_1_1subscription_1_1services_1_1_subscriptions_import_service.html',1,'org::schabi::newpipe::local::subscription::services']]], ['subtitleconverter',['SubtitleConverter',['../classorg_1_1schabi_1_1newpipe_1_1streams_1_1_subtitle_converter.html',1,'org::schabi::newpipe::streams']]], ['suggestionitem',['SuggestionItem',['../classorg_1_1schabi_1_1newpipe_1_1fragments_1_1list_1_1search_1_1_suggestion_item.html',1,'org::schabi::newpipe::fragments::list::search']]], ['suggestionlistadapter',['SuggestionListAdapter',['../classorg_1_1schabi_1_1newpipe_1_1fragments_1_1list_1_1search_1_1_suggestion_list_adapter.html',1,'org::schabi::newpipe::fragments::list::search']]] ];
const { DataTypes } = require('sequelize'); const database = require('../service/database'); const Socket = require('./socket-model'); const Queue = database.define('queue', { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true }, list: { type: DataTypes.JSON, allowNull: true, } }); Queue.belongsTo(Socket, { as: 'socket' }); Queue.sync({ force: true }); module.exports = Queue;
import React from 'react'; import { StyledIcon } from '../StyledIcon'; export const Halt = props => ( <StyledIcon viewBox='0 0 24 24' a11yTitle='Halt' {...props}> <path fill='none' stroke='#000' strokeWidth='2' d='M8,23 C10,23 12.9996892,23 15,23 C18,23 19,21 19,18 L19,6 C19,4.00000008 18,3.99999992 17.5,4 C17,4.00000008 15.9998779,4.00000008 15.9998779,5.99999984 C15.9998779,7.9999996 15.9998782,13 15.9998782,13 C15.9998782,13 15.9998784,5.00000004 15.9998782,4 C15.9998779,2.99999996 15.9998779,2 14.5,2 C13.0001221,2 12.9996891,2.99999994 12.9996891,4.00000006 C12.9996891,5.00000017 12.9996892,13 12.9996892,13 C12.9996892,13 12.9996891,4.00000006 12.9996891,3.00000006 C12.9996891,2.00000006 13,1.00000001 11.5,0.999999996 C10,0.999999981 10,2.00000006 10,3 L10,13 L10,4 C10,3 10.029402,2 8.5,2 C7,2 7,3 7,4 L7,18 L7,14 C7,13 6.44999986,12 5.00000005,12 C5,12 4,12 4,12 C4,12 4.00000001,14.0384045 4,18 C3.99999999,21.9615955 6,23.023861 8,23 Z' /> </StyledIcon> );
import UTree from './UTree.js' export { UTree }
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react' import ReactDOM from 'react-dom' import DefaultParameters from './DefaultParameters' describe('default parameters', () => { it('renders without crashing', () => { const div = document.createElement('div') return new Promise(resolve => { ReactDOM.render(<DefaultParameters onReady={resolve} />, div) }) }) })
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const BigNum = require("bignum"); const constants_1 = require("../constants"); const validation_1 = require("./validation"); const BASE_10 = 10; const PHAETON_MAX_DECIMAL_POINTS = 8; const getDecimalPlaces = (amount) => (amount.split('.')[1] || '').length; exports.convertBeddowsToPHA = (beddowsAmount) => { if (typeof beddowsAmount !== 'string') { throw new Error('Cannot convert non-string amount'); } if (getDecimalPlaces(beddowsAmount)) { throw new Error('Beddows amount should not have decimal points'); } const beddowsAmountBigNum = new BigNum(beddowsAmount); if (validation_1.isGreaterThanMaxTransactionAmount(beddowsAmountBigNum)) { throw new Error('Beddows amount out of range'); } const lskAmountBigNum = beddowsAmountBigNum.div(constants_1.FIXED_POINT); return lskAmountBigNum.toString(BASE_10); }; exports.convertPHAToBeddows = (lskAmount) => { if (typeof lskAmount !== 'string') { throw new Error('Cannot convert non-string amount'); } if (getDecimalPlaces(lskAmount) > PHAETON_MAX_DECIMAL_POINTS) { throw new Error('PHA amount has too many decimal points'); } const lskAmountBigNum = new BigNum(lskAmount); const beddowsAmountBigNum = lskAmountBigNum.mul(constants_1.FIXED_POINT); if (validation_1.isGreaterThanMaxTransactionAmount(beddowsAmountBigNum)) { throw new Error('PHA amount out of range'); } return beddowsAmountBigNum.toString(); }; exports.prependPlusToPublicKeys = (publicKeys) => publicKeys.map(publicKey => `+${publicKey}`); exports.prependMinusToPublicKeys = (publicKeys) => publicKeys.map(publicKey => `-${publicKey}`); //# sourceMappingURL=format.js.map
const configuration = require("./src/infrastructure/configuration"); const logger = require("./src/infrastructure/logger")(configuration); const database = require("./src/infrastructure/database")(configuration); const models = require("./src/infrastructure/models")(database); const schemas = require("./src/infrastructure/schemas")(); const middlewares = require("./src/infrastructure/middlewares")(logger); const services = require("./src/infrastructure/services")(models, schemas); const router = require("./src/infrastructure/router")(services); const server = require("./src/infrastructure/server")(middlewares, router); module.exports = async () => { await database.sync(); return server; };
export const BASEURL = process.env.NODE_ENV === "development" ? "http://127.0.0.1:8000" : "https://www.frynzo.com"; // const BASEURL = "http://127.0.0.1:8000"; export const api = { auth: { login: `${BASEURL}/dj-rest-auth/login/`, register: `${BASEURL}/dj-rest-auth/registration/`, }, orders: { list: `${BASEURL}/api/orders/`, list_total: `${BASEURL}/api/orders/total/`, retrieve: (id) => `${BASEURL}/api/orders/${id}/`, create: `${BASEURL}/api/orders/create/`, update: (id) => `${BASEURL}/api/orders/${id}/update/`, delete: (id) => `${BASEURL}/api/orders/${id}/delete/`, }, players: { list: `${BASEURL}/api/players/`, create: `${BASEURL}/api/players/create/`, }, games: { list: `${BASEURL}/api/games/`, create: `${BASEURL}/api/games/create/`, }, devices: { list: `${BASEURL}/api/devices/`, create: `${BASEURL}/api/devices/create/`, }, market: { list: `${BASEURL}/api/market/`, orders: `${BASEURL}/api/market/orders/`, orders_total: `${BASEURL}/api/market/orders/total`, create_item: `${BASEURL}/api/market/create/`, create: `${BASEURL}/api/market/orders/create/`, delete: (id) => `${BASEURL}/api/market/orders/${id}/delete/`, update: (id) => `${BASEURL}/api/market/orders/${id}/update/`, retrieve: (id) => `${BASEURL}/api/market/orders/${id}/`, }, };
load("bf4b12814bc95f34eeb130127d8438ab.js"); load("93fae755edd261212639eed30afa2ca4.js"); // Copyright (C) 2016 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-date.prototype.setmonth es6id: 20.3.4.25 description: Type coercion of provided "date" info: | 1. Let t be LocalTime(? thisTimeValue(this value)). 2. Let m be ? ToNumber(month). 3. If date is not specified, let dt be DateFromTime(t); otherwise, let dt be ? ToNumber(date). 4. Let newDate be MakeDate(MakeDay(YearFromTime(t), m, dt), TimeWithinDay(t)). 5. Let u be TimeClip(UTC(newDate)). 6. Set the [[DateValue]] internal slot of this Date object to u. 7. Return u. ---*/ var date = new Date(2016, 6, 7, 11, 36, 23, 2); var callCount = 0; var arg = { valueOf: function() { args = arguments; thisValue = this; callCount += 1; return 2; } }; var args, thisValue, returnValue; returnValue = date.setMonth(6, arg); assert.sameValue(callCount, 1, 'invoked exactly once'); assert.sameValue(args.length, 0, 'invoked without arguments'); assert.sameValue(thisValue, arg, '"this" value'); assert.sameValue( returnValue, new Date(2016, 6, 2, 11, 36, 23, 2).getTime(), 'application of specified value' ); returnValue = date.setMonth(6, null); assert.sameValue( returnValue, new Date(2016, 6, 0, 11, 36, 23, 2).getTime(), 'null' ); returnValue = date.setMonth(6, true); assert.sameValue( returnValue, new Date(2016, 6, 1, 11, 36, 23, 2).getTime(), 'true' ); returnValue = date.setMonth(6, false); assert.sameValue( returnValue, new Date(2016, 6, 0, 11, 36, 23, 2).getTime(), 'false' ); returnValue = date.setMonth(6, ' +00200.000E-0002 '); assert.sameValue( returnValue, new Date(2016, 6, 2, 11, 36, 23, 2).getTime(), 'string' ); returnValue = date.setMonth(6, undefined); assert.sameValue(returnValue, NaN, 'undefined');
import React from "react"; import { Button } from "antd"; const buttonStyles = { red: { backgroundColor: "#ffa39e" }, green: { backgroundColor: "#eaff8f" } }; export default ({ theme, icon, label, action }) => { const butTheme = buttonStyles[theme] ? buttonStyles[theme] : null; const butIcon = icon ? icon : null; return ( <Button style={butTheme} icon={butIcon} onClick={action}> {label} </Button> ); };
export const TRANSLATE_INPUT = 'translate_input'; export default function (string) { const words = string.split(/\s+/); const translation = words.reduce((acc, word) => `${acc}${pigLatin(word)} `, '').trim(); return { type: TRANSLATE_INPUT, payload: { original: string, translation, } }; } function pigLatin(word) { const vowelStart = /^[aeiou].*$/; if (word.match(vowelStart)){ return word + 'way'; } else { return word.substr(1) + word.charAt(0) + 'ay'; } }
/* * grunt-strip-rails * https://github.com/Verikon/grunt-strip-rails * * Copyright (c) 2014 Verikon * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('strip_rails', 'The best Grunt plugin ever.', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ punctuation: '.', separator: ', ' }); // Iterate over all specified file groups. this.files.forEach(function(f) { // Concat specified files. var src = f.src.filter(function(filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }).map(function(filepath) { // Read file source. return grunt.file.read(filepath); }).join(grunt.util.normalizelf(options.separator)); // Handle options. src += options.punctuation; // Write the destination file. grunt.file.write(f.dest, src); // Print a success message. grunt.log.writeln('File "' + f.dest + '" created.'); }); }); };
!function(e,t){var n,i={},r=function(e,t){var n,i,r;if("string"==typeof e)return a(e);for(n=[],i=e.length,r=0;i>r;r++)n.push(a(e[r]));return t.apply(null,n)},o=function(e,t,n){2===arguments.length&&(n=t,t=null),r(t||[],function(){s(e,n,arguments)})},s=function(e,t,n){var o,s={exports:t};"function"==typeof t&&(n.length||(n=[r,s.exports,s]),o=t.apply(null,n),void 0!==o&&(s.exports=o)),i[e]=s.exports},a=function(t){var n=i[t]||e[t];if(!n)throw new Error("`"+t+"` is undefined");return n},u=function(e){var t,n,r,o,s,a;a=function(e){return e&&e.charAt(0).toUpperCase()+e.substr(1)};for(t in i)if(n=e,i.hasOwnProperty(t)){for(r=t.split("/"),s=a(r.pop());o=a(r.shift());)n[o]=n[o]||{},n=n[o];n[s]=i[t]}return e},c=function(n){return e.__dollar=n,u(t(e,o,r))};"object"==typeof module&&"object"==typeof module.exports?module.exports=c():"function"==typeof define&&define.amd?define(["jquery"],c):(n=e.WebUploader,e.WebUploader=c(),e.WebUploader.noConflict=function(){e.WebUploader=n})}(window,function(e,t,n){return t("dollar-third",[],function(){var t=e.__dollar||e.jQuery||e.Zepto;if(!t)throw new Error("jQuery or Zepto not found!");return t}),t("dollar",["dollar-third"],function(e){return e}),t("promise-third",["dollar"],function(e){return{Deferred:e.Deferred,when:e.when,isPromise:function(e){return e&&"function"==typeof e.then}}}),t("promise",["promise-third"],function(e){return e}),t("base",["dollar","promise"],function(t,n){function i(e){return function(){return a.apply(e,arguments)}}function r(e,t){return function(){return e.apply(t,arguments)}}function o(e){var t;return Object.create?Object.create(e):(t=function(){},t.prototype=e,new t)}var s=function(){},a=Function.call;return{version:"0.1.5",$:t,Deferred:n.Deferred,isPromise:n.isPromise,when:n.when,browser:function(e){var t={},n=e.match(/WebKit\/([\d.]+)/),i=e.match(/Chrome\/([\d.]+)/)||e.match(/CriOS\/([\d.]+)/),r=e.match(/MSIE\s([\d\.]+)/)||e.match(/(?:trident)(?:.*rv:([\w.]+))?/i),o=e.match(/Firefox\/([\d.]+)/),s=e.match(/Safari\/([\d.]+)/),a=e.match(/OPR\/([\d.]+)/);return n&&(t.webkit=parseFloat(n[1])),i&&(t.chrome=parseFloat(i[1])),r&&(t.ie=parseFloat(r[1])),o&&(t.firefox=parseFloat(o[1])),s&&(t.safari=parseFloat(s[1])),a&&(t.opera=parseFloat(a[1])),t}(navigator.userAgent),os:function(e){var t={},n=e.match(/(?:Android);?[\s\/]+([\d.]+)?/),i=e.match(/(?:iPad|iPod|iPhone).*OS\s([\d_]+)/);return n&&(t.android=parseFloat(n[1])),i&&(t.ios=parseFloat(i[1].replace(/_/g,"."))),t}(navigator.userAgent),inherits:function(e,n,i){var r;return"function"==typeof n?(r=n,n=null):r=n&&n.hasOwnProperty("constructor")?n.constructor:function(){return e.apply(this,arguments)},t.extend(!0,r,e,i||{}),r.__super__=e.prototype,r.prototype=o(e.prototype),n&&t.extend(!0,r.prototype,n),r},noop:s,bindFn:r,log:function(){return e.console?r(console.log,console):s}(),nextTick:function(){return function(e){setTimeout(e,1)}}(),slice:i([].slice),guid:function(){var e=0;return function(t){for(var n=(+new Date).toString(32),i=0;5>i;i++)n+=Math.floor(65535*Math.random()).toString(32);return(t||"wu_")+n+(e++).toString(32)}}(),formatSize:function(e,t,n){var i;for(n=n||["B","K","M","G","TB"];(i=n.shift())&&e>1024;)e/=1024;return("B"===i?e:e.toFixed(t||2))+i}}}),t("mediator",["base"],function(e){function t(e,t,n,i){return o.grep(e,function(e){return!(!e||t&&e.e!==t||n&&e.cb!==n&&e.cb._cb!==n||i&&e.ctx!==i)})}function n(e,t,n){o.each((e||"").split(a),function(e,i){n(i,t)})}function i(e,t){for(var n,i=!1,r=-1,o=e.length;++r<o;)if(n=e[r],n.cb.apply(n.ctx2,t)===!1){i=!0;break}return!i}var r,o=e.$,s=[].slice,a=/\s+/;return r={on:function(e,t,i){var r,o=this;return t?(r=this._events||(this._events=[]),n(e,t,function(e,t){var n={e:e};n.cb=t,n.ctx=i,n.ctx2=i||o,n.id=r.length,r.push(n)}),this):this},once:function(e,t,i){var r=this;return t?(n(e,t,function(e,t){var n=function(){return r.off(e,n),t.apply(i||r,arguments)};n._cb=t,r.on(e,n,i)}),r):r},off:function(e,i,r){var s=this._events;return s?e||i||r?(n(e,i,function(e,n){o.each(t(s,e,n,r),function(){delete s[this.id]})}),this):(this._events=[],this):this},trigger:function(e){var n,r,o;return this._events&&e?(n=s.call(arguments,1),r=t(this._events,e),o=t(this._events,"all"),i(r,n)&&i(o,arguments)):this}},o.extend({installTo:function(e){return o.extend(e,r)}},r)}),t("uploader",["base","mediator"],function(e,t){function n(e){this.options=i.extend(!0,{},n.options,e),this._init(this.options)}var i=e.$;return n.options={},t.installTo(n.prototype),i.each({upload:"start-upload",stop:"stop-upload",getFile:"get-file",getFiles:"get-files",addFile:"add-file",addFiles:"add-file",sort:"sort-files",removeFile:"remove-file",cancelFile:"cancel-file",skipFile:"skip-file",retry:"retry",isInProgress:"is-in-progress",makeThumb:"make-thumb",md5File:"md5-file",getDimension:"get-dimension",addButton:"add-btn",predictRuntimeType:"predict-runtime-type",refresh:"refresh",disable:"disable",enable:"enable",reset:"reset"},function(e,t){n.prototype[e]=function(){return this.request(t,arguments)}}),i.extend(n.prototype,{state:"pending",_init:function(e){var t=this;t.request("init",e,function(){t.state="ready",t.trigger("ready")})},option:function(e,t){var n=this.options;return arguments.length>1?void(i.isPlainObject(t)&&i.isPlainObject(n[e])?i.extend(n[e],t):n[e]=t):e?n[e]:n},getStats:function(){var e=this.request("get-stats");return e?{successNum:e.numOfSuccess,progressNum:e.numOfProgress,cancelNum:e.numOfCancel,invalidNum:e.numOfInvalid,uploadFailNum:e.numOfUploadFailed,queueNum:e.numOfQueue,interruptNum:e.numofInterrupt}:{}},trigger:function(e){var n=[].slice.call(arguments,1),r=this.options,o="on"+e.substring(0,1).toUpperCase()+e.substring(1);return t.trigger.apply(this,arguments)===!1||i.isFunction(r[o])&&r[o].apply(this,n)===!1||i.isFunction(this[o])&&this[o].apply(this,n)===!1||t.trigger.apply(t,[this,e].concat(n))===!1?!1:!0},destroy:function(){this.request("destroy",arguments),this.off()},request:e.noop}),e.create=n.create=function(e){return new n(e)},e.Uploader=n,n}),t("runtime/runtime",["base","mediator"],function(e,t){function n(t){this.options=i.extend({container:document.body},t),this.uid=e.guid("rt_")}var i=e.$,r={},o=function(e){for(var t in e)if(e.hasOwnProperty(t))return t;return null};return i.extend(n.prototype,{getContainer:function(){var e,t,n=this.options;return this._container?this._container:(e=i(n.container||document.body),t=i(document.createElement("div")),t.attr("id","rt_"+this.uid),t.css({position:"absolute",top:"0px",left:"0px",width:"151px",height:"45px",overflow:"hidden"}),e.append(t),e.addClass("webuploader-container"),this._container=t,this._parent=e,t)},init:e.noop,exec:e.noop,destroy:function(){this._container&&this._container.remove(),this._parent&&this._parent.removeClass("webuploader-container"),this.off()}}),n.orders="html5,flash",n.addRuntime=function(e,t){r[e]=t},n.hasRuntime=function(e){return!!(e?r[e]:o(r))},n.create=function(e,t){var s,a;if(t=t||n.orders,i.each(t.split(/\s*,\s*/g),function(){return r[this]?(s=this,!1):void 0}),s=s||o(r),!s)throw new Error("Runtime Error");return a=new r[s](e)},t.installTo(n.prototype),n}),t("runtime/client",["base","mediator","runtime/runtime"],function(e,t,n){function i(t,i){var o,s=e.Deferred();this.uid=e.guid("client_"),this.runtimeReady=function(e){return s.done(e)},this.connectRuntime=function(t,a){if(o)throw new Error("already connected!");return s.done(a),"string"==typeof t&&r.get(t)&&(o=r.get(t)),o=o||r.get(null,i),o?(e.$.extend(o.options,t),o.__promise.then(s.resolve),o.__client++):(o=n.create(t,t.runtimeOrder),o.__promise=s.promise(),o.once("ready",s.resolve),o.init(),r.add(o),o.__client=1),i&&(o.__standalone=i),o},this.getRuntime=function(){return o},this.disconnectRuntime=function(){o&&(o.__client--,o.__client<=0&&(r.remove(o),delete o.__promise,o.destroy()),o=null)},this.exec=function(){if(o){var n=e.slice(arguments);return t&&n.unshift(t),o.exec.apply(this,n)}},this.getRuid=function(){return o&&o.uid},this.destroy=function(e){return function(){e&&e.apply(this,arguments),this.trigger("destroy"),this.off(),this.exec("destroy"),this.disconnectRuntime()}}(this.destroy)}var r;return r=function(){var e={};return{add:function(t){e[t.uid]=t},get:function(t,n){var i;if(t)return e[t];for(i in e)if(!n||!e[i].__standalone)return e[i];return null},remove:function(t){delete e[t.uid]}}}(),t.installTo(i.prototype),i}),t("lib/dnd",["base","mediator","runtime/client"],function(e,t,n){function i(e){e=this.options=r.extend({},i.options,e),e.container=r(e.container),e.container.length&&n.call(this,"DragAndDrop")}var r=e.$;return i.options={accept:null,disableGlobalDnd:!1},e.inherits(n,{constructor:i,init:function(){var e=this;e.connectRuntime(e.options,function(){e.exec("init"),e.trigger("ready")})}}),t.installTo(i.prototype),i}),t("widgets/widget",["base","uploader"],function(e,t){function n(e){if(!e)return!1;var t=e.length,n=r.type(e);return 1===e.nodeType&&t?!0:"array"===n||"function"!==n&&"string"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}function i(e){this.owner=e,this.options=e.options}var r=e.$,o=t.prototype._init,s=t.prototype.destroy,a={},u=[];return r.extend(i.prototype,{init:e.noop,invoke:function(e,t){var n=this.responseMap;return n&&e in n&&n[e]in this&&r.isFunction(this[n[e]])?this[n[e]].apply(this,t):a},request:function(){return this.owner.request.apply(this.owner,arguments)}}),r.extend(t.prototype,{_init:function(){var e=this,t=e._widgets=[],n=e.options.disableWidgets||"";return r.each(u,function(i,r){(!n||!~n.indexOf(r._name))&&t.push(new r(e))}),o.apply(e,arguments)},request:function(t,i,r){var o,s,u,c,l=0,d=this._widgets,f=d&&d.length,h=[],p=[];for(i=n(i)?i:[i];f>l;l++)o=d[l],s=o.invoke(t,i),s!==a&&(e.isPromise(s)?p.push(s):h.push(s));return r||p.length?(u=e.when.apply(e,p),c=u.pipe?"pipe":"then",u[c](function(){var t=e.Deferred(),n=arguments;return 1===n.length&&(n=n[0]),setTimeout(function(){t.resolve(n)},1),t.promise()})[r?c:"done"](r||e.noop)):h[0]},destroy:function(){s.apply(this,arguments),this._widgets=null}}),t.register=i.register=function(t,n){var o,s={init:"init",destroy:"destroy",name:"anonymous"};return 1===arguments.length?(n=t,r.each(n,function(e){return"_"===e[0]||"name"===e?void("name"===e&&(s.name=n.name)):void(s[e.replace(/[A-Z]/g,"-$&").toLowerCase()]=e)})):s=r.extend(s,t),n.responseMap=s,o=e.inherits(i,n),o._name=s.name,u.push(o),o},t.unRegister=i.unRegister=function(e){if(e&&"anonymous"!==e)for(var t=u.length;t--;)u[t]._name===e&&u.splice(t,1)},i}),t("widgets/filednd",["base","uploader","lib/dnd","widgets/widget"],function(e,t,n){var i=e.$;return t.options.dnd="",t.register({name:"dnd",init:function(t){if(t.dnd&&"html5"===this.request("predict-runtime-type")){var r,o=this,s=e.Deferred(),a=i.extend({},{disableGlobalDnd:t.disableGlobalDnd,container:t.dnd,accept:t.accept});return this.dnd=r=new n(a),r.once("ready",s.resolve),r.on("drop",function(e){o.request("add-file",[e])}),r.on("accept",function(e){return o.owner.trigger("dndAccept",e)}),r.init(),s.promise()}},destroy:function(){this.dnd&&this.dnd.destroy()}})}),t("lib/filepaste",["base","mediator","runtime/client"],function(e,t,n){function i(e){e=this.options=r.extend({},e),e.container=r(e.container||document.body),n.call(this,"FilePaste")}var r=e.$;return e.inherits(n,{constructor:i,init:function(){var e=this;e.connectRuntime(e.options,function(){e.exec("init"),e.trigger("ready")})}}),t.installTo(i.prototype),i}),t("widgets/filepaste",["base","uploader","lib/filepaste","widgets/widget"],function(e,t,n){var i=e.$;return t.register({name:"paste",init:function(t){if(t.paste&&"html5"===this.request("predict-runtime-type")){var r,o=this,s=e.Deferred(),a=i.extend({},{container:t.paste,accept:t.accept});return this.paste=r=new n(a),r.once("ready",s.resolve),r.on("paste",function(e){o.owner.request("add-file",[e])}),r.init(),s.promise()}},destroy:function(){this.paste&&this.paste.destroy()}})}),t("lib/blob",["base","runtime/client"],function(e,t){function n(e,n){var i=this;i.source=n,i.ruid=e,this.size=n.size||0,!n.type&&this.ext&&~"jpg,jpeg,png,gif,bmp".indexOf(this.ext)?this.type="image/"+("jpg"===this.ext?"jpeg":this.ext):this.type=n.type||"application/octet-stream",t.call(i,"Blob"),this.uid=n.uid||this.uid,e&&i.connectRuntime(e)}return e.inherits(t,{constructor:n,slice:function(e,t){return this.exec("slice",e,t)},getSource:function(){return this.source}}),n}),t("lib/file",["base","lib/blob"],function(e,t){function n(e,n){var o;this.name=n.name||"untitled"+i++,o=r.exec(n.name)?RegExp.$1.toLowerCase():"",!o&&n.type&&(o=/\/(jpg|jpeg|png|gif|bmp)$/i.exec(n.type)?RegExp.$1.toLowerCase():"",this.name+="."+o),this.ext=o,this.lastModifiedDate=n.lastModifiedDate||(new Date).toLocaleString(),t.apply(this,arguments)}var i=1,r=/\.([^.]+)$/;return e.inherits(t,n)}),t("lib/filepicker",["base","runtime/client","lib/file"],function(t,n,i){function r(e){if(e=this.options=o.extend({},r.options,e),e.container=o(e.id),!e.container.length)throw new Error("按钮指定错误");e.innerHTML=e.innerHTML||e.label||e.container.html()||"",e.button=o(e.button||document.createElement("div")),e.button.html(e.innerHTML),e.container.html(e.button),n.call(this,"FilePicker",!0)}var o=t.$;return r.options={button:null,container:null,label:null,innerHTML:null,multiple:!0,accept:null,name:"file"},t.inherits(n,{constructor:r,init:function(){var n=this,r=n.options,s=r.button;s.addClass("webuploader-pick"),n.on("all",function(e){var t;switch(e){case"mouseenter":s.addClass("webuploader-pick-hover");break;case"mouseleave":s.removeClass("webuploader-pick-hover");break;case"change":t=n.exec("getFiles"),n.trigger("select",o.map(t,function(e){return e=new i(n.getRuid(),e),e._refer=r.container,e}),r.container)}}),n.connectRuntime(r,function(){n.refresh(),n.exec("init",r),n.trigger("ready")}),this._resizeHandler=t.bindFn(this.refresh,this),o(e).on("resize",this._resizeHandler)},refresh:function(){var e=this.getRuntime().getContainer(),t=this.options.button,n=t.outerWidth?t.outerWidth():t.width(),i=t.outerHeight?t.outerHeight():t.height(),r=t.offset();n&&i&&e.css({bottom:"auto",right:"auto",width:n+"px",height:i+"px"}).offset(r)},enable:function(){var e=this.options.button;e.removeClass("webuploader-pick-disable"),this.refresh()},disable:function(){var e=this.options.button;this.getRuntime().getContainer().css({top:"-99999px"}),e.addClass("webuploader-pick-disable")},destroy:function(){var t=this.options.button;o(e).off("resize",this._resizeHandler),t.removeClass("webuploader-pick-disable webuploader-pick-hover webuploader-pick")}}),r}),t("widgets/filepicker",["base","uploader","lib/filepicker","widgets/widget"],function(e,t,n){var i=e.$;return i.extend(t.options,{pick:null,accept:null}),t.register({name:"picker",init:function(e){return this.pickers=[],e.pick&&this.addBtn(e.pick)},refresh:function(){i.each(this.pickers,function(){this.refresh()})},addBtn:function(t){var r=this,o=r.options,s=o.accept,a=[];if(t)return i.isPlainObject(t)||(t={id:t}),i(t.id).each(function(){var u,c,l;l=e.Deferred(),u=i.extend({},t,{accept:i.isPlainObject(s)?[s]:s,swf:o.swf,runtimeOrder:o.runtimeOrder,id:this}),c=new n(u),c.once("ready",l.resolve),c.on("select",function(e){r.owner.request("add-file",[e])}),c.init(),r.pickers.push(c),a.push(l.promise())}),e.when.apply(e,a)},disable:function(){i.each(this.pickers,function(){this.disable()})},enable:function(){i.each(this.pickers,function(){this.enable()})},destroy:function(){i.each(this.pickers,function(){this.destroy()}),this.pickers=null}})}),t("lib/image",["base","runtime/client","lib/blob"],function(e,t,n){function i(e){this.options=r.extend({},i.options,e),t.call(this,"Image"),this.on("load",function(){this._info=this.exec("info"),this._meta=this.exec("meta")})}var r=e.$;return i.options={quality:90,crop:!1,preserveHeaders:!1,allowMagnify:!1},e.inherits(t,{constructor:i,info:function(e){return e?(this._info=e,this):this._info},meta:function(e){return e?(this._meta=e,this):this._meta},loadFromBlob:function(e){var t=this,n=e.getRuid();this.connectRuntime(n,function(){t.exec("init",t.options),t.exec("loadFromBlob",e)})},resize:function(){var t=e.slice(arguments);return this.exec.apply(this,["resize"].concat(t))},crop:function(){var t=e.slice(arguments);return this.exec.apply(this,["crop"].concat(t))},getAsDataUrl:function(e){return this.exec("getAsDataUrl",e)},getAsBlob:function(e){var t=this.exec("getAsBlob",e);return new n(this.getRuid(),t)}}),i}),t("widgets/image",["base","uploader","lib/image","widgets/widget"],function(e,t,n){var i,r=e.$;return i=function(e){var t=0,n=[],i=function(){for(var i;n.length&&e>t;)i=n.shift(),t+=i[0],i[1]()};return function(e,r,o){n.push([r,o]),e.once("destroy",function(){t-=r,setTimeout(i,1)}),setTimeout(i,1)}}(5242880),r.extend(t.options,{thumb:{width:110,height:110,quality:70,allowMagnify:!0,crop:!0,preserveHeaders:!1,type:"image/jpeg"},compress:{width:1600,height:1600,quality:90,allowMagnify:!1,crop:!1,preserveHeaders:!0}}),t.register({name:"image",makeThumb:function(e,t,o,s){var a,u;return e=this.request("get-file",e),e.type.match(/^image/)?(a=r.extend({},this.options.thumb),r.isPlainObject(o)&&(a=r.extend(a,o),o=null),o=o||a.width,s=s||a.height,u=new n(a),u.once("load",function(){e._info=e._info||u.info(),e._meta=e._meta||u.meta(),1>=o&&o>0&&(o=e._info.width*o),1>=s&&s>0&&(s=e._info.height*s),u.resize(o,s)}),u.once("complete",function(){t(!1,u.getAsDataUrl(a.type)),u.destroy()}),u.once("error",function(e){t(e||!0),u.destroy()}),void i(u,e.source.size,function(){e._info&&u.info(e._info),e._meta&&u.meta(e._meta),u.loadFromBlob(e.source)})):void t(!0)},beforeSendFile:function(t){var i,o,s=this.options.compress||this.options.resize,a=s&&s.compressSize||0,u=s&&s.noCompressIfLarger||!1;return t=this.request("get-file",t),!s||!~"image/jpeg,image/jpg".indexOf(t.type)||t.size<a||t._compressed?void 0:(s=r.extend({},s),o=e.Deferred(),i=new n(s),o.always(function(){i.destroy(),i=null}),i.once("error",o.reject),i.once("load",function(){var e=s.width,n=s.height;t._info=t._info||i.info(),t._meta=t._meta||i.meta(),1>=e&&e>0&&(e=t._info.width*e),1>=n&&n>0&&(n=t._info.height*n),i.resize(e,n)}),i.once("complete",function(){var e,n;try{e=i.getAsBlob(s.type),n=t.size,(!u||e.size<n)&&(t.source=e,t.size=e.size,t.trigger("resize",e.size,n)),t._compressed=!0,o.resolve()}catch(r){o.resolve()}}),t._info&&i.info(t._info),t._meta&&i.meta(t._meta),i.loadFromBlob(t.source),o.promise())}})}),t("file",["base","mediator"],function(e,t){function n(){return o+s++}function i(e){this.name=e.name||"Untitled",this.size=e.size||0,this.type=e.type||"application/octet-stream",this.lastModifiedDate=e.lastModifiedDate||1*new Date,this.id=n(),this.ext=a.exec(this.name)?RegExp.$1:"",this.statusText="",u[this.id]=i.Status.INITED,this.source=e,this.loaded=0,this.on("error",function(e){this.setStatus(i.Status.ERROR,e)})}var r=e.$,o="WU_FILE_",s=0,a=/\.([^.]+)$/,u={};return r.extend(i.prototype,{setStatus:function(e,t){var n=u[this.id];"undefined"!=typeof t&&(this.statusText=t),e!==n&&(u[this.id]=e,this.trigger("statuschange",e,n))},getStatus:function(){return u[this.id]},getSource:function(){return this.source},destroy:function(){this.off(),delete u[this.id]}}),t.installTo(i.prototype),i.Status={INITED:"inited",QUEUED:"queued",PROGRESS:"progress",ERROR:"error",COMPLETE:"complete",CANCELLED:"cancelled",INTERRUPT:"interrupt",INVALID:"invalid"},i}),t("queue",["base","mediator","file"],function(e,t,n){function i(){this.stats={numOfQueue:0,numOfSuccess:0,numOfCancel:0,numOfProgress:0,numOfUploadFailed:0,numOfInvalid:0,numofDeleted:0,numofInterrupt:0},this._queue=[],this._map={}}var r=e.$,o=n.Status;return r.extend(i.prototype,{append:function(e){return this._queue.push(e),this._fileAdded(e),this},prepend:function(e){return this._queue.unshift(e),this._fileAdded(e),this},getFile:function(e){return"string"!=typeof e?e:this._map[e]},fetch:function(e){var t,n,i=this._queue.length;for(e=e||o.QUEUED,t=0;i>t;t++)if(n=this._queue[t],e===n.getStatus())return n;return null},sort:function(e){"function"==typeof e&&this._queue.sort(e)},getFiles:function(){for(var e,t=[].slice.call(arguments,0),n=[],i=0,o=this._queue.length;o>i;i++)e=this._queue[i],(!t.length||~r.inArray(e.getStatus(),t))&&n.push(e);return n},removeFile:function(e){var t=this._map[e.id];t&&(delete this._map[e.id],e.destroy(),this.stats.numofDeleted++)},_fileAdded:function(e){var t=this,n=this._map[e.id];n||(this._map[e.id]=e,e.on("statuschange",function(e,n){t._onFileStatusChange(e,n)}))},_onFileStatusChange:function(e,t){var n=this.stats;switch(t){case o.PROGRESS:n.numOfProgress--;break;case o.QUEUED:n.numOfQueue--;break;case o.ERROR:n.numOfUploadFailed--;break;case o.INVALID:n.numOfInvalid--;break;case o.INTERRUPT:n.numofInterrupt--}switch(e){case o.QUEUED:n.numOfQueue++;break;case o.PROGRESS:n.numOfProgress++;break;case o.ERROR:n.numOfUploadFailed++;break;case o.COMPLETE:n.numOfSuccess++;break;case o.CANCELLED:n.numOfCancel++;break;case o.INVALID:n.numOfInvalid++;break;case o.INTERRUPT:n.numofInterrupt++}}}),t.installTo(i.prototype),i}),t("widgets/queue",["base","uploader","queue","file","lib/file","runtime/client","widgets/widget"],function(e,t,n,i,r,o){var s=e.$,a=/\.\w+$/,u=i.Status;return t.register({name:"queue",init:function(t){var i,r,a,u,c,l,d,f=this;if(s.isPlainObject(t.accept)&&(t.accept=[t.accept]),t.accept){for(c=[],a=0,r=t.accept.length;r>a;a++)u=t.accept[a].extensions,u&&c.push(u);c.length&&(l="\\."+c.join(",").replace(/,/g,"$|\\.").replace(/\*/g,".*")+"$"),f.accept=new RegExp(l,"i")}return f.queue=new n,f.stats=f.queue.stats,"html5"===this.request("predict-runtime-type")?(i=e.Deferred(),this.placeholder=d=new o("Placeholder"),d.connectRuntime({runtimeOrder:"html5"},function(){f._ruid=d.getRuid(),i.resolve()}),i.promise()):void 0},_wrapFile:function(e){if(!(e instanceof i)){if(!(e instanceof r)){if(!this._ruid)throw new Error("Can't add external files.");e=new r(this._ruid,e)}e=new i(e)}return e},acceptFile:function(e){var t=!e||!e.size||this.accept&&a.exec(e.name)&&!this.accept.test(e.name);return!t},_addFile:function(e){var t=this;return e=t._wrapFile(e),t.owner.trigger("beforeFileQueued",e)?t.acceptFile(e)?(t.queue.append(e),t.owner.trigger("fileQueued",e),e):void t.owner.trigger("error","Q_TYPE_DENIED",e):void 0},getFile:function(e){return this.queue.getFile(e)},addFile:function(e){var t=this;e.length||(e=[e]),e=s.map(e,function(e){return t._addFile(e)}),t.owner.trigger("filesQueued",e),t.options.auto&&setTimeout(function(){t.request("start-upload")},20)},getStats:function(){return this.stats},removeFile:function(e,t){var n=this;e=e.id?e:n.queue.getFile(e),this.request("cancel-file",e),t&&this.queue.removeFile(e)},getFiles:function(){return this.queue.getFiles.apply(this.queue,arguments)},fetchFile:function(){return this.queue.fetch.apply(this.queue,arguments)},retry:function(e,t){var n,i,r,o=this;if(e)return e=e.id?e:o.queue.getFile(e),e.setStatus(u.QUEUED),void(t||o.request("start-upload"));for(n=o.queue.getFiles(u.ERROR),i=0,r=n.length;r>i;i++)e=n[i],e.setStatus(u.QUEUED);o.request("start-upload")},sortFiles:function(){return this.queue.sort.apply(this.queue,arguments)},reset:function(){this.owner.trigger("reset"),this.queue=new n,this.stats=this.queue.stats},destroy:function(){this.reset(),this.placeholder&&this.placeholder.destroy()}})}),t("widgets/runtime",["uploader","runtime/runtime","widgets/widget"],function(e,t){return e.support=function(){return t.hasRuntime.apply(t,arguments)},e.register({name:"runtime",init:function(){if(!this.predictRuntimeType())throw Error("Runtime Error")},predictRuntimeType:function(){var e,n,i=this.options.runtimeOrder||t.orders,r=this.type;if(!r)for(i=i.split(/\s*,\s*/g),e=0,n=i.length;n>e;e++)if(t.hasRuntime(i[e])){this.type=r=i[e];break}return r}})}),t("lib/transport",["base","runtime/client","mediator"],function(e,t,n){function i(e){var n=this;e=n.options=r.extend(!0,{},i.options,e||{}),t.call(this,"Transport"),this._blob=null,this._formData=e.formData||{},this._headers=e.headers||{},this.on("progress",this._timeout),this.on("load error",function(){n.trigger("progress",1),clearTimeout(n._timer)})}var r=e.$;return i.options={server:"",method:"POST",withCredentials:!1,fileVal:"file",timeout:12e4,formData:{},headers:{},sendAsBinary:!1},r.extend(i.prototype,{appendBlob:function(e,t,n){var i=this,r=i.options;i.getRuid()&&i.disconnectRuntime(),i.connectRuntime(t.ruid,function(){i.exec("init")}),i._blob=t,r.fileVal=e||r.fileVal,r.filename=n||r.filename},append:function(e,t){"object"==typeof e?r.extend(this._formData,e):this._formData[e]=t},setRequestHeader:function(e,t){"object"==typeof e?r.extend(this._headers,e):this._headers[e]=t},send:function(e){this.exec("send",e),this._timeout()},abort:function(){return clearTimeout(this._timer),this.exec("abort")},destroy:function(){this.trigger("destroy"),this.off(),this.exec("destroy"),this.disconnectRuntime()},getResponse:function(){return this.exec("getResponse")},getResponseAsJson:function(){return this.exec("getResponseAsJson")},getStatus:function(){return this.exec("getStatus")},_timeout:function(){var e=this,t=e.options.timeout;t&&(clearTimeout(e._timer),e._timer=setTimeout(function(){e.abort(),e.trigger("error","timeout")},t))}}),n.installTo(i.prototype),i}),t("widgets/upload",["base","uploader","file","lib/transport","widgets/widget"],function(e,t,n,i){function r(e,t){var n,i,r=[],o=e.source,s=o.size,a=t?Math.ceil(s/t):1,u=0,c=0;for(i={file:e,has:function(){return!!r.length},shift:function(){return r.shift()},unshift:function(e){r.unshift(e)}};a>c;)n=Math.min(t,s-u),r.push({file:e,start:u,end:t?u+n:s,total:s,chunks:a,chunk:c++,cuted:i}),u+=n;return e.blocks=r.concat(),e.remaning=r.length,i}var o=e.$,s=e.isPromise,a=n.Status;o.extend(t.options,{prepareNextFile:!1,chunked:!1,chunkSize:5242880,chunkRetry:2,threads:3,formData:{}}),t.register({name:"upload",init:function(){var t=this.owner,n=this;this.runing=!1,this.progress=!1,t.on("startUpload",function(){n.progress=!0}).on("uploadFinished",function(){n.progress=!1}),this.pool=[],this.stack=[],this.pending=[],this.remaning=0,this.__tick=e.bindFn(this._tick,this),t.on("uploadComplete",function(e){e.blocks&&o.each(e.blocks,function(e,t){t.transport&&(t.transport.abort(),t.transport.destroy()),delete t.transport}),delete e.blocks,delete e.remaning})},reset:function(){this.request("stop-upload",!0),this.runing=!1,this.pool=[],this.stack=[],this.pending=[],this.remaning=0,this._trigged=!1,this._promise=null},startUpload:function(t){var n=this;if(o.each(n.request("get-files",a.INVALID),function(){n.request("remove-file",this)}),t)if(t=t.id?t:n.request("get-file",t),t.getStatus()===a.INTERRUPT)o.each(n.pool,function(e,n){n.file===t&&n.transport&&n.transport.send()}),t.setStatus(a.QUEUED);else{if(t.getStatus()===a.PROGRESS)return;t.setStatus(a.QUEUED)}else o.each(n.request("get-files",[a.INITED]),function(){this.setStatus(a.QUEUED)});if(!n.runing){n.runing=!0;var i=[];o.each(n.pool,function(e,t){var r=t.file;r.getStatus()===a.INTERRUPT&&(i.push(r),n._trigged=!1,t.transport&&t.transport.send())});for(var t;t=i.shift();)t.setStatus(a.PROGRESS);t||o.each(n.request("get-files",a.INTERRUPT),function(){this.setStatus(a.PROGRESS)}),n._trigged=!1,e.nextTick(n.__tick),n.owner.trigger("startUpload")}},stopUpload:function(t,n){var i=this;if(t===!0&&(n=t,t=null),i.runing!==!1){if(t){if(t=t.id?t:i.request("get-file",t),t.getStatus()!==a.PROGRESS&&t.getStatus()!==a.QUEUED)return;return t.setStatus(a.INTERRUPT),o.each(i.pool,function(e,n){n.file===t&&(n.transport&&n.transport.abort(),i._putback(n),i._popBlock(n))}),e.nextTick(i.__tick)}i.runing=!1,this._promise&&this._promise.file&&this._promise.file.setStatus(a.INTERRUPT),n&&o.each(i.pool,function(e,t){t.transport&&t.transport.abort(),t.file.setStatus(a.INTERRUPT)}),i.owner.trigger("stopUpload")}},cancelFile:function(e){e=e.id?e:this.request("get-file",e),e.blocks&&o.each(e.blocks,function(e,t){var n=t.transport;n&&(n.abort(),n.destroy(),delete t.transport)}),e.setStatus(a.CANCELLED),this.owner.trigger("fileDequeued",e)},isInProgress:function(){return!!this.progress},_getStats:function(){return this.request("get-stats")},skipFile:function(e,t){e=e.id?e:this.request("get-file",e),e.setStatus(t||a.COMPLETE),e.skipped=!0,e.blocks&&o.each(e.blocks,function(e,t){var n=t.transport;n&&(n.abort(),n.destroy(),delete t.transport)}),this.owner.trigger("uploadSkip",e)},_tick:function(){var t,n,i=this,r=i.options;return i._promise?i._promise.always(i.__tick):void(i.pool.length<r.threads&&(n=i._nextBlock())?(i._trigged=!1,t=function(t){i._promise=null,t&&t.file&&i._startSend(t),e.nextTick(i.__tick)},i._promise=s(n)?n.always(t):t(n)):i.remaning||i._getStats().numOfQueue||i._getStats().numofInterrupt||(i.runing=!1,i._trigged||e.nextTick(function(){i.owner.trigger("uploadFinished")}),i._trigged=!0))},_putback:function(e){var t;e.cuted.unshift(e),t=this.stack.indexOf(e.cuted),~t||this.stack.unshift(e.cuted)},_getStack:function(){for(var e,t=0;e=this.stack[t++];){if(e.has()&&e.file.getStatus()===a.PROGRESS)return e;(!e.has()||e.file.getStatus()!==a.PROGRESS&&e.file.getStatus()!==a.INTERRUPT)&&this.stack.splice(--t,1)}return null},_nextBlock:function(){var e,t,n,i,o=this,a=o.options;return(e=this._getStack())?(a.prepareNextFile&&!o.pending.length&&o._prepareNextFile(),e.shift()):o.runing?(!o.pending.length&&o._getStats().numOfQueue&&o._prepareNextFile(),t=o.pending.shift(),n=function(t){return t?(e=r(t,a.chunked?a.chunkSize:0),o.stack.push(e),e.shift()):null},s(t)?(i=t.file,t=t[t.pipe?"pipe":"then"](n),t.file=i,t):n(t)):void 0},_prepareNextFile:function(){var e,t=this,n=t.request("fetch-file"),i=t.pending;n&&(e=t.request("before-send-file",n,function(){return n.getStatus()===a.PROGRESS||n.getStatus()===a.INTERRUPT?n:t._finishFile(n)}),t.owner.trigger("uploadStart",n),n.setStatus(a.PROGRESS),e.file=n,e.done(function(){var t=o.inArray(e,i);~t&&i.splice(t,1,n)}),e.fail(function(e){n.setStatus(a.ERROR,e),t.owner.trigger("uploadError",n,e),t.owner.trigger("uploadComplete",n)}),i.push(e))},_popBlock:function(e){var t=o.inArray(e,this.pool);this.pool.splice(t,1),e.file.remaning--,this.remaning--},_startSend:function(t){var n,i=this,r=t.file;return r.getStatus()!==a.PROGRESS?void(r.getStatus()===a.INTERRUPT&&i._putback(t)):(i.pool.push(t),i.remaning++,t.blob=1===t.chunks?r.source:r.source.slice(t.start,t.end),n=i.request("before-send",t,function(){r.getStatus()===a.PROGRESS?i._doSend(t):(i._popBlock(t),e.nextTick(i.__tick))}),void n.fail(function(){1===r.remaning?i._finishFile(r).always(function(){t.percentage=1,i._popBlock(t),i.owner.trigger("uploadComplete",r),e.nextTick(i.__tick)}):(t.percentage=1,i.updateFileProgress(r),i._popBlock(t),e.nextTick(i.__tick))}))},_doSend:function(t){var n,r,s=this,u=s.owner,c=s.options,l=t.file,d=new i(c),f=o.extend({},c.formData),h=o.extend({},c.headers);t.transport=d,d.on("destroy",function(){delete t.transport,s._popBlock(t),e.nextTick(s.__tick)}),d.on("progress",function(e){t.percentage=e,s.updateFileProgress(l)}),n=function(e){var n;return r=d.getResponseAsJson()||{},r._raw=d.getResponse(),n=function(t){e=t},u.trigger("uploadAccept",t,r,n)||(e=e||"server"),e},d.on("error",function(e,i){t.retried=t.retried||0,t.chunks>1&&~"http,abort".indexOf(e)&&t.retried<c.chunkRetry?(t.retried++,d.send()):(i||"server"!==e||(e=n(e)),l.setStatus(a.ERROR,e),u.trigger("uploadError",l,e),u.trigger("uploadComplete",l))}),d.on("load",function(){var e;return(e=n())?void d.trigger("error",e,!0):void(1===l.remaning?s._finishFile(l,r):d.destroy())}),f=o.extend(f,{id:l.id,name:l.name,type:l.type,lastModifiedDate:l.lastModifiedDate,size:l.size}),t.chunks>1&&o.extend(f,{chunks:t.chunks,chunk:t.chunk}),u.trigger("uploadBeforeSend",t,f,h),d.appendBlob(c.fileVal,t.blob,l.name),d.append(f),d.setRequestHeader(h),d.send()},_finishFile:function(e,t,n){var i=this.owner;return i.request("after-send-file",arguments,function(){e.setStatus(a.COMPLETE),i.trigger("uploadSuccess",e,t,n)}).fail(function(t){e.getStatus()===a.PROGRESS&&e.setStatus(a.ERROR,t), i.trigger("uploadError",e,t)}).always(function(){i.trigger("uploadComplete",e)})},updateFileProgress:function(e){var t=0,n=0;e.blocks&&(o.each(e.blocks,function(e,t){n+=(t.percentage||0)*(t.end-t.start)}),t=n/e.size,this.owner.trigger("uploadProgress",e,t||0))}})}),t("widgets/validator",["base","uploader","file","widgets/widget"],function(e,t,n){var i,r=e.$,o={};return i={addValidator:function(e,t){o[e]=t},removeValidator:function(e){delete o[e]}},t.register({name:"validator",init:function(){var t=this;e.nextTick(function(){r.each(o,function(){this.call(t.owner)})})}}),i.addValidator("fileNumLimit",function(){var e=this,t=e.options,n=0,i=parseInt(t.fileNumLimit,10),r=!0;i&&(e.on("beforeFileQueued",function(e){return n>=i&&r&&(r=!1,this.trigger("error","Q_EXCEED_NUM_LIMIT",i,e),setTimeout(function(){r=!0},1)),n>=i?!1:!0}),e.on("fileQueued",function(){n++}),e.on("fileDequeued",function(){n--}),e.on("reset",function(){n=0}))}),i.addValidator("fileSizeLimit",function(){var e=this,t=e.options,n=0,i=parseInt(t.fileSizeLimit,10),r=!0;i&&(e.on("beforeFileQueued",function(e){var t=n+e.size>i;return t&&r&&(r=!1,this.trigger("error","Q_EXCEED_SIZE_LIMIT",i,e),setTimeout(function(){r=!0},1)),t?!1:!0}),e.on("fileQueued",function(e){n+=e.size}),e.on("fileDequeued",function(e){n-=e.size}),e.on("reset",function(){n=0}))}),i.addValidator("fileSingleSizeLimit",function(){var e=this,t=e.options,i=t.fileSingleSizeLimit;i&&e.on("beforeFileQueued",function(e){return e.size>i?(e.setStatus(n.Status.INVALID,"exceed_size"),this.trigger("error","F_EXCEED_SIZE",i,e),!1):void 0})}),i.addValidator("duplicate",function(){function e(e){for(var t,n=0,i=0,r=e.length;r>i;i++)t=e.charCodeAt(i),n=t+(n<<6)+(n<<16)-n;return n}var t=this,n=t.options,i={};n.duplicate||(t.on("beforeFileQueued",function(t){var n=t.__hash||(t.__hash=e(t.name+t.size+t.lastModifiedDate));return i[n]?(this.trigger("error","F_DUPLICATE",t),!1):void 0}),t.on("fileQueued",function(e){var t=e.__hash;t&&(i[t]=!0)}),t.on("fileDequeued",function(e){var t=e.__hash;t&&delete i[t]}),t.on("reset",function(){i={}}))}),i}),t("runtime/compbase",[],function(){function e(e,t){this.owner=e,this.options=e.options,this.getRuntime=function(){return t},this.getRuid=function(){return t.uid},this.trigger=function(){return e.trigger.apply(e,arguments)}}return e}),t("runtime/html5/runtime",["base","runtime/runtime","runtime/compbase"],function(t,n,i){function r(){var e={},i=this,r=this.destroy;n.apply(i,arguments),i.type=o,i.exec=function(n,r){var o,a=this,u=a.uid,c=t.slice(arguments,2);return s[n]&&(o=e[u]=e[u]||new s[n](a,i),o[r])?o[r].apply(o,c):void 0},i.destroy=function(){return r&&r.apply(this,arguments)}}var o="html5",s={};return t.inherits(n,{constructor:r,init:function(){var e=this;setTimeout(function(){e.trigger("ready")},1)}}),r.register=function(e,n){var r=s[e]=t.inherits(i,n);return r},e.Blob&&e.FileReader&&e.DataView&&n.addRuntime(o,r),r}),t("runtime/html5/blob",["runtime/html5/runtime","lib/blob"],function(e,t){return e.register("Blob",{slice:function(e,n){var i=this.owner.source,r=i.slice||i.webkitSlice||i.mozSlice;return i=r.call(i,e,n),new t(this.getRuid(),i)}})}),t("runtime/html5/dnd",["base","runtime/html5/runtime","lib/file"],function(e,t,n){var i=e.$,r="webuploader-dnd-";return t.register("DragAndDrop",{init:function(){var t=this.elem=this.options.container;this.dragEnterHandler=e.bindFn(this._dragEnterHandler,this),this.dragOverHandler=e.bindFn(this._dragOverHandler,this),this.dragLeaveHandler=e.bindFn(this._dragLeaveHandler,this),this.dropHandler=e.bindFn(this._dropHandler,this),this.dndOver=!1,t.on("dragenter",this.dragEnterHandler),t.on("dragover",this.dragOverHandler),t.on("dragleave",this.dragLeaveHandler),t.on("drop",this.dropHandler),this.options.disableGlobalDnd&&(i(document).on("dragover",this.dragOverHandler),i(document).on("drop",this.dropHandler))},_dragEnterHandler:function(e){var t,n=this,i=n._denied||!1;return e=e.originalEvent||e,n.dndOver||(n.dndOver=!0,t=e.dataTransfer.items,t&&t.length&&(n._denied=i=!n.trigger("accept",t)),n.elem.addClass(r+"over"),n.elem[i?"addClass":"removeClass"](r+"denied")),e.dataTransfer.dropEffect=i?"none":"copy",!1},_dragOverHandler:function(e){var t=this.elem.parent().get(0);return t&&!i.contains(t,e.currentTarget)?!1:(clearTimeout(this._leaveTimer),this._dragEnterHandler.call(this,e),!1)},_dragLeaveHandler:function(){var e,t=this;return e=function(){t.dndOver=!1,t.elem.removeClass(r+"over "+r+"denied")},clearTimeout(t._leaveTimer),t._leaveTimer=setTimeout(e,100),!1},_dropHandler:function(e){var t,o,s=this,a=s.getRuid(),u=s.elem.parent().get(0);if(u&&!i.contains(u,e.currentTarget))return!1;e=e.originalEvent||e,t=e.dataTransfer;try{o=t.getData("text/html")}catch(c){}return o?void 0:(s._getTansferFiles(t,function(e){s.trigger("drop",i.map(e,function(e){return new n(a,e)}))}),s.dndOver=!1,s.elem.removeClass(r+"over"),!1)},_getTansferFiles:function(t,n){var i,r,o,s,a,u,c,l=[],d=[];for(i=t.items,r=t.files,c=!(!i||!i[0].webkitGetAsEntry),a=0,u=r.length;u>a;a++)o=r[a],s=i&&i[a],c&&s.webkitGetAsEntry().isDirectory?d.push(this._traverseDirectoryTree(s.webkitGetAsEntry(),l)):l.push(o);e.when.apply(e,d).done(function(){l.length&&n(l)})},_traverseDirectoryTree:function(t,n){var i=e.Deferred(),r=this;return t.isFile?t.file(function(e){n.push(e),i.resolve()}):t.isDirectory&&t.createReader().readEntries(function(t){var o,s=t.length,a=[],u=[];for(o=0;s>o;o++)a.push(r._traverseDirectoryTree(t[o],u));e.when.apply(e,a).then(function(){n.push.apply(n,u),i.resolve()},i.reject)}),i.promise()},destroy:function(){var e=this.elem;e&&(e.off("dragenter",this.dragEnterHandler),e.off("dragover",this.dragOverHandler),e.off("dragleave",this.dragLeaveHandler),e.off("drop",this.dropHandler),this.options.disableGlobalDnd&&(i(document).off("dragover",this.dragOverHandler),i(document).off("drop",this.dropHandler)))}})}),t("runtime/html5/filepaste",["base","runtime/html5/runtime","lib/file"],function(e,t,n){return t.register("FilePaste",{init:function(){var t,n,i,r,o=this.options,s=this.elem=o.container,a=".*";if(o.accept){for(t=[],n=0,i=o.accept.length;i>n;n++)r=o.accept[n].mimeTypes,r&&t.push(r);t.length&&(a=t.join(","),a=a.replace(/,/g,"|").replace(/\*/g,".*"))}this.accept=a=new RegExp(a,"i"),this.hander=e.bindFn(this._pasteHander,this),s.on("paste",this.hander)},_pasteHander:function(e){var t,i,r,o,s,a=[],u=this.getRuid();for(e=e.originalEvent||e,t=e.clipboardData.items,o=0,s=t.length;s>o;o++)i=t[o],"file"===i.kind&&(r=i.getAsFile())&&a.push(new n(u,r));a.length&&(e.preventDefault(),e.stopPropagation(),this.trigger("paste",a))},destroy:function(){this.elem.off("paste",this.hander)}})}),t("runtime/html5/filepicker",["base","runtime/html5/runtime"],function(e,t){var n=e.$;return t.register("FilePicker",{init:function(){var e,t,i,r,o=this.getRuntime().getContainer(),s=this,a=s.owner,u=s.options,c=this.label=n(document.createElement("label")),l=this.input=n(document.createElement("input"));if(l.attr("type","file"),l.attr("name",u.name),l.addClass("webuploader-element-invisible"),c.on("click",function(){l.trigger("click")}),c.css({opacity:0,width:"100%",height:"100%",display:"block",cursor:"pointer",background:"#ffffff"}),u.multiple&&l.attr("multiple","multiple"),u.accept&&u.accept.length>0){for(e=[],t=0,i=u.accept.length;i>t;t++)e.push(u.accept[t].mimeTypes);l.attr("accept",e.join(","))}o.append(l),o.append(c),r=function(e){a.trigger(e.type)},l.on("change",function(e){var t,i=arguments.callee;s.files=e.target.files,t=this.cloneNode(!0),t.value=null,this.parentNode.replaceChild(t,this),l.off(),l=n(t).on("change",i).on("mouseenter mouseleave",r),a.trigger("change")}),c.on("mouseenter mouseleave",r)},getFiles:function(){return this.files},destroy:function(){this.input.off(),this.label.off()}})}),t("runtime/html5/util",["base"],function(t){var n=e.createObjectURL&&e||e.URL&&URL.revokeObjectURL&&URL||e.webkitURL,i=t.noop,r=i;return n&&(i=function(){return n.createObjectURL.apply(n,arguments)},r=function(){return n.revokeObjectURL.apply(n,arguments)}),{createObjectURL:i,revokeObjectURL:r,dataURL2Blob:function(e){var t,n,i,r,o,s;for(s=e.split(","),t=~s[0].indexOf("base64")?atob(s[1]):decodeURIComponent(s[1]),i=new ArrayBuffer(t.length),n=new Uint8Array(i),r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return o=s[0].split(":")[1].split(";")[0],this.arrayBufferToBlob(i,o)},dataURL2ArrayBuffer:function(e){var t,n,i,r;for(r=e.split(","),t=~r[0].indexOf("base64")?atob(r[1]):decodeURIComponent(r[1]),n=new Uint8Array(t.length),i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n.buffer},arrayBufferToBlob:function(t,n){var i,r=e.BlobBuilder||e.WebKitBlobBuilder;return r?(i=new r,i.append(t),i.getBlob(n)):new Blob([t],n?{type:n}:{})},canvasToDataUrl:function(e,t,n){return e.toDataURL(t,n/100)},parseMeta:function(e,t){t(!1,{})},updateImageHead:function(e){return e}}}),t("runtime/html5/imagemeta",["runtime/html5/util"],function(e){var t;return t={parsers:{65505:[]},maxMetaDataSize:262144,parse:function(e,t){var n=this,i=new FileReader;i.onload=function(){t(!1,n._parse(this.result)),i=i.onload=i.onerror=null},i.onerror=function(e){t(e.message),i=i.onload=i.onerror=null},e=e.slice(0,n.maxMetaDataSize),i.readAsArrayBuffer(e.getSource())},_parse:function(e,n){if(!(e.byteLength<6)){var i,r,o,s,a=new DataView(e),u=2,c=a.byteLength-4,l=u,d={};if(65496===a.getUint16(0)){for(;c>u&&(i=a.getUint16(u),i>=65504&&65519>=i||65534===i)&&(r=a.getUint16(u+2)+2,!(u+r>a.byteLength));){if(o=t.parsers[i],!n&&o)for(s=0;s<o.length;s+=1)o[s].call(t,a,u,r,d);u+=r,l=u}l>6&&(e.slice?d.imageHead=e.slice(2,l):d.imageHead=new Uint8Array(e).subarray(2,l))}return d}},updateImageHead:function(e,t){var n,i,r,o=this._parse(e,!0);return r=2,o.imageHead&&(r=2+o.imageHead.byteLength),i=e.slice?e.slice(r):new Uint8Array(e).subarray(r),n=new Uint8Array(t.byteLength+2+i.byteLength),n[0]=255,n[1]=216,n.set(new Uint8Array(t),2),n.set(new Uint8Array(i),t.byteLength+2),n.buffer}},e.parseMeta=function(){return t.parse.apply(t,arguments)},e.updateImageHead=function(){return t.updateImageHead.apply(t,arguments)},t}),t("runtime/html5/imagemeta/exif",["base","runtime/html5/imagemeta"],function(e,t){var n={};return n.ExifMap=function(){return this},n.ExifMap.prototype.map={Orientation:274},n.ExifMap.prototype.get=function(e){return this[e]||this[this.map[e]]},n.exifTagTypes={1:{getValue:function(e,t){return e.getUint8(t)},size:1},2:{getValue:function(e,t){return String.fromCharCode(e.getUint8(t))},size:1,ascii:!0},3:{getValue:function(e,t,n){return e.getUint16(t,n)},size:2},4:{getValue:function(e,t,n){return e.getUint32(t,n)},size:4},5:{getValue:function(e,t,n){return e.getUint32(t,n)/e.getUint32(t+4,n)},size:8},9:{getValue:function(e,t,n){return e.getInt32(t,n)},size:4},10:{getValue:function(e,t,n){return e.getInt32(t,n)/e.getInt32(t+4,n)},size:8}},n.exifTagTypes[7]=n.exifTagTypes[1],n.getExifValue=function(t,i,r,o,s,a){var u,c,l,d,f,h,p=n.exifTagTypes[o];if(!p)return void e.log("Invalid Exif data: Invalid tag type.");if(u=p.size*s,c=u>4?i+t.getUint32(r+8,a):r+8,c+u>t.byteLength)return void e.log("Invalid Exif data: Invalid data offset.");if(1===s)return p.getValue(t,c,a);for(l=[],d=0;s>d;d+=1)l[d]=p.getValue(t,c+d*p.size,a);if(p.ascii){for(f="",d=0;d<l.length&&(h=l[d],"\x00"!==h);d+=1)f+=h;return f}return l},n.parseExifTag=function(e,t,i,r,o){var s=e.getUint16(i,r);o.exif[s]=n.getExifValue(e,t,i,e.getUint16(i+2,r),e.getUint32(i+4,r),r)},n.parseExifTags=function(t,n,i,r,o){var s,a,u;if(i+6>t.byteLength)return void e.log("Invalid Exif data: Invalid directory offset.");if(s=t.getUint16(i,r),a=i+2+12*s,a+4>t.byteLength)return void e.log("Invalid Exif data: Invalid directory size.");for(u=0;s>u;u+=1)this.parseExifTag(t,n,i+2+12*u,r,o);return t.getUint32(a,r)},n.parseExifData=function(t,i,r,o){var s,a,u=i+10;if(1165519206===t.getUint32(i+4)){if(u+8>t.byteLength)return void e.log("Invalid Exif data: Invalid segment size.");if(0!==t.getUint16(i+8))return void e.log("Invalid Exif data: Missing byte alignment offset.");switch(t.getUint16(u)){case 18761:s=!0;break;case 19789:s=!1;break;default:return void e.log("Invalid Exif data: Invalid byte alignment marker.")}if(42!==t.getUint16(u+2,s))return void e.log("Invalid Exif data: Missing TIFF marker.");a=t.getUint32(u+4,s),o.exif=new n.ExifMap,a=n.parseExifTags(t,u,u+a,s,o)}},t.parsers[65505].push(n.parseExifData),n}),t("runtime/html5/image",["base","runtime/html5/runtime","runtime/html5/util"],function(e,t,n){var i="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D";return t.register("Image",{modified:!1,init:function(){var e=this,t=new Image;t.onload=function(){e._info={type:e.type,width:this.width,height:this.height},e._metas||"image/jpeg"!==e.type?e.owner.trigger("load"):n.parseMeta(e._blob,function(t,n){e._metas=n,e.owner.trigger("load")})},t.onerror=function(){e.owner.trigger("error")},e._img=t},loadFromBlob:function(e){var t=this,i=t._img;t._blob=e,t.type=e.type,i.src=n.createObjectURL(e.getSource()),t.owner.once("load",function(){n.revokeObjectURL(i.src)})},resize:function(e,t){var n=this._canvas||(this._canvas=document.createElement("canvas"));this._resize(this._img,n,e,t),this._blob=null,this.modified=!0,this.owner.trigger("complete","resize")},crop:function(e,t,n,i,r){var o=this._canvas||(this._canvas=document.createElement("canvas")),s=this.options,a=this._img,u=a.naturalWidth,c=a.naturalHeight,l=this.getOrientation();r=r||1,o.width=n,o.height=i,s.preserveHeaders||this._rotate2Orientaion(o,l),this._renderImageToCanvas(o,a,-e,-t,u*r,c*r),this._blob=null,this.modified=!0,this.owner.trigger("complete","crop")},getAsBlob:function(e){var t,i=this._blob,r=this.options;if(e=e||this.type,this.modified||this.type!==e){if(t=this._canvas,"image/jpeg"===e){if(i=n.canvasToDataUrl(t,e,r.quality),r.preserveHeaders&&this._metas&&this._metas.imageHead)return i=n.dataURL2ArrayBuffer(i),i=n.updateImageHead(i,this._metas.imageHead),i=n.arrayBufferToBlob(i,e)}else i=n.canvasToDataUrl(t,e);i=n.dataURL2Blob(i)}return i},getAsDataUrl:function(e){var t=this.options;return e=e||this.type,"image/jpeg"===e?n.canvasToDataUrl(this._canvas,e,t.quality):this._canvas.toDataURL(e)},getOrientation:function(){return this._metas&&this._metas.exif&&this._metas.exif.get("Orientation")||1},info:function(e){return e?(this._info=e,this):this._info},meta:function(e){return e?(this._meta=e,this):this._meta},destroy:function(){var e=this._canvas;this._img.onload=null,e&&(e.getContext("2d").clearRect(0,0,e.width,e.height),e.width=e.height=0,this._canvas=null),this._img.src=i,this._img=this._blob=null},_resize:function(e,t,n,i){var r,o,s,a,u,c=this.options,l=e.width,d=e.height,f=this.getOrientation();~[5,6,7,8].indexOf(f)&&(n^=i,i^=n,n^=i),r=Math[c.crop?"max":"min"](n/l,i/d),c.allowMagnify||(r=Math.min(1,r)),o=l*r,s=d*r,c.crop?(t.width=n,t.height=i):(t.width=o,t.height=s),a=(t.width-o)/2,u=(t.height-s)/2,c.preserveHeaders||this._rotate2Orientaion(t,f),this._renderImageToCanvas(t,e,a,u,o,s)},_rotate2Orientaion:function(e,t){var n=e.width,i=e.height,r=e.getContext("2d");switch(t){case 5:case 6:case 7:case 8:e.width=i,e.height=n}switch(t){case 2:r.translate(n,0),r.scale(-1,1);break;case 3:r.translate(n,i),r.rotate(Math.PI);break;case 4:r.translate(0,i),r.scale(1,-1);break;case 5:r.rotate(.5*Math.PI),r.scale(1,-1);break;case 6:r.rotate(.5*Math.PI),r.translate(0,-i);break;case 7:r.rotate(.5*Math.PI),r.translate(n,-i),r.scale(-1,1);break;case 8:r.rotate(-.5*Math.PI),r.translate(-n,0)}},_renderImageToCanvas:function(){function t(e,t,n){var i,r,o,s=document.createElement("canvas"),a=s.getContext("2d"),u=0,c=n,l=n;for(s.width=1,s.height=n,a.drawImage(e,0,0),i=a.getImageData(0,0,1,n).data;l>u;)r=i[4*(l-1)+3],0===r?c=l:u=l,l=c+u>>1;return o=l/n,0===o?1:o}function n(e){var t,n,i=e.naturalWidth,r=e.naturalHeight;return i*r>1048576?(t=document.createElement("canvas"),t.width=t.height=1,n=t.getContext("2d"),n.drawImage(e,-i+1,0),0===n.getImageData(0,0,1,1).data[3]):!1}return e.os.ios?e.os.ios>=7?function(e,n,i,r,o,s){var a=n.naturalWidth,u=n.naturalHeight,c=t(n,a,u);return e.getContext("2d").drawImage(n,0,0,a*c,u*c,i,r,o,s)}:function(e,i,r,o,s,a){var u,c,l,d,f,h,p,g=i.naturalWidth,m=i.naturalHeight,v=e.getContext("2d"),b=n(i),_="image/jpeg"===this.type,y=1024,w=0,x=0;for(b&&(g/=2,m/=2),v.save(),u=document.createElement("canvas"),u.width=u.height=y,c=u.getContext("2d"),l=_?t(i,g,m):1,d=Math.ceil(y*s/g),f=Math.ceil(y*a/m/l);m>w;){for(h=0,p=0;g>h;)c.clearRect(0,0,y,y),c.drawImage(i,-h,-w),v.drawImage(u,0,0,y,y,r+p,o+x,d,f),h+=y,p+=d;w+=y,x+=f}v.restore(),u=c=null}:function(t){var n=e.slice(arguments,1),i=t.getContext("2d");i.drawImage.apply(i,n)}}()})}),t("runtime/html5/transport",["base","runtime/html5/runtime"],function(e,t){var n=e.noop,i=e.$;return t.register("Transport",{init:function(){this._status=0,this._response=null},send:function(){var t,n,r,o=this.owner,s=this.options,a=this._initAjax(),u=o._blob,c=s.server;s.sendAsBinary?(c+=(/\?/.test(c)?"&":"?")+i.param(o._formData),n=u.getSource()):(t=new FormData,i.each(o._formData,function(e,n){t.append(e,n)}),t.append(s.fileVal,u.getSource(),s.filename||o._formData.name||"")),s.withCredentials&&"withCredentials"in a?(a.open(s.method,c,!0),a.withCredentials=!0):a.open(s.method,c),this._setRequestHeader(a,s.headers),n?(a.overrideMimeType&&a.overrideMimeType("application/octet-stream"),e.os.android?(r=new FileReader,r.onload=function(){a.send(this.result),r=r.onload=null},r.readAsArrayBuffer(n)):a.send(n)):a.send(t)},getResponse:function(){return this._response},getResponseAsJson:function(){return this._parseJson(this._response)},getStatus:function(){return this._status},abort:function(){var e=this._xhr;e&&(e.upload.onprogress=n,e.onreadystatechange=n,e.abort(),this._xhr=e=null)},destroy:function(){this.abort()},_initAjax:function(){var e=this,t=new XMLHttpRequest,i=this.options;return!i.withCredentials||"withCredentials"in t||"undefined"==typeof XDomainRequest||(t=new XDomainRequest),t.upload.onprogress=function(t){var n=0;return t.lengthComputable&&(n=t.loaded/t.total),e.trigger("progress",n)},t.onreadystatechange=function(){return 4===t.readyState?(t.upload.onprogress=n,t.onreadystatechange=n,e._xhr=null,e._status=t.status,t.status>=200&&t.status<300?(e._response=t.responseText,e.trigger("load")):t.status>=500&&t.status<600?(e._response=t.responseText,e.trigger("error","server")):e.trigger("error",e._status?"http":"abort")):void 0},e._xhr=t,t},_setRequestHeader:function(e,t){i.each(t,function(t,n){e.setRequestHeader(t,n)})},_parseJson:function(e){var t;try{t=JSON.parse(e)}catch(n){t={}}return t}})}),t("preset/html5only",["base","widgets/filednd","widgets/filepaste","widgets/filepicker","widgets/image","widgets/queue","widgets/runtime","widgets/upload","widgets/validator","runtime/html5/blob","runtime/html5/dnd","runtime/html5/filepaste","runtime/html5/filepicker","runtime/html5/imagemeta/exif","runtime/html5/image","runtime/html5/transport"],function(e){return e}),t("webuploader",["preset/html5only"],function(e){return e}),n("webuploader")});
import entity from './index'; test('provides empty resolver for data without relationship', () => expect(entity('posts', { posts: [] })).toEqual({})); const data = { posts: [ { id: 1, title: 'Lorem Ipsum', user_id: 123 }, { id: 2, title: 'Ut enim ad minim', user_id: 456 }, { id: 3, title: 'Sic Dolor amet', user_id: 123 }, ], users: [ { id: 123, name: 'John Doe' }, { id: 456, name: 'Jane Doe' }, ], comments: [ { id: 987, post_id: 1, body: 'Consectetur adipiscing elit' }, { id: 995, post_id: 1, body: 'Nam molestie pellentesque dui' }, { id: 998, post_id: 2, body: 'Sunt in culpa qui officia' }, ], }; test('provides many to one relationship reolvers', () => { const { User } = entity('posts', data); expect(User(data.posts[0])).toEqual({ id: 123, name: 'John Doe' }); expect(User(data.posts[1])).toEqual({ id: 456, name: 'Jane Doe' }); const { Post } = entity('comments', data); expect(Post(data.comments[0])).toEqual({ id: 1, title: 'Lorem Ipsum', user_id: 123, }); expect(Post(data.comments[1])).toEqual({ id: 1, title: 'Lorem Ipsum', user_id: 123, }); expect(Post(data.comments[2])).toEqual({ id: 2, title: 'Ut enim ad minim', user_id: 456, }); }); test('provides one to many relationship reolvers', () => { const { Comments } = entity('posts', data); expect(Comments(data.posts[0])).toEqual([ { id: 987, post_id: 1, body: 'Consectetur adipiscing elit' }, { id: 995, post_id: 1, body: 'Nam molestie pellentesque dui' }, ]); expect(Comments(data.posts[1])).toEqual([ { id: 998, post_id: 2, body: 'Sunt in culpa qui officia' }, ]); expect(Comments(data.posts[2])).toEqual([]); const { Posts } = entity('users', data); expect(Posts(data.users[0])).toEqual([ { id: 1, title: 'Lorem Ipsum', user_id: 123 }, { id: 3, title: 'Sic Dolor amet', user_id: 123 }, ]); expect(Posts(data.users[1])).toEqual([ { id: 2, title: 'Ut enim ad minim', user_id: 456 }, ]); });
var current_star_statusses = []; star_elements = $('.fa-star').parent(); star_elements.find(".fa-star").each(function (i, elem) { current_star_statusses.push($(elem).hasClass('yellow')); }); star_elements.find(".fa-star").mouseenter(changeRatingStars); star_elements.find(".fa-star").mouseleave(resetRatingStars); /** * Changes the rating star colors when hovering over it. */ function changeRatingStars() { // Current star hovered var star = $(this); // Removes all colors first from all stars $('.fa-star').removeClass('gray').removeClass('yellow'); // Makes the current hovered star yellow star.addClass('yellow'); // Makes the previous stars yellow and the next stars gray star.parent().prevAll().children('.fa-star').addClass('yellow'); star.parent().nextAll().children('.fa-star').addClass('gray'); } /** * Resets the rating star colors when not hovered anymore. */ function resetRatingStars() { star_elements.each(function (i, elem) { $(elem).removeClass('yellow').removeClass('gray').addClass(current_star_statusses[i] ? 'yellow' : 'gray'); }); } //Scroll (Added at 30/05/2019) $("a.scroll-from").click(function () { var id = $(this).attr('href'); $("html, body").animate({scrollTop: $(id).offset().top - 90}, 1200); return true; }); $('#frmContact').submit(function (e) { e.preventDefault(); $.ajax({ url: '/api/send-contact', method: 'POST', data: $(this).serialize(), dataType: 'JSON', success: function (resp) { if (resp.success) { swal({ title: "Gửi liên hệ thành công", type: "success" }); $('#mdlContact').modal('hide'); } } }); }) //Login with facebook $('.review-button').click(function (e) { e.preventDefault(); $('.login-fb').attr('data-href', this.dataset.href); }) window.hocwp = window.hocwp || {}; function facebook_login_status_callback(response) { if (response.status === 'connected') { facebook_login_connected_callback(); } else if (response.status === 'not_authorized') { } else { } } function facebook_login() { FB.login(function (response) { facebook_login_status_callback(response); }, {scope: 'email,public_profile'}); } window.fbAsyncInit = function () { FB.init({ appId: '579674162603685', cookie: true, xfbml: true, version: 'v2.10' }); }; function facebook_login_connected_callback() { FB.api('/me', {fields: 'id,name,first_name,last_name,picture,verified,email'}, function (response) { (function ($) { $.ajax({ type: 'POST', dataType: 'json', url: '/api/login-with-fb-sdk', data: response, success: function (response) { /*ar href = window.location.href; if($.trim(response.redirect_to)) { href = response.redirect_to; }*/ window.location.href = $('.login-fb').data('href'); } }); })(jQuery); }); } $('#frmReviews').submit(function (e) { var rating = $('#frmReviews .fa-star.yellow').length; var content = $("#content_review").val(); var construction_id = $('#construction_id').val(); var review_person_id = $('#review_person_id').val(); e.preventDefault(); $.ajax({ url: '/api/add-review', method: 'post', data: {star: rating, content: content, construction_id: construction_id, review_person_id: review_person_id}, dataType: 'JSON', success: function (resp) { if (resp.success == true) { swal({ title: 'Thao tác thành công', type: 'success' }); } $('#frmReviews')[0].reset(); } }); }); $(document).ready(function () { $('.select-munti').select2(); }); var curInputId = undefined; function BrowseServer(div) { curInputId = div; window.KCFinder = { callBack: function (url) { fileUrl = url; //window.KCFinder = null; div.innerHTML = '<div style="margin:5px">Loading...</div>'; var img = new Image(); img.src = url; img.onload = function () { var fileName = fileUrl.split('/'); fileName = fileName[fileName.length - 1]; jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-input-new').removeClass('file-input-new'); jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-caption-name').text(fileName).attr('title', fileName); //Hien tai co anh if (jQuery('#' + curInputId).length && jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-preview-image').length) { if (!$('#' + curInputId + '[multiple]').length) jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-preview-frame').remove(); var count = jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-preview-image').length; var html = '<div class="file-preview-frame" id="preview-' + $.now() + '-' + (count) + '" data-fileindex="' + (count) + '" data-template="image"><div class="kv-file-content"> <img src="' + fileUrl + '" class="kv-preview-data file-preview-image" title="' + fileName + '" alt="' + fileName + '" style="width:auto;height:160px;"> </div><div class="file-thumbnail-footer"> <div class="file-footer-caption" title="' + fileName + '">' + fileName + ' <br></div> <div class="file-actions"> <div class="file-footer-buttons"> <button type="button" class="kv-file-zoom btn btn-link btn-xs btn-icon" title="View Details"><i class="icon-zoomin3"></i></button> </div> <div class="file-upload-indicator" title="Not uploaded yet"><i class="icon-file-plus text-slate"></i></div> <div class="clearfix"></div> </div> </div> </div>'; /* if (jQuery('input[name="'+curInputId+'"]').parents('.form-group').find('.file-initial-thumbs').length){ $('.file-preview-frame').remove(); }*/ if (jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-live-thumbs').length) jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-live-thumbs').append(html); else jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-initial-thumbs').append(html); jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-caption-name:last').prepend('<i class="glyphicon glyphicon-file kv-caption-icon"></i>'); var values = []; if ($('#' + curInputId + '[multiple]').length) values.push(jQuery('input[name="' + curInputId + '"]').val()); values.push(fileUrl); jQuery('input[name="' + curInputId + '"]').val(values.join(',')); } else { if (!$('#' + curInputId + '[multiple]').length) jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-preview-frame').remove(); var html = '<div class="file-preview"> <div class="close fileinput-remove">×</div> <div class="file-drop-disabled"> <div class="file-preview-thumbnails"> <div class="file-live-thumbs"> <div class="file-preview-frame" id="preview-' + $.now() + '-0" data-fileindex="0" data-template="image"><div class="kv-file-content"> <img src="' + fileUrl + '" class="kv-preview-data file-preview-image" title="' + fileName + '" alt="' + fileName + '" style="width:auto;height:160px;"> </div><div class="file-thumbnail-footer"> <div class="file-footer-caption" title="' + fileName + '">' + fileName + ' <br></div> <div class="file-actions"> <div class="file-footer-buttons"> <button type="button" class="kv-file-zoom btn btn-link btn-xs btn-icon" title="View Details"><i class="icon-zoomin3"></i></button> </div> <div class="file-upload-indicator" title="Not uploaded yet"><i class="icon-file-plus text-slate"></i></div> <div class="clearfix"></div> </div> </div> </div> </div> </div></div> <div class="clearfix"></div> <div class="file-preview-status text-center text-success"></div> <div class="kv-fileinput-error file-error-message" style="display: none;"></div> </div> </div>'; jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-input').prepend(html); jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-caption-name').prepend('<i class="glyphicon glyphicon-file kv-caption-icon"></i>'); jQuery('input[name="' + curInputId + '"]').val(fileUrl); //jQuery('input[name="'+curInputId+'"]').parents('.form-group').find('.file-preview:last') } jQuery('input[name="' + curInputId + '"]').parents('.form-group').find('.file-preview-thumbnails').each(function () { if (!$(this).html().trim().length) $(this).parents('.file-preview').remove(); }); } } }; window.open('/assets/backend/kcfinder-3.20/browse.php?type=images', 'kcfinder_image', 'status=0, toolbar=0, location=0, menubar=0, ' + 'directories=0, resizable=1, scrollbars=0, width=800, height=600' ); } function sortImage(elm) { if (elm) { if ($(elm).parents('.form-group').find('.file-preview-thumbnails .file-live-thumbs').length) { $(elm).parents('.form-group').find('.file-preview-thumbnails .file-live-thumbs').sortable({ revert: true, stop: function (event, ui) { $(ui.item[0]).parents('.form-group').find("input[type='hidden']").val($(ui.item[0]).parents('.form-group').find('img:visible').map(function () { return $(this).attr('src'); }).get().join(',')) $(ui.item[0]).parents('.form-group').find('.kv-image-counter').each(function () { $(this).text(parseInt($(this).parents('[data-template]').index(), 10) + 1); }); var str_img = $(ui.item[0]).parents('.form-group').find('img.kv-preview-data').map(function () { return this.src; }).get().join(','); } }); } } else { } } $(function(){ if ($(".file-input-extensions").length) { $('body').delegate('.file-actions .btn-link', 'click', function () { var indx = $(this).parents('[data-template]').index(); var name = $(this).parents('.form-group').find('input[type="hidden"]').attr('name'); var elm_parent = $(this).parents('.file-live-thumbs')[0]; $(this).parents('[data-template]').remove(); if (!$(elm_parent).find('[data-template]').length) { $(elm_parent).parents('.file-input').find('.file-caption-name').text('Không có ảnh'); $(elm_parent).parents('.file-input').toggleClass('file-input-new', true); } $(elm_parent).find('.kv-image-counter').each(function () { $(this).text(parseInt($(this).parents('[data-template]').index(), 10) + 1); }); var str_img = $(elm_parent).find('img.kv-preview-data').map(function () { return this.src; }).get().join(','); $('[name="' + name + '"]').val(str_img); }); var modalTemplate = '<div class="modal-dialog modal-lg" role="document">\n' + ' <div class="modal-content">\n' + ' <div class="modal-header">\n' + ' <div class="kv-zoom-actions btn-group">{toggleheader}{fullscreen}{borderless}{close}</div>\n' + ' <h6 class="modal-title">{heading} <small><span class="kv-zoom-title"></span></small></h6>\n' + ' </div>\n' + ' <div class="modal-body">\n' + ' <div class="floating-buttons btn-group"></div>\n' + ' <div class="kv-zoom-body file-zoom-content"></div>\n' + '{prev} {next}\n' + ' </div>\n' + ' </div>\n' + '</div>\n'; var previewZoomButtonClasses = { toggleheader: 'btn btn-default btn-icon btn-xs btn-header-toggle', fullscreen: 'btn btn-default btn-icon btn-xs', borderless: 'btn btn-default btn-icon btn-xs', close: 'btn btn-default btn-icon btn-xs' }; // Icons inside zoom modal classes var previewZoomButtonIcons = { prev: '<i class="icon-arrow-left32"></i>', next: '<i class="icon-arrow-right32"></i>', toggleheader: '<i class="icon-menu-open"></i>', fullscreen: '<i class="icon-screen-full"></i>', borderless: '<i class="icon-alignment-unalign"></i>', close: '<i class="icon-cross3"></i>' }; // File actions var fileActionSettings = { zoomClass: 'btn btn-link btn-xs btn-icon', zoomIcon: '<i class="icon-zoomin3"></i>', dragClass: 'btn btn-link btn-xs btn-icon', dragIcon: '<i class="icon-three-bars"></i>', removeClass: 'btn btn-link btn-icon btn-xs', removeIcon: '<i class="ion-trash-a"></i>', indicatorNew: '<i class="ion-plus text-slate"></i>', indicatorSuccess: '<i class="ion-checkmark file-icon-large text-success"></i>', indicatorError: '<i class="icon-cross2 text-danger"></i>', indicatorLoading: '<i class="icon-spinner2 spinner text-muted"></i>' }; $(".file-input-extensions").each(function () { var initPreview = $('input[name="' + this.id + '"]').val().split(','); for (i = 0; i < initPreview.length; i++) { initPreview[i] = initPreview[i]; } var initPreviewConfig = []; for (i = 0; i < initPreview.length; i++) { var fileNames = initPreview[i].split('/'); var fileName = fileNames[fileNames.length - 1]; var obj = {caption: fileName, key: i + 1, showDrag: false}; initPreviewConfig.push(obj); } var options = { browseLabel: 'Chọn', removeLabel: 'Xóa', browseClass: 'btn btn-success', uploadClass: 'btn btn-default', layoutTemplates: { icon: '<i class="icon-file-check"></i>', modal: modalTemplate }, maxFilesNum: 10, allowedFileExtensions: ["jpg", "gif", "png", "txt"], initialCaption: 'Không có ảnh', previewZoomButtonClasses: previewZoomButtonClasses, previewZoomButtonIcons: previewZoomButtonIcons, fileActionSettings: fileActionSettings, initialPreviewAsData: true, overwriteInitial: false, }; if (initPreviewConfig.length) { options.initialPreview = initPreview; options.initialPreviewConfig = initPreviewConfig; } $(this).fileinput(options); }).on('filecleared', function (event) { $('input[name="' + event.target.id + '"]').parents('.form-group').find('.file-preview').remove(); $('input[name="' + event.target.id + '"]').val(''); }); } })
'use strict'; var constants = require('inWalletcore/constants.js'); angular.module('copayApp.services').factory('txFormatService', function (profileService, configService, lodash) { var root = {}; var formatAmountStr = function (amount, asset) { if (!amount) return; return profileService.formatAmountWithUnit(amount, asset); }; var formatAmount = function (amount, asset) { return profileService.formatAmountUnit(amount, asset); }; var formatFeeStr = function (fee , asset) { if (!fee) return; let unit = asset =='inve' ? 'inve' : (asset =='btc' ? 'satoshi': 'gas'); return formatAmount(fee, unit) + ' '+(unit =='inve' ? 'INVE' : unit); }; root.processTx = function (tx,asset) { if (!tx) return; //console.log(JSON.stringify(tx)); var outputs = tx.outputs ? tx.outputs.length : 0; if (outputs > 1 && tx.action != 'received') { tx.hasMultiplesOutputs = true; tx.recipientCount = outputs; tx.amount = lodash.reduce(tx.outputs, function (total, o) { o.amountStr = formatAmountStr(o.amount, tx.asset); return total + o.amount; }, 0); } tx.my_address = tx.addressFrom; tx.asset = asset; tx.confirmations = tx.result; tx.time = tx.creation_date; tx.amountStr = formatAmountStr(tx.amount, asset); tx.amountTl = formatAmount(tx.amount, asset);// tx.feeStr = formatFeeStr(tx.fee + tx.fee_point || tx.fees , tx.asset); tx.addressFrom = tx.addressFrom; return tx; }; return root; });
let mode = __dirname.includes('/home/magic/Work/wools/magic/raw') const {Env} = mode ? require('../magic') : require('./magic') const $ = new Env('M幸运抽奖'); $.lz = 'LZ_TOKEN_KEY=lztokef1eb8494b0af868bd18bdaf8;LZ_TOKEN_VALUE=Aa5RE8RuY4X3zA==;'; $.activityUrl = 'https://lzkj-isv.isvjcloud.com/lzclient/1643034332288/cjwx/common/entry.html?activityId=a73d1d61b975438ab2a4f43fd6883335' let stop = false; $.s = 1 $.logic = async function () { if (stop) { return; } $.activityUrl = $.activityUrl.replace("#","&") $.activityId = $.getQueryString($.activityUrl, 'activityId') if (!$.activityId || !$.activityUrl) { $.log(`活动id不存在`); return } $.log(`活动id: ${$.activityId}`, `活动url: ${$.activityUrl}`) $.domain = $.activityUrl.match(/https?:\/\/([^/]+)/) && $.activityUrl.match( /https?:\/\/([^/]+)/)[1] || '' $.UA = `jdapp;iPhone;10.2.2;13.1.2;${$.uuid()};M/5.0;network/wifi;ADID/;model/iPhone8,1;addressid/2308460611;appBuild/167863;jdSupportDarkMode/0;Mozilla/5.0 (iPhone; CPU iPhone OS 13_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1;` let lzToken = await getLzToken() debugger if (typeof lzToken.data == 'string') { if (lzToken.data.match(/(活动已经结束)/) && lzToken.data.match( /(活动已经结束)/)[1] || '') { $.putMsg('活动已结束'); } else { console.log(lzToken); } stop = true; return } $.domain.includes('lzkj-isv.isvjcloud.com') ? await api( 'wxCommonInfo/initActInfo', `activityId=${$.activityId}`) : '' let token = await getToken(); if (token.code !== '0') { $.putMsg(`获取Token失败`); return } $.Token = token?.token let actInfo = await api('customer/getSimpleActInfoVo', `activityId=${$.activityId}`); if (!actInfo.result || !actInfo.data) { $.log(`获取活动信息失败`); return } $.jdActivityId = actInfo.data.jdActivityId; $.venderId = actInfo.data.venderId; $.shopId = actInfo.data.shopId; $.activityType = actInfo.data.activityType; let myPing = await api('customer/getMyPing', `userId=${$.venderId}&token=${$.Token}&fromType=APP`) if (!myPing.result) { $.putMsg(`获取pin失败`); return } $.Pin = myPing.data.secretPin; let shopInfo = await api('wxDrawActivity/shopInfo', `activityId=${$.activityId}`, true); if (!shopInfo.result) { $.putMsg('获取不到店铺信息,结束运行') return } $.userId = shopInfo?.data?.userId $.shopName = shopInfo?.data?.shopName await api('common/accessLogWithAD', `venderId=${$.venderId}&code=${$.activityType}&pin=${encodeURIComponent( $.Pin)}&activityId=${$.activityId}&pageUrl=${$.activityUrl}&subType=app&adSource=`); let activityContent = await api( 'wxDrawActivity/activityContent', `activityId=${$.activityId}&pin=${encodeURIComponent( $.Pin)}`, true); if (!activityContent.result) { $.putMsg('获取不到活动信息,结束运行') return } $.hasFollow = activityContent.data.hasFollow || '' $.needFollow = activityContent.data.needFollow || false $.canDrawTimes = activityContent.data.canDrawTimes || 0 $.content = activityContent.data.content || [] $.drawConsume = activityContent.data.drawConsume || 0 $.startTime = activityContent.data.startTime || 0 $.endTime = activityContent.data.endTime || 0 if ($.startTime > 0 && $.startTime > $.timestamp()) { $.putMsg(`抽奖活动开始时间${$.formatDate($.startTime, 'yyyy-MM-dd HH:mm:ss')}`) stop = true; return; } if ($.endTime !== 0 && ($.timestamp() > $.endTime)) { $.putMsg(`活动已结束于${$.formatDate($.endTime, 'yyyy-MM-dd HH:mm:ss')}`) stop = true; return; } $.log( `抽奖次数 ${$.canDrawTimes} ${$.drawConsume > 0 && $.drawConsume + "积分抽奖一次" || ''}`) if ($.canDrawTimes === 0) { return } $.log(`可抽奖次数:${$.canDrawTimes}`) if ($.needFollow && !$.hasFollow) { let fallow = await api($.domain.includes('cjhy-isv.isvjcloud.com') ? '/wxActionCommon/newFollowShop' : '/wxActionCommon/followShop', $.domain.includes('cjhy-isv.isvjcloud.com') ? `venderId=${$.userId}&activityId=${$.activityId}&buyerPin=${encodeURIComponent( encodeURIComponent($.Pin))}&activityType=${$.activityType}` : `userId=${$.userId}&activityId=${$.activityId}&buyerNick=${encodeURIComponent( $.Pin)}&activityType=${$.activityType}`); if (fallow.result) { $.log('关注成功') } else { $.log(JSON.stringify(fallow)); } await $.wait(2000); } for (let m = 1; $.canDrawTimes--; m++) { let prize = await api('/wxDrawActivity/start', $.domain.includes('cjhy-isv.isvjcloud.com') ? `activityId=${$.activityId}&pin=${encodeURIComponent( encodeURIComponent($.Pin))}` : `activityId=${$.activityId}&pin=${encodeURIComponent( $.Pin)}`); if (prize.result && prize.data.drawOk) { $.canDrawTimes = prize.data.canDrawTimes $.putMsg(`获得 ${prize.data.name}`); } else { $.putMsg(`${prize.errorMessage}`); break } await $.wait(parseInt(Math.random() * 1000 + 500, 10)); if (Number($.canDrawTimes) <= 0 || m >= 5) { break } } } $.after = async function () { if ($.msg.length > 0) { let message = `${$.shopName}奖品\n`; for (let ele of $.content) { if (ele.name.includes('谢谢') || ele.name.includes('再来')) { continue; } message += ` ${ele.name}\n` } $.msg.push(message) $.msg.push($.activityUrl); } } $.run({filename: __filename}).catch( reason => $.log(reason)); async function api(fn, body, isv) { let url = `https://${$.domain}/${fn}` let ck = $.lz + ($.Pin && "AUTH_C_USER=" + $.Pin + ";" || "") ck = isv ? `IsvToken=${$.Token};` + ck : ck; let headers = { "Host": $.domain, "Accept": "application/json", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-cn", "Connection": "keep-alive", "Content-Type": "application/x-www-form-urlencoded", "Origin": `https://${$.domain}`, "Cookie": ck, "Referer": `${$.activityUrl}`, "User-Agent": $.UA } let {data} = await $.request(url, headers, body) // $.log(fn, typeof data === 'string' ? '' : JSON.stringify(data)) await $.wait(200, 300) return data; } async function getToken() { let url = `https://api.m.jd.com/client.action?functionId=isvObfuscator` let body = '' switch ($.domain) { case 'cjhy-isv.isvjcloud.com': body = 'body=%7B%22url%22%3A%22https%3A//cjhy-isv.isvjcloud.com%22%2C%22id%22%3A%22%22%7D&uuid=920cd9b12a1e621d91ca2c066f6348bb5d4b586b&client=apple&clientVersion=10.1.4&st=1633916729623&sv=102&sign=9eee1d69b69daf9e66659a049ffe075b' break case 'lzkj-isv.isvjcloud.com': body = 'body=%7B%22url%22%3A%22https%3A//lzkj-isv.isvjcloud.com%22%2C%22id%22%3A%22%22%7D&uuid=925ce6441339525429252488722251fff6b10499&client=apple&clientVersion=10.1.4&st=1633777078141&sv=111&sign=00ed6b6f929625c69f367f1a0e5ad7c7' break case 'cjhydz-isv.isvjcloud.com': body = 'adid=7B411CD9-D62C-425B-B083-9AFC49B94228&area=16_1332_42932_43102&body=%7B%22url%22%3A%22https%3A%5C/%5C/cjhydz-isv.isvjcloud.com%22%2C%22id%22%3A%22%22%7D&build=167541&client=apple&clientVersion=9.4.0&d_brand=apple&d_model=iPhone8%2C1&eid=eidId10b812191seBCFGmtbeTX2vXF3lbgDAVwQhSA8wKqj6OA9J4foPQm3UzRwrrLdO23B3E2wCUY/bODH01VnxiEnAUvoM6SiEnmP3IPqRuO%2By/%2BZo&isBackground=N&joycious=48&lang=zh_CN&networkType=wifi&networklibtype=JDNetworkBaseAF&openudid=2f7578cb634065f9beae94d013f172e197d62283&osVersion=13.1.2&partner=apple&rfs=0000&scope=11&screen=750%2A1334&sign=60bde51b4b7f7ff6e1bc1f473ecf3d41&st=1613720203903&sv=110&uts=0f31TVRjBStG9NoZJdXLGd939Wv4AlsWNAeL1nxafUsZqiV4NLsVElz6AjC4L7tsnZ1loeT2A8Z5/KfI/YoJAUfJzTd8kCedfnLG522ydI0p40oi8hT2p2sNZiIIRYCfjIr7IAL%2BFkLsrWdSiPZP5QLptc8Cy4Od6/cdYidClR0NwPMd58K5J9narz78y9ocGe8uTfyBIoA9aCd/X3Muxw%3D%3D&uuid=hjudwgohxzVu96krv/T6Hg%3D%3D&wifiBssid=9cf90c586c4468e00678545b16176ed2' break default: body = ''; } let headers = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-cn", "Connection": "keep-alive", "Content-Type": "application/x-www-form-urlencoded", "Host": "api.m.jd.com", "Cookie": $.cookie, "User-Agent": $.UA, } let {data} = await $.request(url, headers, body) return data; } async function getLzToken() { let url = $.activityUrl.includes('cjhy-isv.isvjcloud.com') ? `https://${$.domain}/wxDrawActivity/activity?activityId=${$.activityId}` : `https://${$.domain}/wxCommonInfo/token` let headers = { 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'User-Agent': $.UA, 'Accept-Language': 'zh-cn', 'Cookie': '' } let {data} = await $.request(url, headers) return data; } async function getshopactivityId(venderId) { let url = `https://api.m.jd.com/client.action?appid=jd_shop_member&functionId=getShopOpenCardInfo&body=%7B%22venderId%22%3A%22${venderId}%22%2C%22channel%22%3A401%7D&client=H5&clientVersion=9.2.0&uuid=88888`; let headers = { 'Content-Type': 'text/plain; Charset=UTF-8', 'Origin': 'https://api.m.jd.com', 'Host': 'api.m.jd.com', 'accept': '*/*', 'User-Agent': $.UA, 'content-type': 'application/x-www-form-urlencoded', 'Referer': `https://shopmember.m.jd.com/shopcard/?venderId=${venderId}&shopId=${venderId}&venderType=5&channel=401`, 'Cookie': $.cookie } let data = await $.get(url, headers); if (data.success) { $.shopactivityId = data.result.interestsRuleList && data.result.interestsRuleList[0] && data.result.interestsRuleList[0].interestsInfo && data.result.interestsRuleList[0].interestsInfo.activityId || '' } } async function join(venderId) { $.shopactivityId = '' await $.wait(2000) await getshopactivityId(venderId) let req = ruhui(`${venderId}`); let data = await $.get(req.url, req.headers); if (data.success) { if (data.result && data.result.giftInfo) { for (let i of data.result.giftInfo.giftList) { $.log( `入会获得:${i.discountString}${i.prizeName}${i.secondLineDesc}`) } } } else if (data.message) { $.log(`${data.message || ''}`) } else { $.log(data) } } function ruhui(functionId) { let activityId = `` if ($.shopactivityId) { activityId = `,"activityId":${$.shopactivityId}` } return { url: `https://api.m.jd.com/client.action?appid=jd_shop_member&functionId=bindWithVender&body={"venderId":"${functionId}","shopId":"${functionId}","bindByVerifyCodeFlag":1,"registerExtend":{},"writeChildFlag":0${activityId},"channel":401}&client=H5&clientVersion=9.2.0&uuid=88888`, headers: { 'Content-Type': 'text/plain; Charset=UTF-8', 'Origin': 'https://api.m.jd.com', 'Host': 'api.m.jd.com', 'accept': '*/*', 'User-Agent': $.UA, 'content-type': 'application/x-www-form-urlencoded', 'Referer': `https://shopmember.m.jd.com/shopcard/?venderId=${functionId}&shopId=${functionId}&venderType=5&channel=401`, 'Cookie': $.cookie } } } function taskPostUrl(url, body) { let Referer = activityUrl.includes('cjhy-isv.isvjcloud.com') ? `${activityUrl}/wxDrawActivity/activity?activityId=${activityId}` : `${activityUrl}/lzclient/${activityId}/cjwx/common/entry.html?activityId=${activityId}` return { url: `${activityUrl}${url}`, body: body, headers: { "Accept": "application/json", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-cn", "Connection": "keep-alive", "Content-Type": "application/x-www-form-urlencoded", "Referer": Referer, "Cookie": $.lz + ($.Pin && "AUTH_C_USER=" + $.Pin + ";" || ""), "User-Agent": $.UA, } } }
define(['mout/string/truncate'], function (truncate) { describe('string/truncate()', function(){ var str = 'lorem ipsum dolor sit amet'; it('should limit number of chars', function(){ var r1 = truncate(str, 10); expect( r1.length ).toBeLessThan( 11 ); expect( r1 ).toEqual( 'lorem i...' ); var r2 = truncate(str, 14); expect( r2.length ).toBeLessThan( 15 ); expect( r2 ).toEqual( 'lorem ipsum...' ); }); it('should append string param', function(){ var r1 = truncate(str, 10, '--'); expect( r1.length ).toBeLessThan( 11 ); expect( r1 ).toEqual( 'lorem ip--' ); }); it('last char before append shouldn\'t be a whitespace', function(){ var r1 = truncate(str, 12, '='); var r2 = truncate(str, 13, '='); expect( r2.length ).toBeLessThan( 14 ); expect( r2 ).toEqual( 'lorem ipsum=' ); expect( r1 ).toEqual( r2 ); }); it('should allow cropping at full words', function(){ var r1 = truncate(str, 10, null, true); expect( r1.length ).toBeLessThan( 11 ); expect( r1 ).toEqual( 'lorem...' ); var r2 = truncate(str, 14, null, true); expect( r2.length ).toBeLessThan( 15 ); expect( r2 ).toEqual( 'lorem ipsum...' ); }); it('should treat null as empty string', function(){ expect( truncate(null, 1) ).toBe(''); }); it('should treat undefined as empty string', function(){ expect( truncate(void 0, 1) ).toBe(''); }); }); });
const http=require('http'); const io=require('socket.io'); const fs=require('fs'); const sql=require('mysql'); let db=sql.createPool({ host:"localhost", user:"root", password:"", database:"websocket" }); let server=http.createServer((req,res)=>{ fs.readFile(`www${req.url}`,(err,data)=>{ if(err){ res.writeHeader(404); res.write("没找到") }else{ res.write(data); } res.end(); }) }); server.listen(8080); let wsServer=io.listen(server); //记录用户数的数组 let userArr=[]; wsServer.on("connection",sock=>{ // console.log(sock) userArr.push(sock) //保存用户状态 let Now_user,Now_userId; //注册 sock.on("reg",(user,password)=>{ //1.检验数据 if(!/^\w{6,32}$/.test(user)){ sock.emit("reg_data",0,"用户名不规范") }else if(!/^.{6,32}$/.test(password)){ sock.emit("reg_data",0,"密码不规范") }else{ //2.查询数据 db.query(`SELECT * FROM user_table WHERE username="${user}"`,(err,data)=>{ if(err){ sock.emit("reg_data",0,"数据库有错") }else if(data.length>0){ sock.emit("reg_data",0,"用户名已经存在") }else{ //3.插入数据 db.query(`INSERT INTO user_table(username,password,online) VALUES("${user}","${password}",0)`,err=>{ if(err){ sock.emit("reg_data",0,"数据库有错") }else{ sock.emit("reg_data",1,"注册成功") } }) } }) } }) //登录 sock.on("login",(username,password)=>{ //1.验证数据 if(!/^\w{6,32}$/.test(username)){ sock.emit("login_data",0,"用户名不规范") }else if(!/^.{6,32}$/.test(password)){ sock.emit("login_data",0,"密码不规范") }else{ //2.查询是否存在,并且校验是否与数据库一致 db.query(`SELECT ID,password FROM user_table WHERE username="${username}"`,(err,data)=>{ if(err){ sock.emit("login_data",0,"数据库有错") }else if(data.length==0){ sock.emit("login_data",0,"用户名不存在") }else{ if(data[0].password!=password){ sock.emit("login_data",0,"密码不正确") }else{ db.query(`UPDATE user_table SET online=1 WHERE ID=${data[0].ID}`,err=>{ if(err){ sock.emit("login_data",0,"数据库有错") }else{ sock.emit("login_data",200,"登录成功"); Now_user=username; Now_userId=data[0].ID; } }) } } }) } }) //发送消息的接口 sock.on("msg",txt=>{ //将消息广播给所有人,不包括自己 userArr.forEach(item=>{ if(item==sock)return false; item.emit("otheruserMsg",Now_user,txt) }) //循环结束,告诉发信人发送成功 sock.emit("msg_data",200,txt) } ) //离线 sock.on("disconnect",function(){ db.query(`UPDATE user_table SET online=0 WHERE ID=${Now_userId}`,err=>{ console.log("有错"); Now_user=""; Now_userId=0; }) userArr.filter(item=>item!=sock); }) })
import flush from 'just-flush' import uniqBy from 'lodash.uniqby' import matchSorter from 'match-sorter' import emojiData from './emoji.json' import basicEmoji from 'node-emoji/lib/emoji.json' import emojilib from 'emojilib/emojis.json' function swap (json) { const ret = {} for (const key in json) { if (json.hasOwnProperty(key)) { ret[json[key]] = key } } return ret } const emojiToNameMapping = swap(basicEmoji) function getEmojiDetailsFromEmoji (emoji) { const emojiName = emojiToNameMapping[emoji] return emojiData.filter(x => x.short_name === emojiName)[0] } function getEmoji (name) { return basicEmoji[name] || (emojilib[name.replace('-', '_')] && emojilib[name.replace('-', '_')].char) } export default function getSuggestions (term, cb) { chrome.storage.sync.get({ smartSuggestions: true }, function (items) { const filtered = matchSorter(emojiData, term, { keys: ['name', 'short_names'] }) .filter(x => !!getEmoji(x.short_name)) if (items.smartSuggestions) { fetch(`https://emoji.getdango.com/api/emoji?q=${term}`) .then(res => res.json()) .then(({results}) => { const smartEmojis = flush(results.map(({text}) => { return getEmojiDetailsFromEmoji(text) })) const suggestions = uniqBy(smartEmojis.concat(filtered), 'short_name') const presentSuggestions = suggestions.filter(x => !!getEmoji(x.short_name)) cb(presentSuggestions) }) .catch(error => { const filtered = matchSorter(emojiData, term, { keys: ['name', 'short_names'] }) cb(filtered) }) } else { cb(filtered) } }) }
/* * 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. */ 'use strict'; const { DefaultEventHandlerStrategies, DefaultQueryHandlerStrategies, Gateway } = require('fabric-network'); const { ConnectorBase, CaliperUtils, TxStatus, Version, ConfigUtil } = require('@hyperledger/caliper-core'); const FabricConnectorContext = require('../../FabricConnectorContext'); const logger = CaliperUtils.getLogger('connectors/v2/FabricGateway'); const EventStrategies = { msp_all : DefaultEventHandlerStrategies.MSPID_SCOPE_ALLFORTX, msp_any : DefaultEventHandlerStrategies.MSPID_SCOPE_ANYFORTX, network_all : DefaultEventHandlerStrategies.NETWORK_SCOPE_ALLFORTX, network_any : DefaultEventHandlerStrategies.NETWORK_SCOPE_ANYFORTX, }; const QueryStrategies = { msp_single : DefaultQueryHandlerStrategies.MSPID_SCOPE_SINGLE, msp_round_robin : DefaultQueryHandlerStrategies.MSPID_SCOPE_ROUND_ROBIN, }; ////////////////////// // TYPE DEFINITIONS // ////////////////////// /** * @typedef {Object} FabricRequestSettings * * @property {string} channel Required. The name of the channel whose contract should be invoked. * @property {string} contractId Required. The name/ID of the contract whose function * should be invoked. * @property {string} contractFunction Required. The name of the function that should be * invoked in the contract. * @property {string[]} [contractArguments] Optional. The list of {string} arguments that should * be passed to the contract. * @property {Map<string, Buffer>} [transientMap] Optional. The transient map that should be * passed to the contract. * @property {string} [invokerMspId] Optional. The MspId of the invoker. Required if there are more than * 1 organisation defined in the network configuration file * @property {string} invokerIdentity Required. The identity name of the invoker * @property {boolean} [readOnly] Optional. Indicates whether the request is a submit or evaluation. * contract. If an admin is needed, use the organization name prefixed with a # symbol. * @property {string[]} [targetPeers] Optional. An array of endorsing * peer names as the targets of the invoke. When this * parameter is omitted the target list will include the endorsing peers assigned * to the target contract, or if it is also omitted, to the channel. * @property {string[]} [targetOrganizations] Optional. An array of endorsing * organizations as the targets of the invoke. If both targetPeers and targetOrganizations * are specified then targetPeers will take precedence */ ///////////////////////////// // END OF TYPE DEFINITIONS // ///////////////////////////// /** */ class V2FabricGateway extends ConnectorBase { /** * Initializes the Fabric adapter. * @param {connectorConfiguration} connectorConfiguration the Connector Configuration * @param {number} workerIndex the worker index * @param {string} bcType The target SUT type */ constructor(connectorConfiguration, workerIndex, bcType) { super(workerIndex, bcType); this.connectorConfiguration = connectorConfiguration; this.fabricNetworkVersion = new Version(require('fabric-network/package').version); this.contractInstancesByIdentity = new Map(); this.gatewayInstanceByIdentity = new Map(); this.peerNameToPeerObjectCache = new Map(); this.context = undefined; // Timeouts this.configDefaultTimeout = ConfigUtil.get(ConfigUtil.keys.Fabric.Timeout.InvokeOrQuery, 60); // Gateway connector this.configLocalHost = ConfigUtil.get(ConfigUtil.keys.Fabric.Gateway.LocalHost, true); this.configEventStrategy = ConfigUtil.get(ConfigUtil.keys.Fabric.Gateway.EventStrategy, 'msp_all'); this.configQueryStrategy = ConfigUtil.get(ConfigUtil.keys.Fabric.Gateway.QueryStrategy, 'msp_single'); } ////////////////////////// // PUBLIC API FUNCTIONS // ////////////////////////// /** * Prepares the adapter for use by a worker. * * @param {Number} roundIndex The zero-based round index of the test. * @param {Array<string>} args Unused. * @return {Promise<FabricConnectorContext>} Returns the unique context for the fabric connector * @async */ async getContext(roundIndex, args) { if (!this.context) { this.context = new FabricConnectorContext(this.workerIndex); await this._prepareGatewayAndContractMapsForEachIdentity(); await this._buildPeerCache(); // TODO: might be able to do this just once } return this.context; } /** * Initializes the Fabric adapter for use by the Caliper Manager * @async */ async init() { // Seems to be only for operational initialisation but need to implement as the manager // will call it const defaultOrganization = this.connectorConfiguration.getOrganizations()[0]; const tlsInfo = this.connectorConfiguration.isMutualTLS() ? 'mutual' : ((await this.connectorConfiguration.getConnectionProfileDefinitionForOrganization(defaultOrganization)).isTLSEnabled() ? 'server' : 'none'); logger.info(`Fabric SDK version: ${this.fabricNetworkVersion.toString()}; TLS based on ${defaultOrganization}: ${tlsInfo}`); } /** * Installs and initializes the specified contracts. * @async */ async installSmartContract() { logger.warn(`Install smart contract not available with Fabric SDK version: ${this.fabricNetworkVersion.toString()}`); } /** * Send a single request to the backing SUT. * @param {FabricRequestSettings} request The request object. */ async _sendSingleRequest(request) { if (!request.contractId) { throw new Error('No contractId provided in the request'); } if (!request.channel) { const contractDetails = this.connectorConfiguration.getContractDetailsForContractId(request.contractId); if (!contractDetails) { throw new Error(`Could not find details for contract ID ${request.contractId}`); } request.channel = contractDetails.channel; request.contractId = contractDetails.id; } if (!request.contractFunction) { throw new Error('No contractFunction provided in the request'); } if (!request.contractArguments) { request.contractArguments = []; } return await this._submitOrEvaluateTransaction(request, request.readOnly === undefined || !request.readOnly); } /** * Releases the resources of the adapter. * * @async */ async releaseContext() { for (const userName of this.gatewayInstanceByIdentity.keys()) { const gateway = this.gatewayInstanceByIdentity.get(userName); logger.info(`disconnecting gateway for user ${userName}`); gateway.disconnect(); } this.peerNameToPeerObjectCache.clear(); this.context = undefined; } //////////////////////////////// // INTERNAL UTILITY FUNCTIONS // //////////////////////////////// /** * Extract and persist Contracts from Gateway Networks for identities listed within the wallet * @async */ async _prepareGatewayAndContractMapsForEachIdentity() { logger.debug('Entering _prepareGatewayAndContractMapsForEachIdentity'); for (const organization of this.connectorConfiguration.getOrganizations()) { const aliasNames = await this.connectorConfiguration.getAliasNamesForOrganization(organization); const walletWithIdentities = this.connectorConfiguration.getWallet(); for (const aliasName of aliasNames) { const gateway = await this._createGatewayWithIdentity(organization, aliasName, walletWithIdentities); this.gatewayInstanceByIdentity.set(aliasName, gateway); const contractMap = await this._createChannelAndChaincodeIdToContractMap(gateway, aliasName); this.contractInstancesByIdentity.set(aliasName, contractMap); } } logger.debug('Exiting _prepareGatewayAndContractMapsForEachIdentity'); } /** * Create a map with key of channel+chaincode id to fabric-network contract instances * @param {Gateway} gateway the gateway to use * @param {string} aliasName, the aliasName of the identity being used by the gateway * @returns {Promise<Map<Contract>>} A map of all Contract instances for that identity across all the channels and chaincodes * @async */ async _createChannelAndChaincodeIdToContractMap(gateway, aliasName) { logger.debug('Entering _createChannelAndChaincodeIdToContractMap'); logger.info(`Generating contract map for user ${aliasName}`); const contractMap = new Map(); const channels = this.connectorConfiguration.getAllChannelNames(); for (const channel of channels) { let network; try { network = await gateway.getNetwork(channel); } catch(err) { logger.warn(`Couldn't initialize ${channel} for ${aliasName}. ${aliasName} not available for use on this channel. Error: ${err.message}`); continue; } const contracts = this.connectorConfiguration.getContractDefinitionsForChannelName(channel); for (const contract of contracts) { const networkContract = await network.getContract(contract.id); contractMap.set(`${channel}_${contract.id}`, networkContract); } } logger.debug('Exiting _createChannelAndChaincodeIdToContractMap'); return contractMap; } /** * Create a fabric-network gateway instance associated with a specific identity * @param {string} mspId The msp id of the organisation which owns the identity * @param {string} aliasName The alias name that represents the identity to use * @param {*} wallet, the wallet that holds the identity to be used * @returns {Promise<Gateway>} a gateway object for the passed user identity * @async */ async _createGatewayWithIdentity(mspId, aliasName, wallet) { logger.debug(`Entering _createGatewayWithIdentity for alias name ${aliasName}`); const connectionProfileDefinition = await this.connectorConfiguration.getConnectionProfileDefinitionForOrganization(mspId); const opts = { identity: aliasName, wallet, discovery: { asLocalhost: this.configLocalHost, enabled: connectionProfileDefinition.isDynamicConnectionProfile() }, eventHandlerOptions: { endorseTimeout: this.configDefaultTimeout, commitTimeout: this.configDefaultTimeout, strategy: EventStrategies[this.configEventStrategy] }, queryHandlerOptions: { timeout: this.configDefaultTimeout, strategy: QueryStrategies[this.configQueryStrategy] } }; if (this.connectorConfiguration.isMutualTLS()) { opts.clientTlsIdentity = aliasName; } const gateway = new Gateway(); try { logger.info(`Connecting user with identity ${aliasName} to a Network Gateway`); await gateway.connect(connectionProfileDefinition.getConnectionProfile(), opts); logger.info(`Successfully connected user with identity ${aliasName} to a Network Gateway`); } catch (err) { logger.error(`Connecting user with identity ${aliasName} to a Network Gateway failed with error: ${err}`); throw err; } logger.debug('Exiting _createGatewayWithIdentity'); return gateway; } /** */ async _buildPeerCache() { logger.debug('Entering _buildPeerCache'); for (const aliasName of this.gatewayInstanceByIdentity.keys()) { const gateway = this.gatewayInstanceByIdentity.get(aliasName); const channelNames = this.connectorConfiguration.getAllChannelNames(); for (const channelName of channelNames) { const network = await gateway.getNetwork(channelName); const channel = network.getChannel(); // WARNING: This uses an internal API to get the endorsers for (const peerObject of channel.client.getEndorsers()) { this.peerNameToPeerObjectCache.set(peerObject.name, peerObject); } } } logger.debug('Exiting _buildPeerCache'); } /** * Submit or evaluate a transaction * @param {FabricRequestSettings} invokeSettings The settings associated with the transaction submission. * @param {boolean} isSubmit boolean flag to indicate if the transaction is a submit or evaluate * @return {Promise<TxStatus>} The result and stats of the transaction invocation. * @async */ async _submitOrEvaluateTransaction(invokeSettings, isSubmit) { const smartContract = await this._getContractForIdentityOnChannelWithChaincodeID(invokeSettings.invokerMspId, invokeSettings.invokerIdentity, invokeSettings.channel, invokeSettings.contractId); const transaction = smartContract.createTransaction(invokeSettings.contractFunction); // Build the Caliper TxStatus, this is a reduced item when compared to the low level API capabilities // - TxID is not available until after transaction submit/evaluate and must be set at that point const invokeStatus = new TxStatus(); // Add transient data if present // - passed as key value pairing such as {"hello":"world"} if (invokeSettings.transientMap) { const transientData = {}; const keys = Array.from(Object.keys(invokeSettings.transientMap)); keys.forEach((key) => { transientData[key] = Buffer.from(invokeSettings.transientMap[key]); }); transaction.setTransient(transientData); } if (invokeSettings.targetPeers && isSubmit) { if (Array.isArray(invokeSettings.targetPeers) && invokeSettings.targetPeers.length > 0) { const targetPeerObjects = []; for (const name of invokeSettings.targetPeers) { const peer = this.peerNameToPeerObjectCache.get(name); if (peer) { targetPeerObjects.push(peer); } } if (targetPeerObjects.length > 0) { transaction.setEndorsingPeers(targetPeerObjects); } } else { logger.warn(`${invokeSettings.targetPeers} is not a populated array, no peers targeted`); } } else if (invokeSettings.targetOrganizations && isSubmit) { if (Array.isArray(invokeSettings.targetOrganizations) && invokeSettings.targetOrganizations.length > 0) { transaction.setEndorsingOrganizations(...invokeSettings.targetOrganizations); } else { logger.warn(`${invokeSettings.targetOrganizations} is not a populated array, no orgs targeted`); } } try { let result; if (isSubmit) { invokeStatus.Set('request_type', 'transaction'); invokeStatus.Set('time_create', Date.now()); result = await transaction.submit(...invokeSettings.contractArguments); } else { if (invokeSettings.targetPeers || invokeSettings.targetOrganizations) { logger.warn('targetPeers or targetOrganizations options are not valid for query requests'); } invokeStatus.Set('request_type', 'query'); invokeStatus.Set('time_create', Date.now()); result = await transaction.evaluate(...invokeSettings.contractArguments); } invokeStatus.SetResult(result); invokeStatus.SetVerification(true); invokeStatus.SetStatusSuccess(); invokeStatus.SetID(transaction.getTransactionId()); return invokeStatus; } catch (err) { logger.error(`Failed to perform ${isSubmit ? 'submit' : 'query' } transaction [${invokeSettings.contractFunction}] using arguments [${invokeSettings.contractArguments}], with error: ${err.stack ? err.stack : err}`); invokeStatus.SetStatusFail(); invokeStatus.SetVerification(true); invokeStatus.SetResult(''); invokeStatus.SetID(transaction.getTransactionId()); return invokeStatus; } } /** * Get the the specific contract for the identity invoking the request * @param {string} mspId the mspId of the organisation that owns the identity * @param {string} identityName the identity requested to be used by the workload * @param {string} channelName the channel name the contract exists on * @param {string} contractId the name of the contract to return * @returns {Promise<FabricNetworkAPI.Contract>} A contract that may be used to submit or evaluate transactions * @async */ async _getContractForIdentityOnChannelWithChaincodeID(mspId, identityName, channelName, contractId) { logger.debug('Entering _getContractForIdentityOnChannelWithChaincodeID'); const aliasName = this.connectorConfiguration.getAliasNameForOrganizationAndIdentityName(mspId, identityName); const contractSet = this.contractInstancesByIdentity.get(aliasName); // If no contract set found, there is a user configuration/test specification error, so it should terminate if (!contractSet) { throw Error(`No contracts for invokerIdentity ${identityName}${mspId ? ` in ${mspId}` : ''} found. Identity and/or MspId does not exist`); } const contract = contractSet.get(`${channelName}_${contractId}`); // If no contract found, there is a user configuration/test specification error, so it should terminate if (!contract) { throw Error(`Unable to find specified contract ${contractId} on channel ${channelName}!`); } logger.debug('Exiting _getContractForIdentityOnChannelWithChaincodeID'); return contract; } } module.exports = V2FabricGateway;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.wordlist = void 0; exports.wordlist = `ábaco abdomen abeja abierto abogado abono aborto abrazo abrir abuelo abuso acabar academia acceso acción aceite acelga acento aceptar ácido aclarar acné acoger acoso activo acto actriz actuar acudir acuerdo acusar adicto admitir adoptar adorno aduana adulto aéreo afectar afición afinar afirmar ágil agitar agonía agosto agotar agregar agrio agua agudo águila aguja ahogo ahorro aire aislar ajedrez ajeno ajuste alacrán alambre alarma alba álbum alcalde aldea alegre alejar alerta aleta alfiler alga algodón aliado aliento alivio alma almeja almíbar altar alteza altivo alto altura alumno alzar amable amante amapola amargo amasar ámbar ámbito ameno amigo amistad amor amparo amplio ancho anciano ancla andar andén anemia ángulo anillo ánimo anís anotar antena antiguo antojo anual anular anuncio añadir añejo año apagar aparato apetito apio aplicar apodo aporte apoyo aprender aprobar apuesta apuro arado araña arar árbitro árbol arbusto archivo arco arder ardilla arduo área árido aries armonía arnés aroma arpa arpón arreglo arroz arruga arte artista asa asado asalto ascenso asegurar aseo asesor asiento asilo asistir asno asombro áspero astilla astro astuto asumir asunto atajo ataque atar atento ateo ático atleta átomo atraer atroz atún audaz audio auge aula aumento ausente autor aval avance avaro ave avellana avena avestruz avión aviso ayer ayuda ayuno azafrán azar azote azúcar azufre azul baba babor bache bahía baile bajar balanza balcón balde bambú banco banda baño barba barco barniz barro báscula bastón basura batalla batería batir batuta baúl bazar bebé bebida bello besar beso bestia bicho bien bingo blanco bloque blusa boa bobina bobo boca bocina boda bodega boina bola bolero bolsa bomba bondad bonito bono bonsái borde borrar bosque bote botín bóveda bozal bravo brazo brecha breve brillo brinco brisa broca broma bronce brote bruja brusco bruto buceo bucle bueno buey bufanda bufón búho buitre bulto burbuja burla burro buscar butaca buzón caballo cabeza cabina cabra cacao cadáver cadena caer café caída caimán caja cajón cal calamar calcio caldo calidad calle calma calor calvo cama cambio camello camino campo cáncer candil canela canguro canica canto caña cañón caoba caos capaz capitán capote captar capucha cara carbón cárcel careta carga cariño carne carpeta carro carta casa casco casero caspa castor catorce catre caudal causa cazo cebolla ceder cedro celda célebre celoso célula cemento ceniza centro cerca cerdo cereza cero cerrar certeza césped cetro chacal chaleco champú chancla chapa charla chico chiste chivo choque choza chuleta chupar ciclón ciego cielo cien cierto cifra cigarro cima cinco cine cinta ciprés circo ciruela cisne cita ciudad clamor clan claro clase clave cliente clima clínica cobre cocción cochino cocina coco código codo cofre coger cohete cojín cojo cola colcha colegio colgar colina collar colmo columna combate comer comida cómodo compra conde conejo conga conocer consejo contar copa copia corazón corbata corcho cordón corona correr coser cosmos costa cráneo cráter crear crecer creído crema cría crimen cripta crisis cromo crónica croqueta crudo cruz cuadro cuarto cuatro cubo cubrir cuchara cuello cuento cuerda cuesta cueva cuidar culebra culpa culto cumbre cumplir cuna cuneta cuota cupón cúpula curar curioso curso curva cutis dama danza dar dardo dátil deber débil década decir dedo defensa definir dejar delfín delgado delito demora denso dental deporte derecho derrota desayuno deseo desfile desnudo destino desvío detalle detener deuda día diablo diadema diamante diana diario dibujo dictar diente dieta diez difícil digno dilema diluir dinero directo dirigir disco diseño disfraz diva divino doble doce dolor domingo don donar dorado dormir dorso dos dosis dragón droga ducha duda duelo dueño dulce dúo duque durar dureza duro ébano ebrio echar eco ecuador edad edición edificio editor educar efecto eficaz eje ejemplo elefante elegir elemento elevar elipse élite elixir elogio eludir embudo emitir emoción empate empeño empleo empresa enano encargo enchufe encía enemigo enero enfado enfermo engaño enigma enlace enorme enredo ensayo enseñar entero entrar envase envío época equipo erizo escala escena escolar escribir escudo esencia esfera esfuerzo espada espejo espía esposa espuma esquí estar este estilo estufa etapa eterno ética etnia evadir evaluar evento evitar exacto examen exceso excusa exento exigir exilio existir éxito experto explicar exponer extremo fábrica fábula fachada fácil factor faena faja falda fallo falso faltar fama familia famoso faraón farmacia farol farsa fase fatiga fauna favor fax febrero fecha feliz feo feria feroz fértil fervor festín fiable fianza fiar fibra ficción ficha fideo fiebre fiel fiera fiesta figura fijar fijo fila filete filial filtro fin finca fingir finito firma flaco flauta flecha flor flota fluir flujo flúor fobia foca fogata fogón folio folleto fondo forma forro fortuna forzar fosa foto fracaso frágil franja frase fraude freír freno fresa frío frito fruta fuego fuente fuerza fuga fumar función funda furgón furia fusil fútbol futuro gacela gafas gaita gajo gala galería gallo gamba ganar gancho ganga ganso garaje garza gasolina gastar gato gavilán gemelo gemir gen género genio gente geranio gerente germen gesto gigante gimnasio girar giro glaciar globo gloria gol golfo goloso golpe goma gordo gorila gorra gota goteo gozar grada gráfico grano grasa gratis grave grieta grillo gripe gris grito grosor grúa grueso grumo grupo guante guapo guardia guerra guía guiño guion guiso guitarra gusano gustar haber hábil hablar hacer hacha hada hallar hamaca harina haz hazaña hebilla hebra hecho helado helio hembra herir hermano héroe hervir hielo hierro hígado higiene hijo himno historia hocico hogar hoguera hoja hombre hongo honor honra hora hormiga horno hostil hoyo hueco huelga huerta hueso huevo huida huir humano húmedo humilde humo hundir huracán hurto icono ideal idioma ídolo iglesia iglú igual ilegal ilusión imagen imán imitar impar imperio imponer impulso incapaz índice inerte infiel informe ingenio inicio inmenso inmune innato insecto instante interés íntimo intuir inútil invierno ira iris ironía isla islote jabalí jabón jamón jarabe jardín jarra jaula jazmín jefe jeringa jinete jornada joroba joven joya juerga jueves juez jugador jugo juguete juicio junco jungla junio juntar júpiter jurar justo juvenil juzgar kilo koala labio lacio lacra lado ladrón lagarto lágrima laguna laico lamer lámina lámpara lana lancha langosta lanza lápiz largo larva lástima lata látex latir laurel lavar lazo leal lección leche lector leer legión legumbre lejano lengua lento leña león leopardo lesión letal letra leve leyenda libertad libro licor líder lidiar lienzo liga ligero lima límite limón limpio lince lindo línea lingote lino linterna líquido liso lista litera litio litro llaga llama llanto llave llegar llenar llevar llorar llover lluvia lobo loción loco locura lógica logro lombriz lomo lonja lote lucha lucir lugar lujo luna lunes lupa lustro luto luz maceta macho madera madre maduro maestro mafia magia mago maíz maldad maleta malla malo mamá mambo mamut manco mando manejar manga maniquí manjar mano manso manta mañana mapa máquina mar marco marea marfil margen marido mármol marrón martes marzo masa máscara masivo matar materia matiz matriz máximo mayor mazorca mecha medalla medio médula mejilla mejor melena melón memoria menor mensaje mente menú mercado merengue mérito mes mesón meta meter método metro mezcla miedo miel miembro miga mil milagro militar millón mimo mina minero mínimo minuto miope mirar misa miseria misil mismo mitad mito mochila moción moda modelo moho mojar molde moler molino momento momia monarca moneda monja monto moño morada morder moreno morir morro morsa mortal mosca mostrar motivo mover móvil mozo mucho mudar mueble muela muerte muestra mugre mujer mula muleta multa mundo muñeca mural muro músculo museo musgo música muslo nácar nación nadar naipe naranja nariz narrar nasal natal nativo natural náusea naval nave navidad necio néctar negar negocio negro neón nervio neto neutro nevar nevera nicho nido niebla nieto niñez niño nítido nivel nobleza noche nómina noria norma norte nota noticia novato novela novio nube nuca núcleo nudillo nudo nuera nueve nuez nulo número nutria oasis obeso obispo objeto obra obrero observar obtener obvio oca ocaso océano ochenta ocho ocio ocre octavo octubre oculto ocupar ocurrir odiar odio odisea oeste ofensa oferta oficio ofrecer ogro oído oír ojo ola oleada olfato olivo olla olmo olor olvido ombligo onda onza opaco opción ópera opinar oponer optar óptica opuesto oración orador oral órbita orca orden oreja órgano orgía orgullo oriente origen orilla oro orquesta oruga osadía oscuro osezno oso ostra otoño otro oveja óvulo óxido oxígeno oyente ozono pacto padre paella página pago país pájaro palabra palco paleta pálido palma paloma palpar pan panal pánico pantera pañuelo papá papel papilla paquete parar parcela pared parir paro párpado parque párrafo parte pasar paseo pasión paso pasta pata patio patria pausa pauta pavo payaso peatón pecado pecera pecho pedal pedir pegar peine pelar peldaño pelea peligro pellejo pelo peluca pena pensar peñón peón peor pepino pequeño pera percha perder pereza perfil perico perla permiso perro persona pesa pesca pésimo pestaña pétalo petróleo pez pezuña picar pichón pie piedra pierna pieza pijama pilar piloto pimienta pino pintor pinza piña piojo pipa pirata pisar piscina piso pista pitón pizca placa plan plata playa plaza pleito pleno plomo pluma plural pobre poco poder podio poema poesía poeta polen policía pollo polvo pomada pomelo pomo pompa poner porción portal posada poseer posible poste potencia potro pozo prado precoz pregunta premio prensa preso previo primo príncipe prisión privar proa probar proceso producto proeza profesor programa prole promesa pronto propio próximo prueba público puchero pudor pueblo puerta puesto pulga pulir pulmón pulpo pulso puma punto puñal puño pupa pupila puré quedar queja quemar querer queso quieto química quince quitar rábano rabia rabo ración radical raíz rama rampa rancho rango rapaz rápido rapto rasgo raspa rato rayo raza razón reacción realidad rebaño rebote recaer receta rechazo recoger recreo recto recurso red redondo reducir reflejo reforma refrán refugio regalo regir regla regreso rehén reino reír reja relato relevo relieve relleno reloj remar remedio remo rencor rendir renta reparto repetir reposo reptil res rescate resina respeto resto resumen retiro retorno retrato reunir revés revista rey rezar rico riego rienda riesgo rifa rígido rigor rincón riñón río riqueza risa ritmo rito rizo roble roce rociar rodar rodeo rodilla roer rojizo rojo romero romper ron ronco ronda ropa ropero rosa rosca rostro rotar rubí rubor rudo rueda rugir ruido ruina ruleta rulo rumbo rumor ruptura ruta rutina sábado saber sabio sable sacar sagaz sagrado sala saldo salero salir salmón salón salsa salto salud salvar samba sanción sandía sanear sangre sanidad sano santo sapo saque sardina sartén sastre satán sauna saxofón sección seco secreto secta sed seguir seis sello selva semana semilla senda sensor señal señor separar sepia sequía ser serie sermón servir sesenta sesión seta setenta severo sexo sexto sidra siesta siete siglo signo sílaba silbar silencio silla símbolo simio sirena sistema sitio situar sobre socio sodio sol solapa soldado soledad sólido soltar solución sombra sondeo sonido sonoro sonrisa sopa soplar soporte sordo sorpresa sorteo sostén sótano suave subir suceso sudor suegra suelo sueño suerte sufrir sujeto sultán sumar superar suplir suponer supremo sur surco sureño surgir susto sutil tabaco tabique tabla tabú taco tacto tajo talar talco talento talla talón tamaño tambor tango tanque tapa tapete tapia tapón taquilla tarde tarea tarifa tarjeta tarot tarro tarta tatuaje tauro taza tazón teatro techo tecla técnica tejado tejer tejido tela teléfono tema temor templo tenaz tender tener tenis tenso teoría terapia terco término ternura terror tesis tesoro testigo tetera texto tez tibio tiburón tiempo tienda tierra tieso tigre tijera tilde timbre tímido timo tinta tío típico tipo tira tirón titán títere título tiza toalla tobillo tocar tocino todo toga toldo tomar tono tonto topar tope toque tórax torero tormenta torneo toro torpedo torre torso tortuga tos tosco toser tóxico trabajo tractor traer tráfico trago traje tramo trance trato trauma trazar trébol tregua treinta tren trepar tres tribu trigo tripa triste triunfo trofeo trompa tronco tropa trote trozo truco trueno trufa tubería tubo tuerto tumba tumor túnel túnica turbina turismo turno tutor ubicar úlcera umbral unidad unir universo uno untar uña urbano urbe urgente urna usar usuario útil utopía uva vaca vacío vacuna vagar vago vaina vajilla vale válido valle valor válvula vampiro vara variar varón vaso vecino vector vehículo veinte vejez vela velero veloz vena vencer venda veneno vengar venir venta venus ver verano verbo verde vereda verja verso verter vía viaje vibrar vicio víctima vida vídeo vidrio viejo viernes vigor vil villa vinagre vino viñedo violín viral virgo virtud visor víspera vista vitamina viudo vivaz vivero vivir vivo volcán volumen volver voraz votar voto voz vuelo vulgar yacer yate yegua yema yerno yeso yodo yoga yogur zafiro zanja zapato zarza zona zorro zumo zurdo`.split("\n"); //# sourceMappingURL=spanish.js.map
import { ServerStyleSheet } from 'styled-components' import Document, { Html, Head, Main, NextScript } from 'next/document' export default class MyDocument extends Document { static async getInitialProps(ctx) { const sheet = new ServerStyleSheet() const originalRenderPage = ctx.renderPage try { ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />), }) const initialProps = await Document.getInitialProps(ctx) return { ...initialProps, styles: ( <> {initialProps.styles} {sheet.getStyleElement()} </> ), } } finally { sheet.seal() } } render() { return ( <Html> <Head /> <body className="stork-multitheme"> <Main /> <NextScript /> </body> </Html> ) } }
import React from 'react'; import { mount } from 'enzyme'; import Tag from '..'; describe('Tag', () => { beforeAll(() => { jest.useFakeTimers(); }); afterAll(() => { jest.useRealTimers(); }); it('should be closable', () => { const onClose = jest.fn(); const wrapper = mount( <Tag closable onClose={onClose} /> ); expect(wrapper.find('.anticon-close').length).toBe(1); expect(wrapper.find('.ant-tag').length).toBe(1); wrapper.find('.anticon-close').simulate('click'); expect(onClose).toBeCalled(); jest.runAllTimers(); wrapper.update(); expect(wrapper.find('.ant-tag').length).toBe(0); }); it('should not be closed when prevent default', () => { const onClose = (e) => { e.preventDefault(); }; const wrapper = mount( <Tag closable onClose={onClose} /> ); expect(wrapper.find('.anticon-close').length).toBe(1); expect(wrapper.find('.ant-tag').length).toBe(1); wrapper.find('.anticon-close').simulate('click'); jest.runAllTimers(); expect(wrapper.find('.ant-tag').length).toBe(1); }); describe('visibility', () => { it('can be controlled by visible with visible as initial value', () => { const wrapper = mount( <Tag visible /> ); expect(wrapper.render()).toMatchSnapshot(); wrapper.setProps({ visible: false }); jest.runAllTimers(); expect(wrapper.render()).toMatchSnapshot(); wrapper.setProps({ visible: true }); jest.runAllTimers(); expect(wrapper.render()).toMatchSnapshot(); }); it('can be controlled by visible with hidden as initial value', () => { const wrapper = mount( <Tag visible={false} /> ); expect(wrapper.render()).toMatchSnapshot(); wrapper.setProps({ visible: true }); jest.runAllTimers(); expect(wrapper.render()).toMatchSnapshot(); wrapper.setProps({ visible: false }); jest.runAllTimers(); expect(wrapper.render()).toMatchSnapshot(); }); }); });
import express from 'express'; import imageCtrl from '../controllers/image.controller'; import validate from '../middlewares/validation.middleware'; import upload from '../middlewares/upload.middleware'; import imageValidation from '../validations/image.validation'; const router = express.Router(); router.get('/search/:page/:limit', validate(imageValidation.search), imageCtrl.search); router.post('/create', upload('./upload', 'image'), validate(imageValidation.create, {allowUnknown: true}), imageCtrl.create); router.get('/:id', imageCtrl.details); router.post('/:id/like', imageCtrl.like); router.post('/:id/comment', imageCtrl.comment); export default router;
module.exports = { transform: { '^.+\\.(t|j)sx?$': 'ts-jest', }, testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], globals: { 'ts-jest': { // tsConfigFile: 'tsconfig.json', diagnostics: false }, }, };
/** * Kendo UI v2019.3.1023 (http://www.telerik.com/kendo-ui) * Copyright 2019 Progress Software Corporation and/or one of its subsidiaries or affiliates. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ !function(n){"function"==typeof define&&define.amd?define(["kendo.core.min"],n):n()}(function(){!function(n,y){kendo.cultures["mas-TZ"]={name:"mas-TZ",numberFormat:{pattern:["-n"],decimals:2,",":",",".":".",groupSize:[3],percent:{pattern:["-n%","n%"],decimals:2,",":",",".":".",groupSize:[3],symbol:"%"},currency:{name:"Tanzanian Shilling",abbr:"TZS",pattern:["-$n","$n"],decimals:0,",":",",".":".",groupSize:[3],symbol:"TSh"}},calendars:{standard:{days:{names:["Jumapílí","Jumatátu","Jumane","Jumatánɔ","Alaámisi","Jumáa","Jumamósi"],namesAbbr:["Jpi","Jtt","Jnn","Jtn","Alh","Iju","Jmo"],namesShort:["Jpi","Jtt","Jnn","Jtn","Alh","Iju","Jmo"]},months:{names:["Oladalʉ́","Arát","Ɔɛnɨ́ɔɨŋɔk","Olodoyíóríê inkókúâ","Oloilépūnyīē inkókúâ","Kújúɔrɔk","Mórusásin","Ɔlɔ́ɨ́bɔ́rárɛ","Kúshîn","Olgísan","Pʉshʉ́ka","Ntʉ́ŋʉ́s"],namesAbbr:["Dal","Ará","Ɔɛn","Doy","Lép","Rok","Sás","Bɔ́r","Kús","Gís","Shʉ́","Ntʉ́"]},AM:["AM","am","AM"],PM:["PM","pm","PM"],patterns:{d:"dd/MM/yyyy",D:"dddd, d MMMM yyyy",F:"dddd, d MMMM yyyy HH:mm:ss",g:"dd/MM/yyyy HH:mm",G:"dd/MM/yyyy HH:mm:ss",m:"MMMM d",M:"MMMM d",s:"yyyy'-'MM'-'dd'T'HH':'mm':'ss",t:"HH:mm",T:"HH:mm:ss",u:"yyyy'-'MM'-'dd HH':'mm':'ss'Z'",y:"MMMM yyyy",Y:"MMMM yyyy"},"/":"/",":":":",firstDay:1}}}}(this)}); //# sourceMappingURL=kendo.culture.mas-TZ.min.js.map
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = lightFormat; var _index = _interopRequireDefault(require("../toDate/index.js")); var _index2 = _interopRequireDefault(require("../_lib/format/lightFormatters/index.js")); var _index3 = _interopRequireDefault(require("../_lib/getTimezoneOffsetInMilliseconds/index.js")); var _index4 = _interopRequireDefault(require("../isValid/index.js")); var _index5 = _interopRequireDefault(require("../subMilliseconds/index.js")); var _index6 = _interopRequireDefault(require("../_lib/requiredArgs/index.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // This RegExp consists of three parts separated by `|`: // - (\w)\1* matches any sequences of the same letter // - '' matches two quote characters in a row // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), // except a single quote symbol, which ends the sequence. // Two quote characters do not end the sequence. // If there is no matching single quote // then the sequence will continue until the end of the string. // - . matches any single character unmatched by previous parts of the RegExps var formattingTokensRegExp = /(\w)\1*|''|'(''|[^'])+('|$)|./g; var escapedStringRegExp = /^'([^]*?)'?$/; var doubleQuoteRegExp = /''/g; var unescapedLatinCharacterRegExp = /[a-zA-Z]/; /** * @name lightFormat * @category Common Helpers * @summary Format the date. * * @description * Return the formatted date string in the given format. Unlike `format`, * `lightFormat` doesn't use locales and outputs date using the most popular tokens. * * > ⚠️ Please note that the `lightFormat` tokens differ from Moment.js and other libraries. * > See: https://git.io/fxCyr * * The characters wrapped between two single quotes characters (') are escaped. * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. * * Format of the string is based on Unicode Technical Standard #35: * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table * * Accepted patterns: * | Unit | Pattern | Result examples | * |---------------------------------|---------|-----------------------------------| * | AM, PM | a..aaa | AM, PM | * | | aaaa | a.m., p.m. | * | | aaaaa | a, p | * | Calendar year | y | 44, 1, 1900, 2017 | * | | yy | 44, 01, 00, 17 | * | | yyy | 044, 001, 000, 017 | * | | yyyy | 0044, 0001, 1900, 2017 | * | Month (formatting) | M | 1, 2, ..., 12 | * | | MM | 01, 02, ..., 12 | * | Day of month | d | 1, 2, ..., 31 | * | | dd | 01, 02, ..., 31 | * | Hour [1-12] | h | 1, 2, ..., 11, 12 | * | | hh | 01, 02, ..., 11, 12 | * | Hour [0-23] | H | 0, 1, 2, ..., 23 | * | | HH | 00, 01, 02, ..., 23 | * | Minute | m | 0, 1, ..., 59 | * | | mm | 00, 01, ..., 59 | * | Second | s | 0, 1, ..., 59 | * | | ss | 00, 01, ..., 59 | * | Fraction of second | S | 0, 1, ..., 9 | * | | SS | 00, 01, ..., 99 | * | | SSS | 000, 0001, ..., 999 | * | | SSSS | ... | * * @param {Date|Number} date - the original date * @param {String} format - the string of tokens * @returns {String} the formatted date string * @throws {TypeError} 2 arguments required * @throws {RangeError} format string contains an unescaped latin alphabet character * * @example * const result = lightFormat(new Date(2014, 1, 11), 'yyyy-MM-dd') * //=> '2014-02-11' */ function lightFormat(dirtyDate, formatStr) { (0, _index6.default)(2, arguments); var originalDate = (0, _index.default)(dirtyDate); if (!(0, _index4.default)(originalDate)) { throw new RangeError('Invalid time value'); } // Convert the date in system timezone to the same date in UTC+00:00 timezone. // This ensures that when UTC functions will be implemented, locales will be compatible with them. // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376 var timezoneOffset = (0, _index3.default)(originalDate); var utcDate = (0, _index5.default)(originalDate, timezoneOffset); var tokens = formatStr.match(formattingTokensRegExp); // The only case when formattingTokensRegExp doesn't match the string is when it's empty if (!tokens) return ''; var result = tokens.map(function (substring) { // Replace two single quote characters with one single quote character if (substring === "''") { return "'"; } var firstCharacter = substring[0]; if (firstCharacter === "'") { return cleanEscapedString(substring); } var formatter = _index2.default[firstCharacter]; if (formatter) { return formatter(utcDate, substring); } if (firstCharacter.match(unescapedLatinCharacterRegExp)) { throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); } return substring; }).join(''); return result; } function cleanEscapedString(input) { var matches = input.match(escapedStringRegExp); if (!matches) { return input; } return matches[1].replace(doubleQuoteRegExp, "'"); } module.exports = exports.default;
$(document).ready(function() { // Include Underscore.string methods to Underscore namespace _.mixin(_.str.exports()); module("String extensions"); test("Strings: trim", function() { equals(_.trim(123), "123", "Non string"); equals(_(" foo").trim(), "foo"); equals(_("foo ").trim(), "foo"); equals(_(" foo ").trim(), "foo"); equals(_(" foo ").trim(), "foo"); equals(_(" foo ", " ").trim(), "foo", "Manually set whitespace"); equals(_("ffoo").trim("f"), "oo"); equals(_("ooff").trim("f"), "oo"); equals(_("ffooff").trim("f"), "oo"); equals(_("_-foobar-_").trim("_-"), "foobar"); equals(_("http://foo/").trim("/"), "http://foo"); equals(_("c:\\").trim('\\'), "c:"); equals(_(123).trim(), '123'); equals(_(123).trim(3), '12'); }); test("Strings: ltrim", function() { equals(_(" foo").ltrim(), "foo"); equals(_(" foo").ltrim(), "foo"); equals(_("foo ").ltrim(), "foo "); equals(_(" foo ").ltrim(), "foo "); equals(_("ffoo").ltrim("f"), "oo"); equals(_("ooff").ltrim("f"), "ooff"); equals(_("ffooff").ltrim("f"), "ooff"); equals(_("_-foobar-_").ltrim("_-"), "foobar-_"); equals(_(123).ltrim(1), '23'); }); test("Strings: rtrim", function() { equals(_("http://foo/").rtrim("/"), "http://foo", 'clean trailing slash'); equals(_(" foo").rtrim(), " foo"); equals(_("foo ").rtrim(), "foo"); equals(_("foo ").rtrim(), "foo"); equals(_("foo bar ").rtrim(), "foo bar"); equals(_(" foo ").rtrim(), " foo"); equals(_("ffoo").rtrim("f"), "ffoo"); equals(_("ooff").rtrim("f"), "oo"); equals(_("ffooff").rtrim("f"), "ffoo"); equals(_("_-foobar-_").rtrim("_-"), "_-foobar"); equals(_(123).rtrim(3), '12'); }); test("Strings: capitalize", function() { equals(_("fabio").capitalize(), "Fabio", 'First letter is upper case'); equals(_.capitalize("fabio"), "Fabio", 'First letter is upper case'); equals(_.capitalize('FOO'), 'FOO', 'Other letters unchanged'); equals(_(123).capitalize(), "123", "Non string"); }); test("Strings: join", function() { equals(_.join("", "foo", "bar"), "foobar", 'basic join'); equals(_.join("", 1, "foo", 2), "1foo2", 'join numbers and strings'); equals(_.join(" ","foo", "bar"), "foo bar", 'join with spaces'); equals(_.join("1", "2", "2"), "212", 'join number strings'); equals(_.join(1, 2, 2), "212", 'join numbers'); equals(_(" ").join("foo", "bar"), "foo bar", 'join object oriented'); }); test("Strings: reverse", function() { equals(_.str.reverse("foo"), "oof" ); equals(_.str.reverse("foobar"), "raboof" ); equals(_.str.reverse("foo bar"), "rab oof" ); equals(_.str.reverse("saippuakauppias"), "saippuakauppias" ); equals(_.str.reverse(123), "321", "Non string"); equals(_.str.reverse(123.45), "54.321", "Non string"); }); test("Strings: clean", function() { equals(_(" foo bar ").clean(), "foo bar"); equals(_(123).clean(), "123"); }); test("Strings: sprintf", function() { // Should be very tested function already. Thanks to // http://www.diveintojavascript.com/projects/sprintf-for-javascript equals(_.sprintf("Hello %s", "me"), "Hello me", 'basic'); equals(_("Hello %s").sprintf("me"), "Hello me", 'object'); equals(_("hello %s").chain().sprintf("me").capitalize().value(), "Hello me", 'Chaining works'); equals(_.sprintf("%.1f", 1.22222), "1.2", 'round'); equals(_.sprintf("%.1f", 1.17), "1.2", 'round 2'); equals(_.sprintf("%(id)d - %(name)s", {id: 824, name: "Hello World"}), "824 - Hello World", 'Named replacements work'); equals(_.sprintf("%(args[0].id)d - %(args[1].name)s", {args: [{id: 824}, {name: "Hello World"}]}), "824 - Hello World", 'Named replacements with arrays work'); }); test("Strings: vsprintf", function() { equals(_.vsprintf("Hello %s", ["me"]), "Hello me", 'basic'); equals(_("Hello %s").vsprintf(["me"]), "Hello me", 'object'); equals(_("hello %s").chain().vsprintf(["me"]).capitalize().value(), "Hello me", 'Chaining works'); equals(_.vsprintf("%.1f", [1.22222]), "1.2", 'round'); equals(_.vsprintf("%.1f", [1.17]), "1.2", 'round 2'); equals(_.vsprintf("%(id)d - %(name)s", [{id: 824, name: "Hello World"}]), "824 - Hello World", 'Named replacement works'); equals(_.vsprintf("%(args[0].id)d - %(args[1].name)s", [{args: [{id: 824}, {name: "Hello World"}]}]), "824 - Hello World", 'Named replacement with arrays works'); }); test("Strings: startsWith", function() { ok(_("foobar").startsWith("foo"), 'foobar starts with foo'); ok(!_("oobar").startsWith("foo"), 'oobar does not start with foo'); ok(_(12345).startsWith(123), '12345 starts with 123'); ok(!_(2345).startsWith(123), '2345 does not start with 123'); }); test("Strings: endsWith", function() { ok(_("foobar").endsWith("bar"), 'foobar ends with bar'); ok(_.endsWith("foobar", "bar"), 'foobar ends with bar'); ok(_.endsWith("00018-0000062.Plone.sdh264.1a7264e6912a91aa4a81b64dc5517df7b8875994.mp4", "mp4"), 'endsWith .mp4'); ok(!_("fooba").endsWith("bar"), 'fooba does not end with bar'); ok(_.endsWith(12345, 45), '12345 ends with 45'); ok(!_.endsWith(12345, 6), '12345 does not end with 6'); }); test("Strings: include", function() { ok(_.str.include("foobar", "bar"), 'foobar includes bar'); ok(!_.str.include("foobar", "buzz"), 'foobar does not includes buzz'); ok(_.str.include(12345, 34), '12345 includes 34'); ok(!_.str.contains(12345, 6), '12345 does not includes 6'); }); test('String: chop', function(){ ok(_('whitespace').chop(2).length === 5, "output ['wh','it','es','pa','ce']"); ok(_('whitespace').chop(3).length === 4, "output ['whi','tes','pac','e']"); ok(_('whitespace').chop()[0].length === 10, "output ['whitespace']"); ok(_(12345).chop(1).length === 5, "output ['1','2','3','4','5']"); }); test('String: clean', function(){ equals(_.clean(' foo bar '), 'foo bar'); equals(_.clean(1), '1'); }); test('String: count', function(){ equals(_('Hello world').count('l'), 3); equals(_('Hello world').count('Hello'), 1); equals(_('Hello world').count('foo'), 0); equals(_('x.xx....x.x').count('x'), 5); equals(_(12345).count(1), 1); equals(_(11345).count(1), 2); }); test('String: insert', function(){ equals(_('Hello ').insert(6, 'Jessy'), 'Hello Jessy'); equals(_('Hello ').insert(100, 'Jessy'), 'Hello Jessy'); equals(_(12345).insert(6, 'Jessy'), '12345Jessy'); }); test('String: splice', function(){ equals(_('https://edtsech@bitbucket.org/edtsech/underscore.strings').splice(30, 7, 'epeli'), 'https://edtsech@bitbucket.org/epeli/underscore.strings'); equals(_.splice(12345, 1, 2, 321), '132145', 'Non strings'); }); test('String: succ', function(){ equals(_('a').succ(), 'b'); equals(_('A').succ(), 'B'); equals(_('+').succ(), ','); equals(_(1).succ(), '2'); }); test('String: titleize', function(){ equals(_('the titleize string method').titleize(), 'The Titleize String Method'); equals(_('the titleize string method').titleize(), 'The Titleize String Method'); equals(_(123).titleize(), '123'); }); test('String: camelize', function(){ equals(_('the_camelize_string_method').camelize(), 'theCamelizeStringMethod'); equals(_('-the-camelize-string-method').camelize(), 'TheCamelizeStringMethod'); equals(_('the camelize string method').camelize(), 'theCamelizeStringMethod'); equals(_(' the camelize string method').camelize(), 'theCamelizeStringMethod'); equals(_('the camelize string method').camelize(), 'theCamelizeStringMethod'); equals(_(123).camelize(), '123'); }); test('String: underscored', function(){ equals(_('the-underscored-string-method').underscored(), 'the_underscored_string_method'); equals(_('theUnderscoredStringMethod').underscored(), 'the_underscored_string_method'); equals(_('TheUnderscoredStringMethod').underscored(), 'the_underscored_string_method'); equals(_(' the underscored string method').underscored(), 'the_underscored_string_method'); equals(_(123).underscored(), '123'); }); test('String: dasherize', function(){ equals(_('the_dasherize_string_method').dasherize(), 'the-dasherize-string-method'); equals(_('TheDasherizeStringMethod').dasherize(), '-the-dasherize-string-method'); equals(_('thisIsATest').dasherize(), 'this-is-a-test'); equals(_('this Is A Test').dasherize(), 'this-is-a-test'); equals(_('thisIsATest123').dasherize(), 'this-is-a-test123'); equals(_('123thisIsATest').dasherize(), '123this-is-a-test'); equals(_('the dasherize string method').dasherize(), 'the-dasherize-string-method'); equals(_('the dasherize string method ').dasherize(), 'the-dasherize-string-method'); equals(_('téléphone').dasherize(), 'téléphone'); equals(_('foo$bar').dasherize(), 'foo$bar'); equals(_(123).dasherize(), '123'); }); test('String: camelize', function(){ equals(_.camelize('-moz-transform'), 'MozTransform'); equals(_.camelize('webkit-transform'), 'webkitTransform'); equals(_.camelize('under_scored'), 'underScored'); equals(_.camelize(' with spaces'), 'withSpaces'); }); test('String: join', function(){ equals(_.join(1, 2, 3, 4), '21314'); equals(_.join('|', 'foo', 'bar', 'baz'), 'foo|bar|baz'); }); test('String: classify', function(){ equals(_.classify(1), '1'); equals(_('some_class_name').classify(), 'SomeClassName'); }); test('String: humanize', function(){ equals(_('the_humanize_string_method').humanize(), 'The humanize string method'); equals(_('ThehumanizeStringMethod').humanize(), 'Thehumanize string method'); equals(_('the humanize string method').humanize(), 'The humanize string method'); equals(_('the humanize_id string method_id').humanize(), 'The humanize id string method'); equals(_('the humanize string method ').humanize(), 'The humanize string method'); equals(_(' capitalize dash-CamelCase_underscore trim ').humanize(), 'Capitalize dash camel case underscore trim'); equals(_(123).humanize(), '123'); }); test('String: truncate', function(){ equals(_('Hello world').truncate(6, 'read more'), 'Hello read more'); equals(_('Hello world').truncate(5), 'Hello...'); equals(_('Hello').truncate(10), 'Hello'); equals(_(1234567890).truncate(5), '12345...'); }); test('String: prune', function(){ equals(_('Hello, cruel world').prune(6, ' read more'), 'Hello read more'); equals(_('Hello, world').prune(5, 'read a lot more'), 'Hello, world'); equals(_('Hello, world').prune(5), 'Hello...'); equals(_('Hello, world').prune(8), 'Hello...'); equals(_('Hello, cruel world').prune(15), 'Hello, cruel...'); equals(_('Hello world').prune(22), 'Hello world'); equals(_('Привет, жестокий мир').prune(6, ' read more'), 'Привет read more'); equals(_('Привет, мир').prune(6, 'read a lot more'), 'Привет, мир'); equals(_('Привет, мир').prune(6), 'Привет...'); equals(_('Привет, мир').prune(8), 'Привет...'); equals(_('Привет, жестокий мир').prune(16), 'Привет, жестокий...'); equals(_('Привет, мир').prune(22), 'Привет, мир'); equals(_(123).prune(10), '123'); equals(_(123).prune(1,1), '11'); }); test('String: isBlank', function(){ ok(_('').isBlank()); ok(_(' ').isBlank()); ok(_('\n').isBlank()); ok(!_('a').isBlank()); ok(!_('0').isBlank()); ok(!_(0).isBlank()); }); test('String: escapeHTML', function(){ equals(_('<div>Blah & "blah" & \'blah\'</div>').escapeHTML(), '&lt;div&gt;Blah &amp; &quot;blah&quot; &amp; &apos;blah&apos;&lt;/div&gt;'); equals(_('&lt;').escapeHTML(), '&amp;lt;'); equals(_(5).escapeHTML(), '5'); // equals(_(undefined).escapeHTML(), ''); }); test('String: unescapeHTML', function(){ equals(_('&lt;div&gt;Blah &amp; &quot;blah&quot; &amp; &apos;blah&apos;&lt;/div&gt;').unescapeHTML(), '<div>Blah & "blah" & \'blah\'</div>'); equals(_('&amp;lt;').unescapeHTML(), '&lt;'); equals(_('&#39;').unescapeHTML(), "'"); equals(_('&#0039;').unescapeHTML(), "'"); equals(_('&#x4a;').unescapeHTML(), "J"); equals(_('&#x04A;').unescapeHTML(), "J"); equals(_('&#X4A;').unescapeHTML(), "&#X4A;"); equals(_('&_#39;').unescapeHTML(), "&_#39;"); equals(_('&#39_;').unescapeHTML(), "&#39_;"); equals(_('&amp;#38;').unescapeHTML(), "&#38;"); equals(_('&#38;amp;').unescapeHTML(), "&amp;"); equals(_(5).unescapeHTML(), '5'); // equals(_(undefined).unescapeHTML(), ''); }); test('String: words', function() { equals(_("I love you!").words().length, 3); equals(_(" I love you! ").words().length, 3); equals(_("I_love_you!").words('_').length, 3); equals(_("I-love-you!").words(/-/).length, 3); equals(_(123).words().length, 1); }); test('String: chars', function() { equals(_("Hello").chars().length, 5); equals(_(123).chars().length, 3); }); test('String: lines', function() { equals(_("Hello\nWorld").lines().length, 2); equals(_("Hello World").lines().length, 1); equals(_(123).lines().length, 1); }); test('String: pad', function() { equals(_("1").pad(8), ' 1'); equals(_(1).pad(8), ' 1'); equals(_("1").pad(8, '0'), '00000001'); equals(_("1").pad(8, '0', 'left'), '00000001'); equals(_("1").pad(8, '0', 'right'), '10000000'); equals(_("1").pad(8, '0', 'both'), '00001000'); equals(_("foo").pad(8, '0', 'both'), '000foo00'); equals(_("foo").pad(7, '0', 'both'), '00foo00'); equals(_("foo").pad(7, '!@$%dofjrofj', 'both'), '!!foo!!'); }); test('String: lpad', function() { equals(_("1").lpad(8), ' 1'); equals(_(1).lpad(8), ' 1'); equals(_("1").lpad(8, '0'), '00000001'); equals(_("1").lpad(8, '0', 'left'), '00000001'); }); test('String: rpad', function() { equals(_("1").rpad(8), '1 '); equals(_(1).lpad(8), ' 1'); equals(_("1").rpad(8, '0'), '10000000'); equals(_("foo").rpad(8, '0'), 'foo00000'); equals(_("foo").rpad(7, '0'), 'foo0000'); }); test('String: lrpad', function() { equals(_("1").lrpad(8), ' 1 '); equals(_(1).lrpad(8), ' 1 '); equals(_("1").lrpad(8, '0'), '00001000'); equals(_("foo").lrpad(8, '0'), '000foo00'); equals(_("foo").lrpad(7, '0'), '00foo00'); equals(_("foo").lrpad(7, '!@$%dofjrofj'), '!!foo!!'); }); test('String: toNumber', function() { deepEqual(_("not a number").toNumber(), Number.NaN); equals(_(0).toNumber(), 0); equals(_("0").toNumber(), 0); equals(_("0000").toNumber(), 0); equals(_("2.345").toNumber(), 2); equals(_("2.345").toNumber(NaN), 2); equals(_("2.345").toNumber(2), 2.35); equals(_("2.344").toNumber(2), 2.34); equals(_("2").toNumber(2), 2.00); equals(_(2).toNumber(2), 2.00); equals(_(-2).toNumber(), -2); equals(_("-2").toNumber(), -2); }); test('String: strRight', function() { equals(_("This_is_a_test_string").strRight("_"), "is_a_test_string"); equals(_("This_is_a_test_string").strRight("string"), ""); equals(_("This_is_a_test_string").strRight(), "This_is_a_test_string"); equals(_("This_is_a_test_string").strRight(""), "This_is_a_test_string"); equals(_("This_is_a_test_string").strRight("-"), "This_is_a_test_string"); equals(_(12345).strRight(2), "345"); }); test('String: strRightBack', function() { equals(_("This_is_a_test_string").strRightBack("_"), "string"); equals(_("This_is_a_test_string").strRightBack("string"), ""); equals(_("This_is_a_test_string").strRightBack(), "This_is_a_test_string"); equals(_("This_is_a_test_string").strRightBack(""), "This_is_a_test_string"); equals(_("This_is_a_test_string").strRightBack("-"), "This_is_a_test_string"); equals(_(12345).strRightBack(2), "345"); }); test('String: strLeft', function() { equals(_("This_is_a_test_string").strLeft("_"), "This"); equals(_("This_is_a_test_string").strLeft("This"), ""); equals(_("This_is_a_test_string").strLeft(), "This_is_a_test_string"); equals(_("This_is_a_test_string").strLeft(""), "This_is_a_test_string"); equals(_("This_is_a_test_string").strLeft("-"), "This_is_a_test_string"); equals(_(123454321).strLeft(3), "12"); }); test('String: strLeftBack', function() { equals(_("This_is_a_test_string").strLeftBack("_"), "This_is_a_test"); equals(_("This_is_a_test_string").strLeftBack("This"), ""); equals(_("This_is_a_test_string").strLeftBack(), "This_is_a_test_string"); equals(_("This_is_a_test_string").strLeftBack(""), "This_is_a_test_string"); equals(_("This_is_a_test_string").strLeftBack("-"), "This_is_a_test_string"); equals(_(123454321).strLeftBack(3), "123454"); }); test('Strings: stripTags', function() { equals(_('a <a href="#">link</a>').stripTags(), 'a link'); equals(_('a <a href="#">link</a><script>alert("hello world!")</scr'+'ipt>').stripTags(), 'a linkalert("hello world!")'); equals(_('<html><body>hello world</body></html>').stripTags(), 'hello world'); equals(_(123).stripTags(), '123'); }); test('Strings: toSentence', function() { equals(_.toSentence(['jQuery']), 'jQuery', 'array with a single element'); equals(_.toSentence(['jQuery', 'MooTools']), 'jQuery and MooTools', 'array with two elements'); equals(_.toSentence(['jQuery', 'MooTools', 'Prototype']), 'jQuery, MooTools and Prototype', 'array with three elements'); equals(_.toSentence(['jQuery', 'MooTools', 'Prototype', 'YUI']), 'jQuery, MooTools, Prototype and YUI', 'array with multiple elements'); equals(_.toSentence(['jQuery', 'MooTools', 'Prototype'], ',', ' or '), 'jQuery,MooTools or Prototype', 'handles custom separators'); }); test('Strings: slugify', function() { equals(_("Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/").slugify(), "jack-jill-like-numbers-123-and-4-and-silly-characters"); equals(_("Un éléphant à l'orée du bois").slugify(), "un-elephant-a-loree-du-bois"); equals(_("I know latin characters: á í ó ú ç ã õ ñ ü").slugify(), "i-know-latin-characters-a-i-o-u-c-a-o-n-u"); equals(_("I am a word too, even though I am but a single letter: i!").slugify(), "i-am-a-word-too-even-though-i-am-but-a-single-letter-i"); }); test('Strings: repeat', function() { equals(_.repeat('foo'), ''); equals(_.repeat('foo', 3), 'foofoofoo'); equals(_.repeat('foo', '3'), 'foofoofoo'); equals(_.repeat(123, 2), '123123'); equals(_.repeat(1234, 2, '*'), '1234*1234'); equals(_.repeat(1234, 2, 5), '123451234'); }); });
import {Container, Shape, Stage, Text, Ticker} from "@createjs/easeljs"; import {GraphicConfig} from "./GraphicConfig"; import {StrColors} from "./StrConsts"; /*+ * カードのレンダリング用ラス */ export class Card extends Container { /** * @param isOpen {boolean} 表側表示か * @param inDeck {boolean} デッキの中にいるか */ constructor(isOpen = false, inDeck = false) { super(); this.isOpen = isOpen; this.inDeck = inDeck; //外枠 const frame = new Shape(); frame.graphics .beginStroke(StrColors.WHITE) .setStrokeStyle(GraphicConfig.CardFrameThickness) .drawRect(0, 0, GraphicConfig.CardWidth, GraphicConfig.CardHeight); this.frame = frame; this.addChild(frame); if (isOpen) { this.Opend(); } else { this.Reversed(); } } /** * カードを表側表示にする */ Opend() { //TODO 未実装 } /** * カードを裏側表示にする */ Reversed() { //TODO 表側を消す処理 const back = new Shape(); back.graphics .beginFill('Black') .setStrokeStyle(GraphicConfig.CardFrameThickness) .drawRect(GraphicConfig.CardFrameThickness, GraphicConfig.CardFrameThickness, GraphicConfig.CardWidth - (GraphicConfig.CardFrameThickness * 2), GraphicConfig.CardHeight - (GraphicConfig.CardFrameThickness * 2)); this.back = back; this.addChild(back); } /** * 非表示にする ドローアニメ用 */ _Hidden() { this.frame.graphics.clear(); this.back.graphics.clear(); } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. 'use strict'; function main(name) { // [START dialogflow_v3beta1_generated_Agents_GetAgentValidationResult_async] /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The agent name. * Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent * ID>/validationResult`. */ // const name = 'abc123' /** * If not specified, the agent's default language is used. */ // const languageCode = 'abc123' // Imports the Cx library const {AgentsClient} = require('@google-cloud/dialogflow-cx').v3beta1; // Instantiates a client const cxClient = new AgentsClient(); async function callGetAgentValidationResult() { // Construct request const request = { name, }; // Run request const response = await cxClient.getAgentValidationResult(request); console.log(response); } callGetAgentValidationResult(); // [END dialogflow_v3beta1_generated_Agents_GetAgentValidationResult_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
describe('Check file exists', () => { const connectionString = 'connectionString' const container = 'container' const file = 'file' let mockExists const mockBlockBlobClient = jest.fn(() => { return { exists: mockExists } }) jest.mock('@azure/storage-blob', () => { return { BlockBlobClient: mockBlockBlobClient } }) let checkFileExists beforeEach(() => { jest.clearAllMocks() checkFileExists = require('../../../../server/lib/data/check-file-exists') }) test('returns true when file exists', async () => { mockExists = jest.fn().mockResolvedValue(true) mockBlockBlobClient.prototype.exists = mockExists const fileExists = await checkFileExists(connectionString, container, file) expect(mockBlockBlobClient).toHaveBeenCalledTimes(1) expect(mockBlockBlobClient).toHaveBeenCalledWith(connectionString, container, file) expect(mockExists).toHaveBeenCalledTimes(1) expect(fileExists).toEqual(true) }) test('returns false when file does not exist', async () => { mockExists = jest.fn().mockResolvedValue(false) mockBlockBlobClient.prototype.exists = mockExists const fileExists = await checkFileExists(connectionString, container, file) expect(mockBlockBlobClient).toHaveBeenCalledTimes(1) expect(mockBlockBlobClient).toHaveBeenCalledWith(connectionString, container, file) expect(mockExists).toHaveBeenCalledTimes(1) expect(fileExists).toEqual(false) }) })
/* * kony-sdk-ide Version 8.3.10 */ /** * Kony namespace * @namespace kony */ if (typeof(kony) === "undefined") { kony = {}; } /** * Constructor for creating the kony client instance. * @class * @classdesc kony Class * @memberof kony */ kony.sdk = function() { var currentObj = this; this.mainRef = {}; var clientParams = {}; this.tokens = {}; this.currentClaimToken = null; this.globalRequestParams = { "headers": {}, "queryparams": {}, "bodyparams": {} }; var userId = ""; var sessionId = ""; this.reportingheaders_allowed = false; if (kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_IDE && typeof(kony.setUserID) === 'function') { var userIDflagGet = kony.ds.read("userIDFromLicenseFlag"); if (kony.sdk.isNullOrUndefined(userIDflagGet)) { var userIDflagSet = []; userIDflagSet.push("false"); kony.ds.save(userIDflagSet, "userIDFromLicenseFlag"); } } if (kony.internal && kony.internal.sdk && kony.internal.sdk.Services) { this.internalSdkObject = new kony.internal.sdk.Services(); } this.getUserId = function() { return userId; }; this.setCurrentUserId = function(newUserID) { userId = newUserID; }; this.getSessionId = function() { return sessionId; }; this.setSessionId = function(newSessionId) { sessionId = newSessionId; }; this.setClientParams = function(clientParamsMap) { clientParams = clientParamsMap; }; this.getClientParams = function() { return clientParams; }; this.globalRequestParamType = { headers: "headers", queryParams: "queryparams", bodyParams: "bodyparams" }; this.getGlobalRequestParams = function(paramType) { kony.sdk.logsdk.trace("Entering getGlobalRequestParams"); if (kony.sdk.isNullOrUndefined(paramType)) { return currentObj.globalRequestParams; } else if (paramType === currentObj.globalRequestParamType.headers) { return currentObj.globalRequestParams.headers; } else if (paramType === currentObj.globalRequestParamType.queryParams) { return currentObj.globalRequestParams.queryparams; } else if (paramType === currentObj.globalRequestParamType.bodyParams) { return currentObj.globalRequestParams.bodyparams; } }; this.setGlobalRequestParam = function(paramName, paramValue, paramType) { kony.sdk.logsdk.trace("Entering setGlobalRequestParam"); if (typeof(paramName) === 'string' && typeof(paramValue) === 'string' && typeof(paramType) === 'string') { if (paramType === currentObj.globalRequestParamType.headers) { currentObj.globalRequestParams.headers[paramName] = paramValue; } else if (paramType === currentObj.globalRequestParamType.queryParams) { currentObj.globalRequestParams.queryparams[paramName] = paramValue; } else if (paramType === currentObj.globalRequestParamType.bodyParams) { currentObj.globalRequestParams.bodyparams[paramName] = paramValue; } } }; this.removeGlobalRequestParam = function(paramName, paramType) { kony.sdk.logsdk.trace("Entering removeGlobalRequestParam"); if (typeof(paramName) === 'string' && typeof(paramType) === 'string') { if (paramType.toLowerCase() === currentObj.globalRequestParamType.headers && !kony.sdk.isNullOrUndefined(currentObj.globalRequestParams.headers[paramName])) { delete currentObj.globalRequestParams.headers[paramName]; } else if (paramType.toLowerCase() === currentObj.globalRequestParamType.queryParams && !kony.sdk.isNullOrUndefined(currentObj.globalRequestParams.queryparams[paramName])) { delete currentObj.globalRequestParams.queryparams[paramName]; } else if (paramType.toLowerCase() === currentObj.globalRequestParamType.bodyParams && !kony.sdk.isNullOrUndefined(currentObj.globalRequestParams.bodyparams[paramName])) { delete currentObj.globalRequestParams.bodyparams[paramName]; } } }; this.resetGlobalRequestParams = function() { kony.sdk.logsdk.trace("Entering resetGlobalRequestParams"); currentObj.globalRequestParams = { "headers": {}, "queryparams": {}, "bodyparams": {} }; }; this.appendGlobalHeaders = function(headers) { kony.sdk.logsdk.trace("Entering appendGlobalHeaders"); var globalHeaders = currentObj.getGlobalRequestParams(currentObj.globalRequestParamType.headers); if (!kony.sdk.isNullOrUndefined(globalHeaders)) { if (kony.sdk.isNullOrUndefined(headers)) { headers = {}; } for (var obj in globalHeaders) { if (kony.sdk.isNullOrUndefined(headers[obj])) { headers[obj] = globalHeaders[obj]; } } } }; this.appendGlobalBodyParams = function(params) { kony.sdk.logsdk.trace("Entering appendGlobalBodyParams"); var globalBodyParams = currentObj.getGlobalRequestParams(currentObj.globalRequestParamType.bodyParams); if (!kony.sdk.isNullOrUndefined(globalBodyParams)) { if (kony.sdk.isNullOrUndefined(params)) { params = {}; } for (var obj in globalBodyParams) { if (kony.sdk.isNullOrUndefined(params[obj])) { params[obj] = globalBodyParams[obj]; } } } }; this.appendGlobalQueryParams = function(url) { kony.sdk.logsdk.trace("Entering appendGlobalQueryParams"); var globalQueryParams = currentObj.getGlobalRequestParams(currentObj.globalRequestParamType.queryParams); if (!kony.sdk.isNullOrUndefined(globalQueryParams) && Object.keys(globalQueryParams).length !== 0) { if (url.indexOf("?") < 0) { url = url + "?" + kony.sdk.util.objectToQueryParams(globalQueryParams); } else { url = url + "&" + kony.sdk.util.objectToQueryParams(globalQueryParams); } } return url; }; this.appendGlobalParams = function(url, headers, params) { kony.sdk.logsdk.trace("Entering appendGlobalParams"); currentObj.appendGlobalHeaders(headers); currentObj.appendGlobalBodyParams(params); return currentObj.appendGlobalQueryParams(url); }; }; kony.mbaas = kony.sdk; kony.sdk.isDebugEnabled = true; kony.sdk.isInitialized = false; kony.sdk.currentInstance = null; kony.sdk.isLicenseUrlAvailable = true; kony.sdk.constants = kony.sdk.constants || {}; kony.sdk.version = "8.3.10"; kony.sdk.logsdk = new konySdkLogger(); kony.sdk.syncService = null; kony.sdk.dataStore = kony.sdk.dataStore || new konyDataStore(); kony.sdk.skipAnonymousCall = false; kony.sdk.getDefaultInstance = function() { return kony.sdk.currentInstance; }; // This is to be deprecated with getDefaultInstance kony.sdk.getCurrentInstance = function() { return kony.sdk.currentInstance; }; // This is to be set by client to skip anonymous login calls. kony.sdk.skipAnonymousLoginCall = function(state) { // If enabled then client can only access public integration services. // If disabled then client can access protected integration services. // To access private client needs to get authenticated by an identity service. kony.sdk.skipAnonymousCall = state; }; kony.sdk.claimsRefresh = function(callback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.claimsRefresh"); var konyRef = kony.sdk.getCurrentInstance(); var networkProvider = new konyNetworkProvider(); var loginWithAnonymousProvider = function(successCallback, failureCallback) { var identityObject = konyRef.getIdentityService("$anonymousProvider"); identityObject.login(null, function(res) { successCallback(); }, function(res) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getAuthErrObj(res)); }); }; if (konyRef.currentClaimToken === null) { kony.sdk.logsdk.warn("claims Token is Unavialable"); if (konyRef.isAnonymousProvider) { loginWithAnonymousProvider(callback, failureCallback); } else { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getNullClaimsTokenErrObj()); } } else if (konyRef.claimTokenExpiry && new Date().getTime() > konyRef.claimTokenExpiry) { if (konyRef.isAnonymousProvider) { loginWithAnonymousProvider(callback, failureCallback); } else { kony.sdk.fetchClaimsTokenFromServer(false, callback, failureCallback); } } else { callback(); } }; kony.sdk.claimsAndProviderTokenRefresh = function(callback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.claimsAndProviderTokenRefresh"); kony.sdk.fetchClaimsTokenFromServer(true, callback, failureCallback); }; /** * Checks for the etag in the response data. Gets the service doc & caches it if etag is updated. * @param data{JSON} response data from claimsRefresh or login. * @param callback{function} callback to be invoked. */ function getLatestServiceDocIfAvailable(data, callback) { //Disabling this for phonegap and plain-js as there is not concept of auto-init there if (kony.sdk.getSdkType() !== kony.sdk.constants.SDK_TYPE_IDE) { kony.sdk.verifyAndCallClosure(callback); return; } var currentETag = kony.sdk.dataStore.getItem("etagID"); var serverETag = data.service_doc_etag; if (!kony.sdk.isNullOrUndefined(serverETag) && (kony.sdk.isNullOrUndefined(currentETag) || currentETag != serverETag)) { kony.sdk.logsdk.info("Service doc update found."); var networkProvider = new konyNetworkProvider(); var _serviceUrl = stripTrailingCharacter(konyRef.rec.url, "/") + "/appconfig"; var headers = {}; headers[kony.sdk.constants.APP_KEY_HEADER] = konyRef.mainRef.appKey; headers[kony.sdk.constants.APP_SECRET_HEADER] = konyRef.mainRef.appSecret; headers["X-HTTP-Method-Override"] = "GET"; populateHeaderWithFabricAppVersion(headers); networkProvider.post(_serviceUrl, null, headers, function(successResponse) { kony.sdk.dataStore.setItem("etagID", serverETag); kony.sdk.logsdk.debug("Update done. Current version = " + currentETag + " Updated to " + serverETag); kony.sdk.dataStore.setItem(appConfig.appId + "_mobileFabricServiceDoc", JSON.stringify(successResponse)); kony.sdk.verifyAndCallClosure(callback); }, function(failureResponse) { kony.sdk.logsdk.error("Refresh of serviceDoc failed:" + JSON.stringify(failureResponse)); kony.sdk.verifyAndCallClosure(callback); }); } else { kony.sdk.verifyAndCallClosure(callback); } } kony.sdk.fetchClaimsTokenFromServer = function(isBackendTokenRefreshRequired, callback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.fetchClaimsTokenFromServer"); var konyRef = kony.sdk.getCurrentInstance(); var networkProvider = new konyNetworkProvider(); kony.sdk.logsdk.debug("claims token has expired. fetching new token and isBackendTokenRefreshRequired :", isBackendTokenRefreshRequired); var _serviceUrl = stripTrailingCharacter(konyRef.rec.url, "/"); var _url = _serviceUrl + "/claims"; if (isBackendTokenRefreshRequired) { _url = _url + "?refresh=true"; } kony.sdk.logsdk.debug("service url is " + _url); if (konyRef.currentRefreshToken === null) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getNullRefreshTokenErrObj()); } else { var headers = {}; headers[kony.sdk.constants.AUTHORIZATION_HEADER] = konyRef.currentRefreshToken; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; networkProvider.post(_url, {}, headers, function(tokens) { kony.sdk.logsdk.trace("refresh success..acquiring new tokens"); var response = kony.sdk.processClaimsSuccessResponse(tokens, konyRef, false); function serviceDocCallback() { kony.sdk.verifyAndCallClosure(callback, response); } getLatestServiceDocIfAvailable(tokens, serviceDocCallback); }, function(data) { kony.sdk.logsdk.error("failed to acquire refresh token", data); kony.sdk.processClaimsErrorResponse(data, konyRef, true, failureCallback); }); } }; kony.sdk.processClaimsSuccessResponse = function(data, konyRef, isAsync, callBack) { kony.sdk.logsdk.trace("Entering kony.sdk.processClaimsSuccessResponse"); data = kony.sdk.formatSuccessResponse(data); konyRef.currentClaimToken = data.claims_token.value; konyRef.claimTokenExpiry = data.claims_token.exp; konyRef.currentRefreshToken = data.refresh_token; kony.logger.setClaimsToken(); //if offline login enabled then updating the claimstoken in the store if (kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_IDE && kony.sdk.getAType() === kony.sdk.constants.SDK_ATYPE_NATIVE && kony.sdk.getPlatformName() !== kony.sdk.constants.PLATFORM_WINDOWS) { if (kony.sdk.offline.isOfflineEnabled && kony.sdk.offline.isOfflineEnabled == true) { kony.sdk.offline.updateAuthToken(data); } if (kony.sdk.offline.persistToken || kony.sdk.util.isPersistentLoginResponseEnabled()) { kony.sdk.offline.updatePersistedToken(data); } } if (!isAsync) { return { "message": "success" }; } else if (callBack) { callBack(); } }; kony.sdk.processClaimsErrorResponse = function(data, konyRef, isAsync, callBack) { kony.sdk.logsdk.trace("Entering kony.sdk.processClaimsErrorResponse"); /*reset the claims token*/ konyRef.currentClaimToken = null; konyRef.claimTokenExpiry = null; konyRef.currentRefreshToken = null; //setting the anonymous provider as true to access the public protected urls without any issue konyRef.isAnonymousProvider = true; if (!isAsync) { return kony.sdk.error.getAuthErrObj(data); } else if (callBack) { kony.sdk.verifyAndCallClosure(callBack, kony.sdk.error.getAuthErrObj(data)); } }; /** * Init success callback method. * @callback initSuccessCallback * @param {json} mainRef - Application Configuration */ /** * Init failure callback method. * @callback initFailureCallback */ /** * Initialization method for the kony SDK. * This method will fetch the app configuration from the kony server and stores in memory. * This method has to be invoked before invoking any other SDK methods. * @param {string} appKey - Appkey of the kony application * @param {string} appSecret - App Secret of the kony application * @param {string} serviceUrl - URL of the kony Server * @param {initSuccessCallback} successCallback - Callback method on success * @param {initFailureCallback} failureCallback - Callback method on failure */ kony.sdk.prototype.init = function(appKey, appSecret, serviceUrl, successCallback, failureCallback, initOptions) { // removing app metadata with key for the latest app metadata kony.sdk.logsdk.trace("Entering kony.sdk.prototype.init"); kony.sdk.deleteMetadatafromDs(); if (!(appKey && appSecret && serviceUrl)) { kony.sdk.logsdk.error("### init:: Invalid credentials passed"); kony.sdk.verifyAndCallClosure(failureCallback, "Invalid initialization parameters passed. Please check appKey, appSecret and ServiceUrl parameters"); return; } var networkProvider = new konyNetworkProvider(); serviceUrl = serviceUrl.trim(); this.mainRef.serviceUrl = serviceUrl; this.mainRef.appSecret = appSecret; konyRef = this; KNYMobileFabric = this; var options = {}; options["ignoreintegrity"] = true; setIntegrityParams(); kony.sdk.logsdk.trace("### init:: calling GET on appConfig to retrieve servicedoc"); var headers = {}; headers[kony.sdk.constants.APP_KEY_HEADER] = appKey; headers[kony.sdk.constants.APP_SECRET_HEADER] = appSecret; headers["X-HTTP-Method-Override"] = "GET"; //Resetting the value. kony.sdk.setFabricAppVersion(null); if (!kony.sdk.isNullOrUndefined(initOptions) && initOptions["MFAppVersion"]) { kony.sdk.setFabricAppVersion(initOptions["MFAppVersion"]); } populateHeaderWithFabricAppVersion(headers); networkProvider.post(serviceUrl, null, headers, function(data) { data = kony.sdk.formatSuccessResponse(data); kony.sdk.logsdk.info("### init::_doInit fetched servicedoc successfuly"); kony.sdk.logsdk.debug("### init:: retrieved data from service doc", data); konyRef.mainRef.config = data; konyRef.servicedoc = data; konyRef.mainRef.appId = data.appId; var processServiceDocResult = konyRef.initWithServiceDoc(appKey, appSecret, data); if (processServiceDocResult === true) { kony.sdk.logsdk.info("### init::_doInit processing service document successful"); kony.sdk.logsdk.debug("### init::_doInit saving done. Calling success callback", data); kony.sdk.initiateSession(konyRef); if (typeof(KNYMetricsService) !== "undefined" && kony.sdk.currentInstance.getMetricsService) { KNYMetricsService = kony.sdk.currentInstance.getMetricsService(); if (KNYMetricsService && typeof(appConfig) !== "undefined" && kony.sdk.util.isJsonObject(appConfig) && appConfig.hasOwnProperty("eventTypes") && kony.sdk.isArray(appConfig.eventTypes) && appConfig.eventTypes.length !== 0) { KNYMetricsService.setEventTracking(appConfig.eventTypes); } } if (kony.sdk.skipAnonymousCall) { kony.sdk.logsdk.info("### init::skipping anonymous login call"); // Enabling this flag to connect to any protected integration service. konyRef.isAnonymousProvider = true; kony.sdk.verifyAndCallClosure(successCallback, konyRef.mainRef); } else { var identityObject = kony.sdk.getCurrentInstance().getIdentityService("$anonymousProvider"); identityObject.login(null, function(res) { kony.sdk.verifyAndCallClosure(successCallback, konyRef.mainRef); }, function(res) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getAuthErrObj(res)); }); } } else { kony.sdk.logsdk.error("### init::_doInit processing servicedoc failed. Calling failure callback"); kony.sdk.verifyAndCallClosure(failureCallback, JSON.stringify(processServiceDocResult)); } }, function(data) { kony.sdk.logsdk.error("### init::_doInit fetching service document from Server failed" + data); kony.sdk.logsdk.info("### init::_doInit calling failure callback"); kony.sdk.isInitialized = false; kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getAuthErrObj(data)); }, null, options); }; kony.sdk.prototype.initWithServiceDoc = function(appKey, appSecret, serviceDoc) { kony.sdk.logsdk.trace("Entering kony.sdk.prototype.initWithServiceDoc"); konyRef = this; KNYMobileFabric = this; kony.sdk.currentInstance = this; var unprocessedServiceDoc = kony.sdk.cloneObject(serviceDoc); if (kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_IDE) { if (!kony.sdk.isNullOrUndefined(serviceDoc)) { if (serviceDoc.hasOwnProperty("integrity_check_required") && serviceDoc.integrity_check_required === true) { //MF server >=8.2 konyRef.mainRef.integrityKey = true; } else { //MF server < 8.2 and integrity is disabled konyRef.mainRef.integrityKey = false; } } } else { //platform phonegap and plain-js doesn't support http integrity konyRef.mainRef.integrityKey = false; } if (serviceDoc instanceof kony.sdk.serviceDoc) { var servConfig = serviceDoc.toJSON(); processServiceDocMap(servConfig); } else { return processServiceDocMap(serviceDoc); } function processServiceDocMap(servConfig) { for (var item in servConfig) { if (kony.sdk.isNullOrUndefined(servConfig[item]) || kony.sdk.isEmptyObject(servConfig[item])) { delete servConfig[item]; } } kony.sdk.logsdk.debug("### init::_doInit::_processServiceDoc", servConfig); try { konyRef.mainRef.appKey = appKey; konyRef.mainRef.appSecret = appSecret; konyRef.mainRef.appId = servConfig.appId; konyRef.mainRef.config = serviceDoc; /* if (!servConfig.baseId) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, "invalid baseId " + servConfig.baseId); } */ konyRef.mainRef.baseId = servConfig.baseId; /* if (!servConfig.name) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, "invalid name " + servConfig.name); } */ konyRef.mainRef.name = servConfig.name; if (servConfig.login) { konyRef.login = servConfig.login; } else { konyRef.login = []; } var url = servConfig.selflink; if (url) { var lastPos = url.indexOf("/appconfig"); if (lastPos != -1) { url = url.slice(0, lastPos); } else { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, "invalid self link"); } var anonymousLoginProvider = {}; anonymousLoginProvider.type = "anonymous"; anonymousLoginProvider.url = url; anonymousLoginProvider.prov = "$anonymousProvider"; konyRef.login.push(anonymousLoginProvider); } if (typeof(servConfig.integsvc) !== 'undefined') { kony.sdk.logsdk.info("### init::_doInit::_processServiceDoc parsing Integration services"); konyRef.integsvc = servConfig.integsvc; kony.sdk.logsdk.debug("### init::_doInit::konyRef integration Services", konyRef.integsvc); } if (typeof(servConfig.services_meta) === 'object') { kony.sdk.logsdk.info("### init::_doInit::_processServiceDoc parsing Object services"); kony.sdk.util.populateIndividualServiceLists(servConfig, konyRef); } if (typeof(servConfig.messagingsvc) !== 'undefined') { kony.sdk.logsdk.info("### init::_doInit::_processServiceDoc parsing Messaging services"); konyRef.messagingsvc = servConfig.messagingsvc; } if (typeof(servConfig.logicsvc) !== 'undefined') { kony.sdk.logsdk.info("### init::_doInit::_processServiceDoc parsing Logic services"); konyRef.logicsvc = servConfig.logicsvc; } if (typeof(servConfig.sync) !== 'undefined') { konyRef.sync = servConfig.sync; } if (servConfig.identity_features && servConfig.identity_features.reporting_params_header_allowed) { kony.sdk.logsdk.info("### init::_doInit::_processServiceDoc parsing Identity features"); konyRef.reportingheaders_allowed = servConfig.identity_features.reporting_params_header_allowed; } if (kony.sdk.isLicenseUrlAvailable) { if (servConfig.reportingsvc && servConfig.reportingsvc.custom && servConfig.reportingsvc.session) { konyRef.customReportingURL = servConfig.reportingsvc.custom; konyRef.sessionReportingURL = servConfig.reportingsvc.session; if (konyRef.sessionReportingURL && kony.logger.isNativeLoggerAvailable()) { var lastIndex = konyRef.sessionReportingURL.lastIndexOf("/"); if (lastIndex !== -1) { var networkUrl = konyRef.sessionReportingURL.substring(0, lastIndex + 1) + kony.logger.networkPersistorUrlEndpoint; var networkPersistor = kony.logger.createNetworkPersistor(); networkPersistor.URL = networkUrl; kony.logger.setPersistorConfig(networkPersistor); } } } else { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, "invalid url for reporting service"); } } if (konyRef.internalSdkObject) { konyRef.internalSdkObject.initWithServiceDoc(appKey, appSecret, servConfig); if (konyRef.internalSdkObject.setClientParams) { if (appConfig) { konyRef.internalSdkObject.setClientParams({ "aid": appConfig.appId, "aname": appConfig.appName }); } else { konyRef.internalSdkObject.setClientParams(konyRef.getClientParams()); } } kony.sdk.logsdk.info("### init::internal sdk object initialized"); } kony.sdk.logsdk.info("### init::_doInit::_processServiceDoc parsing service document done"); kony.sdk.isInitialized = true; if (kony.sdk.metric && kony.os.deviceInfo().name === kony.sdk.constants.PLATFORM_SPA) { kony.sdk.metric.flushEvents(); } if (!kony.sdk.isNullOrUndefined(servConfig.reportingsvc)) { kony.sdk.saveMetadatainDs(appKey, appSecret, unprocessedServiceDoc); kony.sdk.setLicenseCall(appKey, appSecret, unprocessedServiceDoc); } var sdkType = kony.sdk.getSdkType(); var type = kony.sdk.getAType(); var platformName = kony.sdk.getPlatformName(); if (sdkType == kony.sdk.constants.SDK_TYPE_IDE && ((type === kony.sdk.constants.SDK_ATYPE_NATIVE && platformName !== kony.sdk.constants.PLATFORM_WINDOWS) || type === kony.sdk.constants.SDK_ATYPE_SPA)) { if ((!kony.sdk.isNullOrUndefined(konyRef.offlineObjectsvc)) && !(kony.sdk.isEmptyObject(konyRef.offlineObjectsvc))) { konyRef.OfflineObjects = new kony.sdk.OfflineObjects(konyRef.offlineObjectsvc); } } if (kony.license) { if (kony.licensevar && kony.licensevar.changeHandlers && kony.licensevar.changeHandlers.length == 0 && kony.license.registerChangeListener) { kony.license.registerChangeListener(konyRef.sessionChangeHandler); konyRef.overrideUserIdFlag = true; } } if (konyRef.mainRef.integrityKey === true) { setIntegrityParams(); try { if (!(kony.sdk.getPlatformName() === kony.sdk.constants.PLATFORM_WINDOWS || kony.sdk.getAType() === kony.sdk.constants.SDK_ATYPE_SPA || kony.sdk.getAType() === "watch")) { //invoke NFI only for android and ios. kony.sdk.httpIntegrity.setIntegrityCheck(konyRef.mainRef.integrityParams); } } catch (e) { kony.sdk.logsdk.warn("Invalid Integrity properties received"); throw new Exception(kony.sdk.errorConstants.INTEGRITY_FAILURE, "Invalid Integrity properties"); } } else { resetIntegrityParams(); if (!(kony.sdk.getPlatformName() === kony.sdk.constants.PLATFORM_WINDOWS || kony.sdk.getAType() === kony.sdk.constants.SDK_ATYPE_SPA || kony.sdk.getAType() === "watch")) { //invoke NFI only for android and ios kony.sdk.httpIntegrity.removeIntegrityCheck(); } } return true; } catch (err) { kony.sdk.logsdk.error("### init::_doInit::_processServiceDoc failed with an exception: ", err); return ("processing the ServiceDoc failed with an exception: " + JSON.stringify(err)); } } }; kony.sdk.prototype.sessionChangeHandler = function(changes) { kony.sdk.logsdk.trace("Entering kony.sdk.prototype.sessionChangeHandler"); var konyRef = kony.sdk.getCurrentInstance(); konyRef.getMetricsService(); var sessionId = null; var userId = null; if (changes["sessionId"] != undefined) { sessionId = changes["sessionId"]; konyRef.setSessionId(sessionId); if (konyRef.metricsServiceObject && konyRef.metricsServiceObject.setSessionId) { konyRef.metricsServiceObject.setSessionId(sessionId); } } if (changes["userId"] != undefined) { konyRef.overrideUserIdFlag = true; userId = changes["userId"]; konyRef.setCurrentUserId(userId); if (konyRef.metricsServiceObject && konyRef.metricsServiceObject.setUserId) { konyRef.metricsServiceObject.setUserId(userId); } } }; function setIntegrityParams() { var integrityParams = { "algo": kony.sdk.constants.HASHING_ALGORITHM, "salt": konyRef.mainRef.appSecret, "headerName": kony.sdk.constants.INTEGRITY_HEADER, "validateResp": true }; konyRef.mainRef.integrityKey = true; konyRef.mainRef.integrityParams = integrityParams; } function resetIntegrityParams() { konyRef.mainRef.integrityKey = false; konyRef.mainRef.integrityParams = {}; } /** * MFSDK * Created by KH1969 on 18-01-2018. * Copyright © 2018 Kony. All rights reserved. */ /** * Constructor for ClientCache service, uses lruCache.js internally to save key, value pairs. * This is a singleton class, object gets created for the first time of instantiation and the same object is * returned for next initializations. * * @param size {Number} Maximum size of the cache. It should be non zero positive number. * @return {kony.sdk.ClientCache} * */ kony.sdk.ClientCache = function(size) { if (typeof kony.sdk.ClientCache.instance === 'object') return kony.sdk.ClientCache.instance; var lruCacheObj = null; if (size === undefined || size === null) lruCacheObj = new lruCache(kony.sdk.constants.DEFAULT_CACHE_SIZE); else if (typeof size != 'number' || size <= 0) { kony.sdk.logsdk.warn("cache cannot be created of size <= 0"); return null; } else lruCacheObj = new lruCache(size); /** * Gets the response cached for the key. Returns null if not found. * @param key {string} * @return {null|object} */ this.get = function(key) { return lruCacheObj.get(key); } /** * Gets the boolean assertion for key existence in the cache. * @param key {string} * @return {boolean} */ this.has = function(key) { return lruCacheObj.has(key); } /** * Adds the key, value pair to cache. * @param key {string} * @param value {string} * @param expiryTime {number} Expiry time in seconds. */ this.add = function(key, value, expiryTime) { lruCacheObj.add(key, value, expiryTime); } /** * Removes the key, value from cache. * @param key {string} */ this.remove = function(key) { lruCacheObj.remove(key); } kony.sdk.ClientCache.instance = this; } /** * MFSDK * Created by KH1969 on 18-01-2018. * Copyright © 2018 Kony. All rights reserved. */ /** * Constructor for standalone LRU page replacement implementation. * Implementation is done using a double linked list data structure and a hashmap. * Upon every insert & get the head gets updated to the newest element. * Cached nodes gets removed if size is more than the requested capacity. * Default cache size is 100. * * Should not be called by the developer. * * Below is the list structure if elements are inserted in the order A, B, C & D * Head = D, Tail = A * D--(older)-->C--(older)-->B--(older)-->A--(older)-->NULL * NULL<--(newer)--D<--(newer)--C<--(newer)--B<--(newer)--A * * Now if B is accessed the list structure will be modified as, * Head = B, Tail = A * * B--(older)-->D--(older)-->C--(older)-->A--(older)-->NULL * NULL<--(newer)--B<--(newer)--D<--(newer)--C<--(newer)--A */ lruCache = function(size) { var LOG_PREFIX = "SDK_CACHE "; if (size === undefined || size === null) this.capacity = kony.sdk.constants.DEFAULT_CACHE_SIZE; else if (typeof size != 'number' || size <= 0) { kony.sdk.logsdk.warn("cache cannot be created of size <= 0"); return null; } else this.capacity = size; this.length = 0; this.map = {}; // save the head and tail so we can update it easily this.head = null; this.tail = null; /** * Gets the current time in seconds. * @returns {number} */ function getCurrentTimeInSeconds() { return Math.floor(new Date().getTime() / 1000); } /** * Double linked list data structure. * @param key * @param value */ function cacheNode(key, value, expiry) { this.key = key; this.val = value; this.newer = null; // Next newer node this.older = null; // Previous older node this.expiryTime = 0; if (expiry !== undefined && typeof expiry === 'number' && expiry != 0) { this.expiryTime = getCurrentTimeInSeconds() + expiry; } } /** * Shuffles the cache by last recently used. * @param key */ function shuffleLRUCache(key) { var node = this.map[key]; if (this.head === node) { // No need to shuffle the cache, as the head itself is the recently accessed node. return; } // Head will not have newer node. if (node.newer) { node.newer.older = node.older; } else { this.head = node.older; } // Tail will not have older node. if (node.older) { node.older.newer = node.newer; } else { this.tail = node.newer; } // Now node is detached. Place it at head. // Updates are done in this way // 1: node--(older)-->head // 2: null<--(newer)--node // 3: node<--(newer)--head // 4: node is assigned to head. So current head got updated to node. node.older = this.head; node.newer = null; if (this.head) { this.head.newer = node; } this.head = node; } /** * Returns the current size of the cache. * @returns {number} */ this.getSize = function() { return this.length; } /** * Adds the key value pair to the cache. * Key gets removed upon expiry, expiry time is calculated by currentTimeInSeconds + expiryTime. * If no expiryTime is specified then key will not expire. * @param key {String} * @param value {Object} * @param expiryTime {Number} */ this.add = function(key, value, expiryTime) { if (key === undefined || value === undefined || key === null || value === null) return; // update the value for existing entries if (this.has(key)) { this.map[key].val = value; kony.sdk.logsdk.debug(LOG_PREFIX + "Key: " + key + " updated"); shuffleLRUCache.call(this, key); return; } if (this.length >= this.capacity) { // remove the least recently used item this.remove(this.tail.key) } var node = new cacheNode(key, value, expiryTime); // Additions are done in this way // 1: node--(older)-->head // 2: node<--(newer)--head // 3: node is assigned to head. So current head got updated to node. // 4: tail = node, if there is no tail node then current node is tail node. This happens only for the first add. node.older = this.head; // if have head, we need re-connect node with other nodes older than head if (this.head) { this.head.newer = node; } this.head = node; // if no tail which means first insert, set the tail to node too if (!this.tail) { this.tail = node; } this.map[key] = node; this.length++; kony.sdk.logsdk.debug(LOG_PREFIX + "Key: " + key + " added"); } /** * Gets the cached node by key. Returns null if key is not found. * The key is removed if it is expired, returns null here as well. * @param key {String} * @returns {Object} */ this.get = function(key) { if (this.has(key)) { if (this.map[key].expiryTime != 0 && getCurrentTimeInSeconds() > this.map[key].expiryTime) { this.remove(key); kony.sdk.logsdk.debug(LOG_PREFIX + "Key: " + key + " expired"); return null; } shuffleLRUCache.call(this, key); return this.map[key].val; } else { return null; } } /** * Removes the key, value from the cache by key. * @param key {String} Key to delete from the cache */ this.remove = function(key) { if (this.has(key)) { var node = this.map[key]; // Head node will not have newer node. if (node.newer) { node.newer.older = node.older; } else { this.head = node.older; } // Tail node will not have older node. if (node.older) { node.older.newer = node.newer; } else { this.tail = node.newer; } delete this.map[key]; node = null; this.length--; } } /** * Clears the cache. */ this.clear = function() { this.map = {}; this.length = 0; } /** * Check if key exists. * @param key {string} Key to be found in the cache * @returns {boolean} */ this.has = function(key) { return this.map.hasOwnProperty(key); } /** * Updates the cache size. * @param size {number} */ this.setMaxCacheSize = function(size) { // Todo: If requested size < capacity remove the last (N - size) nodes from tail. kony.sdk.logsdk.debug(LOG_PREFIX + "updating cache size from " + this.capacity + " to " + size); this.capacity = size; } } /** * Method to create the configuration service instance * @returns {ConfigurationService} Configuration service instance */ kony.sdk.prototype.getConfigurationService = function() { kony.sdk.logsdk.trace("Entering kony.sdk.prototype.getConfigurationService") if (!kony.sdk.isInitialized) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, kony.sdk.constants.INIT_FAILURE_MESSAGE + " Configuration service."); } var configObj = new ConfigurationService(this); if (configObj) { return configObj; } else { throw new Exception(kony.sdk.errorConstants.CONFIGURATION_FAILURE, "Error in creating configuration object"); } }; /** * Should not be called by the developer. * @class * @classdesc Configuration service instance for fetching client app properties. */ function ConfigurationService(konyRef) { var istUrl = konyRef.mainRef.config.reportingsvc.session.split("/IST")[0]; kony.sdk.logsdk.debug("IST url fetched from service doc is :" + istUrl); var configUrl = istUrl + kony.sdk.constants.GET_CLIENT_PROPERTY_URL; kony.sdk.logsdk.debug("Configuration url formed is :" + configUrl); var networkProvider = new konyNetworkProvider(); /** * Configuration svc method to get all the client app properties which is configured in admin console. * @successCallback this is called on successfull retrieval of properties * @failureCallback this is called on failure in retrieving properties * @returns {json} key value pair of all client app properties */ this.getAllClientAppProperties = function(successCallback, failureCallback) { function fetchClientPropertiesHandler() { _getAllClientAppProperties(successCallback, failureCallback); } kony.sdk.claimsRefresh(fetchClientPropertiesHandler, failureCallback); }; function _getAllClientAppProperties(successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering into _getAllClientAppProperties"); var defaultHeaders = {}; var token = konyRef.currentClaimToken; if (!token) { token = kony.sdk.getCurrentInstance().currentClaimToken; } defaultHeaders[kony.sdk.constants.KONY_AUTHORIZATION_HEADER] = token; var options = {}; options["disableIntegrity"] = true; networkProvider.get(configUrl, null, defaultHeaders, function(res) { kony.sdk.logsdk.trace("Entering Configuration service network success"); kony.sdk.logsdk.debug("response from server for client properties is :" + JSON.stringify(res)); var tempArray = ["httpresponse", kony.sdk.constants.MF_OPSTATUS]; var tempJSON = {}; for (var key in res) { if (tempArray.indexOf(key.toLowerCase()) > -1) { continue; } tempJSON[key] = res[key]; } kony.sdk.verifyAndCallClosure(successCallback, tempJSON); }, function(xhr, status, err) { kony.sdk.logsdk.trace("Entering Configuration service network error"); if (xhr && !(status && err)) { err = xhr; } kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getObjectServiceErrObj(err)); }, null, options); } } kony.sdk.constants = { /**Logger Constants**/ LOGGER_NAME: "MFSDK", SYNC_LOGGER_NAME: "SYNCV1", APP_LOGGER_NAME: "KonyLogger", /**Network constants**/ LAUNCHMODE_DEEPLINK: 3, DEEPLINK_VALID_PARAM: "code", HASHING_ALGORITHM: "SHA256", REMOVE_INTEGRITY_CHECK: "removeIntegrityCheck", SET_INTEGRITY_CHECK: "setIntegrityCheck", DEFAULT_CACHE_SIZE: 100, GET_CLIENT_PROPERTY_URL: "/metadata/configurations/client/properties", DEFAULT_CACHE_EXPIRY_TIME: 0, //Which means it doesn't expire in the application session. /**Service ID's for Identity Calls**/ GET_BACKEND_TOKEN: "getBackendToken", GET_SECURITY_ATTRIBUTES: "getSecurityAttributes", GET_USER_ATTRIBUTES: "getUserAttributes", GET_USER_DATA: "getUserData", GET_PROFILE: "getProfile", /** Identity Options**/ OAUTH_REDIRECT_SUCCESS_URL: "success_url", //OAuth for IE11 Workaround Constants, MFSDK-3657 IE11_CROSS_DOMAIN_OAUTH_BASE_URL: "IE11CrossDomainOAuthBaseUrl", KNY_OAUTH_REDIRECT_HTML: "KNYOAuthRedirect.html", KNY_OAUTH_CALLBACK_HTML: "KNYOAuthCallback.html", KNY_OAUTH_REDIRECT_URL: "kny_oauth_redirect_url", /**HttpMethods and header constants**/ HTTP_METHOD_GET: "GET", HTTP_METHOD_POST: "POST", HTTP_METHOD_DELETE: "DELETE", HTTP_CONTENT_HEADER: "Content-Type", HTTP_REQUEST_HEADER_ACCEPT: "Accept", /**Content Type Value Constants**/ CONTENT_TYPE_FORM_URL_ENCODED: "application/x-www-form-urlencoded", CONTENT_TYPE_JSON: "application/json", CONTENT_TYPE_OCTET_STREAM: "application/octet-stream", CONTENT_TYPE_TEXT_HTML: "text/html", CONTENT_TYPE_TEXT_PLAIN: "text/plain", /**SDK Plugin Type**/ SDK_TYPE_IDE: "js", SDK_TYPE_PHONEGAP: "phonegap", SDK_TYPE_PLAIN_JS: "plain-js", /**SDK Architecture Type**/ SDK_ATYPE_NATIVE: "native", SDK_ATYPE_SPA: "spa", /**Device platform**/ PLATFORM_WINDOWS: "windows", PLATFORM_ANDROID: "android", PLATFORM_IOS: "ios", //kony.os.device.info() for SPA returns thinclient PLATFORM_SPA: "thinclient", /***Metrics Constants**/ REPORTING_PARAMS: "konyreportingparams", KEY_DEVICE_ID: "deviceID", /**Headers**/ APP_KEY_HEADER: "X-Kony-App-Key", APP_SECRET_HEADER: "X-Kony-App-Secret", KONY_AUTHORIZATION_HEADER: "X-Kony-Authorization", AUTHORIZATION_HEADER: "Authorization", REPORTING_HEADER: "X-Kony-ReportingParams", INTEGRITY_HEADER: "X-Kony-Integrity", DEVICEID_HEADER: "X-Kony-DeviceId", API_VERSION_HEADER: "X-Kony-API-Version", APP_VERSION_HEADER: "X-Kony-App-Version", SDK_TYPE_HEADER: "X-Kony-SDK-Type", SDK_VERSION_HEADER: "X-Kony-SDK-Version", PLATFORM_TYPE_HEADER: "X-Kony-Platform-Type", HTTP_OVERRIDE_HEADER: "X-HTTP-Method-Override", /**Mobilefabric constants**/ HTTP_STATUS_CODE: "httpStatusCode", MF_OPSTATUS: "opstatus", MF_CODE: "mfcode", MF_ERROR_MSG: "errmsg", MF_ERROR_CODE: "errcode", MF_SERVICE: "service", /**Engagement service API constants**/ SUBSCRIBE_AUDIENCE: "/subscribeaudience", BEACON_UPDATE: "/beaconupdate", RICH_PUSH_MESSAGE: "/messages/rich/", LAST_ACTIVE_DATE: "lastActiveDate", KSID: "ksid", AUTH_TOKEN: "authToken", DEVICE_AUTHTOKEN_HEADER: "X-Device-AuthToken", /**Parsed Template Constants**/ PROCESSED_TEMPLATE: "processedTemplate", MISSING_VARIABLES: "missingVariables", /**Mandatory Binary Params**/ FILE_PATH: "FilePath", RAW_BYTES: "rawBytes", FILE_OBJECT: "fileObject", FILE_NAME: "fileName", /**Miscellaneous**/ KONYUUID: "konyUUID", BROWSER_WIDGET: "browserWidget", INIT_FAILURE_MESSAGE: "SDK is not initialized, call init before invoking any operation on", DISABLE_INTEGRITY: "disableIntegrity", PASSTHROUGH: "passthrough", BINARY_DATATYPE: "binary" }; if (typeof(kony.sdk) === "undefined") { kony.sdk = {}; } if (typeof(kony.sdk.error) === "undefined") { kony.sdk.error = {}; } kony.sdk.error.getAuthErrObj = function(errResponse) { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getAuthErrObj"); if (errResponse && errResponse.httpresponse) { delete errResponse.httpresponse; } if (errResponse && (errResponse.opstatus == 1013 || errResponse.opstatus == 1011)) { errResponse["message"] = errResponse[kony.sdk.constants.MF_ERROR_MSG]; delete errResponse.errmsg; } try { var mfcode = errResponse[kony.sdk.constants.MF_CODE]; var message = errResponse["message"]; var details = errResponse["details"]; if (mfcode) { return kony.sdk.error.getMFcodeErrObj(mfcode, message, details, ""); } return errResponse; } catch (err) { return errResponse; } } kony.sdk.error.getNullClaimsTokenErrObj = function() { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getNullClaimsTokenErrObj"); var errorObj = {}; errorObj.opstatus = kony.sdk.errorcodes.cliams_token_null errorObj.message = kony.sdk.errormessages.cliams_token_null errorObj.details = {}; errorObj.mfcode = ""; return errorObj; } kony.sdk.error.getIdentitySessionInactiveErrObj = function() { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getIdentitySessionInactiveErrObj"); var errorObj = {}; errorObj.opstatus = kony.sdk.errorcodes.identity_session_inactive errorObj.message = kony.sdk.errormessages.identity_session_inactive errorObj.details = {}; errorObj.mfcode = ""; return errorObj; } kony.sdk.error.getNullRefreshTokenErrObj = function() { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getNullRefreshTokenErrObj"); var errorObj = {}; errorObj.opstatus = kony.sdk.errorcodes.invalid_session_or_token_expiry errorObj.message = kony.sdk.errormessages.invalid_session_or_token_expiry errorObj.details = {}; errorObj.mfcode = ""; return errorObj; } kony.sdk.error.getIntegrationErrObj = function(errResponse) { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getIntegrationErrObj"); try { var mfcode = errResponse[kony.sdk.constants.MF_CODE]; var message = errResponse[kony.sdk.constants.MF_ERROR_MSG]; var details = errResponse["mferrmsg"]; var service = errResponse[kony.sdk.constants.MF_SERVICE]; if (!service) { service = ""; } if (!details) { details = ""; } var errorMessagePrefixForIntegration = ""; if (service) { errorMessagePrefixForIntegration = "Integration Service Request Failed for " + service + ":"; } else { errorMessagePrefixForIntegration = "Integration Service Request Failed:"; } if (mfcode) { return kony.sdk.error.getMFcodeErrObj(mfcode, message, details, errorMessagePrefixForIntegration); } return errResponse; } catch (err) { return errResponse; } } kony.sdk.error.getLogicErrObj = function(errResponse) { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getLogicErrObj"); try { var mfcode = errResponse[kony.sdk.constants.MF_CODE]; var message = errResponse[kony.sdk.constants.MF_ERROR_MSG]; var details = errResponse["mferrmsg"]; var service = errResponse[kony.sdk.constants.MF_SERVICE]; if (!service) { service = ""; } if (!details) { details = ""; } var errorMessagePrefixForLogic = ""; if (service) { errorMessagePrefixForLogic = "Logic Service Request Failed for " + service + ":"; } else { errorMessagePrefixForLogic = "Logic Service Request Failed:"; } if (mfcode) { return kony.sdk.error.getMFcodeErrObj(mfcode, message, details, errorMessagePrefixForLogic); } return errResponse; } catch (err) { return errResponse; } } kony.sdk.error.getMFcodeErrObj = function(mfcode, message, details, errMessagePrefix) { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getMFcodeErrObj"); var errorObj = {}; errorObj.details = {}; if (details) { errorObj.details = details; } errorObj.mfcode = mfcode; if (mfcode === "Auth-4") { if (!message) { message = kony.sdk.errormessages.invalid_user_credentials } errorObj.opstatus = kony.sdk.errorcodes.invalid_user_credentials errorObj.message = errMessagePrefix + message; } else if (mfcode === "Auth-9") { if (!message) { message = kony.sdk.errormessages.invalid_app_credentials } errorObj.opstatus = kony.sdk.errorcodes.invalid_app_credentials errorObj.message = errMessagePrefix + message; } else if (mfcode === "Auth-3") { if (!message) { message = kony.sdk.errormessages.invalid_user_app_credentials } errorObj.opstatus = kony.sdk.errorcodes.invalid_user_app_credentials errorObj.message = errMessagePrefix + message; } else if ((mfcode === "Auth-5") || (mfcode === "Auth-6") || (mfcode === "Gateway-31") || (mfcode === "Gateway-33") || (mfcode === "Gateway-35") || (mfcode === "Gateway-36") || (mfcode === "Auth-46") || (mfcode === "Auth-55")) { errorObj.opstatus = kony.sdk.errorcodes.invalid_session_or_token_expiry errorObj.message = errMessagePrefix + kony.sdk.errormessages.invalid_session_or_token_expiry } else if (mfcode === "Auth-7" || mfcode === "Auth-27") { if (!message) { message = errMessagePrefix + kony.sdk.errormessages.invalid_user_app_services } errorObj.opstatus = kony.sdk.errorcodes.invalid_user_app_services errorObj.message = message; } else { errorObj.opstatus = kony.sdk.errorcodes.default_code errorObj.message = errMessagePrefix + kony.sdk.errormessages.default_message } return errorObj; } function getAuthErrorMessage(mfcode) { kony.sdk.logsdk.trace("Entering into getAuthErrorMessage"); if (mfcode === "Auth-4") { return kony.sdk.errormessages.invalid_user_credentials } else if (mfcode === "Auth-9") { return kony.sdk.errormessages.invalid_app_credentials } else if (mfcode === "Auth-3") { return kony.sdk.errormessages.invalid_user_app_credentials } else if ((mfcode === "Auth-5") || (mfcode === "Auth-6") || (mfcode === "Gateway-31") || (mfcode === "Gateway-33") || (mfcode === "Gateway-35") || (mfcode === "Gateway-36") || (mfcode === "Auth-46") || (mfcode === "Auth-55")) { return kony.sdk.errormessages.invalid_session_or_token_expiry } else if (mfcode === "Auth-7" || mfcode === "Auth-27") { return kony.sdk.errormessages.invalid_user_app_services } else { return mfcode + ":" + kony.sdk.errormessages.default_message } } kony.sdk.error.getObjectServiceErrObj = function(errResponse) { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getObjectServiceErrObj"); try { var mfcode = errResponse[kony.sdk.constants.MF_CODE]; var message = errResponse[kony.sdk.constants.MF_ERROR_MSG]; var details = errResponse["mferrmsg"]; var service = errResponse[kony.sdk.constants.MF_SERVICE]; if (!service) { service = ""; } if (!details) { details = ""; } var errorMessagePrefixForIntegration = ""; if (service) { errorMessagePrefixForIntegration = "Object Service Request Failed for " + service + ":"; } else { errorMessagePrefixForIntegration = "Object Service Request Failed:"; } if (mfcode) { return kony.sdk.error.getMFcodeErrObj(mfcode, message, details, errorMessagePrefixForIntegration); } return errResponse; } catch (err) { return errResponse; } } kony.sdk.error.getClientErrObj = function(errCode, errMsg) { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getClientErrObj"); var errObj = new Object(); errObj.opstatus = kony.sdk.errorcodes.clientvalidation_error_opstatus; errObj.errmsg = errMsg; errObj.errcode = errCode; return errObj; } kony.sdk.error.getMessagingError = function(errMsg) { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getMessagingError"); var errObj = new Object(); errObj.opstatus = kony.sdk.errorcodes.messaging_service_fail; errObj.errmsg = kony.sdk.errormessages.messaging_service_fail + errMsg; errObj.errcode = kony.sdk.errorcodes.messaging_service_fail; return errObj; } kony.sdk.error.getConfigServiceErrObject = function(errResponse) { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getConfigServiceErrObject"); try { var mfcode = errResponse[kony.sdk.constants.MF_CODE]; var message = errResponse[kony.sdk.constants.MF_ERROR_MSG]; var details = errResponse["mferrmsg"]; var service = errResponse[kony.sdk.constants.MF_SERVICE]; if (!service) { service = ""; } if (!details) { details = ""; } var errorMessagePrefixForIntegration = ""; if (service) { errorMessagePrefixForIntegration = "Configuration Service Request Failed for " + service + ":"; } else { errorMessagePrefixForIntegration = "Configuration Service Request Failed:"; } if (mfcode) { return kony.sdk.error.getMFcodeErrObj(mfcode, message, details, errorMessagePrefixForIntegration); } return errResponse; } catch (err) { return errResponse; } }; kony.sdk.error.getIntegrityErrorMessage = function(httpRequest, url) { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getIntegrityErrorMessage"); var errorMessage = {}; errorMessage.httpresponse = {}; errorMessage[kony.sdk.constants.MF_OPSTATUS] = kony.sdk.errorcodes.integrity_check_failed; errorMessage[kony.sdk.constants.MF_ERROR_MSG] = kony.sdk.errormessages.integrity_check_failed; errorMessage[kony.sdk.constants.MF_ERROR_CODE] = kony.sdk.errorcodes.integrity_check_failed; errorMessage[kony.sdk.constants.HTTP_STATUS_CODE] = httpRequest.status.toString(); errorMessage.httpresponse["response"] = httpRequest.response; errorMessage.httpresponse.headers = httpRequest.getAllResponseHeaders(); errorMessage.httpresponse.url = url; errorMessage.httpresponse.responsecode = httpRequest.status.toString(); return errorMessage; }; kony.sdk.error.getOperationFailedErrorMessage = function(httpRequest, url) { kony.sdk.logsdk.trace("Entering into kony.sdk.error.getOperationFailedErrorMessage"); var errorMessage = {}; errorMessage[kony.sdk.constants.MF_OPSTATUS] = httpRequest.response.opstatus; errorMessage[kony.sdk.constants.MF_ERROR_MSG] = kony.sdk.errormessages.server_operation_failed; errorMessage[kony.sdk.constants.MF_ERROR_CODE] = kony.sdk.errorcodes.server_operation_failed; errorMessage[kony.sdk.constants.HTTP_STATUS_CODE] = httpRequest.status.toString(); var httpResponse = {}; httpResponse.response = httpRequest.response; httpResponse.headers = httpRequest.getAllResponseHeaders(); httpResponse.responsecode = httpRequest.status.toString(); httpResponse.url = url; errorMessage.httpResponse = httpResponse; return errorMessage; }; if (typeof(kony.sdk) === "undefined") { kony.sdk = {}; } if (typeof(kony.sdk.errorcodes) === "undefined") { kony.sdk.errorcodes = {}; } if (typeof(kony.sdk.errormessages) === "undefined") { kony.sdk.errormessages = {}; } kony.sdk.errorcodes.invalid_user_credentials = 101; kony.sdk.errormessages.invalid_user_credentials = "Invalid User Credentials."; kony.sdk.errorcodes.invalid_app_credentials = 102; kony.sdk.errormessages.invalid_app_credentials = "Invalid App Credentials."; kony.sdk.errorcodes.invalid_user_app_credentials = 103; kony.sdk.errormessages.invalid_user_app_credentials = "Invalid User/App Credentials."; kony.sdk.errorcodes.invalid_session_or_token_expiry = 104; kony.sdk.errormessages.invalid_session_or_token_expiry = "Session/Token got invalidated in the backend.Please login."; kony.sdk.errorcodes.invalid_user_app_services = 105; kony.sdk.errormessages.invalid_user_app_services = "Invalid provider in appServices."; kony.sdk.errorcodes.cliams_token_null = 106; kony.sdk.errormessages.cliams_token_null = "Claims Token is Unavialable"; kony.sdk.errorcodes.identity_session_inactive = 107; kony.sdk.errormessages.identity_session_inactive = "Identity Provider's sessions is not active. Please login"; kony.sdk.errorcodes.default_code = 100; kony.sdk.errormessages.default_message = "UnhandledMFcode"; kony.sdk.errorcodes.unknown_error_code = 1000; kony.sdk.errormessages.unknown_error_message = "An unknown error has occured"; kony.sdk.errorcodes.connectivity_error_code = 1011; kony.sdk.errormessages.connectivity_error_message = "An error occurred while making the request. Please check device connectivity, server url and request parameters"; kony.sdk.errorcodes.invalid_json_code = 1013; kony.sdk.errormessages.invalid_json_message = "Invalid Json response was returned"; kony.sdk.errorcodes.request_timed_out_code = 1014; kony.sdk.errormessages.request_timed_out_message = "Request to server has timed out"; kony.sdk.errorcodes.offline_auth_failed = 1015; kony.sdk.errormessages.offline_auth_failed = "Offline Authentication failed, User should atleast login once when network connectivity is available."; kony.sdk.errorcodes.servicedoc_unavailable = 1016; kony.sdk.errormessages.servicedoc_unavailable = "MBAAS app is not initialized properly. Service document is unavailable."; kony.sdk.errorcodes.transient_login_fail = 1017; kony.sdk.errormessages.transient_login_fail = "Transient Login failed, Previous Identity Token expired in backend."; kony.sdk.errorcodes.messaging_service_fail = 1018; kony.sdk.errormessages.messaging_service_fail = "Failure in Messaging Service. "; kony.sdk.errorcodes.integrity_check_failed = 1019; kony.sdk.errormessages.integrity_check_failed = "Http message Body Integrity Check failed."; kony.sdk.errorcodes.server_operation_failed = 1020; kony.sdk.errormessages.server_operation_failed = "Operation Failed on server"; kony.sdk.errorcodes.populating_template_failed = 1021; kony.sdk.errormessages.populating_template_failed = "Template population failed, template parameters are invalid or template is malformed"; kony.sdk.errorcodes.clientvalidation_error_opstatus = 112233; //Invaild API's for phonegap and plain-js kony.sdk.errorcodes.invalid_api = 7000; kony.sdk.errormessages.invalid_api = "Invalid Operation name, Operation Failed."; //Object Service Error Messages kony.sdk.errorcodes.invalid_dataobject_instance = 90001; kony.sdk.errormessages.invalid_dataobject_instance = "Provided dataobject is invalid and should be instance of kony.sdk.dto.DataObject"; kony.sdk.errorcodes.primarykey_unavailable = 90002; kony.sdk.errormessages.primarykey_unavailable = "Primary Keys missing, Operation Failed"; kony.sdk.errorcodes.null_or_undefined = 90003; kony.sdk.errormessages.null_or_undefined = " cannot be null or undefined"; kony.sdk.errorcodes.transaction_failed = 90004; kony.sdk.errormessages.transaction_failed = "Some error occurred, Operation Failed"; kony.sdk.errorcodes.norecords_to_delete = 90005; kony.sdk.errormessages.norecords_to_delete = "No records deleted with the specified criteria"; kony.sdk.errorcodes.invalid_queryparams_instance = 90006; kony.sdk.errormessages.invalid_queryparams_instance = "Provided queryParams is invalid and should be a json object"; kony.sdk.errorcodes.invalid_params_instance = 90007; kony.sdk.errormessages.invalid_params_instance = "Provided params are invalid"; kony.sdk.errorcodes.invalid_object = 90008; kony.sdk.errormessages.invalid_object = "Invalid object name, Operation Failed."; kony.sdk.errorcodes.invalid_blob = 90009; kony.sdk.errormessages.invalid_blob = "Failed to read from binary file, either the file does not exist or invalid"; kony.sdk.errorConstants = { INIT_FAILURE: "INIT_FAILURE", DATA_STORE_EXCEPTION: "DATASTORE_FAILURE", AUTH_FAILURE: "AUTH_FAILURE", INTEGRATION_FAILURE: "INTEGRATION_FAILURE", MESSAGING_FAILURE: "MESSAGING_FAILURE", SYNC_FAILURE: "SYNC_FAILURE", METRICS_FAILURE: "METRICS_FAILURE", MISC_FAILURE: "MISCELLANEOUS_FAILURE", OBJECT_FAILURE: "OBJECT_FAILURE", LOGIC_SERVICE_FAILURE: "LOGIC_SERVICE_FAILURE", SYNC_V2_FAILURE: "SYNC_V2_FAILURE", CONFIGURATION_URL_FAILURE: "CONFIGURATION_URL_FAILURE", CONFIGURATION_FAILURE: "CONFIGURATION_FAILURE", INTEGRITY_FAILURE: "INTEGRITY_FAILURE", INVALID_API_FAILURE: "INVALID_API_FAILURE" }; /** * Method to create the Identity service instance with the provided provider name. * @param {string} providerName - Name of the provider * @returns {IdentityService} Identity service instance */ kony.sdk.offline = kony.sdk.offline || {}; kony.sdk.sso = kony.sdk.sso || {}; kony.sdk.isSSOLoginSuccess = kony.sdk.isSSOLoginSuccess || true; kony.sdk.prototype.getIdentityService = function(providerName) { kony.sdk.logsdk.trace("Entering kony.sdk.prototype.getIdentityService"); if (!kony.sdk.isInitialized) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, kony.sdk.constants.INIT_FAILURE_MESSAGE + " Identity service."); } var provider = null; if (providerName) { if (this.login != null) { for (var i = 0; i < this.login.length; i++) { var rec = this.login[i]; if ((rec.alias && rec.alias.toUpperCase() === providerName.toUpperCase()) || (rec.prov.toUpperCase() === providerName.toUpperCase())) { provider = new IdentityService(this, rec); break; } } if (provider === null) { throw new Exception(kony.sdk.errorConstants.AUTH_FAILURE, "Invalid providerName"); } //TODO: what if the providerName is not passed by the user? kony.sdk.logsdk.debug("### auth:: returning authService for providerName = " + provider.getProviderName()); return provider; } } else { throw new Exception(kony.sdk.errorConstants.AUTH_FAILURE, "Invalid providerName"); } }; /** * Should not be called by the developer. * @class * @classdesc Identity service instance for handling login/logout calls. */ function IdentityService(konyRef, rec) { kony.sdk.logsdk.trace("Entering IdentityService"); var networkProvider = new konyNetworkProvider(); var dataStore = new konyDataStore(); var serviceObj = rec; konyRef.rec = rec; var mainRef = konyRef.mainRef; var user_attributes = {}; var offlineEnabled = false; var persistToken = false; if (serviceObj === undefined || serviceObj.prov == undefined || serviceObj.type == undefined) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, "Invalid service url and service type"); } var _type = serviceObj.type; var _serviceUrl = stripTrailingCharacter(serviceObj.url, "/"); var _providerName = serviceObj.prov; kony.sdk.logsdk.debug("### AuthService:: initialized for provider " + _providerName + " with type " + _type); function isLoggedIn() { if (kony.sdk.getCurrentInstance() && kony.sdk.getCurrentInstance().tokens && kony.sdk.getCurrentInstance().tokens.hasOwnProperty(_providerName) && !kony.sdk.isNullOrUndefined(kony.sdk.getCurrentInstance().tokens[_providerName]) && Object.keys(kony.sdk.getCurrentInstance().tokens[_providerName]).length !== 0) { return true; } return false; } var dsKey = _serviceUrl + "::" + _providerName + "::" + _type + "::RAW"; function resetAllCurrentTokens(konyRef, _providerName) { kony.sdk.resetProviderKeys(konyRef, _providerName); } /** * Login with the given credentials asynchronously and executes the given callback. * @param {object} options - User name and password * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure */ this.login = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering Login"); var continueOnRefreshError = true; var reportingData = kony.sdk.getPayload(konyRef); var sessionId = null; if (kony.ds) { sessionId = kony.ds.read(kony.sdk.constants.KONYUUID); } if (sessionId) { reportingData.rsid = sessionId[0]; } reportingData.svcid = "login_" + _providerName; if (!reportingData.rsid) { kony.sdk.logsdk.warn("### login:: rsid is either empty,null or undefined"); } kony.sdk.logsdk.debug("### AuthService::login Invoked login for provider " + _providerName + " of type " + _type); if (typeof(options) == 'undefined') { throw new Exception(kony.sdk.errorConstants.AUTH_FAILURE, "Missing required number of arguments to login function"); } if (options && options["loginOptions"] && options["loginOptions"]["continueOnRefreshError"] === false) { continueOnRefreshError = false; } if (options && options["loginOptions"] && options["loginOptions"]["persistLoginResponse"] === true) { persistToken = true; dataStore.setItem("persistLoginResponseFlag", true); kony.sdk.offline.persistToken = true; } if (options && options["loginOptions"]) { offlineEnabled = options["loginOptions"]["isOfflineEnabled"] || false; kony.sdk.offline.isOfflineEnabled = kony.sdk.offline.isOfflineEnabled || offlineEnabled; kony.sdk.sso.isSSOEnabled = options["loginOptions"]["isSSOEnabled"] || false; } else { kony.sdk.sso.isSSOEnabled = false; } function invokeAjaxCall(url, params, headers) { if (!headers) { headers = {}; } if (!kony.sdk.isNullOrUndefined(konyRef.currentClaimToken) && (new Date().getTime() < konyRef.claimTokenExpiry)) { headers[kony.sdk.constants.KONY_AUTHORIZATION_HEADER] = konyRef.currentClaimToken; } headers[kony.sdk.constants.APP_KEY_HEADER] = mainRef.appKey; headers[kony.sdk.constants.APP_SECRET_HEADER] = mainRef.appSecret; headers[kony.sdk.constants.SDK_TYPE_HEADER] = kony.sdk.getSdkType(); headers[kony.sdk.constants.SDK_VERSION_HEADER] = kony.sdk.version; headers[kony.sdk.constants.PLATFORM_TYPE_HEADER] = kony.sdk.getPlatformName(); headers[kony.sdk.constants.HTTP_REQUEST_HEADER_ACCEPT] = kony.sdk.constants.CONTENT_TYPE_JSON; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; populateHeaderWithFabricAppVersion(headers); if (konyRef.reportingheaders_allowed) { if (reportingData != null && reportingData != undefined) { try { headers[kony.sdk.constants.REPORTING_HEADER] = encodeURI(JSON.stringify(reportingData)) } catch (error) { kony.sdk.logsdk.error("### login::error while parsing metrics payload" + error); } } } if (kony.sdk.sso.isSSOEnabled === true) { var ssotoken = kony.sdk.util.getSSOToken(); if (ssotoken != null && ssotoken != "" && ssotoken != undefined) { headers[kony.sdk.constants.AUTHORIZATION_HEADER] = ssotoken; } } var endPointUrl = null; if (_type === "anonymous") { endPointUrl = _serviceUrl + url; } else { endPointUrl = _serviceUrl + url + "?provider=" + _providerName; params["provider"] = _providerName; } if (kony.sdk.getPlatformName() !== kony.sdk.constants.PLATFORM_WINDOWS) { //Save the user entered form data to a temporary store and only if login is successful, we store the value in this to proper credentials store. if (kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_IDE && (_type === "basic" || (options && options["userid"] && options["password"])) && offlineEnabled === true) { kony.sdk.offline.saveTempUserCredentials(options); if (!kony.sdk.isNetworkAvailable()) { kony.sdk.offline.loginOffline(_providerName, function(cachedAuthResponse) { kony.sdk.logsdk.info("successfully authenticated offline"); processLoginSuccessResponse(cachedAuthResponse, konyRef, true, successCallback); }, function(error) { kony.sdk.logsdk.error("offline authentication also failed"); resetAllCurrentTokens(konyRef, _providerName); if (failureCallback) { failureCallback(kony.sdk.error.getAuthErrObj(error)); } }); return; } } } if (options && options["include_profile"]) { params["include_profile"] = params["include_profile"] ? params["include_profile"] : options["include_profile"]; } var networkOptions = {}; if (options && options["httpRequestOptions"] && options["httpRequestOptions"] instanceof Object) { networkOptions["httpRequestOptions"] = options["httpRequestOptions"]; } networkProvider.post(endPointUrl, params, headers, function(data) { var response = processLoginSuccessResponse(data, konyRef, false); function serviceDocCallback() { kony.sdk.verifyAndCallClosure(successCallback, response); } getLatestServiceDocIfAvailable(data, serviceDocCallback); }, function(data) { processLoginErrorResponse(data, konyRef, true, failureCallback) }, null, networkOptions); } function loginHelper(url, params, headers, isError) { if (isError) { var error = {}; err.message = "Login Failed"; err.opstatus = kony.sdk.errorcodes.transient_login_fail; err.code = (params && params.error) ? params.error : ""; kony.sdk.verifyAndCallClosure(failureCallback, err); return; } kony.sdk.logsdk.trace("Entering loginHelper"); if (!kony.sdk.isNullOrUndefined(konyRef.currentClaimToken) && !konyRef.isAnonymousProvider) { kony.sdk.claimsRefresh(function(res) { invokeAjaxCall(url, params, headers) }, function(err) { if (continueOnRefreshError) { kony.sdk.logsdk.error("### AuthService::login claimsRefresh failed, performing force login"); invokeAjaxCall(url, params, headers); } else { kony.sdk.logsdk.error("### AuthService::login claimsRefresh failed, invoking failurecallback"); err.message = kony.sdk.errormessages.transient_login_fail; err.opstatus = kony.sdk.errorcodes.transient_login_fail; kony.sdk.verifyAndCallClosure(failureCallback, err); } }) } else { kony.sdk.logsdk.info("### AuthService::login Claims token unavailable, performing regular login"); invokeAjaxCall(url, params, headers); } } /** * Login once the deeplink redirection is done. . * @param {map} options */ function loginForDeeplink(options) { kony.sdk.logsdk.trace("Entering loginForDeeplink"); if (options) { var code = options[kony.sdk.constants.DEEPLINK_VALID_PARAM]; var urlType = options["urlType"]; try { kony.sdk.logsdk.debug("### AuthService::login received authorization code"); loginHelper("/" + urlType + "/" + "token", { code: code }, {}); } catch (err) { kony.sdk.logsdk.error("exception ::" + err); failureCallback(); } } } if (_type === "anonymous") { konyRef.isAnonymousProvider = true; kony.sdk.logsdk.info("### AuthService::login Adapter type is anonymous"); loginHelper("/login", {}, {}); } else if (_type == "basic") { var mandatory_fields = ["userid", "password"]; if (kony.sdk.sso.isSSOEnabled === false) { if (serviceObj.mandatory_fields && kony.sdk.isArray(serviceObj.mandatory_fields)) { mandatory_fields = serviceObj.mandatory_fields; } for (var i = 0; i < mandatory_fields.length; ++i) { if (kony.sdk.isNullOrUndefined(options[mandatory_fields[i]])) { throw new Exception(kony.sdk.errorConstants.AUTH_FAILURE, " Require " + mandatory_fields[i]); } } } var payload = {}; var encryptedStorage = {}; if (options != null && options != undefined) { for (var option in options) { payload[option] = options[option]; } } payload["provider"] = _providerName; kony.sdk.logsdk.info("### AuthService::login Adapter type is basic"); loginHelper("/login", payload, {}); } else { if (options && options.userid && options.password) { var payload = {}; for (var option in options) { payload[option] = options[option]; } payload["provider"] = _providerName; loginHelper("/login", payload); } else { kony.sdk.logsdk.debug("### AuthService::login Adapter type is " + _type); if (kony.sdk.isSSOLoginSuccess && kony.sdk.sso.isSSOEnabled == true && kony.sdk.util.getSSOToken() != null && kony.sdk.util.getSSOToken() != "" && kony.sdk.util.getSSOToken() != undefined) { if (_type === "oauth2") { loginHelper("/oauth2/token", {}, {}); } else if (_type === "saml") { loginHelper("/saml/token", {}, {}); } else { loginHelper("/login", {}, {}); } } else { //To provide backward compatibility, if MF is an older it will not have the changes for blocking the popup or opening the login url in the native browser. //Identity will add a new tuple in the service doc "identity_meta". SDK will validate the compatibility with the existance of serviceDoc["identity_meta"][<priovider_name>]["success_url"] var isMFVersionCompatible = false; var oauthOptions = {}; if (options && options["loginOptions"] && options["loginOptions"]["customQueryParamsForOAuth"] && options["loginOptions"]["customQueryParamsForOAuth"] instanceof Object) { oauthOptions["customQueryParamsForOAuth"] = options["loginOptions"]["customQueryParamsForOAuth"]; } if (mainRef && mainRef.config && mainRef.config.identity_meta && mainRef.config.identity_meta[_providerName] && mainRef.config.identity_meta[_providerName].success_url) { isMFVersionCompatible = true; } if (kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_PLAIN_JS) { //Case to handle plain-js OAuth flow. // Popup needs to be blocked for oauth2 type & redirect to the url "success_url" if provided in query params else the default one declared in the MF application. if (options && options["noPopup"]) { oauthOptions["noPopup"] = true } if (options && options[kony.sdk.constants.DEEPLINK_VALID_PARAM] && options["urlType"]) { //Validating the identity service once after deeplink is redirected. Params "code" & "urlType" are mandatory and are used to distinguish the request. loginForDeeplink(options); } else { oauthOptions["appSecret"] = mainRef.appSecret; oauthOptions["serviceDoc"] = mainRef.config; if (options && options["include_profile"]) { oauthOptions["include_profile"] = options["include_profile"] } OAuthHandler(_serviceUrl, _providerName, mainRef.appKey, loginHelper, _type, oauthOptions, isMFVersionCompatible); } } else { if (kony.sdk.util.hasBrowserWidget(options)) { //Case to handle OAuth for IDE oauthOptions[kony.sdk.constants.BROWSER_WIDGET] = options[kony.sdk.constants.BROWSER_WIDGET]; } else { //Default case if param browserWidget and UseDeviceBrowser not present. We create one browser widget and open the url in it. if (options && options["UseDeviceBrowser"]) { //Validating to check the existence of param "UseDeviceBrowser". // if found login url will be opened in device native broser, else in browser widget. oauthOptions["UseDeviceBrowser"] = options["UseDeviceBrowser"]; } if (options && options[kony.sdk.constants.OAUTH_REDIRECT_SUCCESS_URL]) { //Validating to check the existence of param "success_url". // if found after login success we will redirect to the url specified in param "success_url". var success_url = options[kony.sdk.constants.OAUTH_REDIRECT_SUCCESS_URL]; //Encoding is being done specifically for android because, in android kony.application.openUrl is not // opening the url without encoding where as in ios its encoding and opening. if (kony.sdk.getPlatformName() === kony.sdk.constants.PLATFORM_ANDROID) { //decoding and encoding, to handle the case where in the user himself is giving us the encoded value. success_url = encodeURIComponent(decodeURIComponent(options[kony.sdk.constants.OAUTH_REDIRECT_SUCCESS_URL])); } oauthOptions[kony.sdk.constants.OAUTH_REDIRECT_SUCCESS_URL] = success_url; } } if (options && kony.sdk.util.isValidString(options[kony.sdk.constants.IE11_CROSS_DOMAIN_OAUTH_BASE_URL])) { oauthOptions[kony.sdk.constants.IE11_CROSS_DOMAIN_OAUTH_BASE_URL] = options[kony.sdk.constants.IE11_CROSS_DOMAIN_OAUTH_BASE_URL]; } OAuthHandler(_serviceUrl, _providerName, mainRef.appKey, loginHelper, _type, oauthOptions, isMFVersionCompatible); } } } } }; /** * Tries to get persisted token from local store and update sdk. */ this.usePersistedLogin = function() { kony.sdk.logsdk.trace("Entering usePersistedLogin"); var stringifiedResponse = kony.sdk.offline.getUserAuthInformation("persistedAuthResponse"); if (stringifiedResponse && kony.sdk.isJson(stringifiedResponse)) { var persistedAuthResponse = JSON.parse(stringifiedResponse); // To support multilogin we are checking for the existence of provider name in profiles. if (persistedAuthResponse && persistedAuthResponse.profiles && persistedAuthResponse.profiles[_providerName]) { konyRef.isAnonymousProvider = false; processMultipleProvidersResponse(persistedAuthResponse, _providerName); return true; } } return false; }; var processMultipleProvidersResponse = function(data, providerName) { if (data && data.profiles) { konyRef.isAnonymousProvider = false; for (var provider in data.profiles) { if (!konyRef.tokens[provider]) { konyRef.tokens[provider] = {}; } konyRef.tokens[provider].profile = data.profiles[provider]; } } else if (data && providerName && data.profile) { konyRef.isAnonymousProvider = false; konyRef.tokens[providerName].profile = data.profile; } if (data && data.provider_tokens) { for (var provider in data.provider_tokens) { if (!konyRef.tokens[provider]) { konyRef.tokens[provider] = {}; } if (!konyRef.tokens[provider].provider_token) { konyRef.tokens[provider].provider_token = {} } konyRef.tokens[provider].provider_token.value = data.provider_tokens[provider]; } } if (data && providerName && data.provider_token) { konyRef.tokens[providerName].provider_token = data.provider_token; } konyRef.currentClaimToken = data.claims_token.value; konyRef.claimTokenExpiry = data.claims_token.exp; konyRef.currentRefreshToken = data.refresh_token; }; var processLoginSuccessResponse = function(data, konyRef, isAsync, callBack) { kony.sdk.logsdk.trace("Entering processLoginSuccessResponse"); data = kony.sdk.formatSuccessResponse(data); if (_type !== "anonymous" && !konyRef.tokens[_providerName]) { konyRef.tokens[_providerName] = {}; } kony.sdk.logsdk.info("### AuthService::login successful. Retrieved Data::"); processMultipleProvidersResponse(data, _providerName); kony.sdk.logsdk.info("### AuthService::login extracted token. Calling success callback"); if (kony.sdk.sso.isSSOEnabled === true) { if (data.sso_token) { var isSSOSaved = kony.sdk.util.saveSSOToken(data.sso_token); if (isSSOSaved === true) { kony.sdk.isSSOLoginSuccess = true; kony.sdk.logsdk.info("### SSOLoginService::SSOToken being saved successfully."); } else { kony.sdk.logsdk.info("### SSOLoginService::Failed to save SSOToken.This might result in failure of corresponding sso Logins. Please check the configuration params"); } } else { kony.sdk.logsdk.info("### SSOLoginService::Unable to fetch sso token."); } } if (data.profile && data.profile != undefined && data.profile.user_attributes != undefined) { user_attributes = data.profile.user_attributes; } if (data.profile) { kony.sdk.overrideUserId(data.profile.userid); } if (kony.sdk.getPlatformName() !== kony.sdk.constants.PLATFORM_WINDOWS && kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_IDE) { //We store the user credentials and the success auth response only on successful online login. if (kony.sdk.offline.isOfflineEnabled === true) { if (kony.sdk.isNetworkAvailable() && offlineEnabled && _type === "basic") { kony.sdk.offline.updateSuccessUserCredentials(_providerName); } kony.sdk.offline.saveUserAuthInformation("authResponse", data); } if (_type !== "anonymous") { if (persistToken || kony.sdk.offline.persistToken || kony.sdk.util.isPersistentLoginResponseEnabled()) { kony.sdk.offline.saveUserAuthInformation("persistedAuthResponse", data); } } } kony.logger.setClaimsToken(); if (!isAsync) { return {}; } else if (callBack) { kony.sdk.verifyAndCallClosure(callBack, {}); } }; var processLoginErrorResponse = function(data, konyRef, isAsync, callBack) { kony.sdk.logsdk.trace("Entering processLoginErrorResponse"); kony.sdk.logsdk.info("### AuthService::login Calling failure callback"); /*resetting all the token in case of error */ resetAllCurrentTokens(konyRef, _providerName); if (kony.sdk.sso.isSSOEnabled === true) { if (data.mfcode == "Auth-55") { kony.sdk.util.deleteSSOToken(); } kony.sdk.isSSOLoginSuccess = false; } if (!isAsync) { return kony.sdk.error.getAuthErrObj(data); } else if (callBack) { callBack(kony.sdk.error.getAuthErrObj(data)); } }; /** * Login anonymous with the given credentials synchronously and executes the given callback. * @param {object} options - User name and password */ this.anonymousLoginSync = function(options) { kony.sdk.logsdk.trace("Entering anonymousLoginSync"); konyRef.isAnonymousProvider = false; var reportingData = kony.sdk.getPayload(konyRef); var sessionId = null; if (kony.ds) { sessionId = kony.ds.read(kony.sdk.constants.KONYUUID); } if (sessionId) { reportingData.rsid = sessionId[0]; } reportingData.svcid = "login_" + _providerName; if (!reportingData.rsid) { kony.sdk.logsdk.warn("### anonymousLoginSync:: rsid is either empty,null or undefined"); } kony.sdk.logsdk.debug("### AuthService::login Invoked login for provider " + _providerName + " of type " + _type); if (typeof(options) == 'undefined') { throw new Exception(kony.sdk.errorConstants.AUTH_FAILURE, "Missing required number of arguments to login function"); } function invokeAjaxCall(url, params, headers) { if (!headers) { headers = {}; } headers[kony.sdk.constants.APP_KEY_HEADER] = mainRef.appKey; headers[kony.sdk.constants.APP_SECRET_HEADER] = mainRef.appSecret; headers[kony.sdk.constants.HTTP_REQUEST_HEADER_ACCEPT] = kony.sdk.constants.CONTENT_TYPE_JSON; if (konyRef.reportingheaders_allowed) { if (reportingData != null && reportingData != undefined) { try { headers[kony.sdk.constants.REPORTING_HEADER] = encodeURI(JSON.stringify(reportingData)) } catch (error) { kony.sdk.logsdk.error("### anonymousLoginSync::error while parsing metrics payload" + error); } } } var endPointUrl = null; if (_type === "anonymous") { endPointUrl = _serviceUrl + url; } else { endPointUrl = _serviceUrl + url + "?provider=" + _providerName; params["provider"] = _providerName; } var data = networkProvider.postSync(endPointUrl, params, headers); if (data.opstatus == 0) { return processLoginSuccessResponse(data, konyRef, false); } else { return processLoginErrorResponse(data, konyRef, false); } } konyRef.isAnonymousProvider = true; kony.sdk.logsdk.info("### AuthService::login Adapter type is anonymous"); var headers = {}; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; return invokeAjaxCall("/login", {}, headers); }; /** * Logout and executes the given callback. * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure * @param {object} options - additional options for logout */ this.logout = function(successCallback, failureCallback, options) { kony.sdk.logsdk.trace("Entering logout"); function logoutHandler() { _logout(successCallback, failureCallback, options); } if (kony.sdk.getPlatformName() !== kony.sdk.constants.PLATFORM_WINDOWS) { //if the user logged in using offline logout if (offlineEnabled == true && kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_IDE && _type === "basic" && !kony.sdk.isNetworkAvailable()) { logoutHandler(); } else { kony.sdk.claimsRefresh(logoutHandler, failureCallback); } } else { kony.sdk.claimsRefresh(logoutHandler, failureCallback); } }; function _logout(successCallback, failureCallback, options) { function invokeLogoutHelper(formData, invokeLogoutSuccess, invokeLogoutFailure) { var claimsTokenValue = null; var reportingData = kony.sdk.getPayload(konyRef); var sessionId = null; if (kony.ds) { sessionId = kony.ds.read(kony.sdk.constants.KONYUUID); } if (sessionId) { reportingData.rsid = sessionId[0]; } reportingData.svcid = "logout_" + _providerName; if (!reportingData.rsid) { kony.sdk.logsdk.warn("### _logout:: rsid is either empty,null or undefined"); } if (!kony.sdk.isNullOrUndefined(konyRef.currentClaimToken)) { claimsTokenValue = konyRef.currentClaimToken; } formdata.provider = _providerName; var url = ""; if (_type == "oauth2" && kony.sdk.getSdkType() == kony.sdk.constants.SDK_TYPE_IDE) { url = _serviceUrl + "/oauth2/logout?provider=" + _providerName; } else { url = _serviceUrl + "/logout?provider=" + _providerName; } var headers = {}; headers[kony.sdk.constants.KONY_AUTHORIZATION_HEADER] = claimsTokenValue; headers[kony.sdk.constants.HTTP_REQUEST_HEADER_ACCEPT] = "*/*"; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; if (konyRef.reportingheaders_allowed) { if (reportingData != null && reportingData != undefined) { try { headers[kony.sdk.constants.REPORTING_HEADER] = encodeURI(JSON.stringify(reportingData)) } catch (error) { kony.sdk.logsdk.error("### login::error while parsing metrics payload" + error); } } } populateHeaderWithFabricAppVersion(headers); networkProvider.post(url, formdata, headers, function(data) { kony.sdk.logsdk.info("AuthService::logout successfully logged out. Calling success callback"); function serviceDocCallback() { logoutSuccess(data); return; } getLatestServiceDocIfAvailable(data, serviceDocCallback); }, function(err) { kony.sdk.logsdk.error("### AuthService::logout logged out Failed. Calling failure callback"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getAuthErrObj(err)); }); } function logoutSuccess(data) { kony.sdk.logsdk.trace("Entering logoutSuccess"); data = kony.sdk.formatSuccessResponse(data); delete konyRef.tokens[_providerName]; //reset all current keys kony.sdk.resetCurrentKeys(konyRef, _providerName); //processing multiple profiles if (data && data.claims_token) { processMultipleProvidersResponse(data); konyRef.isAnonymousProvider = false; } if (offlineEnabled) { kony.sdk.offline.isOfflineEnabled = false; kony.sdk.offline.removeUserAuthInformation(); kony.sdk.offline.removeUserCredentials(_providerName); } if (persistToken || kony.sdk.offline.persistToken || kony.sdk.util.isPersistentLoginResponseEnabled()) { kony.sdk.offline.removePersistedUserAuthInformation(); persistToken = false; kony.sdk.offline.persistToken = false; dataStore.setItem("persistLoginResponseFlag", false); } if (slo === true) { kony.sdk.util.deleteSSOToken(); } kony.sdk.verifyAndCallClosure(successCallback, {}); } kony.sdk.logsdk.debug("### AuthService::logout invoked on provider " + _providerName + " of type " + _type); var slo = false; if (!kony.sdk.isNullOrUndefined(options) && (options["slo"] === true || options["slo"] === false)) { slo = options["slo"]; } var formdata = {}; formdata = { "slo": slo }; if (!isLoggedIn()) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getIdentitySessionInactiveErrObj()); } else if (_type == "oauth2" && kony.sdk.getSdkType() == kony.sdk.constants.SDK_TYPE_IDE) { var callback_invoke = true; var oauth_status; function oAuthCallback(status) { oauth_status = status; //Workaround to get around redirects if (callback_invoke) { callback_invoke = false; kony.timer.schedule("oAuthCallbackHandle", function() { if (oauth_status) invokeLogoutHelper(formdata, logoutSuccess, failureCallback); else kony.sdk.verifyAndCallClosure(failureCallback, {}); }, 3, false); } } var oauthOptions = {}; oauthOptions["logout"] = true; oauthOptions["slo"] = slo; if (kony.sdk.util.hasBrowserWidget(options)) { oauthOptions[kony.sdk.constants.BROWSER_WIDGET] = options[kony.sdk.constants.BROWSER_WIDGET]; } OAuthHandler(_serviceUrl, _providerName, mainRef.appKey, oAuthCallback, _type, oauthOptions); } else { if (kony.sdk.getPlatformName() !== kony.sdk.constants.PLATFORM_WINDOWS) { //if the user logged in using offline login if (kony.sdk.offline.isOfflineEnabled == true && kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_IDE && _type === "basic" && !kony.sdk.isNetworkAvailable()) { kony.sdk.logsdk.info("AuthService::offline logout successfully logged out. Calling success callback"); logoutSuccess(); return; } } invokeLogoutHelper(formdata, logoutSuccess, failureCallback); } } /** * Fetch the backend datasource token. * @param {boolean} fromserver - Flag to force fetch from server only. * @param {object} options - Options * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure */ this.getBackendToken = function(fromserver, options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering getBackendToken"); function _claimsRefreshSuccess(token) { kony.sdk.logsdk.trace("Entering _claimsRefreshSuccess with valid token"); processMultipleProvidersResponse(token); //konyRef.currentBackEndToken = token.provider_token; //if offline login enabled then updating the backend token in the store if (kony.sdk.getPlatformName() !== kony.sdk.constants.PLATFORM_WINDOWS && kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_IDE) { if (kony.sdk.offline.isOfflineEnabled && kony.sdk.offline.isOfflineEnabled == true) { kony.sdk.offline.updateAuthToken(token); } if (persistToken || kony.sdk.offline.persistToken || kony.sdk.util.isPersistentLoginResponseEnabled()) { kony.sdk.offline.updatePersistedToken("persistedAuthResponse", token); } } kony.sdk.verifyAndCallClosure(successCallback, konyRef.tokens[_providerName].provider_token); } function _claimsRefreshFailure(error) { kony.sdk.logsdk.trace("Entering _claimsRefreshFailure"); kony.sdk.logsdk.info("### AuthService::getBackendToken fetching refresh failed. Calling failure callback"); // konyRef.tokens[_providerName] = null; // konyRef.currentBackEndToken = null; kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getAuthErrObj(error)); } kony.sdk.logsdk.debug("### AuthService::getBackendToken called for provider " + _providerName + " of type " + _type); if (!isLoggedIn()) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getIdentitySessionInactiveErrObj()); } var claimsOptions = null; if (options && options.refresh && options.refresh === true) { claimsOptions = { "requestParams": { "refresh": "true" } }; } if (fromserver != undefined && fromserver === true) { kony.sdk.logsdk.info("### AuthService::getBackendToken fromserver is enabled. Trying to login"); _claimsRefresh(claimsOptions, _claimsRefreshSuccess, _claimsRefreshFailure); } else { if (konyRef.tokens[_providerName]) { var val = konyRef.tokens[_providerName]; var _exp = val.provider_token.exp; kony.sdk.logsdk.debug("token expiry time: " + _exp); kony.sdk.logsdk.debug("Current time: " + (new Date().getTime())); if (_exp && _exp < (new Date().getTime())) { kony.sdk.logsdk.info("### AuthService::getBackendToken Token expired. Fetching refresh from claims api"); _claimsRefresh(claimsOptions, _claimsRefreshSuccess, _claimsRefreshFailure); } else { kony.sdk.logsdk.info("### AuthService::getBackendToken present token is valid/doesn't have expiry time. Calling success callback"); //konyRef.currentBackEndToken = val.provider_token; kony.sdk.verifyAndCallClosure(successCallback, konyRef.tokens[_providerName].provider_token); } } else { kony.sdk.logsdk.info("### AuthService::getBackendToken failed for find info for key " + dsKey + "in database. calling failure callback"); kony.sdk.verifyAndCallClosure(failureCallback, null); } } }; /** * Get profile. * @param {boolean} fromserver - Flag to force fetch from server only. * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure */ this.getProfile = function(fromserver, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering getProfile"); if (!isLoggedIn()) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getIdentitySessionInactiveErrObj()); } else if (fromserver && fromserver == true) { profileRefresh(function(token) { konyRef.tokens[_providerName].profile = token; kony.sdk.verifyAndCallClosure(successCallback, token); }, failureCallback) } else { if (konyRef.tokens[_providerName]) { var val = konyRef.tokens[_providerName]; kony.sdk.verifyAndCallClosure(successCallback, val.profile); } else { kony.sdk.verifyAndCallClosure(failureCallback, null); } } }; /** * Get the provider name. * @returns {string} Provider name. */ this.getProviderName = function() { return _providerName; }; /** * Get the provider type. * @returns {string} Provider type. */ this.getProviderType = function() { return _type; }; /** * Get the generic session data type. * @returns {string} session data. */ this.getUserData = function(successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering getUserData (Get the generic session data type)"); if (!isLoggedIn()) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getIdentitySessionInactiveErrObj()); } else { var userDataUrl = _serviceUrl + "/session/user_data"; var options = {}; options["invokedFrom"] = kony.sdk.constants.GET_USER_DATA; getSessionData(userDataUrl, successCallback, failureCallback, options); } }; /** * Get the user attributes returned by a provider * @returns {string} user attributes. */ this.getUserAttributes = function(successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering getUserAttributes"); if (!isLoggedIn()) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getIdentitySessionInactiveErrObj()); } else if (user_attributes && Object.keys(user_attributes).length === 0) { var userAttributesUrl = _serviceUrl + "/session/user_attributes?provider=" + _providerName; var options = {}; options["invokedFrom"] = kony.sdk.constants.GET_USER_ATTRIBUTES; getSessionData(userAttributesUrl, function(res) { user_attributes = res; kony.sdk.verifyAndCallClosure(successCallback, user_attributes); }, failureCallback, options); } else { if (konyRef.currentClaimToken === null) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getNullClaimsTokenErrObj()); } else { kony.sdk.verifyAndCallClosure(successCallback, user_attributes); } } }; /** * Get the security attributes returned by a provider * @returns {string} security attributes. */ this.getSecurityAttributes = function(successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering getSecurityAttributes"); if (!isLoggedIn()) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getIdentitySessionInactiveErrObj()); } else { var securityAttributesUrl = _serviceUrl + "/session/security_attributes?provider=" + _providerName; var options = {}; options["invokedFrom"] = kony.sdk.constants.GET_SECURITY_ATTRIBUTES; getSessionData(securityAttributesUrl, successCallback, failureCallback, options); } }; /** utility method to get session data @private */ var getSessionData = function(sessionAttributesEndPointUrl, successCallback, failureCallback, options) { var reportingData = kony.sdk.getPayload(konyRef); var sessionId = null; if (kony.ds) { sessionId = kony.ds.read(kony.sdk.constants.KONYUUID); } if (sessionId) { reportingData.rsid = sessionId[0]; } if (options["invokedFrom"] == kony.sdk.constants.GET_USER_ATTRIBUTES) { reportingData.svcid = kony.sdk.constants.GET_USER_ATTRIBUTES; } else if (options["invokedFrom"] == kony.sdk.constants.GET_SECURITY_ATTRIBUTES) { reportingData.svcid = kony.sdk.constants.GET_SECURITY_ATTRIBUTES; } else { reportingData.svcid = kony.sdk.constants.GET_USER_DATA; } if (!reportingData.rsid) { kony.sdk.logsdk.warn("### getsessiondata:: rsid is either empty,null or undefined"); } if (konyRef.currentClaimToken === null) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getNullClaimsTokenErrObj()); } else { var headers = {}; headers[kony.sdk.constants.AUTHORIZATION_HEADER] = konyRef.currentClaimToken; if (konyRef.reportingheaders_allowed) { if (reportingData != null && reportingData != undefined) { try { headers[kony.sdk.constants.REPORTING_HEADER] = encodeURI(JSON.stringify(reportingData)) } catch (error) { kony.sdk.logsdk.error("### getSessionData::error while parsing metrics payload" + error); } } } populateHeaderWithFabricAppVersion(headers); networkProvider.get(sessionAttributesEndPointUrl, {}, headers, function(data) { data = kony.sdk.formatSuccessResponse(data); kony.sdk.verifyAndCallClosure(successCallback, data); }, function(err) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getAuthErrObj(err)); }); } }; /** * Method to refresh the claims token. * @private */ var _claimsRefresh = function(options, success, failure) { kony.sdk.logsdk.debug("### AuthService::_claimsRefresh fetching claims from server for provider " + _providerName); var refreshToken = null; var reportingData = kony.sdk.getPayload(konyRef); var sessionId = null; if (kony.ds) { sessionId = kony.ds.read(kony.sdk.constants.KONYUUID); } if (sessionId) { reportingData.rsid = sessionId[0]; } reportingData.svcid = kony.sdk.constants.GET_BACKEND_TOKEN; if (!reportingData.rsid) { kony.sdk.logsdk.warn("### _claimsRefresh:: rsid is either empty,null or undefined"); } if (!kony.sdk.isNullOrUndefined(konyRef.currentRefreshToken)) { refreshToken = konyRef.currentRefreshToken; } var _url = _serviceUrl + "/claims"; if (options && options.requestParams != null) { _url = _url + "?"; for (var i in options.requestParams) { if (options.requestParams.hasOwnProperty(i) && typeof(i) !== 'function') { _url = _url + (i + "=" + options.requestParams[i] + "&"); } } _url = stripTrailingCharacter(_url, "&"); } if (refreshToken) { kony.sdk.logsdk.info("### AuthService::_claimsRefresh making POST request to claims endpoint"); var headers = {}; headers[kony.sdk.constants.AUTHORIZATION_HEADER] = refreshToken; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; if (konyRef.reportingheaders_allowed) { if (reportingData != null && reportingData != undefined) { try { headers[kony.sdk.constants.REPORTING_HEADER] = encodeURI(JSON.stringify(reportingData)) } catch (error) { kony.sdk.logsdk.error("### _claimsRefresh::error while parsing metrics payload" + error); } } } populateHeaderWithFabricAppVersion(headers); networkProvider.post(_url, {}, headers, function(data) { data = kony.sdk.formatSuccessResponse(data); kony.sdk.logsdk.info("### AuthService::_claimsRefresh Fetching claims succcessfull"); processMultipleProvidersResponse(data); kony.sdk.logsdk.info("### AuthService::_claimsRefresh saved locally. Calling success callback"); kony.sdk.verifyAndCallClosure(success, data); }, function(xhr, status, err) { kony.sdk.logsdk.error("### AuthService::_claimsRefresh fetching claims failed. Calling failure callback"); kony.sdk.verifyAndCallClosure(failure, kony.sdk.error.getAuthErrObj(err)); }); } else { kony.sdk.logsdk.info("### AuthService::_claimsRefresh no refreshtoken found. calling failure callback"); kony.sdk.verifyAndCallClosure(failure, kony.sdk.error.getNullRefreshTokenErrObj()); } }; var profileRefresh = function(success, failure) { kony.sdk.logsdk.trace("Entering profileRefresh"); kony.sdk.logsdk.debug("### AuthService::profileRefresh fetching profile from server for provider " + _providerName); var reportingData = kony.sdk.getPayload(konyRef); var sessionId = null; if (kony.ds) { sessionId = kony.ds.read(kony.sdk.constants.KONYUUID); } if (sessionId) { reportingData.rsid = sessionId[0]; } reportingData.svcid = kony.sdk.constants.GET_PROFILE; if (!reportingData.rsid) { kony.sdk.logsdk.warn("### profileRefresh:: rsid is either empty,null or undefined"); } var refreshToken = null; if (!kony.sdk.isNullOrUndefined(konyRef.currentRefreshToken)) { refreshToken = konyRef.currentRefreshToken; } var _url = _serviceUrl + "/profile?provider=" + _providerName; if (refreshToken) { kony.sdk.logsdk.info("### AuthService::profileRefresh making POST request to profile endpoint"); var headers = {}; headers[kony.sdk.constants.AUTHORIZATION_HEADER] = refreshToken; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; if (konyRef.reportingheaders_allowed) { if (reportingData != null && reportingData != undefined) { try { headers[kony.sdk.constants.REPORTING_HEADER] = encodeURI(JSON.stringify(reportingData)) } catch (error) { kony.sdk.logsdk.error("### profileRefresh::error while parsing metrics payload" + error); } } } populateHeaderWithFabricAppVersion(headers); networkProvider.get(_url, null, headers, function(data) { data = kony.sdk.formatSuccessResponse(data); konyRef.tokens[_providerName].profile = data; kony.sdk.logsdk.info("### AuthService::profileRefresh Fetching profile succcessfull, Calling success callback"); kony.sdk.verifyAndCallClosure(success, data); }, function(xhr, status, err) { kony.sdk.logsdk.error("### AuthService::profileRefresh fetching profile failed. Calling failure callback"); kony.sdk.verifyAndCallClosure(failure, kony.sdk.error.getAuthErrObj(err)); }); } else { kony.sdk.logsdk.info("### AuthService::profileRefresh no refreshtoken found. calling failure callback"); kony.sdk.verifyAndCallClosure(failure, kony.sdk.error.getNullRefreshTokenErrObj()); } }; } function konySdkLogger() { this.INDIRECTIONLEVEL = 1; this.trace = function(msg, params) { this.getInstance().trace(msg, params); }; this.debug = function(msg, params) { this.getInstance().debug(msg, params); }; this.info = function(msg, params) { this.getInstance().info(msg, params); }; this.perf = function(msg, params) { this.getInstance().perf(msg, params); }; this.warn = function(msg, params) { this.getInstance().warn(msg, params); }; this.error = function(msg, params) { this.getInstance().error(msg, params); }; this.fatal = function(msg, params) { this.getInstance().fatal(msg, params); }; this.loggerEngineInit = function() { KonySDKLoggerObj = kony.logger.createNewLogger(kony.sdk.constants.LOGGER_NAME, null); KonySDKLoggerObj.setIndirectionLevel = this.INDIRECTIONLEVEL; }; this.getInstance = function() { if (typeof(KonySDKLoggerObj) === 'undefined') this.loggerEngineInit(); return KonySDKLoggerObj; } } /** * Method to create the logic service instance with the provided service name. * @param {string} serviceName - Name of the service * @returns The url to connect to the logic service * @throws Exception if the serviceName or access is invalid. */ kony.sdk.prototype.getLogicService = function(serviceName) { if (!kony.sdk.isInitialized) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, kony.sdk.constants.INIT_FAILURE_MESSAGE + " Logic service - " + serviceName); } if (this.logicsvc != null) { if (this.logicsvc[serviceName] != null) { kony.sdk.logsdk.debug("### getLogicService::found Logic service" + this.logicsvc[serviceName]); return new kony.sdk.LogicService(this, serviceName); } } throw new Exception(kony.sdk.errorConstants.LOGIC_SERVICE_FAILURE, "Invalid serviceName:" + serviceName); }; kony.sdk.LogicService = function(konyRef, serviceName) { this.konyRef = konyRef; this.serviceName = serviceName; this.logicServiceUrl = null; this.getLogicServiceUrl = function() { if (this.logicServiceUrl == null) { this.logicServiceUrl = stripTrailingCharacter(konyRef.logicsvc[serviceName], "/"); } return this.logicServiceUrl; }; kony.sdk.logsdk.info(" ###LogicService Created & LogicService Url = " + this.getLogicServiceUrl()); var networkProvider = new konyNetworkProvider(); this.invokeOperation = function(serviceName, path, methodType, headers, data, successCallback, failureCallback, options) { function invokeOperationHandler() { _invokeOperation(serviceName, path, methodType, headers, data, true, successCallback, failureCallback, options); } kony.sdk.claimsRefresh(invokeOperationHandler, failureCallback); }; function invokeOperationRetry(serviceName, path, methodType, headers, data, successCallback, failureCallback, options) { function invokeOperationRetryHandler() { _invokeOperation(serviceName, path, methodType, headers, data, false, successCallback, failureCallback, options); } kony.sdk.claimsAndProviderTokenRefresh(invokeOperationRetryHandler, failureCallback); } function retryServiceCall(errorResponse) { if (errorResponse[kony.sdk.constants.MF_CODE]) { // check for the mf code for which, // retry should be done. } else { if (errorResponse[kony.sdk.constants.HTTP_STATUS_CODE] && errorResponse[kony.sdk.constants.HTTP_STATUS_CODE] === 401) { return true; } } } function _invokeOperation(serviceName, path, methodType, headers, data, isRetryNeeded, successCallback, failureCallback, options) { var requestData = {}; kony.sdk.logsdk.trace("Entered into _invokeOperation servicePath: " + serviceName + ", methodType: " + methodType + ", path" + path + ", isRetryNeeded: " + isRetryNeeded); var reportingData = kony.sdk.getPayload(konyRef); var sessionId = kony.ds.read(kony.sdk.constants.KONYUUID); if (sessionId) { reportingData.rsid = sessionId[0]; } if (!reportingData.rsid) { kony.sdk.logsdk.warn("rsid is either empty,null or undefined"); } if (kony.sdk.metric) { if (kony.sdk.metric.reportEventBufferBackupArray.length === 0) { kony.sdk.metric.readFromDS(); } kony.sdk.metric.pushEventsToBufferArray(); requestData.events = kony.sdk.metric.reportEventBufferBackupArray; } for (var key in data) { requestData[key] = data[key]; } reportingData.svcid = serviceName; requestData[kony.sdk.constants.REPORTING_PARAMS] = JSON.stringify(reportingData); var defaultHeaders = {}; defaultHeaders[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; defaultHeaders[kony.sdk.constants.KONY_AUTHORIZATION_HEADER] = konyRef.currentClaimToken; if (typeof(svcObj) === 'object' && svcObj.version) { defaultHeaders[kony.sdk.constants.API_VERSION_HEADER] = svcObj.version; } // if the user has defined his own headers, use them if (headers) { for (var header in headers) { defaultHeaders[header] = headers[header]; } } function networkSuccessCallback(response) { if (kony.sdk.metric) { kony.sdk.metric.clearBufferEvents(); } kony.sdk.verifyAndCallClosure(successCallback, response); } function networkFailureCallback(xhr, status, err) { if (isRetryNeeded === true && retryServiceCall(xhr) === true) { invokeOperationRetry(serviceName, path, methodType, headers, data, successCallback, failureCallback, options); return; } kony.sdk.processLogicErrorResponse(xhr, true, failureCallback); } switch (methodType) { case "GET": networkProvider.get(konyRef.logicsvc[serviceName] + path, requestData, defaultHeaders, networkSuccessCallback, networkFailureCallback, null, options); break; case "PUT": networkProvider.put(konyRef.logicsvc[serviceName] + path, requestData, defaultHeaders, networkSuccessCallback, networkFailureCallback, null, options); break; case "DELETE": networkProvider.invokeDeleteRequest(konyRef.logicsvc[serviceName] + path, requestData, defaultHeaders, networkSuccessCallback, networkFailureCallback, null, options); break; default: networkProvider.post(konyRef.logicsvc[serviceName] + path, requestData, defaultHeaders, networkSuccessCallback, networkFailureCallback, null, options); break; } } kony.sdk.processLogicErrorResponse = function(err, isAsync, callBack) { if (kony.sdk.metric) { if (kony.sdk.metric.errorCodeMap[err.opstatus]) { kony.sdk.metric.saveInDS(); } } if (err[kony.sdk.constants.MF_CODE]) { var konyRef = kony.sdk.getCurrentInstance(); //clear the cache if the error code related to session/token expiry if (kony.sdk.isSessionOrTokenExpired(err[kony.sdk.constants.MF_CODE])) { kony.sdk.logsdk.warn("###LogicService::invokeOperationFailure Session/Token expired. Authenticate and Try again"); //kony.sdk.resetCacheKeys(konyRef); } } if (!isAsync) { return kony.sdk.error.getLogicErrObj(err); } else if (callBack) { kony.sdk.verifyAndCallClosure(callBack, kony.sdk.error.getLogicErrObj(err)); } }; }; kony.sdk.prototype.registerObjectService = function(objectServiceType, objectServiceClass) { kony.sdk.logsdk.trace("Entering kony.sdk.prototype.registerObjectService"); kony.sdk.registeredobjsvcs = kony.sdk.registeredobjsvcs || {}; kony.sdk.registeredobjsvcs[objectServiceType] = objectServiceClass; }; /** * Method to create the object service instance with the provided service name. * @param {string} serviceName - Name of the service * @param {map} options - Map of key values like {"access":"offline"/"online"/"registered Object Service Name"} * @returns {@link kony.sdk.OnlineObjectService / @link kony.sdk.OfflineObjectService} Object service instance * @throws Exception if the serviceName or access is invalid. */ kony.sdk.prototype.getObjectService = function(serviceName, options) { kony.sdk.logsdk.trace("Entering kony.sdk.prototype.getObjectService"); if (!kony.sdk.isInitialized) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, kony.sdk.constants.INIT_FAILURE_MESSAGE + " Object service - " + serviceName); } var access; if (!kony.sdk.isNullOrUndefined(options)) { access = options["access"]; } if (this.objectsvc != null && this.objectsvc[serviceName] != null) { kony.sdk.logsdk.debug("### getObjectService::found Object service" + this.objectsvc[serviceName]); if (kony.sdk.util.isNullOrEmptyString(access) || access.toLowerCase() === "online") { return new kony.sdk.OnlineObjectService(this, serviceName, this.objectsvc[serviceName]); } else if (access.toLowerCase() === "offline") { //This returns SyncV1 object service return new kony.sdk.OfflineObjectService(this, serviceName); } } else if (this.offlineObjectsvc != null) { if (this.offlineObjectsvc[serviceName] != null) { if (kony.sdk.util.isNullOrEmptyString(access) || access.toLowerCase() === "online") { // This returns Online Object Service Instance return new kony.sdk.OnlineObjectService(this, serviceName, this.offlineObjectsvc[serviceName]); } else if (access.toLowerCase() === "offline") { //This returns Offline Enabled or SyncV2 object service return new kony.sdk.OfflineEnabledObjectService(this, serviceName); } } } kony.sdk.registeredobjsvcs = kony.sdk.registeredobjsvcs || {}; //verifying if the servicetype available in registeredservices if available initialize and return if (kony.sdk.registeredobjsvcs[access] != null && kony.sdk.registeredobjsvcs[access] != undefined) { return new kony.sdk.registeredobjsvcs[access](this, serviceName); } throw new Exception(kony.sdk.errorConstants.OBJECT_FAILURE, "Invalid serviceName:" + serviceName + "or access type:" + access); }; /** * Method which returns the online ObjectService object * @param konyRef * @param serviceName * @constructor */ kony.sdk.OnlineObjectService = function(konyRef, serviceName, serviceInfo) { kony.sdk.logsdk.trace("Entering kony.sdk.OnlineObjectService"); this.konyRef = konyRef; this.serviceName = serviceName; this.serviceInfo = serviceInfo; this.dataUrl = null; this.binaryUrl = null; this.operationsUrl = null; this.metadataUrl = null; this.version = null; var currentObject = this; /** * This method is used to create a record on the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject),"headers":<map of http headers>} * @param successCallback * @param failureCallback */ this.create = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OnlineObjectService.create"); if (options == null || options == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } if (!(options["dataObject"] instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } if (!(options["queryParams"] == null || options["queryParams"] == undefined)) { if (!(options["queryParams"] instanceof Object)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_queryparams_instance, kony.sdk.errormessages.invalid_queryparams_instance)); } } var tmpDataUrl = this.getDataUrl(); var objName = options["dataObject"].objectName; function createOperationHandler() { currentObject.getMetadataOfObject(objName, {}, function(result) { _create(options, tmpDataUrl, successCallback, failureCallback); }, function(error) { kony.sdk.logsdk.error("### OnlineObjectService::create Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); }); } if (kony.sdk.skipAnonymousCall) { createOperationHandler(); } else { kony.sdk.claimsRefresh(createOperationHandler, failureCallback); } }; /** * This method is used to fetch a record on the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject),"headers":<map of http headers>} * @param successCallback * @param failureCallback */ this.fetch = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OnlineObjectService.fetch"); if (options == null || options == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } if (!(options["dataObject"] instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } if (!(options["queryParams"] == null || options["queryParams"] == undefined)) { if (!(options["queryParams"] instanceof Object)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_queryparams_instance, kony.sdk.errormessages.invalid_queryparams_instance)); } } var tmpDataUrl = this.getDataUrl(); var objName = options["dataObject"].objectName; function fetchOperationHandler() { currentObject.getMetadataOfObject(objName, {}, function(result) { _fetch(options, tmpDataUrl, successCallback, failureCallback); }, function(error) { kony.sdk.logsdk.error("### OnlineObjectService::fetch Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); }); } if (kony.sdk.skipAnonymousCall) { fetchOperationHandler(); } else { kony.sdk.claimsRefresh(fetchOperationHandler, failureCallback); } }; /** * This method is used to update a record on the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject),"headers":<map of http headers>} * @param successCallback * @param failureCallback */ this.update = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OnlineObjectService.update"); if (options == null || options == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } if (!(options["dataObject"] instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } if (!(options["queryParams"] == null || options["queryParams"] == undefined)) { if (!(options["queryParams"] instanceof Object)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_queryparams_instance, kony.sdk.errormessages.invalid_queryparams_instance)); return; } } var tmpDataUrl = this.getDataUrl(); var objName = options["dataObject"].objectName; function updateOperationHandler() { currentObject.getMetadataOfObject(objName, {}, function(result) { _update(options, tmpDataUrl, successCallback, failureCallback); }, function(error) { kony.sdk.logsdk.error("### OnlineObjectService::update Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); }); } if (kony.sdk.skipAnonymousCall) { updateOperationHandler(); } else { kony.sdk.claimsRefresh(updateOperationHandler, failureCallback); } }; /** * This method is used to partial update a record on the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject),"headers":<map of http headers>} * @param successCallback * @param failureCallback */ this.partialUpdate = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OnlineObjectService.partialUpdate"); if (options == null || options == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } if (!(options["dataObject"] instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } if (!(options["queryParams"] == null || options["queryParams"] == undefined)) { if (!(options["queryParams"] instanceof Object)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_queryparams_instance, kony.sdk.errormessages.invalid_queryparams_instance)); return; } } var tmpDataUrl = this.getDataUrl(); var objName = options["dataObject"].objectName; function partialUpdateOperationHandler() { currentObject.getMetadataOfObject(objName, {}, function(result) { _partialUpdate(options, tmpDataUrl, successCallback, failureCallback); }, function(error) { kony.sdk.logsdk.error("### OnlineObjectService::partialUpdate Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); }); } if (kony.sdk.skipAnonymousCall) { partialUpdateOperationHandler(); } else { kony.sdk.claimsRefresh(partialUpdateOperationHandler, failureCallback); } }; /** * This method is used to delete a record on the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject),"headers":<map of http headers>} * @param successCallback * @param failureCallback */ this.deleteRecord = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OnlineObjectService.deleteRecord"); if (options == null || options == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } if (!(options["dataObject"] instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } if (!(options["queryParams"] == null || options["queryParams"] == undefined)) { if (!(options["queryParams"] instanceof Object)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_queryparams_instance, kony.sdk.errormessages.invalid_queryparams_instance)); return; } } var tmpDataUrl = this.getDataUrl(); var objName = options["dataObject"].objectName; function deleteOperationHandler() { currentObject.getMetadataOfObject(objName, {}, function(result) { _deleteRecord(options, tmpDataUrl, successCallback, failureCallback); }, function(error) { kony.sdk.logsdk.error("### OnlineObjectService::delete Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); }); } if (kony.sdk.skipAnonymousCall) { deleteOperationHandler(); } else { kony.sdk.claimsRefresh(deleteOperationHandler, failureCallback); } }; /** * This method is used to for performing custom operation * @param {string} verbName - custom verb identifier * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject),"headers":<map of http headers>} * @param successCallback * @param failureCallback */ this.customVerb = function(verbName, options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OnlineObjectService.customVerb"); if (verbName == null || verbName == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "verbName" + kony.sdk.errormessages.null_or_undefined)); return; } if (options == null || options == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } if (!(options["dataObject"] instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } if (!(options["queryParams"] == null || options["queryParams"] == undefined)) { if (!(options["queryParams"] instanceof Object)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_queryparams_instance, kony.sdk.errormessages.invalid_queryparams_instance)); return; } } var tmpDataUrl = this.getOperationsUrl(); var objName = options["dataObject"].objectName; function customVerbHandler() { currentObject.getMetadataOfObject(objName, {}, function(result) { _customverb(verbName, options, tmpDataUrl, successCallback, failureCallback); }, function(error) { kony.sdk.logsdk.error("### OnlineObjectService::customverb Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); }); } if (kony.sdk.skipAnonymousCall) { customVerbHandler(); } else { kony.sdk.claimsRefresh(customVerbHandler, failureCallback); } }; /** * This method is used to retrive metadata of all objects * @param {map} options - includes {"getFromServer":boolean,"headers":<map of http headers>} * @param successCallback * @param failureCallback */ this.getMetadataOfAllObjects = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OnlineObjectService.getMetadataOfAllObjects"); _getMetadataForObjectsOrServiceOnlineUtil(konyRef, serviceName, null, options, successCallback, failureCallback); kony.sdk.logsdk.trace("Exiting kony.sdk.OnlineObjectService.getMetadataOfAllObjects"); }; /** * This method is used to retrive metadata of a specific object * @param objectName * @param {map} options - includes {"getFromServer":boolean,"headers":<map of http headers>} * @param successCallback * @param failureCallback */ this.getMetadataOfObject = function(objectName, options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OnlineObjectService.getMetadataOfObject"); _getMetadataForObjectsOrServiceOnlineUtil(konyRef, serviceName, objectName, options, successCallback, failureCallback); kony.sdk.logsdk.trace("Exiting kony.sdk.OnlineObjectService.getMetadataOfObject"); }; this.getDataUrl = function() { if (kony.sdk.isNullOrUndefined(currentObject.dataUrl)) { currentObject.dataUrl = encodeURI(stripTrailingCharacter(currentObject.serviceInfo["url"] + "/objects/", "/")); } return currentObject.dataUrl; }; this.getBinaryUrl = function() { if (kony.sdk.isNullOrUndefined(currentObject.binaryUrl)) { currentObject.binaryUrl = encodeURI(stripTrailingCharacter(currentObject.serviceInfo["url"] + "/binary/", "/")); } return currentObject.binaryUrl; }; this.getOperationsUrl = function() { if (kony.sdk.isNullOrUndefined(currentObject.operationsUrl)) { currentObject.operationsUrl = encodeURI(stripTrailingCharacter(currentObject.serviceInfo["url"] + "/operations/", "/")); } return currentObject.operationsUrl; }; this.getMetadataUrl = function() { if (kony.sdk.isNullOrUndefined(currentObject.metadataUrl)) { currentObject.metadataUrl = encodeURI(stripTrailingCharacter(currentObject.serviceInfo["metadata_url"], "/")); } return currentObject.metadataUrl; }; this.getVersion = function() { if (kony.sdk.isNullOrUndefined(currentObject.version)) { currentObject.version = currentObject.serviceInfo["version"]; } return currentObject.version; }; /* * API for uploading binary data (either file or raw bytes) to backend */ this.uploadBinaryData = function(options, onFileUploadStartedCallback, onChunkUploadCompletedCallback, onFileUploadCompletedCallback, onFileUploadFailureCallback) { var fileUploadStartedCallback = null; var chunkUploadCompletedCallback = null; var fileUploadCompletedCallback = null; var fileUploadFailureCallback = null; var uploadParams = null; /* validations for callbacks */ // validation for onFileUploadStartedCallback if (kony.sdk.isNullOrUndefined(onFileUploadStartedCallback) || (typeof(onFileUploadStartedCallback) !== 'function')) { kony.sdk.logsdk.warn("### OnlineObjectService::uploadBinaryData onFileUploadStartedCallback is null or undefined or not a function"); } else { fileUploadStartedCallback = onFileUploadStartedCallback; } // validation for onChunkUploadCompletedCallback if (kony.sdk.isNullOrUndefined(onChunkUploadCompletedCallback) || (typeof(onChunkUploadCompletedCallback) !== 'function')) { kony.sdk.logsdk.warn("### OnlineObjectService::uploadBinaryData onChunkUploadCompletedCallback is null or undefined or not a function"); } else { chunkUploadCompletedCallback = onChunkUploadCompletedCallback; } // validation for onFileUploadCompletedCallback if (kony.sdk.isNullOrUndefined(onFileUploadCompletedCallback) || (typeof(onFileUploadCompletedCallback) !== 'function')) { kony.sdk.logsdk.warn("### OnlineObjectService::uploadBinaryData onFileUploadCompletedCallback is null or undefined or not a function"); } else { fileUploadCompletedCallback = onFileUploadCompletedCallback; } // validation for onFileUploadFailureCallback if (kony.sdk.isNullOrUndefined(onFileUploadFailureCallback) || (typeof(onFileUploadFailureCallback) !== 'function')) { kony.sdk.logsdk.warn("### OnlineObjectService::uploadBinaryData onFileUploadFailureCallback is null or undefined or not a function"); } else { fileUploadFailureCallback = onFileUploadFailureCallback; } // validation for options if (kony.sdk.isNullOrUndefined(options)) { kony.sdk.logsdk.error("### OnlineObjectService::uploadBinaryData options is null or undefined"); kony.sdk.verifyAndCallClosure(fileUploadFailureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options " + kony.sdk.errormessages.null_or_undefined)); return; } var dataObject = options["dataObject"]; if (kony.sdk.isNullOrUndefined(dataObject)) { kony.sdk.verifyAndCallClosure(fileUploadFailureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } if (!(dataObject instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(fileUploadFailureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } var objName = dataObject.getObjectName(); var mfEndpointUrl = this.getDataUrl() + "/" + objName; if (kony.sdk.isNullOrUndefined(dataObject.getRecord())) { kony.sdk.logsdk.error("### OnlineObjectService::uploadBinaryData Error: Please provide record to upload Binary content."); kony.sdk.verifyAndCallClosure(fileUploadFailureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } uploadParams = dataObject.getRecord(); var errorObj = kony.sdk.binary.validateUploadParams(uploadParams); if (errorObj) { kony.sdk.verifyAndCallClosure(fileUploadFailureCallback, errorObj); return; } // if rawbytes are provided, converting to base64 string as FFI can only receive base datatypes if (!kony.sdk.isNullOrUndefined(uploadParams[kony.sdk.constants.RAW_BYTES])) { var base64String = kony.convertToBase64(uploadParams[kony.sdk.constants.RAW_BYTES]); uploadParams[kony.sdk.constants.RAW_BYTES] = base64String; } function uploadBinaryDataOperationHandler() { currentObject.getMetadataOfObject(objName, {}, function(response) { _uploadBinaryData(mfEndpointUrl, uploadParams, fileUploadStartedCallback, chunkUploadCompletedCallback, fileUploadCompletedCallback, fileUploadFailureCallback); }, function(error) { kony.sdk.logsdk.error("### OnlineObjectService::uploadBinaryData Error:", error); kony.sdk.verifyAndCallClosure(fileUploadFailureCallback, error); }); } if (kony.sdk.skipAnonymousCall) { uploadBinaryDataOperationHandler(); } else { kony.sdk.claimsRefresh(uploadBinaryDataOperationHandler, fileUploadFailureCallback); } }; /* * Helper method to perform file upload */ function _uploadBinaryData(mfEndpointUrl, uploadParams, fileUploadStartedCallback, chunkUploadCompletedCallback, fileUploadCompletedCallback, fileUploadFailureCallback) { var uploadOptions = {}; if (uploadParams) { //Extracting Mandatory Params from uploadParams before fetching template if (uploadParams[kony.sdk.constants.FILE_PATH]) { uploadOptions[kony.sdk.constants.FILE_PATH] = uploadParams[kony.sdk.constants.FILE_PATH]; delete uploadParams[kony.sdk.constants.FILE_PATH]; } else if (uploadParams[kony.sdk.constants.RAW_BYTES]) { uploadOptions[kony.sdk.constants.RAW_BYTES] = uploadParams[kony.sdk.constants.RAW_BYTES]; delete uploadParams[kony.sdk.constants.RAW_BYTES]; } else if (uploadParams[kony.sdk.constants.FILE_OBJECT]) { uploadOptions[kony.sdk.constants.FILE_OBJECT] = uploadParams[kony.sdk.constants.FILE_OBJECT]; delete uploadParams[kony.sdk.constants.FILE_OBJECT] } uploadOptions["uploadParams"] = uploadParams; } var headers = {}; if (!kony.sdk.skipAnonymousCall) { headers[kony.sdk.constants.KONY_AUTHORIZATION_HEADER] = kony.sdk.getCurrentInstance().currentClaimToken; } uploadOptions["headers"] = headers; uploadOptions["URL"] = mfEndpointUrl; kony.sdk.binary.uploadBinaryData(uploadOptions, fileUploadStartedCallback, chunkUploadCompletedCallback, fileUploadCompletedCallback, fileUploadFailureCallback); } this.getBinaryData = function(options, arg1, arg2, arg3, arg4, arg5) { var externalSource = true; var fileDownloadStartedCallback = null; var chunkDownloadCompletedCallback = null; var fileDownloadCompletedCallback = null; var downloadFailureCallback = null; var binaryAttributeName = null; if (kony.sdk.isNullOrUndefined(arg5)) { if (kony.sdk.isNullOrUndefined(arg1)) { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData fileDownloadStartedCallback is null or undefined"); } else if (typeof(arg1) === 'function') { fileDownloadStartedCallback = arg1; } else { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData invalid param provided for fileDownloadStartedCallback"); } if (kony.sdk.isNullOrUndefined(arg2)) { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData chunkDownloadCompletedCallback is null or undefined"); } else if (typeof(arg2) === 'function') { chunkDownloadCompletedCallback = arg2; } else { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData invalid param provided for chunkDownloadCompletedCallback"); } if (kony.sdk.isNullOrUndefined(arg3)) { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData fileDownloadCompletedCallback is null or undefined"); } else if (typeof(arg3) === 'function') { fileDownloadCompletedCallback = arg3; } else { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData invalid param provided for fileDownloadCompletedCallback"); } if (kony.sdk.isNullOrUndefined(arg4)) { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData downloadFailureCallback is null or undefined"); } else if (typeof(arg4) === 'function') { downloadFailureCallback = arg4; } else { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData invalid param provided for downloadFailureCallback"); } } else { binaryAttributeName = arg1; externalSource = false; if (kony.sdk.isNullOrUndefined(arg2)) { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData fileDownloadStartedCallback is null or undefined"); } else if (typeof(arg2) === 'function') { fileDownloadStartedCallback = arg2; } else { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData invalid param provided for fileDownloadStartedCallback"); } if (kony.sdk.isNullOrUndefined(arg3)) { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData chunkDownloadCompletedCallback is null or undefined"); } else if (typeof(arg3) === 'function') { chunkDownloadCompletedCallback = arg3; } else { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData invalid param provided for chunkDownloadCompletedCallback"); } if (kony.sdk.isNullOrUndefined(arg4)) { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData fileDownloadCompletedCallback is null or undefined"); } else if (typeof(arg4) === 'function') { fileDownloadCompletedCallback = arg4; } else { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData invalid param provided for fileDownloadCompletedCallback"); } if (kony.sdk.isNullOrUndefined(arg5)) { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData downloadFailureCallback is null or undefined"); } else if (typeof(arg5) === 'function') { downloadFailureCallback = arg5; } else { kony.sdk.logsdk.warn("### OnlineObjectService::getBinaryData invalid param provided for downloadFailureCallback"); } } if (kony.sdk.getSdkType() !== kony.sdk.constants.SDK_TYPE_IDE && kony.sdk.getAType() !== kony.sdk.constants.SDK_ATYPE_NATIVE) { kony.sdk.verifyAndCallClosure(downloadFailureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_api, kony.sdk.errormessages.invalid_api + "platform :" + kony.sdk.getSdkType().toString())); return; } if (kony.sdk.isNullOrUndefined(options)) { kony.sdk.verifyAndCallClosure(downloadFailureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } var tmpDataUrl = null; if (externalSource) { tmpDataUrl = this.getDataUrl(); } else { tmpDataUrl = this.getBinaryUrl(); } var dataObject = options["dataObject"]; if (!(dataObject instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(downloadFailureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } if (!(kony.sdk.isNullOrUndefined(options["queryParams"]))) { if (!(options["queryParams"] instanceof Object)) { kony.sdk.verifyAndCallClosure(downloadFailureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_queryparams_instance, kony.sdk.errormessages.invalid_queryparams_instance)); return; } } var objName = dataObject.getObjectName(); var streamingFlag = false; if (!kony.sdk.isNullOrUndefined(options["streaming"]) && options["streaming"] === true) { streamingFlag = true; } if (!externalSource) { if (kony.sdk.isNullOrUndefined(binaryAttributeName) || typeof(binaryAttributeName) !== "string") { kony.sdk.logsdk.error("### OnlineObjectService::getBinaryData Error: Please provide column name to fetch binary content"); kony.sdk.verifyAndCallClosure(downloadFailureCallback, kony.sdk.error.getClientErrObj("90000", "Please provide column name to fetch binary content")); return; } else { options["binaryAttrName"] = binaryAttributeName; } } if (kony.sdk.isNullOrUndefined(dataObject.getRecord())) { kony.sdk.logsdk.error("### OnlineObjectService::_getBinaryData Error: Please provide primary key details or fileParams to get Binary content."); kony.sdk.verifyAndCallClosure(downloadFailureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } function getBinaryDataOperationHandler() { currentObject.getMetadataOfObject(objName, {}, function(response) { _getBinaryData(options, tmpDataUrl, externalSource, streamingFlag, fileDownloadStartedCallback, chunkDownloadCompletedCallback, fileDownloadCompletedCallback, downloadFailureCallback); }, function(error) { kony.sdk.logsdk.error("### OnlineObjectService::getBinaryData Error:", error); kony.sdk.verifyAndCallClosure(downloadFailureCallback, error); }); } if (kony.sdk.skipAnonymousCall) { getBinaryDataOperationHandler(); } else { kony.sdk.claimsRefresh(getBinaryDataOperationHandler, downloadFailureCallback); } }; /** * Helps to get the binary content of the specified column on the Object * @param {map} options - includes {"dataObject":{@link kony.sdk.dto.DataObject}, "binaryAttrName":columnName} * @param successCallback * @param failureCallback */ this.getBinaryContent = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OnlineObjectService.getBinaryContent"); if (options == null || options == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } var tmpDataUrl = this.getBinaryUrl(); var dataObject = options["dataObject"]; if (!(dataObject instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } if (!(options["queryParams"] == null || options["queryParams"] == undefined)) { if (!(options["queryParams"] instanceof Object)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_queryparams_instance, kony.sdk.errormessages.invalid_queryparams_instance)); return; } } var objName = dataObject.getObjectName(); var binaryColName = options["binaryAttrName"]; if (binaryColName == null || binaryColName == undefined) { kony.sdk.logsdk.error("### OnlineObjectService::getBinaryContent Error: Please provide column name to fetch binary content"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj("90000", "Please provide column name to fetch binary content")); return; } function getBinaryContentOperationHandler() { currentObject.getMetadataOfObject(objName, {}, function(response) { _getBinaryContent(options, tmpDataUrl, successCallback, failureCallback); }, function(error) { kony.sdk.logsdk.error("### OnlineObjectService::getBinaryContent Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); }); } if (kony.sdk.skipAnonymousCall) { getBinaryContentOperationHandler(); } else { kony.sdk.claimsRefresh(getBinaryContentOperationHandler, failureCallback); } }; /** * Helps to create the binary content of the specified column on the Object * @param {map} options - includes {"dataObject": {@link kony.sdk.dto.DataObject}, "binaryAttrName":columnName} * @param successCallback * @param failureCallback */ this.createBinaryContent = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OnlineObjectService.createBinaryContent"); var tmpDataUrl = this.getBinaryUrl(); if (options == null || options == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } var dataObject = options["dataObject"]; if (!(dataObject instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } if (!(options["queryParams"] == null || options["queryParams"] == undefined)) { if (!(options["queryParams"] instanceof Object)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_queryparams_instance, kony.sdk.errormessages.invalid_queryparams_instance)); return; } } var objName = dataObject.getObjectName(); var binaryColName = options["binaryAttrName"]; if (binaryColName == null || binaryColName == undefined) { kony.sdk.logsdk.error("### OnlineObjectService::createBinaryContent Error: Please provide column name to create binary content"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj("900000", "Please provide column name to create binary content")); return; } function createBinaryContentOperationHandler() { currentObject.getMetadataOfObject(objName, {}, function(response) { _createBinaryContent(options, tmpDataUrl, successCallback, failureCallback); }, function(error) { kony.sdk.logsdk.error("### OnlineObjectService::createBinaryContent Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); }); } if (kony.sdk.skipAnonymousCall) { createBinaryContentOperationHandler(); } else { kony.sdk.claimsRefresh(createBinaryContentOperationHandler, failureCallback); } }; /** * Helps to update the binary content of the specified column on the Object * @param {map} options - includes {"dataObject": {@link kony.sdk.dto.DataObject}, "binaryAttrName":columnName} * @param successCallback * @param failureCallback */ this.updateBinaryContent = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OnlineObjectService.updateBinaryContent"); var tmpDataUrl = this.getBinaryUrl(); if (options == null || options == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } var dataObject = options["dataObject"]; if (!(dataObject instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } if (!(options["queryParams"] == null || options["queryParams"] == undefined)) { if (!(options["queryParams"] instanceof Object)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_queryparams_instance, kony.sdk.errormessages.invalid_queryparams_instance)); return; } } var objName = dataObject.getObjectName(); var binaryColName = options["binaryAttrName"]; if (binaryColName == null || binaryColName == undefined) { kony.sdk.logsdk.error("### OnlineObjectService::updateBinaryContent Error: Please provide column name to create binary content"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj("90000", "Please provide column name to create binary content")); return; } function updateBinaryContentOperationHandler() { currentObject.getMetadataOfObject(objName, {}, function(response) { _updateBinaryContent(options, tmpDataUrl, successCallback, failureCallback); }, function(error) { kony.sdk.logsdk.error("### OnlineObjectService::updateBinaryContent Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); }); } if (kony.sdk.skipAnonymousCall) { updateBinaryContentOperationHandler(); } else { kony.sdk.claimsRefresh(updateBinaryContentOperationHandler, failureCallback); } }; function _getBinaryContent(options, tmpDataUrl, successCallback, failureCallback) { var dataObject = options["dataObject"]; var headers = options["headers"]; var binaryColName = options["binaryAttrName"]; var objName = dataObject.getObjectName(); var queryParams = options["queryParams"]; var url = tmpDataUrl + "/" + objName; var objMetadata = kony.sdk.ObjectServiceUtil.getCachedObjectMetadata(serviceName, objName); if (objMetadata.primaryKey != undefined && objMetadata.primaryKey != null) { var pkCount = objMetadata.primaryKey.length; if (pkCount == 0) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } //reading primarykey and framing filter clause var pkey = objMetadata.primaryKey[0]; if (dataObject.getRecord()[pkey] == undefined || dataObject.getRecord()[pkey] == null) { kony.sdk.logsdk.error("### OnlineObjectService::_getBinaryContent Error: Please provide primary key details to get Binary content."); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } url = url + "?" + pkey + "=" + dataObject.getRecord()[pkey]; //passing binary column name to server if (binaryColName != null && binaryColName != undefined) { url = url + "&fieldName=" + binaryColName; } if (queryParams != undefined && queryParams != null) { url = url + "&" + kony.sdk.util.objectToQueryParams(queryParams); } } else { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } if (!headers) { //if headers not sent by the deveolper headers = {}; } var isKonyApiVersionAvailable = false; if (typeof(headers) !== 'undefined' && headers !== null) { //check for x-kony-api-version case insensitive for (var header in headers) { if (header !== null && header !== 'undefined') { if (header.toLowerCase() === kony.sdk.constants.API_VERSION_HEADER.toLowerCase()) isKonyApiVersionAvailable = true } } if (!isKonyApiVersionAvailable) { headers[kony.sdk.constants.API_VERSION_HEADER] = currentObject.getVersion(); } } function invokeSuccessCallback(response) { kony.sdk.logsdk.debug("### OnlineObjectService::_getBinaryContent::invokeSuccessCallback Response:", response); kony.sdk.verifyAndCallClosure(successCallback, response["data"]); } function invokeFailureCallback(error) { kony.sdk.logsdk.error("### OnlineObjectService::_getBinaryContent::invokeFailureCallback Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); } invokeObjectOperation(url, dataObject.getObjectName(), headers, null, kony.sdk.constants.HTTP_METHOD_GET, invokeSuccessCallback, invokeFailureCallback, checkAndFetchNetworkProviderOptions(options)); } function _getBinaryData(options, tmpDataUrl, externalSource, streamingFlag, fileDownloadStartedCallback, chunkDownloadCompletedCallback, fileDownloadCompletedCallback, downloadFailureCallback) { var dataObject = options["dataObject"]; var headers = options["headers"]; var binaryColName = options["binaryAttrName"]; var objName = dataObject.getObjectName(); var queryParams = options["queryParams"]; var url = tmpDataUrl + "/" + objName; var objMetadata = kony.sdk.ObjectServiceUtil.getCachedObjectMetadata(serviceName, objName); if (!externalSource) { if (!kony.sdk.isNullOrUndefined(objMetadata.primaryKey)) { var pkCount = objMetadata.primaryKey.length; if (pkCount == 0) { kony.sdk.verifyAndCallClosure(downloadFailureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } //reading primarykey and framing filter clause var pkey = objMetadata.primaryKey[0]; if (kony.sdk.isNullOrUndefined(dataObject.getRecord()[pkey])) { kony.sdk.logsdk.error("### OnlineObjectService::_getBinaryData Error: Please provide primary key details to get Binary content."); kony.sdk.verifyAndCallClosure(downloadFailureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } url = url + "?" + pkey + "=" + dataObject.getRecord()[pkey]; //passing binary column name to server if (!kony.sdk.isNullOrUndefined(binaryColName)) { url = url + "&fieldName=" + binaryColName; } url = url + "&type=bytes"; if (!kony.sdk.isNullOrUndefined(queryParams)) { url = url + "&" + kony.sdk.util.objectToQueryParams(queryParams); } } else { kony.sdk.verifyAndCallClosure(downloadFailureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } } if (!headers) { //if headers not sent by the deveolper headers = {}; } var isKonyApiVersionAvailable = false; if (typeof(headers) !== 'undefined' && headers !== null) { //check for x-kony-api-version case insensitive for (var headerKey in headers) { if (!kony.sdk.isNullOrUndefined(headerKey)) { if (headerKey.toLowerCase() === kony.sdk.constants.API_VERSION_HEADER.toLowerCase()) { isKonyApiVersionAvailable = true; headers[kony.sdk.constants.API_VERSION_HEADER] = headers[headerKey]; } } } if (!isKonyApiVersionAvailable) { headers[kony.sdk.constants.API_VERSION_HEADER] = currentObject.getVersion(); } } function invokeSuccessCallback(response) { kony.sdk.logsdk.debug("### OnlineObjectService::_getBinaryData::invokeSuccessCallback Response:", response); var downloadConfig = response["records"][0]; downloadConfig.httpStatusCode = response.httpStatusCode; if (options && options["ChunkSize"]) { downloadConfig.ChunkSize = options["ChunkSize"]; } var fileParams = dataObject.getRecord(); if (kony.sdk.isNullOrUndefined(fileParams["fileId"])) { fileParams["fileId"] = new Date().getTime().toString(); } kony.sdk.binary.getBinaryData(fileParams, streamingFlag, downloadConfig, fileDownloadStartedCallback, chunkDownloadCompletedCallback, fileDownloadCompletedCallback, downloadFailureCallback); } function invokeFailureCallback(error) { kony.sdk.logsdk.error("### OnlineObjectService::_getBinaryData::invokeFailureCallback Error:", error); kony.sdk.verifyAndCallClosure(downloadFailureCallback, error); } if (externalSource) { invokeObjectOperation(url, dataObject.getObjectName(), headers, null, kony.sdk.constants.HTTP_METHOD_GET, invokeSuccessCallback, invokeFailureCallback, checkAndFetchNetworkProviderOptions(options)); } else { var fileParams = dataObject.getRecord(); if (kony.sdk.isNullOrUndefined(fileParams["fileId"])) { fileParams["fileId"] = dataObject.getRecord()[pkey]; } if (!kony.sdk.skipAnonymousCall) { headers[kony.sdk.constants.KONY_AUTHORIZATION_HEADER] = kony.sdk.getCurrentInstance().currentClaimToken; } var downloadConfig = {}; downloadConfig["endpointUrl"] = url; downloadConfig["headers"] = headers; //for bypasing template call we need to add method and httpstatus code 309 downloadConfig.method = kony.sdk.constants.HTTP_METHOD_GET; downloadConfig.httpStatusCode = kony.sdk.binary.constants.VALID_HTTP_REDIRECT_CODE; if (options && options["ChunkSize"]) { downloadConfig.ChunkSize = options["ChunkSize"]; } kony.sdk.binary.getBinaryData(fileParams, streamingFlag, downloadConfig, fileDownloadStartedCallback, chunkDownloadCompletedCallback, fileDownloadCompletedCallback, downloadFailureCallback); } } function _createBinaryContent(options, tmpDataUrl, successCallback, failureCallback) { var dataObject = options["dataObject"]; var headers = options["headers"]; var binaryColName = options["binaryAttrName"]; var objName = dataObject.getObjectName(); var queryParams = options["queryParams"]; var url = tmpDataUrl + "/" + objName; var objMetadata = kony.sdk.ObjectServiceUtil.getCachedObjectMetadata(serviceName, objName); var jsonPayload = {}; var pkey; if (objMetadata.primaryKey != undefined && objMetadata.primaryKey != null) { var pkCount = objMetadata.primaryKey.length; if (pkCount == 0) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } //reading primarykey and framing filter clause pkey = objMetadata.primaryKey[0]; if (dataObject.getRecord()[pkey] == undefined || dataObject.getRecord()[pkey] == null) { kony.sdk.logsdk.error("### OnlineObjectService::_createBinaryContent Error: Please provide primary key details to create Binary content."); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } jsonPayload[pkey] = dataObject.getRecord()[pkey]; jsonPayload["data"] = dataObject.getRecord()[binaryColName]; jsonPayload["fieldName"] = binaryColName; } else { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } if (!headers) { //if headers not sent by the deveolper headers = {}; } var isKonyApiVersionAvailable = false; if (typeof(headers) !== 'undefined' && headers !== null) { //check for x-kony-api-version case insensitive for (var header in headers) { if (header !== null && header !== 'undefined') { if (header.toLowerCase() === kony.sdk.constants.API_VERSION_HEADER.toLowerCase()) isKonyApiVersionAvailable = true } } if (!isKonyApiVersionAvailable) { headers[kony.sdk.constants.API_VERSION_HEADER] = currentObject.getVersion(); } } var formData = new kony.sdk.getFormData(jsonPayload); if (!kony.sdk.isNullOrUndefined(queryParams)) { kony.sdk.updateFormData(formData, "queryparams", queryParams); } function invokeSuccessCallback(response) { kony.sdk.logsdk.debug("### OnlineObjectService::_createBinaryContent::invokeSuccessCallback Response:", response); kony.sdk.verifyAndCallClosure(successCallback, response[pkey]); } function invokeFailureCallback(error) { kony.sdk.logsdk.error("### OnlineObjectService::_createBinaryContent::invokeFailureCallback Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); } invokeObjectOperation(url, dataObject.getObjectName(), headers, formData, null, invokeSuccessCallback, invokeFailureCallback, checkAndFetchNetworkProviderOptions(options)); } function _updateBinaryContent(options, tmpDataUrl, successCallback, failureCallback) { var dataObject = options["dataObject"]; var headers = options["headers"]; var binaryColName = options["binaryAttrName"]; var objName = dataObject.getObjectName(); var queryParams = options["queryParams"]; var url = tmpDataUrl + "/" + objName; var objMetadata = kony.sdk.ObjectServiceUtil.getCachedObjectMetadata(serviceName, objName); var jsonPayload = {}; var pkey; if (objMetadata.primaryKey != undefined && objMetadata.primaryKey != null) { var pkCount = objMetadata.primaryKey.length; if (pkCount == 0) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } //reading primarykey and framing filter clause pkey = objMetadata.primaryKey[0]; if (dataObject.getRecord()[pkey] == undefined || dataObject.getRecord()[pkey] == null) { kony.sdk.logsdk.error("### OnlineObjectService::_updateBinaryContent Error: Please provide primary key details to create Binary content."); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } jsonPayload[pkey] = dataObject.getRecord()[pkey]; jsonPayload["data"] = dataObject.getRecord()[binaryColName]; jsonPayload["fieldName"] = binaryColName; } else { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } if (!headers) { //if headers not sent by the deveolper headers = {}; } headers["X-HTTP-Method-Override"] = "PUT"; var isKonyApiVersionAvailable = false; if (typeof(headers) !== 'undefined' && headers !== null) { //check for x-kony-api-version case insensitive for (var header in headers) { if (header !== null && header !== 'undefined') { if (header.toLowerCase() === kony.sdk.constants.API_VERSION_HEADER.toLowerCase()) isKonyApiVersionAvailable = true } } if (!isKonyApiVersionAvailable) { headers[kony.sdk.constants.API_VERSION_HEADER] = currentObject.getVersion(); } } var formData = new kony.sdk.getFormData(jsonPayload); if (queryParams != undefined && queryParams != null) { kony.sdk.updateFormData(formData, "queryparams", queryParams); } function invokeSuccessCallback(response) { kony.sdk.logsdk.debug("### OnlineObjectService::_updateBinaryContent::invokeSuccessCallback Response:", response); kony.sdk.verifyAndCallClosure(successCallback, response[pkey]); } function invokeFailureCallback(error) { kony.sdk.logsdk.error("### OnlineObjectService::_updateBinaryContent::invokeFailureCallback Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); } invokeObjectOperation(url, dataObject.getObjectName(), headers, formData, null, invokeSuccessCallback, invokeFailureCallback, checkAndFetchNetworkProviderOptions(options)); } function _create(options, tmpDataUrl, successCallback, failureCallback) { var dataObject = options["dataObject"]; var headers = options["headers"]; var url = tmpDataUrl + "/" + dataObject.objectName; var record = dataObject.getRecord(); var queryParams = options["queryParams"]; if (record == null || record == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "record " + kony.sdk.errormessages.null_or_undefined)); return; } if (!headers) { //if headers not sent by the deveolper headers = {}; } var isKonyApiVersionAvailable = false; if (typeof(headers) !== 'undefined' && headers !== null) { //check for x-kony-api-version case insensitive for (var header in headers) { if (header !== null && header !== 'undefined') { if (header.toLowerCase() === kony.sdk.constants.API_VERSION_HEADER.toLowerCase()) isKonyApiVersionAvailable = true } } if (!isKonyApiVersionAvailable) { headers[kony.sdk.constants.API_VERSION_HEADER] = currentObject.getVersion(); } } var formData = new kony.sdk.getFormData(record, null); if (queryParams != undefined && queryParams != null) { kony.sdk.updateFormData(formData, "queryparams", queryParams); } function invokeSuccessCallback(response) { kony.sdk.logsdk.debug("### OnlineObjectService::_create::invokeSuccessCallback Response:", response); kony.sdk.verifyAndCallClosure(successCallback, response); } function invokeFailureCallback(error) { kony.sdk.logsdk.error("### OnlineObjectService::_create::invokeFailureCallback Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error) } invokeObjectOperation(url, dataObject.objectName, headers, formData, null, invokeSuccessCallback, invokeFailureCallback, checkAndFetchNetworkProviderOptions(options)); } function _fetch(options, tmpDataUrl, successCallback, serviceErrorCallback) { var dataObject = options["dataObject"]; var odataqueryStr = dataObject.getOdataUrl(); var headers = options["headers"]; var queryParams = options["queryParams"]; var url = tmpDataUrl + "/" + dataObject.objectName; if (odataqueryStr != undefined && odataqueryStr != null) { url = url + "?" + encodeURI(odataqueryStr); if (queryParams != undefined && queryParams != null) { url = url + "&" + kony.sdk.util.objectToQueryParams(queryParams); } } else if (queryParams != undefined && queryParams != null) { url = url + "?" + kony.sdk.util.objectToQueryParams(queryParams); } if (!headers) { //if headers not sent by the deveolper headers = {}; } var isKonyApiVersionAvailable = false; if (typeof(headers) !== 'undefined' && headers !== null) { //check for x-kony-api-version case insensitive for (var header in headers) { if (header !== null && header !== 'undefined') { if (header.toLowerCase() === kony.sdk.constants.API_VERSION_HEADER.toLowerCase()) isKonyApiVersionAvailable = true } } if (!isKonyApiVersionAvailable) { headers[kony.sdk.constants.API_VERSION_HEADER] = currentObject.getVersion(); } } // If useCache is enabled and cacheID is present then network call will be skipped and cached response will be returned. if (options && options["useCache"] && options["cacheID"]) { var cacheResponse = new kony.sdk.ClientCache().get(options["cacheID"]); if (cacheResponse) { kony.sdk.logsdk.debug("### OnlineObjectService::_fetch:: key found in cache, invokeSuccessCallback Response:", cacheResponse); kony.sdk.verifyAndCallClosure(successCallback, cacheResponse); return; } } function invokeSuccessCallback(response) { kony.sdk.logsdk.debug("### OnlineObjectService::_fetch::invokeSuccessCallback Response:", response); // If useCache is enabled then the response is cached and returned. if (options && options["useCache"]) { cacheResponseForKey(options, url, { "objectName": dataObject.objectName }, response); } kony.sdk.verifyAndCallClosure(successCallback, response); } function invokeFailureCallback(error) { kony.sdk.logsdk.error("### OnlineObjectService::_fetch::invokeFailureCallback Error:", error); kony.sdk.verifyAndCallClosure(serviceErrorCallback, error); } invokeObjectOperation(url, dataObject.objectName, headers, null, kony.sdk.constants.HTTP_METHOD_GET, invokeSuccessCallback, invokeFailureCallback, checkAndFetchNetworkProviderOptions(options)); } function _update(options, tmpDataUrl, updateServiceCallback, serviceErrorCallback) { var dataObject = options["dataObject"]; var headers = options["headers"]; var url = tmpDataUrl + "/" + dataObject.objectName; var queryParams = options["queryParams"]; if (!headers) { //if headers not sent by the deveolper headers = {}; } var isKonyApiVersionAvailable = false; if (typeof(headers) !== 'undefined' && headers !== null) { //check for x-kony-api-version case insensitive for (var header in headers) { if (header !== null && header !== 'undefined') { if (header.toLowerCase() === kony.sdk.constants.API_VERSION_HEADER.toLowerCase()) isKonyApiVersionAvailable = true } } if (!isKonyApiVersionAvailable) { headers[kony.sdk.constants.API_VERSION_HEADER] = currentObject.getVersion(); } } headers["X-HTTP-Method-Override"] = "PUT"; var formData = new kony.sdk.getFormData(dataObject.getRecord(), null); if (queryParams != undefined && queryParams != null) { kony.sdk.updateFormData(formData, "queryparams", queryParams); } function invokeSuccessCallback(response) { kony.sdk.logsdk.debug("### OnlineObjectService::_update::invokeSuccessCallback Response:", response); kony.sdk.verifyAndCallClosure(updateServiceCallback, response); } function invokeFailureCallback(error) { kony.sdk.logsdk.error("### OnlineObjectService::_update::invokeFailureCallback Error:", error); kony.sdk.verifyAndCallClosure(serviceErrorCallback, error); } invokeObjectOperation(url, dataObject.objectName, headers, formData, null, invokeSuccessCallback, invokeFailureCallback, checkAndFetchNetworkProviderOptions(options)); } function _partialUpdate(options, tmpDataUrl, partialUpdateServiceCallback, serviceErrorCallback) { var dataObject = options["dataObject"]; var headers = options["headers"]; var url = tmpDataUrl + "/" + dataObject.objectName; var queryParams = options["queryParams"]; if (!headers) { //if headers not sent by the deveolper headers = {}; } headers["X-HTTP-Method-Override"] = "PATCH"; var isKonyApiVersionAvailable = false; if (typeof(headers) !== 'undefined' && headers !== null) { //check for x-kony-api-version case insensitive for (var header in headers) { if (header !== null && header !== 'undefined') { if (header.toLowerCase() === kony.sdk.constants.API_VERSION_HEADER.toLowerCase()) isKonyApiVersionAvailable = true } } if (!isKonyApiVersionAvailable) { headers[kony.sdk.constants.API_VERSION_HEADER] = currentObject.getVersion(); } } var formData = new kony.sdk.getFormData(dataObject.getRecord(), null); if (queryParams != undefined && queryParams != null) { kony.sdk.updateFormData(formData, "queryparams", queryParams); } function invokeSuccessCallback(response) { kony.sdk.logsdk.debug("### OnlineObjectService::_partialUpdate::invokeSuccessCallback Success Response:", response); kony.sdk.verifyAndCallClosure(partialUpdateServiceCallback, response); } function invokeFailureCallback(error) { kony.sdk.logsdk.error("### OnlineObjectService::_partialUpdate::invokeFailureCallback Error:", error); kony.sdk.verifyAndCallClosure(serviceErrorCallback, error); } invokeObjectOperation(url, dataObject.objectName, headers, formData, null, invokeSuccessCallback, invokeFailureCallback, checkAndFetchNetworkProviderOptions(options)); } function _deleteRecord(options, tmpDataUrl, deleteSuccessCallback, serviceErrorCallback) { var dataObject = options["dataObject"]; var headers = options["headers"]; var objMetadata = kony.sdk.ObjectServiceUtil.getCachedObjectMetadata(serviceName, dataObject.objectName); var url = tmpDataUrl + "/" + dataObject.objectName; var queryParams = options["queryParams"]; var odataUrl = ""; if (objMetadata.primaryKey != undefined && objMetadata.primaryKey != null) { var pkCount = objMetadata.primaryKey.length; for (var i = 0; i < pkCount; i++) { //reading primarykey and framing filter clause var pkey = objMetadata.primaryKey[i]; if (dataObject.getRecord()[pkey] == undefined || dataObject.getRecord()[pkey] == null) { kony.sdk.logsdk.error("### OnlineObjectService::_delete Error: Please provide all primary keys to process the request"); kony.sdk.verifyAndCallClosure(serviceErrorCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } if (i == 0) { odataUrl = "?$filter=" + pkey + " eq '" + dataObject.getRecord()[pkey] + "'"; } else { //appending the condition incase of composite primary key odataUrl = odataUrl + " and " + pkey + " eq '" + dataObject.getRecord()[pkey] + "'"; } } } url = url + encodeURI(odataUrl); if (queryParams != undefined && queryParams != null) { if (odataUrl && odataUrl.length != 0) { url = url + "&" + kony.sdk.util.objectToQueryParams(queryParams); } else { url = url + "?" + kony.sdk.util.objectToQueryParams(queryParams); } } if (!headers) { //if headers not sent by the deveolper headers = {}; } var isKonyApiVersionAvailable = false; if (typeof(headers) !== 'undefined' && headers !== null) { //check for x-kony-api-version case insensitive for (var header in headers) { if (header !== null && header !== 'undefined') { if (header.toLowerCase() === kony.sdk.constants.API_VERSION_HEADER.toLowerCase()) isKonyApiVersionAvailable = true } } if (!isKonyApiVersionAvailable) { headers[kony.sdk.constants.API_VERSION_HEADER] = currentObject.getVersion(); } } headers["X-HTTP-Method-Override"] = "DELETE"; function invokeSuccessCallback(response) { kony.sdk.logsdk.debug("### OnlineObjectService::_delete::invokeSuccessCallback Response:", response); kony.sdk.verifyAndCallClosure(deleteSuccessCallback, response); } function invokeFailureCallback(error) { kony.sdk.logsdk.error("### OnlineObjectService::_delete::invokeFailureCallback Error:", error); kony.sdk.verifyAndCallClosure(serviceErrorCallback, error); } invokeObjectOperation(url, dataObject.objectName, headers, null, kony.sdk.constants.HTTP_METHOD_GET, invokeSuccessCallback, invokeFailureCallback, checkAndFetchNetworkProviderOptions(options)); } function _customverb(verbName, options, tmpDataUrl, customVerbServiceCallback, serviceErrorCallback) { var dataObject = options["dataObject"]; var headers = options["headers"]; var url = tmpDataUrl + "/" + dataObject.objectName + "/" + verbName; var queryParams = options["queryParams"]; if (!headers) { //if headers not sent by the deveolper headers = {}; } var isKonyApiVersionAvailable = false; if (typeof(headers) !== 'undefined' && headers !== null) { //check for x-kony-api-version case insensitive for (var header in headers) { if (header !== null && header !== 'undefined') { if (header.toLowerCase() === kony.sdk.constants.API_VERSION_HEADER.toLowerCase()) isKonyApiVersionAvailable = true } } if (!isKonyApiVersionAvailable) { headers[kony.sdk.constants.API_VERSION_HEADER] = currentObject.getVersion(); } } var formData = new kony.sdk.getFormData(dataObject.getRecord(), null); if (queryParams != undefined && queryParams != null) { kony.sdk.updateFormData(formData, "queryparams", queryParams); } function invokeSuccessCallback(response) { kony.sdk.logsdk.debug("### OnlineObjectService::_customverb::invokeSuccessCallback Success Response:", response); kony.sdk.verifyAndCallClosure(customVerbServiceCallback, response); } function invokeFailureCallback(error) { kony.sdk.logsdk.error("### OnlineObjectService::_customverb::invokeFailureCallback Error:", error); kony.sdk.verifyAndCallClosure(serviceErrorCallback, error); } invokeObjectOperation(url, dataObject.objectName, headers, formData, null, invokeSuccessCallback, invokeFailureCallback, checkAndFetchNetworkProviderOptions(options)); } }; function _getMetadataUrl(konyRef, serviceName) { var metadataUrl = null; if (konyRef.objectsvc[serviceName]) { metadataUrl = encodeURI(stripTrailingCharacter(konyRef.objectsvc[serviceName]["metadata_url"], "/")); } else if (konyRef.offlineObjectsvc[serviceName]) { metadataUrl = encodeURI(stripTrailingCharacter(konyRef.offlineObjectsvc[serviceName]["metadata_url"], "/")); } return metadataUrl; } function _getVersion(konyRef, serviceName) { var version = null; if (konyRef.objectsvc[serviceName]) { version = konyRef.objectsvc[serviceName]["version"]; } else if (konyRef.offlineObjectsvc[serviceName]) { version = konyRef.offlineObjectsvc[serviceName]["version"]; } return version; } /*This method is used to fetch metadata for Object/Objectservice. * It is fetched from cache first, if it not available in cache then fetches method data from metadata URL. */ function _getMetadataForObjectsOrServiceOnlineUtil(konyRef, serviceName, objectName, options, successCallback, failureCallback) { var tmpMetadataUrl = _getMetadataUrl(konyRef, serviceName);; if (!(kony.sdk.isNullOrUndefined(options)) && !(options["queryParams"] == null || options["queryParams"] == undefined)) { if (!(options["queryParams"] instanceof Object)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_queryparams_instance, kony.sdk.errormessages.invalid_queryparams_instance)); } } function getMetadataOfObjectOperationHandler() { _getMetadataForObjectOrService(konyRef, serviceName, objectName, options, tmpMetadataUrl, successCallback, failureCallback); } if (kony.sdk.skipAnonymousCall) { getMetadataOfObjectOperationHandler(); } else { kony.sdk.claimsRefresh(getMetadataOfObjectOperationHandler, failureCallback); } } function _getMetadataForObjectOrService(konyRef, serviceName, objectName, options, tmpMetadataUrl, successCallback, failureCallback) { //if the getFromServer flag is true then get metadata from server even though its available in cache var getFromServer = false; var headers = null; var queryParams = null; if (options != null && options != undefined) { getFromServer = options["getFromServer"]; headers = options["headers"]; queryParams = options["queryParams"]; } var tmpObjOrSvcMetadata = null; if (objectName) { tmpObjOrSvcMetadata = kony.sdk.ObjectServiceUtil.getCachedObjectMetadata(serviceName, objectName); } else { tmpObjOrSvcMetadata = kony.sdk.ObjectServiceUtil.getCachedMetadata(serviceName); } if (getFromServer != true && tmpObjOrSvcMetadata != null && tmpObjOrSvcMetadata != undefined) { kony.sdk.logsdk.debug("### OnlineObjectService::_getMetadataOfObject from KonyStore:", tmpObjOrSvcMetadata); kony.sdk.verifyAndCallClosure(successCallback, tmpObjOrSvcMetadata); } else { if (!headers) { //if headers not sent by the deveolper headers = {}; } var isKonyApiVersionAvailable = false; if (typeof(headers) !== 'undefined' && headers !== null) { //check for x-kony-api-version case insensitive for (var header in headers) { if (header !== null && header !== 'undefined') { if (header.toLowerCase() === kony.sdk.constants.API_VERSION_HEADER.toLowerCase()) isKonyApiVersionAvailable = true } } if (!isKonyApiVersionAvailable) { headers[kony.sdk.constants.API_VERSION_HEADER] = _getVersion(konyRef, serviceName); } } var url = tmpMetadataUrl; var svcid = "metadata"; if (objectName) { url = url + "/" + objectName; svcid = svcid + "_" + objectName; } if (queryParams != undefined && queryParams != null) { url = url + "?" + kony.sdk.util.objectToQueryParams(queryParams); } function invokeSuccessCallback(result) { kony.sdk.logsdk.debug("### OnlineObjectService::_getMetadataForObjectOrService::invokeSuccessCallback Response:", result); if (objectName) { var table = result["Metadata"]["table"]; kony.sdk.ObjectServiceUtil.cacheObjectMetadata(serviceName, table); var tmpObjMetadata = kony.sdk.ObjectServiceUtil.getCachedObjectMetadata(serviceName, objectName); kony.sdk.verifyAndCallClosure(successCallback, tmpObjMetadata); } else { var tableArray = result["Metadata"]["tables"]; kony.sdk.ObjectServiceUtil.cacheMetadata(serviceName, tableArray); var tmpMetadata = kony.sdk.ObjectServiceUtil.getCachedMetadata(serviceName); kony.sdk.verifyAndCallClosure(successCallback, tmpMetadata); } } function invokeFailureCallback(error) { kony.sdk.logsdk.error("### OnlineObjectService::_getMetadataForObjectOrService::invokeFailureCallback Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); } invokeObjectOperation(url, svcid, headers, null, kony.sdk.constants.HTTP_METHOD_GET, invokeSuccessCallback, invokeFailureCallback, checkAndFetchNetworkProviderOptions(options)); } } function checkAndFetchNetworkProviderOptions(options) { var providerOptions = {}; //Fetching httpRequestOptions if (options && options["httpRequestOptions"] && options["httpRequestOptions"] instanceof Object) { providerOptions["httpRequestOptions"] = options["httpRequestOptions"]; } //Fetching XMLHttpRequestOptions if (options && options["xmlHttpRequestOptions"] && options["xmlHttpRequestOptions"] instanceof Object) { providerOptions["xmlHttpRequestOptions"] = options["xmlHttpRequestOptions"]; } return providerOptions; } //Method is used to send http request for ObjectService operations function invokeObjectOperation(url, svcid, headers, formData, httpMethod, successCallback, failureCallback, networkProviderOptions) { kony.sdk.logsdk.trace("Entering invokeObjectOperation"); var requestData = {}; var networkProvider = new konyNetworkProvider(); var reportingData = kony.sdk.getPayload(konyRef); var sessionId = null; var defaultHeaders = {}; if (kony.ds) { sessionId = kony.ds.read(kony.sdk.constants.KONYUUID); } if (sessionId) { reportingData.rsid = sessionId[0]; } if (!reportingData.rsid) { kony.sdk.logsdk.warn("### invokeObjectOperation:: rsid is either empty,null or undefined"); } if (!httpMethod) { //default http method is post httpMethod = "POST"; } if (!kony.sdk.skipAnonymousCall) { // Check to find if the service is public or not, in case of public service no token is required. defaultHeaders[kony.sdk.constants.KONY_AUTHORIZATION_HEADER] = konyRef.currentClaimToken; } defaultHeaders[kony.sdk.constants.HTTP_REQUEST_HEADER_ACCEPT] = kony.sdk.constants.CONTENT_TYPE_JSON; defaultHeaders[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_JSON; var deviceId = kony.sdk.getDeviceId(); if (!kony.sdk.isNullOrUndefined(deviceId)) { defaultHeaders[kony.sdk.constants.DEVICEID_HEADER] = deviceId; } if (reportingData != null && reportingData != undefined) { try { defaultHeaders[kony.sdk.constants.REPORTING_HEADER] = encodeURI(JSON.stringify(reportingData)) } catch (error) { kony.sdk.logsdk.error("### invokeObjectOperation::error while parsing metrics payload" + error); } } // if the user has defined his own headers, use them if (headers) { var tempHeader = ""; for (var header in headers) { if (kony.sdk.constants.HTTP_REQUEST_HEADER_ACCEPT.toLowerCase() === header.toLowerCase()) { //Accept can be multiple //Reason being client can be programmed to accept more than one type of content from server. tempHeader = kony.sdk.constants.HTTP_REQUEST_HEADER_ACCEPT; if (defaultHeaders[tempHeader].toLowerCase() !== headers[header].toLowerCase()) { defaultHeaders[header] = defaultHeaders[tempHeader] + "," + headers[header]; } } else if (kony.sdk.constants.KONY_AUTHORIZATION_HEADER.toLowerCase() === header.toLowerCase()) { tempHeader = kony.sdk.constants.KONY_AUTHORIZATION_HEADER; if (defaultHeaders[tempHeader] !== headers[header]) { defaultHeaders[tempHeader] = headers[header]; } } else if ("content-type" === header.toLowerCase()) { tempHeader = kony.sdk.constants.HTTP_CONTENT_HEADER; //Content-type can and should be a single value. //Reason being client can only send a single kind of content at a single instance if (defaultHeaders[tempHeader].toLowerCase() !== headers[header].toLowerCase()) { defaultHeaders[tempHeader] = headers[header]; } } else { if (defaultHeaders[header] !== headers[header]) { defaultHeaders[header] = headers[header]; } } } } function networksuccess(res) { kony.sdk.logsdk.trace("Entering networksuccess"); if (kony.sdk.metric) { kony.sdk.metric.clearBufferEvents(); } kony.sdk.verifyAndCallClosure(successCallback, res); } function networkerror(xhr, status, err) { kony.sdk.logsdk.trace("Entering networkerror"); if (xhr && !(status && err)) { err = xhr; } if (kony.sdk.metric) { if (kony.sdk.metric.errorCodeMap[xhr.opstatus]) { kony.sdk.metric.saveInDS(); } } if (err[kony.sdk.constants.MF_CODE]) { var konyRef = kony.sdk.getCurrentInstance(); //clear the cache if the error code related to session/token expiry if (kony.sdk.isSessionOrTokenExpired(err[kony.sdk.constants.MF_CODE])) { kony.sdk.logsdk.warn("###ObjectService::invokeObjectOperationFailure Session/Token expired. Authenticate and Try again"); //kony.sdk.resetCacheKeys(konyRef); } } kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getObjectServiceErrObj(err)); } if (httpMethod === "GET") { networkProvider.get(url, null, defaultHeaders, networksuccess, networkerror, "formdata", networkProviderOptions); } else { networkProvider.post(url, formData, defaultHeaders, networksuccess, networkerror, "formdata", networkProviderOptions); } } kony.sdk.util = kony.sdk.util || {}; kony.sdk.ObjectServiceUtil = kony.sdk.ObjectServiceUtil || {}; kony.sdk.dto = kony.sdk.dto || {}; kony.sdk.constants.DateTimeType = { TODAY: "TODAY", YESTERDAY: "YESTERDAY", TOMORROW: "TOMORROW", CURRENTWEEK: "CURRENTWEEK", LASTWEEK: "LASTWEEK", NEXTWEEK: "NEXTWEEK", CURRENTMONTH: "CURRENTMONTH", LASTMONTH: "LASTMONTH", NEXTMONTH: "NEXTMONTH" }; kony.sdk.constants.Aggregation = { NONE: "", COUNT: "COUNT", SUM: "SUM", MAX: "MAX", MIN: "MIN", AVG: "AVG" }; kony.sdk.constants.OrderType = { ASCENDING: "ASC", DESCENDING: "DESC" }; kony.sdk.constants.MatchType = { EQUALS: { value: "=", name: "EQUALS" }, GREATER: { value: ">", name: "GREATER" }, GREATEREQUAL: { value: ">=", name: "GREATEREQUAL" }, LESS: { value: "<", name: "LESS" }, LESSEQUAL: { value: "<=", name: "LESSEQUAL" }, STARTSWITH: { value: "LIKE", name: "STARTSWITH" }, CONTAINS: { value: "LIKE", name: "CONTAINS" }, LIKE: { value: "LIKE", name: "LIKE" }, ENDSWITH: { value: "LIKE", name: "ENDSWITH" }, NOTEQUAL: { value: "<>", name: "NOTEQUAL" }, ISNULL: { value: "IS NULL", name: "ISNULL" }, ISNOTNULL: { value: "IS NOT NULL", name: "ISNOTNULL" } }; kony.sdk.constants.JoinType = { INNER: "INNER", LEFT: "LEFT", RIGHT: "RIGHT" }; kony.sdk.constants.Operator = { AND: "AND", OR: "OR" }; kony.sdk.constants.ObjectServiceConstants = { DATAOBJECT: "dataObject", QUERYPARAMS: "queryParams" }; /** * This is a utility function used to check whether the two strings provided * would match with each other. * @param string1 * @param string2 * @return boolean */ kony.sdk.util.matchIgnoreCase = function(string1, string2) { if (string1 === null || string2 === null || string1 === undefined || string2 === undefined) { return false; } return (string1.toUpperCase() === string2.toUpperCase()); }; kony.sdk.util.isNull = function(val) { if (val === null || val === undefined) return true; val = val + ""; return (kony.sdk.util.matchIgnoreCase(val, "null")); }; kony.sdk.util.isValidNumberType = function(val) { if (kony.sdk.util.matchIgnoreCase(typeof val, "number")) return true; else if (kony.sdk.util.matchIgnoreCase(typeof val, "string") && null != kony.sdk.util.toNumber(val)) return true; else return false; }; kony.sdk.util.toNumber = function(arg) { if (arguments.length != 1) { throw new Error("Invalid argument to kony.sdk.util.toNumber"); } if (typeof(arg) === "number") { return arg; } else if (typeof(arg) === "string") { var str = arg.replace(/^\s*/, '').replace(/\s*$/, ''); if (str === '') { return null; } else { var num = str - 0; return (isNaN(num) ? null : num); } } else { return null; } }; kony.sdk.util.validateCriteriaObject = function(criteria) { if (criteria !== null && criteria !== undefined) { return (criteria instanceof kony.sdk.dto.Criteria || criteria instanceof kony.sdk.dto.Match || criteria instanceof kony.sdk.dto.Between || criteria instanceof kony.sdk.dto.LogicGroup || criteria instanceof kony.sdk.dto.And || criteria instanceof kony.sdk.dto.Or || criteria instanceof kony.sdk.dto.Not || criteria instanceof kony.sdk.dto.Expression || criteria instanceof kony.sdk.dto.InCriteria || criteria instanceof kony.sdk.dto.Exists || criteria instanceof kony.sdk.dto.Join); } else { return false; } }; kony.sdk.ObjectServiceUtil.cacheMetadata = function(serviceName, objects) { if (objects !== undefined && objects !== null) { kony.sdk.dataStore.removeItem(serviceName); for (var i = 0; i < objects.length; i++) { var object = objects[i]; //clearing the existing metadata of service and updating it with the latest metadata kony.sdk.ObjectServiceUtil.cacheObjectMetadata(serviceName, object); } } }; kony.sdk.ObjectServiceUtil.cacheObjectMetadata = function(serviceName, object) { if (object !== undefined && object !== null) { //getting metadata of servicename var metadataOfAllObjs = kony.sdk.dataStore.getItem(serviceName); var jsonObject = JSON.parse('{}'); //if metadata available get it if (metadataOfAllObjs !== null && metadataOfAllObjs !== undefined && metadataOfAllObjs !== "{}") { jsonObject = JSON.parse(metadataOfAllObjs); } //adding metadata of object to the existing metadata jsonObject[object.name] = object; var jsonStr = JSON.stringify(jsonObject); kony.sdk.dataStore.setItem(serviceName, jsonStr); } }; kony.sdk.ObjectServiceUtil.getCachedMetadata = function(serviceName) { kony.sdk.logsdk.trace("Entering into kony.sdk.ObjectServiceUtil.getCachedMetadata"); var appMetadata = kony.sdk.util.getPackagedMetadata(); if (appMetadata != null && appMetadata != undefined) { if (serviceName != undefined && serviceName != null) return appMetadata[serviceName]; } else { //reading metadata from the store var jsonObject = null; var metadataOfAllObjs = kony.sdk.dataStore.getItem(serviceName); if (metadataOfAllObjs !== null && metadataOfAllObjs !== undefined && metadataOfAllObjs !== "{}") { jsonObject = JSON.parse(metadataOfAllObjs); } return jsonObject; } return null; }; kony.sdk.ObjectServiceUtil.getCachedObjectMetadata = function(serviceName, objectName) { kony.sdk.logsdk.trace("Entering into kony.sdk.ObjectServiceUtil.getCachedObjectMetadata"); var objectMetadata; if (objectName !== undefined && objectName !== null) { var metadataOfAllObjs = kony.sdk.ObjectServiceUtil.getCachedMetadata(serviceName); var jsonObject = null; if (metadataOfAllObjs !== null && metadataOfAllObjs !== undefined && metadataOfAllObjs !== "{}") { jsonObject = metadataOfAllObjs; //getting the object's metadata from the stored metadata objectMetadata = jsonObject[objectName]; } } return objectMetadata; }; /** * An object used to perform CRUD operations on objects * @param objectName * @param record * @constructor */ kony.sdk.dto.DataObject = function(objectName, record) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.DataObject"); this.objectName = objectName; if (record != null && record != undefined) { this.record = record; } else { this.record = {}; } this.odataUrl = null; this.selectQueryObject = null; this.offlineObjectsOptions = {}; this.setOfflineObjectsOptions = function(offlineObjectsOptions) { this.offlineObjectsOptions = offlineObjectsOptions; }; this.getOfflineObjectsOptions = function() { return this.offlineObjectsOptions; }; /** * This function is used to add fields and their values to the dataobject * @param fieldName * @param value */ this.addField = function(fieldName, value) { this.record[fieldName] = value; }; /** * This function is used to set a map of records to the dataobject * @param fieldValuesMap */ this.setRecord = function(fieldValuesMap) { this.record = fieldValuesMap; }; /** * This function is used to get the map of records present in the DataObject * @returns {JSON} record */ this.getRecord = function() { return this.record; }; /** * This function is used to add a child Dataobject into the data object * @param childDataObject {@link kony.sdk.dto.DataObject} */ this.addChildDataObject = function(childDataObject) { if (this.record[childDataObject.objectName] == null || this.record[childDataObject.objectName] == undefined) { this.record[childDataObject.objectName] = []; } this.record[childDataObject.objectName].push(childDataObject.getRecord()); }; /** * This function is used to set the odata url to query * @param odataUrl */ this.setOdataUrl = function(odataUrl) { this.odataUrl = odataUrl; }; /** * This function is used to get the odata url to query * @returns {null} */ this.getOdataUrl = function() { return this.odataUrl; }; /** * This function is used to set a SelectQueryObject {@link kony.sdk.dto.SelectQuery} * @param selectQueryObject {@link kony.sdk.dto.SelectQuery} */ this.setSelectQueryObject = function(selectQueryObject) { this.selectQueryObject = selectQueryObject; }; /** * This function is used to get a SelectQueryObject {@link kony.sdk.dto.SelectQuery} * @returns selectQueryObject {@link kony.sdk.dto.SelectQuery} */ this.getSelectQueryObject = function() { return this.selectQueryObject; }; /** * This function is used to get the object name * @returns objectName {string} */ this.getObjectName = function() { return this.objectName; }; }; /** * This object is used to define a record object used in Offline CRUD * @constructor */ kony.sdk.dto.RecordObject = function() { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.RecordObject"); this.tableName = ""; this.columnValues = {}; this.childRecords = []; }; kony.sdk.util.getSyncDbName = function() { return kony.sync.getDBName(); }; kony.sdk.util.getPrimarykeysFromMetadata = function(objMetadata) { var tmpSrcAttributes = null; if (objMetadata.primaryKey != null && objMetadata.primaryKey != undefined && objMetadata.primaryKey.length > 0) { tmpSrcAttributes = {}; var pkLen = objMetadata.primaryKey.length; for (var indx = 0; indx < pkLen; indx++) { var pKey = objMetadata.primaryKey[indx]; //adding primarykey column names in srcattributes which will be useful while deleting children tmpSrcAttributes[pKey] = pKey; } } return tmpSrcAttributes; }; /** * This is a replaceAll utility function * @param string * @param toReplace * @param replaceWith * @return String temp */ kony.sdk.util.replaceAll = function(string, toReplace, replaceWith) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.replaceAll"); var temp = string; var index = temp.indexOf(toReplace); while (index != -1) { temp = temp.replace(toReplace, replaceWith); index = temp.indexOf(toReplace); } return temp; }; kony.sdk.util.validateDateTypeInput = function(dateType) { return (kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.TODAY) || kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.TOMORROW) || kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.YESTERDAY) || kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.CURRENTWEEK) || kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.NEXTWEEK) || kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.LASTWEEK) || kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.CURRENTMONTH) || kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.NEXTMONTH) || kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.LASTMONTH)); }; kony.sdk.util.getDateRange = function(dateType) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.getDateRange"); var result = []; var currentDate = new Date(); var formattedDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds(), currentDate.getMilliseconds()); var start; var end; if (kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.TODAY)) { end = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), formattedDate.getDate(), 23, 59, 59); start = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), formattedDate.getDate(), 0, 0, 0); } else if (kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.TOMORROW)) { formattedDate.setDate(formattedDate.getDate() + 1); end = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), formattedDate.getDate(), 23, 59, 59); start = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), formattedDate.getDate(), 0, 0, 0); } else if (kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.YESTERDAY)) { formattedDate.setDate(formattedDate.getDate() - 1); end = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), formattedDate.getDate(), 23, 59, 59); start = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), formattedDate.getDate(), 0, 0, 0); } else if (kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.CURRENTWEEK)) { var firstDayofWeek = formattedDate.getDate() - formattedDate.getDay(); var lastDayofWeek = firstDayofWeek + 6; formattedDate.setDate(firstDayofWeek); start = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), formattedDate.getDate(), 0, 0, 0); formattedDate.setDate(lastDayofWeek); end = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), formattedDate.getDate(), 23, 59, 59); } else if (kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.LASTWEEK)) { formattedDate.setDate(formattedDate.getDate() - 7); var firstDayofWeek = formattedDate.getDate() - formattedDate.getDay(); var lastDayofWeek = firstDayofWeek + 6; formattedDate.setDate(firstDayofWeek); start = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), formattedDate.getDate(), 0, 0, 0); formattedDate.setDate(lastDayofWeek); end = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), formattedDate.getDate(), 23, 59, 59); } else if (kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.NEXTWEEK)) { formattedDate.setDate(formattedDate.getDate() + 7); var firstDayofWeek = formattedDate.getDate() - formattedDate.getDay(); var lastDayofWeek = firstDayofWeek + 6; formattedDate.setDate(firstDayofWeek); start = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), formattedDate.getDate(), 0, 0, 0); formattedDate.setDate(lastDayofWeek); end = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), formattedDate.getDate(), 23, 59, 59); } else if (kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.CURRENTMONTH)) { start = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), 1, 0, 0, 0); end = new Date(formattedDate.getFullYear(), formattedDate.getMonth() + 1, 0, 23, 59, 59); } else if (kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.LASTMONTH)) { start = new Date(formattedDate.getFullYear(), formattedDate.getMonth() - 1, 1, 0, 0, 0, 0); end = new Date(formattedDate.getFullYear(), formattedDate.getMonth(), 0, 23, 59, 59, 999); } else if (kony.sdk.util.matchIgnoreCase(dateType, kony.sdk.constants.DateTimeType.NEXTMONTH)) { start = new Date(formattedDate.getFullYear(), formattedDate.getMonth() + 1, 1, 0, 0, 0, 0); end = new Date(formattedDate.getFullYear(), formattedDate.getMonth() + 2, 0, 23, 59, 59, 999); } else { start = 0; end = 0; } result.push(start); result.push(end); return result; }; //Helps to prepare the primary condition to get binary data kony.sdk.util.getPkTableForBinary = function(objMetadata, columnValues, failureCallback) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.getPkTableForBinary"); var pkTable = {}; var whereClause = []; if (!kony.sdk.isNullOrUndefined(objMetadata.primaryKey)) { for (var indx = 0; indx < objMetadata.primaryKey.length; indx++) { var pKey = objMetadata.primaryKey[indx]; var pKeyValue = columnValues[pKey]; if (kony.sdk.isNullOrUndefined(pKeyValue)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } pkTable[pKey] = pKeyValue; } return pkTable; } else { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); } }; //Helps to provide the Metadata of column in a Object kony.sdk.util.getMetadataOfColumn = function(objMetadata, colName) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.getMetadataOfColumn"); if (objMetadata != null && objMetadata != undefined) { var columns = objMetadata["columns"]; if (columns != null && columns != undefined) { for (var indx in columns) { var colMeta = columns[indx]; if (colMeta["name"] == colName) { return colMeta; } } } } return null; }; //Helps in generating kony.sdk.dto.RecordObject from a given complex record kony.sdk.util.populateColumnValues = function(record, childRecords) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.populateColumnValues"); var columnValues = {}; var recordsLength = Object.keys(record).length; for (var index = 0; index < recordsLength; index++) { var colName = Object.keys(record)[index]; var colVal = record[colName]; if (colVal instanceof Array) { for (var tempIndex = 0; tempIndex < colVal.length; tempIndex++) { var tempRecord = new kony.sdk.dto.RecordObject(); tempRecord.tableName = colName; tempRecord.columnValues = kony.sdk.util.populateColumnValues(record[colName][tempIndex], tempRecord.childRecords); childRecords.push(tempRecord); } } else { columnValues[colName] = colVal; } } return columnValues; }; //Helps in getting the relationship data of an entity from a given relationship list kony.sdk.util.getRelationOfEntity = function(relationshipList, entityName) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.getRelationOfEntity"); var i = 0; for (; i < relationshipList.length; i++) { //considering only OneToMany relationships as it will have parent and child hierarchy if (relationshipList[i] != null && relationshipList[i]["relationshipType"] == "OneToMany" && relationshipList[i].relatedEntity.localeCompare(entityName) == 0) { return relationshipList[i]; } } return null; }; //Helps in finding if a given column name is a primary key kony.sdk.util.isPrimaryKey = function(primaryKeyList, columnValue) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.isPrimaryKey"); for (var i = 0; i < primaryKeyList.length; i++) { if (primaryKeyList[i] == columnValue) return true; } return false; }; kony.sdk.util.objectToQueryParams = function(valueObject) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.objectToQueryParams "); var queryParams = ""; if (!kony.sdk.isNullOrUndefined(valueObject) && valueObject instanceof Object && Object.keys(valueObject).length > 0) { var objCount = Object.keys(valueObject).length; for (var i = 0; i < objCount; i++) { var tempKey = Object.keys(valueObject)[i]; if (queryParams.length === 0) queryParams = encodeURIComponent(tempKey) + "=" + encodeURIComponent(valueObject[tempKey]); else queryParams = queryParams + "&" + encodeURIComponent(tempKey) + "=" + encodeURIComponent(valueObject[tempKey]); } } return queryParams; }; kony.sdk.util.getPackagedMetadata = function() { kony.sdk.logsdk.trace("Entering into kony.sdk.util.getPackagedMetadata"); if (kony.sdk.APP_META === undefined || kony.sdk.APP_META === null) { kony.sdk.APP_META = {}; } return kony.sdk.APP_META["objectsvc_meta"]; }; /** User needs to call this API to prepackage the metadata of the app. The data needs to be passed as json object or a stringified version of json object */ kony.sdk.util.setPackagedMetadata = function(metadataJson) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.setPackagedMetadata"); try { if (typeof metadataJson == "object") { kony.sdk.APP_META = metadataJson; } else if (typeof metadataJson == "string") { var parsedMetadata = JSON.parse(metadataJson); kony.sdk.APP_META = parsedMetadata; } } catch (error) { kony.sdk.logsdk.error("### kony.sdk.setPackagedMetadata::error while validating the input packaged metadata", error); } }; stripTrailingCharacter = function(str, character) { kony.sdk.logsdk.trace("Entering into stripTrailingCharacter"); if (str.substr(str.length - 1) === character) { return str.substr(0, str.length - 1); } return str; }; kony.sdk.setLogLevelFromServerResponse = function(responseHeaders) { kony.sdk.logsdk.trace("Entering into kony.sdk.setLogLevelFromServerResponse"); var sdkRef = kony.sdk.getCurrentInstance(); if (responseHeaders && responseHeaders[kony.logger.deviceLogLevelHeader]) { logLevel = responseHeaders[kony.logger.deviceLogLevelHeader].toUpperCase(); if (!logLevel.localeCompare(kony.logger.logLevel.NONE.code) && kony.logger.currentLogLevel !== kony.logger.logLevel.NONE) kony.logger.currentLogLevel = kony.logger.logLevel.NONE; else if (!logLevel.localeCompare(kony.logger.logLevel.FATAL.code) && kony.logger.currentLogLevel !== kony.logger.logLevel.FATAL) kony.logger.currentLogLevel = kony.logger.logLevel.FATAL; else if (!logLevel.localeCompare(kony.logger.logLevel.ERROR.code) && kony.logger.currentLogLevel !== kony.logger.logLevel.ERROR) kony.logger.currentLogLevel = kony.logger.logLevel.ERROR; else if (!logLevel.localeCompare(kony.logger.logLevel.WARN.code) && kony.logger.currentLogLevel !== kony.logger.logLevel.WARN) kony.logger.currentLogLevel = kony.logger.logLevel.WARN; else if (!logLevel.localeCompare(kony.logger.logLevel.PERF.code) && kony.logger.currentLogLevel !== kony.logger.logLevel.PERF) kony.logger.currentLogLevel = kony.logger.logLevel.PERF; else if (!logLevel.localeCompare(kony.logger.logLevel.INFO.code) && kony.logger.currentLogLevel !== kony.logger.logLevel.INFO) kony.logger.currentLogLevel = kony.logger.logLevel.INFO; else if (!logLevel.localeCompare(kony.logger.logLevel.DEBUG.code) && kony.logger.currentLogLevel !== kony.logger.logLevel.DEBUG) kony.logger.currentLogLevel = kony.logger.logLevel.DEBUG; else if (!logLevel.localeCompare(kony.logger.logLevel.TRACE.code) && kony.logger.currentLogLevel !== kony.logger.logLevel.TRACE) kony.logger.currentLogLevel = kony.logger.logLevel.TRACE; else if (!logLevel.localeCompare(kony.logger.logLevel.ALL.code) && kony.logger.currentLogLevel !== kony.logger.logLevel.ALL) kony.logger.currentLogLevel = kony.logger.logLevel.ALL; else if (!logLevel.localeCompare('OFF')) { kony.logger.deactivatePersistors(kony.logger.networkPersistor); kony.logger.currentLogLevel = kony.logger.logLevel.NONE; sdkRef.removeGlobalRequestParam(kony.logger.deviceLogLevelHeader, sdkRef.globalRequestParamType.headers); return; } else { return; } sdkRef.setGlobalRequestParam(kony.logger.deviceLogLevelHeader, logLevel, sdkRef.globalRequestParamType.headers); kony.logger.activatePersistors(kony.logger.networkPersistor); } }; kony.sdk.prototype.enableDebug = function() { kony.sdk.logsdk.trace("Entering into kony.sdk.prototype.enableDebug"); kony.sdk.isDebugEnabled = true; }; kony.sdk.prototype.disableDebug = function() { kony.sdk.logsdk.trace("Entering into kony.sdk.prototype.disableDebug"); kony.sdk.isDebugEnabled = false; }; function Exception(name, message) { kony.sdk.logsdk.error("Exception --> " + name + ": " + message); return { code: name, message: message }; } kony.sdk.verifyAndCallClosure = function(closure, params) { if (typeof(closure) === 'function') { closure(params); } else { kony.sdk.logsdk.warn("invalid callback", JSON.stringify(closure)); } }; kony.sdk.overrideUserId = function(userId) { kony.sdk.logsdk.trace("Entering into kony.sdk.overrideUserId"); if (kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_IDE && typeof(kony.setUserID) === 'function') { kony.setUserID(userId, true); } else { konyRef.setCurrentUserId(userId); } }; kony.sdk.formatCurrentDate = function(inputDateString) { kony.sdk.logsdk.trace("Entering into kony.sdk.formatCurrentDate"); var dateObj = new Date(inputDateString); var year = dateObj.getUTCFullYear(); var month = kony.sdk.formatDateComponent(dateObj.getUTCMonth() + 1); var date = kony.sdk.formatDateComponent(dateObj.getUTCDate()); var hours = kony.sdk.formatDateComponent(dateObj.getUTCHours()); var minutes = kony.sdk.formatDateComponent(dateObj.getUTCMinutes()); var seconds = kony.sdk.formatDateComponent(dateObj.getUTCSeconds()); var dateSeparator = "-"; var timeSeparator = ":"; var dateString = year + dateSeparator + month + dateSeparator + date + " " + hours + timeSeparator + minutes + timeSeparator + seconds; return dateString; }; kony.sdk.formatDateComponent = function(dateComponent) { kony.sdk.logsdk.trace("Entering into kony.sdk.formatDateComponent"); if (dateComponent < 10) { dateComponent = "0" + dateComponent; } return dateComponent; }; kony.sdk.isNullOrUndefined = function(val) { if (val === null || val === undefined) { return true; } else { return false; } }; kony.sdk.constants.reportingType = { session: "session", custom: "custom" }; kony.sdk.isEmptyObject = function(obj) { if (typeof(obj) === "boolean" || typeof(obj) === "number") { return false; } else if (typeof(obj) === "string") { return obj.trim().length === 0; } for (var prop in obj) { return false; } return true; }; kony.sdk.isArray = function(data) { if (data && Object.prototype.toString.call(data) === '[object Array]') { return true; } return false; }; kony.sdk.formatSuccessResponse = function(data) { if (data && data.httpresponse) { delete data.httpresponse; } return data; }; kony.sdk.isJson = function(str) { try { JSON.parse(str); } catch (e) { return false; } return true; }; kony.sdk.util.getString = function(val) { if (!kony.sdk.isNullOrUndefined(val) && (val.toString()).toLocaleLowerCase() !== "null") { return val.toString(); } return ""; }; //private method to identify whether session/token expired or not based on error code kony.sdk.isSessionOrTokenExpired = function(mfcode) { if (mfcode && (mfcode === "Auth-5" || mfcode === "Auth-6" || mfcode === "Gateway-31" || mfcode === "Gateway-33" || mfcode === "Gateway-35" || mfcode === "Gateway-36" || mfcode === "Auth-46" || mfcode === "Auth-55")) { return true; } return false; }; //private method to clear cache kony.sdk.resetProviderKeys = function(konyRef, _providerName) { try { if (konyRef) { if (_providerName) { if (konyRef.tokens.hasOwnProperty(_providerName)) { konyRef.tokens[_providerName] = null; } } } } catch (e) { kony.sdk.logsdk.error("Error while clearing the cache.."); } }; //private method to clear cache kony.sdk.resetCurrentKeys = function(konyRef, _providerName) { try { if (konyRef) { konyRef.currentClaimToken = null; konyRef.currentBackEndToken = null; konyRef.claimTokenExpiry = null; konyRef.currentRefreshToken = null; //setting the anonymous provider as true to access the public protected urls without any issue konyRef.isAnonymousProvider = true; if (_providerName) { if (konyRef.tokens.hasOwnProperty(_providerName)) { konyRef.tokens[_providerName] = null; } } } } catch (e) { kony.sdk.logsdk.error("Error while clearing the cache.."); } }; kony.sdk.util.populateIndividualServiceLists = function(serviceConfig, objectToPopulate) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.populateIndividualServiceLists"); var svcMeta = serviceConfig["services_meta"]; if (kony.sdk.isNullOrUndefined(objectToPopulate["objectsvc"])) { objectToPopulate["objectsvc"] = {}; } if (kony.sdk.isNullOrUndefined(objectToPopulate["offlineObjectsvc"])) { objectToPopulate["offlineObjectsvc"] = {}; } if (svcMeta) { for (var svc in svcMeta) { if (svcMeta.hasOwnProperty(svc)) { var svcObj = svcMeta[svc]; if (svcObj && svcObj["type"] === "objectsvc") { if (!kony.sdk.isNullOrUndefined(svcObj["offline"])) { if (svcObj["offline"] === false) { objectToPopulate["objectsvc"][svc] = svcObj; } else if (svcObj["offline"] === true) { objectToPopulate["offlineObjectsvc"][svc] = svcObj; } } else { objectToPopulate["objectsvc"][svc] = svcObj; objectToPopulate["offlineObjectsvc"][svc] = svcObj; } } else if (svcObj && svcObj["type"] === "integsvc") { objectToPopulate["integsvc"][svc] = svcObj; } } } } }; /** * Generates hash code for the URL by sha512 algorithm * @param url * @param requestParams * @return {*} */ kony.sdk.util.generateHashcodeForURL = function(url, requestParams) { var concatenatedResult = ""; var hashID = null; if (!kony.sdk.isNullOrUndefined(url)) concatenatedResult += url; if (!kony.sdk.isNullOrUndefined(requestParams)) { concatenatedResult += JSON.stringify(requestParams); } if (kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_IDE && !kony.sdk.util.isNullOrEmptyString(concatenatedResult)) { hashID = kony.crypto.createHash("sha512", concatenatedResult); } return hashID; }; /** * Utility function to save the response in the cache. * @param options {object} save the response with key options["cacheID"]. If not provided then we will calculate hashcode by url and requestData. * @param url {string} * @param requestData {object} * @param response {object} */ function cacheResponseForKey(options, url, requestData, response) { var hashCode = null; if (options["cacheID"]) hashCode = options["cacheID"]; else hashCode = kony.sdk.util.generateHashcodeForURL(url, requestData); if (hashCode) { if (typeof(hashCode) !== "string") { hashCode = hashCode.toString(); } var expiry = options["expiryTime"] ? options["expiryTime"] : kony.sdk.constants.DEFAULT_CACHE_EXPIRY_TIME; response["cacheID"] = hashCode; new kony.sdk.ClientCache().add(hashCode, response, expiry); } } kony.sdk.util.isNullOrEmptyString = function(val) { if (kony.sdk.isNullOrUndefined(val) || (typeof(val) === "string" && val.trim() === "")) { return true; } return false; }; function doesMFSupportsAppversioning() { // In case of IDE platforms we will check the existence of appConfig.svcDoc.service_doc_etag for compatibility of app version with the MF. // In case of plain-js & phone gap initOptions should not be sent during init call. if (kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_IDE && !kony.sdk.isNullOrUndefined(appConfig) && !kony.sdk.isNullOrUndefined(appConfig.svcDoc) && !kony.sdk.isNullOrUndefined(appConfig.svcDoc.service_doc_etag)) { return true; } else if (kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_PLAIN_JS || kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_PHONEGAP) { return true; } else { return false; } } function populateHeaderWithFabricAppVersion(headers) { if (doesMFSupportsAppversioning() && !kony.sdk.isNullOrUndefined(headers) && !kony.sdk.isNullOrUndefined(kony.sdk.getFabricAppVersion())) { headers[kony.sdk.constants.APP_VERSION_HEADER] = kony.sdk.getFabricAppVersion(); } } /* * Utility method to check whether options has browserWidget or not * @return true if it supports * */ kony.sdk.util.hasBrowserWidget = function(options) { return options && options[kony.sdk.constants.BROWSER_WIDGET] && kony.sdk.util.type(options[kony.sdk.constants.BROWSER_WIDGET]) === "kony.ui.Browser"; }; /* * Utility method to check whether binary is supported * @return true if it supports * */ kony.sdk.util.isBinarySupported = function() { return kony.sdk.getSdkType() === kony.sdk.constants.SDK_TYPE_IDE && kony.sdk.getAType() === kony.sdk.constants.SDK_ATYPE_NATIVE; }; /* ** Intializing SSO FFI's with null implementation * Supporting platforms like IDE has sso_handler which has implementation. */ kony.sdk.util.saveSSOToken = function() { return null; }; kony.sdk.util.getSSOToken = function() { return null; }; kony.sdk.util.deleteSSOToken = function() { return null; }; /* ** Utility method to clone any object * @return cloned object */ kony.sdk.cloneObject = function(obj) { var clonedObject; try { clonedObject = JSON.parse(JSON.stringify(obj)); } catch (err) { kony.sdk.logsdk.error("cloning object failed, reverting back to copy"); clonedObject = obj; } return clonedObject; }; /** * Utility method to check if a given variable is JSON Object * @param obj * @returns {boolean} */ kony.sdk.util.isJsonObject = function(obj) { if (obj === null || obj === undefined) { return false; } return obj.constructor === {}.constructor; }; /** * Utility method to check whether the given variable is a valid string * @param str * @returns {boolean} */ kony.sdk.util.isValidString = function(str) { if (str === null || str === undefined || str.constructor !== "".constructor) { return false; } return str.trim() !== "" }; /** * Utility method to convert JSON object keys to lower case * @param obj {Object} - JSON object * @returns convertedJSON {Object} - JSON object keys in lower case and values assigned to respective keys. */ kony.sdk.util.convertJsonKeysToLowerCase = function(obj) { var convertedJSON = {}; if (!kony.sdk.util.isJsonObject(obj)) { return obj; } var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { convertedJSON[keys[i].toLowerCase()] = obj[keys[i]]; } return convertedJSON; }; /** * Utility method to get JSON property case-insensitively * @param {Object} jsonObject * @param {String} key * @returns {*} */ kony.sdk.util.getValueForKeyAndIgnoreCase = function(jsonObject, key) { var keysInJSON = Object.keys(jsonObject); var index = 0; for (var jsonKey in keysInJSON) { if (keysInJSON[jsonKey].toLocaleLowerCase() === key.toLocaleLowerCase()) { return Object.values(jsonObject)[index]; } else { index++ } } return null; }; /** * Utility method to populate JSON Template * @param {String} template * @param {Object} templateParams : Input Params provided by the User * @return Object containing processed template and missing variables */ kony.sdk.util.populateTemplate = function(template, templateParams) { if (kony.sdk.util.isNullOrEmptyString(template) || !kony.sdk.util.isJsonObject(templateParams)) { kony.sdk.logsdk.error(kony.sdk.errorConstants.populating_template_failed + " " + kony.sdk.errormessages.populating_template_failed); return null; } var DOLLAR_VARIABLE_PATTERN = /(\${)+(\w.*?)+(})/g; var templateVariables = []; var missingVariables = []; var resultSet = {}; var populatedTemplate = kony.sdk.cloneObject(template); var inputTemplateVariables = populatedTemplate.match(DOLLAR_VARIABLE_PATTERN); //Match returns Array of all the matches. //Iterating over the array and extracting all template variables. for (var iteratorVariable in inputTemplateVariables) { var inputVariable = inputTemplateVariables[iteratorVariable].toString(); var templateParameter = inputVariable.slice(2, (inputVariable.length) - 1); templateVariables.push(templateParameter); } //Populating the template with user inputs. for (var iterateVariable = 0; iterateVariable < templateVariables.length; iterateVariable++) { var inputParameter = templateVariables[iterateVariable]; if (templateParams.hasOwnProperty(inputParameter)) { populatedTemplate = populatedTemplate.replace("${" + inputParameter + "}", templateParams[inputParameter]); } else { missingVariables.push(inputParameter); } } resultSet[kony.sdk.constants.PROCESSED_TEMPLATE] = populatedTemplate; resultSet[kony.sdk.constants.MISSING_VARIABLES] = missingVariables; return resultSet; }; /** * Checks if the browser is IE11 * @returns {boolean} */ kony.sdk.util.checkForIE11 = function() { //Checking if this is being run in DesktopWeb if (typeof(XMLHttpRequest) !== 'undefined') { var ua = window.navigator.userAgent; var trident = ua.indexOf('Trident/'); if (trident > 0) { // IE 11 => return version number var rv = ua.indexOf('rv:'); return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10) === 11; } } return false; }; /** * Utility method to get persistToken flag from data store * * @returns {boolean} */ kony.sdk.util.isPersistentLoginResponseEnabled = function() { var dataStore = new konyDataStore(); var persistTokenFlag = dataStore.getItem("persistLoginResponseFlag"); if (!kony.sdk.isNullOrUndefined(persistTokenFlag) && persistTokenFlag === true) { return true; } return false; } kony.sdk.serviceDoc = function() { kony.sdk.logsdk.trace("Entering into kony.sdk.serviceDoc"); var appId = ""; var baseId = ""; var services_meta = {}; var name = ""; var selflink = ""; var login = null; var integsvc = {}; var reportingsvc = {}; var messagingsvc = {}; var sync = {}; var objectsvc = {}; var logicsvc = {}; this.toJSON = function() { servConfig = {}; servConfig.appId = this.getAppId(); servConfig.baseId = this.getBaseId(); servConfig.name = this.getAppName(); servConfig.selflink = this.getSelfLink(); servConfig.services_meta = this.getServicesMeta(); servConfig.login = this.getAuthServices(); servConfig.integsvc = this.getIntegrationServices(); servConfig.messagingsvc = this.getMessagingServices(); servConfig.sync = this.getSyncServices(); servConfig.reportingsvc = this.getReportingServices(); servConfig.objectsvc = this.getObjectServices(); servConfig.logicsvc = this.getLogicServices(); kony.sdk.util.populateIndividualServiceLists(this, servConfig); return servConfig; } this.setAppId = function(appIdStr) { appId = appIdStr; }; this.getAppId = function() { return appId; }; this.setBaseId = function(baseIdStr) { baseId = baseIdStr; }; this.getBaseId = function() { return baseId; }; this.setAppName = function(appName) { name = appName; }; this.getAppName = function() { return name; }; this.setSelfLink = function(selfLinkStr) { selflink = selfLinkStr; }; this.getSelfLink = function() { return selflink; }; function setEndPoints(providerType, providerValues) { for (var provider in providerValues) { providerType[provider] = providerValues[provider]; } } this.setAuthService = function(loginProvider) { if (login === null) { login = []; } login.push(loginProvider); }; //what will this return? name? this.getAuthServiceByName = function(authServiceProvider) { if (login === null) { return null; } for (var i in login) { var provider = login[i]; if (provider.prov == authServiceProvider) { return provider; } } }; this.getAuthServices = function() { return login; }; this.setIntegrationService = function(providerName, endPointUrl) { integsvc[providerName] = endPointUrl; }; this.getIntegrationServiceByName = function(integrationServiceProviderName) { return integsvc[integrationServiceProviderName]; }; this.getIntegrationServices = function() { return integsvc; }; this.setObjectService = function(providerName, endPointUrl) { objectsvc[providerName] = endPointUrl; }; this.getObjectServiceByName = function(objectServiceProviderName) { return objectsvc[objectServiceProviderName]; }; this.getObjectServices = function() { return objectsvc; }; this.getLogicServices = function() { return logicsvc; }; this.getServicesMeta = function() { return services_meta; }; this.setReportingService = function(reportingType, url) { if (reportingType == kony.sdk.constants.reportingType.session || reportingType == kony.sdk.constants.reportingType.custom) { reportingsvc[reportingType] = url; } else { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, "invalid reporting type " + reportingType); } } this.getReportingServiceByType = function(reportingServiceProviderType) { return reportingsvc[reportingServiceProviderType]; }; this.getReportingServices = function() { return reportingsvc; }; this.setMessagingService = function(appId, url) { messagingsvc[appId] = url; }; this.getMessagingServiceByName = function(messagingServiceProviderName) { return messagingsvc[messagingServiceProviderName]; }; this.getMessagingServices = function() { return messagingsvc; } this.setSyncService = function(syncServiceProvider) { sync = syncServiceProvider; }; this.getSyncServices = function() { return sync; }; }; kony.logger = kony.logger || {}; kony.logger = { // Logger constants networkPersistorUrlEndpoint: "deviceLogs", deviceLogLevelHeader: "X-KONY-DEVICE-LOG-LEVEL", filePersistor: 1, consolePersistor: 2, networkPersistor: 4, // Log Level Block which gives all the handle for setting and getting //ALL(0) < TRACE(1) < DEBUG(2) < INFO(4) < PEF(8) < WARN(16) < ERROR(32) < FATAL(64) < NONE(127) logLevel: { NONE: { value: 127, name: "none", code: "NONE" }, FATAL: { value: 64, name: "fatal", code: "FATAL" }, ERROR: { value: 32, name: "error", code: "ERROR" }, WARN: { value: 16, name: "warn", code: "WARN" }, PERF: { value: 8, name: "perf", code: "PERF" }, INFO: { value: 4, name: "info", code: "INFO" }, DEBUG: { value: 2, name: "debug", code: "DEBUG" }, TRACE: { value: 1, name: "trace", code: "TRACE" }, ALL: { value: 0, name: "all", code: "ALL" } }, get currentLogLevel() { if (typeof(currentLevel) === 'undefined') currentLevel = kony.logger.logLevel.NONE; if (kony.logger.isNativeLoggerAvailable()) { var logLevelValue = KonyLogger.getLogLevel(); for (var key in kony.logger.logLevel) { if (kony.logger.logLevel.hasOwnProperty(key)) { if (kony.logger.logLevel[key].value == logLevelValue) { currentLevel = kony.logger.logLevel[key]; break; } } } } return currentLevel; }, set currentLogLevel(level) { currentLevel = level; if (kony.logger.isNativeLoggerAvailable()) KonyLogger.setLogLevel(currentLevel.value); }, isNativeLoggerAvailable: function() { if (typeof(KonyLogger) === 'undefined') return false; else return true; }, flush: function() { if (kony.logger.isNativeLoggerAvailable()) KonyLogger.flush(); }, // Persister block for activating and deactivating activatePersistors: function(activatedList) { if (kony.logger.isNativeLoggerAvailable()) KonyLogger.activatePersistors(activatedList); }, deactivatePersistors: function(deactivatedList) { if (kony.logger.isNativeLoggerAvailable()) KonyLogger.deactivatePersistors(deactivatedList); }, //setting claims token after referesh setClaimsToken: function() { var token = kony.sdk.getCurrentInstance().currentClaimToken; if (kony.logger.isNativeLoggerAvailable()) KonyLogger.setClaimsToken(token); }, setConfig: function(loggerConfig) { if (kony.logger.isNativeLoggerAvailable()) { KonyLogger.setConfig(loggerConfig.getLoggerConfig()); } }, setPersistorConfig: function(persistor) { if (kony.logger.isNativeLoggerAvailable()) { KonyLogger.setPersistorConfig(persistor.getPersistorConfig()); } }, createLoggerObject: function(loggerName, loggerConfig) { var loggerObj = {}; loggerObj.config = parseConfig(loggerConfig); loggerObj.trace = function(msg, params) { logMessage(loggerObj, kony.logger.logLevel.TRACE, msg, params); }; loggerObj.debug = function(msg, params) { logMessage(loggerObj, kony.logger.logLevel.DEBUG, msg, params); }; loggerObj.info = function(msg, params) { logMessage(loggerObj, kony.logger.logLevel.INFO, msg, params); }; loggerObj.perf = function(msg, params) { logMessage(loggerObj, kony.logger.logLevel.PERF, msg, params); }; loggerObj.warn = function(msg, params) { logMessage(loggerObj, kony.logger.logLevel.WARN, msg, params); }; loggerObj.error = function(msg, params) { logMessage(loggerObj, kony.logger.logLevel.ERROR, msg, params); }; loggerObj.fatal = function(msg, params) { logMessage(loggerObj, kony.logger.logLevel.FATAL, msg, params); }; var indirectionLevel = 0; loggerObj.setIndirectionLevel = function(_indirectionLevel) { indirectionLevel = _indirectionLevel; } loggerObj.getIndirectionLevel = function() { return indirectionLevel; } loggerObj.loggerName = loggerName; return loggerObj; }, createLoggerConfig: function() { var formatC = {}; var logFilterC = {}; var accConfig = {}; var overrideConfig = null; var persistorList = []; var config = { //formatterConfig //timeformat set timeFormat(val) { formatC.timeFormat = val; }, //timeZone set timeZone(val) { formatC.timeZone = val; }, //FilterConfig //logLevel set logLevel(val) { logFilterC.logLevel = val; }, //accumulatorConfig //bytesLimit set bytesLimit(val) { accConfig.bytesLimit = val; }, //statementsLimit set statementsLimit(val) { accConfig.statementsLimit = val; }, //overrideConfig set overrideConfig(val) { overrideConfig = val; }, //peristorList get persistorList() { return persistorList; }, addPersistor: function(val) { persistorList.push(val.getPersistorConfig()); }, getLoggerConfig: function() { var loggerConfig = {}; if (Object.keys(formatC).length > 0) loggerConfig.formatterConfig = formatC; if (Object.keys(logFilterC).length > 0) loggerConfig.logFilterConfig = logFilterC; if (Object.keys(accConfig).length > 0) loggerConfig.accumulatorConfig = accConfig; if (overrideConfig !== null) loggerConfig.overrideConfig = overrideConfig; loggerConfig.persistors = persistorList; return loggerConfig; } }; return config; }, createFilePersistor: function() { var prop = {}; var persistorProperties = { //Persistor properites get persistorType() { return kony.logger.filePersistor; }, //maxNumberOfLogFiles set maxNumberOfLogFiles(val) { prop.maxNumberOfLogFiles = val; }, //maxFileSize set maxFileSize(val) { prop.maxFileSize = val; }, getPersistorConfig: function() { var perConfig = {}; perConfig.type = this.persistorType; if (Object.keys(prop).length > 0) perConfig.properties = prop; return perConfig; } }; return persistorProperties; }, createNetworkPersistor: function() { var prop = {}; var persistorProperties = { //persistorType get persistorType() { return kony.logger.networkPersistor; }, //URL set URL(val) { prop.URL = val; }, getPersistorConfig: function() { var perConfig = {}; perConfig.type = this.persistorType; if (Object.keys(prop).length > 0) perConfig.properties = prop; return perConfig; } }; return persistorProperties; }, appLoggerInitialisation: function() { var loggerObj = {}; loggerObj = new kony.logger.createNewLogger(kony.sdk.constants.APP_LOGGER_NAME, null); return loggerObj; }, isValidJSTable: function(inputTable) { if (kony.sdk.isNullOrUndefined(inputTable)) { return false; } if (typeof inputTable === "object" || typeof inputTable === "Object" || typeof inputTable === "Array" || typeof inputTable === "array") { return true; } else { return false; } } }; kony.sdk.KNYObj = function(name, objectServiceName, namespace) { var LOG_PREFIX = "KNYObj"; kony.sdk.logsdk.info(LOG_PREFIX + ": Creating KNYObj with name " + name); var sdkObjectSync = kony.sdk.KNYObj.createSDKObjectSync(name, objectServiceName, namespace); this.name = name; this.getSdkObjectSync = function() { return sdkObjectSync; } this.startSync = function(syncConfig, successCallback, failureCallback, progressCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Starting sync on " + this.name + " object"); kony.sdk.logsdk.debug(LOG_PREFIX + ": Refreshing claims token"); kony.sdk.claimsRefresh(function() { //claims refresh success callback kony.sdk.logsdk.info(LOG_PREFIX + ": Refresh claims token SUCCESS"); var token = kony.sdk.getCurrentInstance().currentClaimToken; kony.sdk.OfflineObjects.setToken(token); kony.sdk.OfflineObjects.setReportingParams(kony.sdk.getReportingParamsForOfflineObjects()); kony.sdk.KNYObj.startSync(this, syncConfig, successCallback, failureCallback, progressCallback) }.bind(this), function(error) { //claims refresh failure callback kony.sdk.logsdk.info(LOG_PREFIX + ": Refresh claims token FAILED"); failureCallback(error); }); }; this.create = function(record, options, successCallback, failureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Create record in " + this.name + " object"); kony.sdk.KNYObj.create(this, record, options, successCallback, failureCallback); }; this.updateByPK = function(record, options, successCallback, failureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Update record in " + this.name + " object"); kony.sdk.KNYObj.updateByPK(this, record, options, successCallback, failureCallback); }; this.deleteByPK = function(options, successCallback, failureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Delete record in " + this.name + " object"); kony.sdk.KNYObj.deleteByPK(this, options, successCallback, failureCallback); }; this.get = function(options, successCallback, failureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Get record from " + this.name + " object"); kony.sdk.KNYObj.get(this, options, successCallback, failureCallback); }; this.getBinary = function(options, fileDownloadStartedCallback, chunkDownloadCompletedCallback, streamDownloadCompletedCallback, fileDownloadCompletedCallback, downloadFailureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Get binary for " + this.name + " object"); kony.sdk.KNYObj.getBinary(this, options, fileDownloadStartedCallback, chunkDownloadCompletedCallback, streamDownloadCompletedCallback, fileDownloadCompletedCallback, downloadFailureCallback); }; this.getBinaryStatus = function(options, successCallback, failureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": getBinaryStatus for " + this.name + " object"); kony.sdk.KNYObj.getBinaryStatus(this, options, successCallback, failureCallback); }; this.rollback = function(primaryKeyValueMap, successCallback, failureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Rollback for " + this.name + " object"); kony.sdk.KNYObj.rollback(this, primaryKeyValueMap, successCallback, failureCallback); }; this.markForUpload = function(options, successCallback, failureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": MarkForUpload for " + this.name + " object"); kony.sdk.KNYObj.markForUpload(this, options, successCallback, failureCallback); }; this.getUploadDeferredRecordKeys = function(successCallback, failureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Get deferred record primary keys in " + this.name + " object"); kony.sdk.KNYObj.getUploadDeferredRecordKeys(this, successCallback, failureCallback); }; this.cancelSync = function(options, successCallback, failureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Cancel for " + this.name + " object"); kony.sdk.KNYObj.cancelSync(this, options, successCallback, failureCallback); }; }; kony.sdk.KNYObjSvc = function(name) { var LOG_PREFIX = "KNYObjSvc"; kony.sdk.logsdk.debug(LOG_PREFIX + ": Creating KNYObjSvc with name " + name); var sdkObjectServiceSync = kony.sdk.KNYObjSvc.createSDKObjectServiceSync(name); this.name = name; this.getSdkObjectServiceSync = function() { return sdkObjectServiceSync; } this.getSdkObjectByName = function(name) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Creating KNYObj with name " + name + " and objectServiceName " + this.name); return new kony.sdk.KNYObj(name, this.name); } this.startSync = function(syncConfig, successCallback, failureCallback, progressCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Starting sync on " + this.name + " object service"); kony.sdk.logsdk.trace(LOG_PREFIX + ": Refreshing claims token"); kony.sdk.claimsRefresh(function() { //claims refresh success callback kony.sdk.logsdk.info(LOG_PREFIX + ": Refresh claims token SUCCESS"); var token = kony.sdk.getCurrentInstance().currentClaimToken; kony.sdk.OfflineObjects.setToken(token); kony.sdk.OfflineObjects.setReportingParams(kony.sdk.getReportingParamsForOfflineObjects()); kony.sdk.KNYObjSvc.startSync(this, syncConfig, successCallback, failureCallback, progressCallback) }.bind(this), function(error) { //claims refresh failure callback kony.sdk.logsdk.error(LOG_PREFIX + ": Refresh claims token FAILED"); failureCallback(error); }); }; this.rollback = function(successCallback, failureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Rollback on " + this.name + " object service"); kony.sdk.KNYObjSvc.rollback(this, successCallback, failureCallback) } this.cancelSync = function(options, successCallback, failureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Cancel for " + this.name + " object service"); kony.sdk.KNYObjSvc.cancelSync(this, options, successCallback, failureCallback); } this.clearOfflineData = function(options, successCallback, failureCallback) { kony.sdk.logsdk.debug(LOG_PREFIX + ": Clearing Offline Data for " + this.name + " object service."); kony.sdk.KNYObjSvc.clearOfflineData(this, options, successCallback, failureCallback); } }; kony.sdk.OfflineObjects = function(objServiceList) { var LOG_PREFIX = "OfflineObjects"; kony.sdk.logsdk.trace(LOG_PREFIX + ": Creating OfflineObjects"); this.setup = function(options, successCallback, failureCallback) { // This check is required for app upgrade from 8.0 to 8.1 var argSuccessCallback = successCallback; var argFailueCallback = failureCallback; var setupOptions = (typeof arguments[0] != "function") ? options : null; if (setupOptions === null) { argSuccessCallback = options; argFailueCallback = successCallback; } kony.sdk.logsdk.trace(LOG_PREFIX + ": OfflineObjects.setup() called"); kony.sdk.logsdk.trace(LOG_PREFIX + ": Refreshing claims token"); kony.sdk.claimsRefresh(function() { //claims refresh success callback kony.sdk.logsdk.trace(LOG_PREFIX + ": Refresh claims token SUCCESS"); var token = kony.sdk.getCurrentInstance().currentClaimToken; //kony.sdk.logsdk.debug(LOG_PREFIX+": Token : "+token); kony.sdk.OfflineObjects.setToken(token); kony.sdk.OfflineObjects.setReportingParams(kony.sdk.getReportingParamsForOfflineObjects()); kony.sdk.OfflineObjects.setup(objServiceList, setupOptions, argSuccessCallback, argFailueCallback); }, function() { //claims refresh failure callback kony.sdk.logsdk.error(LOG_PREFIX + ": Refresh claims token FAILED. Setup offline started."); kony.sdk.OfflineObjects.setup(objServiceList, setupOptions, argSuccessCallback, argFailueCallback); }); }; this.incrementalSetup = function(options, successCallback, failureCallback) { if (!options) { options = {}; } options.incrementalSetup = true; this.setup(options, successCallback, failureCallback); } this.drop = function(options, successCallback, failureCallback) { // This change is required for app upgrade from 8.0 to 8.1 var argSuccessCallback = successCallback; var argFailueCallback = failureCallback; var dropOptions = (typeof arguments[0] != "function") ? options : null; if (dropOptions === null) { argSuccessCallback = options; argFailueCallback = successCallback; } kony.sdk.logsdk.trace(LOG_PREFIX + ": OfflineObjects.drop() called"); kony.sdk.OfflineObjects.drop(dropOptions, argSuccessCallback, argFailueCallback); } this.reset = function(options, successCallback, failureCallback) { // This change is required for app upgrade from 8.0 to 8.1 var argSuccessCallback = successCallback; var argFailueCallback = failureCallback; var resetOptions = (typeof arguments[0] != "function") ? options : null; if (resetOptions === null) { argSuccessCallback = options; argFailueCallback = successCallback; } kony.sdk.logsdk.trace(LOG_PREFIX + ": OfflineObjects.reset called"); kony.sdk.logsdk.trace(LOG_PREFIX + ": Refreshing claims token"); kony.sdk.claimsRefresh(function() { //claims refresh success callback kony.sdk.logsdk.trace(LOG_PREFIX + ": Refresh claims token SUCCESS"); var token = kony.sdk.getCurrentInstance().currentClaimToken; //kony.sdk.logsdk.debug(LOG_PREFIX+": Token : "+token); kony.sdk.OfflineObjects.setToken(token); kony.sdk.OfflineObjects.setReportingParams(kony.sdk.getReportingParamsForOfflineObjects()); kony.sdk.OfflineObjects.reset(objServiceList, resetOptions, argSuccessCallback, argFailueCallback); }, function(error) { //claims refresh failure callback kony.sdk.logsdk.error(LOG_PREFIX + ": Refresh claims token FAILED"); failureCallback(error); }); } this.rollback = function(successCallback, failureCallback) { kony.sdk.logsdk.trace(LOG_PREFIX + ": OfflineObjects.rollback() called"); kony.sdk.OfflineObjects.rollback(successCallback, failureCallback); } this.executeSelectQuery = function(query, successCallback, failureCallback) { kony.sdk.logsdk.trace(LOG_PREFIX + ": OfflineObjects.executeSelectQuery() called"); kony.sdk.OfflineObjects.executeSelectQuery(query, successCallback, failureCallback); } }; kony.sdk.OfflineObjects.BinaryStatus = { "pending": 2, "completed": 4, "errored": 8 } // //Binary FFI related functions // if (kony.sdk) { kony.sdk.binary = {}; } kony.sdk.binary.constants = { ENDPOINT_URL: "endpointUrl", DOMAIN: "domain", RELATIVE_PATH: "relativepath", URL: "URL", HEADERS: "headers", METHOD: "method", UPLOAD_MODE: "uploadMode", BLOB: "blob", FILE_CONTENT: "${fileContent}", FILE: "file", HTTP_STATUS_CODE: "httpStatusCode", VALID_HTTP_REDIRECT_CODE: "309", UPLOAD_MODE_BINARY: "binary", UPLOAD_MODE_MULTIPART: "multipart", UPLOAD_PARAMS: "uploadParams", BLOB_ID: "BlobID", CONTEXT: "Context", SESSION_ID: "SessionID", BLOB_OBJECT: "BlobObject", ERROR: "Error", FILE_DETAILS: "FileDetails" }; kony.sdk.binary.addMandatoryInternalOptions = function(options) { if (kony.sdk.isNullOrUndefined(options)) { options = {}; } options[kony.sdk.binary.constants.DOMAIN] = konyRef.sessionReportingURL.split("/IST")[0]; if (!kony.sdk.isNullOrUndefined(konyRef.currentClaimToken)) { options[kony.sdk.constants.KONY_AUTHORIZATION_HEADER] = konyRef.currentClaimToken; } return options; }; kony.sdk.binary.validateUploadParams = function(uploadParams) { //Validating user input. if (!kony.sdk.util.isJsonObject(uploadParams)) { kony.sdk.logsdk.error("### kony.sdk.binary.validateUploadParams :: Error: Upload params should be supplied as valid JSON object"); return kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_params_instance, "Invalid datatype of uploadParams " + kony.sdk.util.type(uploadParams) + " " + kony.sdk.errormessages.invalid_params_instance) } // check for fileName if (!kony.sdk.util.isValidString(uploadParams[kony.sdk.constants.FILE_NAME])) { kony.sdk.logsdk.error("### kony.sdk.binary.validateUploadParams :: Error: fileName : expected string not found"); return kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_params_instance, "" + "Invalid datatype of fileName " + kony.sdk.util.type(uploadParams[kony.sdk.constants.FILE_NAME]) + " " + kony.sdk.errormessages.invalid_params_instance); } // check if both are defined if (!kony.sdk.isNullOrUndefined(uploadParams[kony.sdk.constants.FILE_PATH]) && !kony.sdk.isNullOrUndefined(uploadParams[kony.sdk.constants.RAW_BYTES])) { kony.sdk.logsdk.error("### kony.sdk.binary.validateUploadParams :: Error: BOTH FilePath and rawBytes are provided - please" + " provide only one of them"); return kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_params_instance, "BOTH FilePath and rawBytes are provided " + " " + kony.sdk.errormessages.invalid_params_instance) } // check if neither are defined if (kony.sdk.isNullOrUndefined(uploadParams[kony.sdk.constants.FILE_PATH]) && kony.sdk.isNullOrUndefined(uploadParams[kony.sdk.constants.RAW_BYTES])) { kony.sdk.logsdk.error("### kony.sdk.binary.validateUploadParams :: Error: Neither FilePath nor rawBytes is provided - please" + " provide one of them"); return kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_params_instance, "Neither FilePath nor rawBytes is provided " + " " + kony.sdk.errormessages.invalid_params_instance); } // check for datatype of filePath (if defined) if (!kony.sdk.isNullOrUndefined(uploadParams[kony.sdk.constants.FILE_PATH]) && !kony.sdk.util.isValidString(uploadParams[kony.sdk.constants.FILE_PATH])) { kony.sdk.logsdk.error("### kony.sdk.binary.validateUploadParams :: Error: FilePath : expected string and found " + kony.sdk.util.type(uploadParams[kony.sdk.constants.FILE_PATH])); return kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_params_instance, "Invalid datatype of FilePath " + kony.sdk.util.type(uploadParams[kony.sdk.constants.FILE_PATH]) + " " + kony.sdk.errormessages.invalid_params_instance); } // check for datatype of rawBytes if (!kony.sdk.isNullOrUndefined(uploadParams[kony.sdk.constants.RAW_BYTES]) && kony.sdk.util.type(uploadParams[kony.sdk.constants.RAW_BYTES]) !== "kony.types.RawBytes") { kony.sdk.logsdk.error("### kony.sdk.binary.validateUploadParams :: Error: rawBytes : expected kony.types.RawBytes object and found " + kony.sdk.util.type(uploadParams[kony.sdk.constants.RAW_BYTES])); return kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_params_instance, "Invalid datatype of rawBytes " + kony.sdk.util.type(uploadParams[kony.sdk.constants.RAW_BYTES]) + " " + kony.sdk.errormessages.invalid_params_instance); } return null; }; kony.sdk.binary.getBinaryData = function(inputParams, streaming, downloadConfig, fileDownloadStartedCallback, chunkDownloadCompletedCallback, fileDownloadCompletedCallback, downloadFailureCallback, options) { if (kony.sdk.isNullOrUndefined(downloadConfig[kony.sdk.binary.constants.ENDPOINT_URL]) && kony.sdk.isNullOrUndefined(downloadConfig[kony.sdk.binary.constants.DOMAIN]) && kony.sdk.isNullOrUndefined(downloadConfig[kony.sdk.binary.constants.RELATIVE_PATH])) { kony.sdk.verifyAndCallClosure(downloadFailureCallback, "endpointUrl or domain and relative path is required in order to download a file"); return; } options = kony.sdk.binary.addMandatoryInternalOptions(options); if (typeof(binarydata) !== "undefined") { binarydata.getOnlineBinaryData(inputParams, streaming, downloadConfig, fileDownloadStartedCallback, chunkDownloadCompletedCallback, fileDownloadCompletedCallback, downloadFailureCallback, options); } else { kony.sdk.verifyAndCallClosure(downloadFailureCallback, "FFI is not configured to use Binary Apis"); } }; kony.sdk.binary.uploadBinaryData = function(uploadParams, fileUploadStartedCallback, chunkUploadCompletedCallback, fileUploadCompletedCallback, fileUploadFailureCallback, options) { if (kony.sdk.isNullOrUndefined(uploadParams[kony.sdk.binary.constants.URL])) { kony.sdk.verifyAndCallClosure(fileUploadFailureCallback, "URL is required in order to download a file"); return; } options = kony.sdk.binary.addMandatoryInternalOptions(options); if (typeof(binarydata) !== "undefined") { binarydata.uploadBinaryData(uploadParams, fileUploadStartedCallback, chunkUploadCompletedCallback, fileUploadCompletedCallback, fileUploadFailureCallback, options); } else { kony.sdk.verifyAndCallClosure(fileUploadFailureCallback, "FFI is not configured to use Binary Apis"); } }; if (typeof(kony.sdk.metric) === "undefined") { kony.sdk.metric = {}; } kony.sdk.metric.eventFlowTag = ""; kony.sdk.metric.eventConfig = { "confType": "BUFFER", "eventBufferAutoFlushCount": kony.sdk.metric.eventBufferAutoFlushValue, "eventBufferMaxCount": kony.sdk.metric.eventBufferMaxValue }; kony.sdk.metric.eventBufferMaxValue = 1000; kony.sdk.metric.eventBufferAutoFlushValue = 15; kony.sdk.metric.characterLengthLimit = 256; kony.sdk.metric.reportEventBufferArray = []; kony.sdk.metric.reportEventBufferBackupArray = []; kony.sdk.metric.retrievedDS = false; kony.sdk.metric.eventBufferCount = 0; kony.sdk.metric.eventTypeMap = { "formentry": "FormEntry", "touch": "Touch", "servicecall": "ServiceCall", "gesture": "Gesture", "orientation": "Orientation", "custom": "Custom" }; kony.sdk.metric.errorCodeMap = { "1000": true, "1011": true, "1012": true, "1014": true, "1015": true, "1016": true }; kony.sdk.metric.setEventFlowTag = function(flowTag) { if (kony.sdk.isNullOrUndefined(flowTag)) { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Invalid value for event flow tag"); } else if (flowTag.length <= kony.sdk.metric.characterLengthLimit) { kony.sdk.metric.eventFlowTag = flowTag; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Length exceeded, Maximum length of event flow tag is " + kony.sdk.metric.characterLengthLimit + " characters"); } }; kony.sdk.metric.clearEventFlowTag = function() { kony.sdk.metric.eventFlowTag = ""; }; kony.sdk.metric.getEventFlowTag = function() { return kony.sdk.metric.eventFlowTag; }; kony.sdk.metric.setEventConfig = function(confType, eventBufferAutoFlushCount, eventBufferMaxCount) { if (kony.sdk.isNullOrUndefined(confType)) { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Config Type can not be null"); } else { confType = confType.toUpperCase(); } if (confType === "BUFFER") { kony.sdk.metric.eventConfig["confType"] = confType; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Invalid value for config type"); } if (!kony.sdk.isNullOrUndefined(eventBufferMaxCount) && typeof(eventBufferMaxCount) === "number" && eventBufferMaxCount > 0) { kony.sdk.metric.eventConfig["eventBufferMaxCount"] = eventBufferMaxCount; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "eventBufferMaxCount has to be a Number and greater than 0"); } if (!kony.sdk.isNullOrUndefined(eventBufferAutoFlushCount) && typeof(eventBufferAutoFlushCount) === "number" && eventBufferAutoFlushCount > 0 && eventBufferAutoFlushCount <= eventBufferMaxCount) { kony.sdk.metric.eventConfig["eventBufferAutoFlushCount"] = eventBufferAutoFlushCount; } else if (eventBufferAutoFlushCount >= eventBufferMaxCount) { kony.sdk.metric.eventConfig["eventBufferMaxCount"] = 1000; throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "eventBufferAutoFlushCount can not be greater than eventBufferMaxCount"); } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "eventBufferAutoFlushCount has to be a Number and greater than 0"); } }; kony.sdk.metric.reportEvent = function(evttype, evtSubType, formID, widgetID, flowTag) { if (kony.sdk.metric.reportEventBufferBackupArray.length === 0) { kony.sdk.metric.readFromDS(); } kony.sdk.metric.eventBufferCount = kony.sdk.metric.reportEventBufferBackupArray.length + kony.sdk.metric.reportEventBufferArray.length; if (kony.sdk.metric.eventBufferCount === kony.sdk.metric.eventConfig["eventBufferMaxCount"]) { throw new Exception(kony.sdk.errorConstants.DATA_STORE_EXCEPTION, "Reached maximum limit to store events"); return; } var reportEventMap = {}; reportEventMap.ts = kony.sdk.formatCurrentDate(new Date()); evttype = evttype.toLowerCase(); if (kony.sdk.isNullOrUndefined(kony.sdk.metric.eventTypeMap[evttype])) { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Invalid value for event type"); return; } else { reportEventMap["evttype"] = kony.sdk.metric.eventTypeMap[evttype]; } if (kony.sdk.isNullOrUndefined(evtSubType)) { reportEventMap["evtSubType"] = ""; } else if (evtSubType.length <= kony.sdk.metric.characterLengthLimit) { reportEventMap["evtSubType"] = evtSubType; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Length exceeded, Maximum length of event flow tag is " + kony.sdk.metric.characterLengthLimit + " characters"); return; } if (kony.sdk.isNullOrUndefined(formID)) { reportEventMap["formID"] = kony.application.getCurrentForm().id; } else if (formID.length <= kony.sdk.metric.characterLengthLimit) { reportEventMap["formID"] = formID; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Length exceeded, Maximum length of event flow tag is " + kony.sdk.metric.characterLengthLimit + " characters"); return; } if (kony.sdk.isNullOrUndefined(widgetID)) { reportEventMap["widgetID"] = ""; } else if (widgetID.length <= kony.sdk.metric.characterLengthLimit) { reportEventMap["widgetID"] = widgetID; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Length exceeded, Maximum length of event flow tag is " + kony.sdk.metric.characterLengthLimit + " characters"); return; } if (kony.sdk.isNullOrUndefined(flowTag)) { reportEventMap["flowTag"] = kony.sdk.metric.getEventFlowTag(); } else if (flowTag.length <= kony.sdk.metric.characterLengthLimit) { reportEventMap["flowTag"] = flowTag; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Length exceeded, Maximum length of event flow tag is " + kony.sdk.metric.characterLengthLimit + " characters"); return; } reportEventMap.SID = kony.ds.read(kony.sdk.constants.KONYUUID)[0]; kony.sdk.metric.reportEventBufferArray.push(reportEventMap); if (kony.sdk.metric.reportEventBufferArray.length % kony.sdk.metric.eventConfig["eventBufferAutoFlushCount"] === 0) { kony.sdk.metric.flushEvents(); } }; kony.sdk.metric.flushEvents = function() { if (kony.sdk.metric.reportEventBufferBackupArray.length === 0) { kony.sdk.metric.readFromDS(); } if (kony.sdk.metric.reportEventBufferBackupArray.length === 0 && kony.sdk.metric.reportEventBufferArray.length === 0) { kony.sdk.logsdk.warn("There are no events to flush"); return; } var payload = kony.sdk.getPayload(kony.sdk.getCurrentInstance()); var params = {}; if (kony.sdk.metric.reportEventBufferArray.length !== 0) { kony.sdk.metric.pushEventsToBufferArray(); } var headers = {}; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; params.httpheaders = headers; payload.events = kony.sdk.metric.reportEventBufferBackupArray; payload.svcid = "SendEvents"; payload.rsid = kony.sdk.metric.reportEventBufferBackupArray[0].SID; params[kony.sdk.constants.REPORTING_PARAMS] = JSON.stringify(payload); kony.net.invokeServiceAsync(kony.sdk.currentInstance.customReportingURL, params, flushCallback); function flushCallback(status, response) { if (status === 400) { if (response.opstatus == 0) { kony.sdk.metric.clearBufferEvents(); } else if (kony.sdk.metric.errorCodeMap[response.opstatus]) { kony.sdk.metric.saveInDS(); } else { kony.sdk.metric.clearBufferEvents(); } } else if (status === 300) { kony.sdk.metric.saveInDS(); } } }; /*Stores event data in Data Store on failure of service Call*/ kony.sdk.metric.saveInDS = function() { if (!kony.sdk.isNullOrUndefined(kony.sdk.metric.reportEventBufferBackupArray) && kony.sdk.metric.reportEventBufferBackupArray.length > 0) { var eventsToSave = []; eventsToSave.push(JSON.stringify(kony.sdk.metric.reportEventBufferBackupArray)); kony.ds.save(eventsToSave, "konyMetricsBuffer"); kony.sdk.metric.reportEventBufferBackupArray = []; } }; /*Clearing events sent to server */ kony.sdk.metric.clearBufferEvents = function() { kony.sdk.metric.reportEventBufferBackupArray = []; kony.ds.remove("konyMetricsBuffer"); }; /*Reading any pending events from Data Store */ kony.sdk.metric.readFromDS = function() { var eventsFromDS = kony.ds.read("konyMetricsBuffer"); if (eventsFromDS !== null) { var pushToArray = []; pushToArray.push(JSON.parse(eventsFromDS[0])); kony.sdk.metric.reportEventBufferBackupArray.push.apply(kony.sdk.metric.reportEventBufferBackupArray, pushToArray); } }; /*Pushes events received from user to BufferBackupArray which will be flushed to server */ kony.sdk.metric.pushEventsToBufferArray = function() { kony.sdk.metric.reportEventBufferBackupArray.push.apply(kony.sdk.metric.reportEventBufferBackupArray, kony.sdk.metric.reportEventBufferArray); kony.sdk.metric.reportEventBufferArray = []; }; kony.sdk.metric.getEventsInBuffer = function() { var eventsFromDS = kony.ds.read("konyMetricsBuffer"); var eventsToReturn = []; if (!kony.sdk.isNullOrUndefined(eventsFromDS)) { eventsToReturn.push(JSON.parse(eventsFromDS[0])); } if (kony.sdk.metric.reportEventBufferArray.length !== 0) { eventsToReturn.push.apply(eventsToReturn, kony.sdk.metric.reportEventBufferArray); } if (eventsToReturn.length !== 0) { return eventsToReturn; } else { return null; } }; /* JS Bindings to SyncV2 native classes */ kony.sdk.SyncV2Classes = (function() { var instance = null; var LOG_PREFIX = "kony.sdk.SyncV2Classes"; function createInstance() { kony.sdk.logsdk.info(LOG_PREFIX + ": Creating instance of SyncV2Classes"); var obj = {}; obj.ApplicationSync = objc.import("ApplicationSync"); obj.SDKObjectSync = objc.import("SDKObjectSync"); obj.SDKObjectServiceSync = objc.import("SDKObjectServiceSync"); return obj; } return { import: function() { kony.sdk.logsdk.info(LOG_PREFIX + ": Importing native SyncV2 Classes"); if (instance === null) { instance = createInstance(); } return instance; } }; })(); kony.sdk.messageIntegrityManager = (function() { var instance = null; var LOG_PREFIX = "kony.sdk.messageIntegrityManager"; function createInstance() { kony.sdk.logsdk.info(LOG_PREFIX + ": Creating instance of messageIntegrityManager"); var obj = {}; obj.httpMessageIntegrityManager = objc.import("KNYHTTPMessageIntegrityManager"); return obj; } return { import: function() { kony.sdk.logsdk.info(LOG_PREFIX + ": Importing native classes for HTTP message integrity."); if (instance === null) { instance = createInstance(); } return instance; } }; })(); kony.sdk.httpIntegrity = kony.sdk.httpIntegrity || {}; kony.sdk.httpIntegrity.getHTTPIntegrityManager = function() { var LOG_PREFIX = "kony.sdk.httpIntegrity.getHTTPIntegrityManager"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var httpIntegrityManager = kony.sdk.messageIntegrityManager.import(); return httpIntegrityManager; }; kony.sdk.httpIntegrity.setIntegrityCheck = function(propertiesForIntegrity) { var LOG_PREFIX = "kony.sdk.httpIntegrity.setIntegrityCheck"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var importedClasses = kony.sdk.httpIntegrity.getHTTPIntegrityManager(); var err = {}; importedClasses.httpMessageIntegrityManager.setIntegrityCheckError(propertiesForIntegrity, err); if (err.error) { var exception = new Exception(err.error.code, err.error.localizedDescription); if (err.error.domain) { exception.domain = err.error.domain; } if (err.error.userInfo && err.error.userInfo.callStack) { exception.callStack = err.error.userInfo.callStack; } throw exception; } }; kony.sdk.httpIntegrity.removeIntegrityCheck = function() { var LOG_PREFIX = "kony.sdk.httpIntegrity.removeIntegrityCheck"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var importedClasses = kony.sdk.httpIntegrity.getHTTPIntegrityManager(); importedClasses.httpMessageIntegrityManager.removeIntegrityCheck(); }; kony.sdk.OfflineObjects.setToken = function(token) { var LOG_PREFIX = "kony.sdk.OfflineObjects.setToken"; var syncV2Classes = kony.sdk.SyncV2Classes.import(); syncV2Classes.ApplicationSync.setToken(token); }; kony.sdk.OfflineObjects.setReportingParams = function(reportingParams) { var LOG_PREFIX = "kony.sdk.OfflineObjects.setReportingParams"; var syncV2Classes = kony.sdk.SyncV2Classes.import(); syncV2Classes.ApplicationSync.setReportingParams(reportingParams); }; kony.sdk.OfflineObjects.createSyncCallback = function(successLog, successCallback, failureLog, failureCallback) { return { onSuccess: function(obj) { kony.sdk.logsdk.info("SyncCallback : " + successLog); successCallback(obj); }, onFailure: function(error) { kony.sdk.logsdk.error("SyncCallback : " + failureLog); var exception = new Exception(error.code, error.localizedDescription); if (error.userInfo && error.userInfo.syncErrors) { exception.syncErrors = error.userInfo.syncErrors; } if (error.domain) { exception.domain = error.domain; } if (error.userInfo && error.userInfo.callStack) { exception.callStack = error.userInfo.callStack; } failureCallback(exception); } }; } kony.sdk.OfflineObjects.createKonySyncProgressCallback = function(progressLog, progressCallback) { return { onProgress: function(obj) { kony.sdk.logsdk.info("SyncCallback : " + progressLog); progressCallback(obj); } }; } kony.sdk.OfflineObjects.createKonyBinaryDownloadCallback = function(onFileDownloadStartedLog, fileDownloadStartedCompletionBlock, onChunkDownloadCompletedLog, streamDownloadCompletionBlock, onStreamDownloadCompletedLog, chunkDownloadCompletedCompletionBlock, onFileDownloadCompletedLog, fileDownloadCompletedCompletionBlock, onDownloadFailureLog, downloadFailureCompletionBlock) { return { onFileDownloadStarted: function(obj) { kony.sdk.logsdk.trace("BinaryDownloadCallback : " + this.onFileDownloadStartedLog); fileDownloadStartedCompletionBlock(obj); }, onStreamDownloadCompleted: function(obj) { kony.sdk.logsdk.trace("BinaryDownloadCallback : " + this.onStreamDownloadCompletedLog); streamDownloadCompletionBlock(obj); }, onChunkDownloadCompleted: function(obj) { kony.sdk.logsdk.trace("BinaryDownloadCallback : " + this.onChunkDownloadCompletedLog); chunkDownloadCompletedCompletionBlock(obj); }, onFileDownloadCompleted: function(obj) { kony.sdk.logsdk.trace("BinaryDownloadCallback : " + this.onFileDownloadCompletedLog); fileDownloadCompletedCompletionBlock(obj); }, onDownloadFailure: function(error) { kony.sdk.logsdk.trace("BinaryDownloadCallback : " + this.onDownloadFailureLog); var exception = new Exception(error.code, error.localizedDescription); if (error.userInfo && error.userInfo.syncErrors) { exception.syncErrors = error.userInfo.syncErrors; } if (error.domain) { exception.domain = error.domain; } if (error.userInfo && error.userInfo.callStack) { exception.callStack = error.userInfo.callStack; } downloadFailureCompletionBlock(exception); } }; } kony.sdk.OfflineObjects.setup = function(objServiceList, options, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.OfflineObjects.setup"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncV2Classes = kony.sdk.SyncV2Classes.import(); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Setup Success", successCallback, "Setup Failed", failureCallback); syncV2Classes.ApplicationSync.setupSyncWithOptionsOnSuccessOnFailure(objServiceList, options, syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.OfflineObjects.reset = function(objServiceList, options, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.OfflineObjects.reset"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncV2Classes = kony.sdk.SyncV2Classes.import(); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Reset Success", successCallback, "Reset Failed", failureCallback); syncV2Classes.ApplicationSync.resetWithOptionsOnSuccessOnFailure(objServiceList, options, syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.OfflineObjects.drop = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Invoking DROP operation from function kony.sdk.OfflineObjects.drop"); var syncV2Classes = kony.sdk.SyncV2Classes.import(); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Drop Success", successCallback, "Drop Failed", failureCallback); syncV2Classes.ApplicationSync.dropOnSuccessOnFailure(options, syncCallback.onSuccess, syncCallback.onFailure); } kony.sdk.OfflineObjects.rollback = function(successCallback, failureCallback) { kony.sdk.logsdk.trace("Invoking Rollback operation from function kony.sdk.OfflineObjects.rollback"); var syncV2Classes = kony.sdk.SyncV2Classes.import(); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Rollback Success", successCallback, "Rollback Failed", failureCallback); syncV2Classes.ApplicationSync.rollbackOnFailure(syncCallback.onSuccess, syncCallback.onFailure); } kony.sdk.OfflineObjects.executeSelectQuery = function(query, successCallback, failureCallback) { kony.sdk.logsdk.trace("Invoking executeSelectQuery operation from function kony.sdk.OfflineObjects.executeSelectQuery"); var syncV2Classes = kony.sdk.SyncV2Classes.import(); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("ExecuteSelectQuery Success", successCallback, "ExecuteSelectQuery Failed", failureCallback); syncV2Classes.ApplicationSync.executeSelectQueryOnSuccessOnFailure(query, syncCallback.onSuccess, syncCallback.onFailure); } kony.sdk.KNYObj.createSDKObjectSync = function(name, objectServiceName, namespace) { var LOG_PREFIX = "kony.sdk.KNYObj.createSDKObjectSync"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var sdkObjectSync; var syncV2Classes = kony.sdk.SyncV2Classes.import(); var err = {}; if (!kony.sdk.util.isNullOrEmptyString(objectServiceName)) { sdkObjectSync = syncV2Classes.SDKObjectSync.alloc().initWithNameAndObjectServiceNameError(name, objectServiceName, err); } else { sdkObjectSync = syncV2Classes.SDKObjectSync.alloc().initWithNameError(name, err); } if (err.error) { var exception = new Exception(err.error.code, err.error.localizedDescription); if (err.error.domain) { exception.domain = err.error.domain; } if (err.error.userInfo && err.error.userInfo.callStack) { exception.callStack = err.error.userInfo.callStack; } throw exception; } return sdkObjectSync; }; kony.sdk.KNYObj.startSync = function(knyObj, syncConfig, successCallback, failureCallback, progressCallback) { var LOG_PREFIX = "kony.sdk.KNYObj.startSync"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Syncing " + knyObj.name + " object success", successCallback, "Syncing " + knyObj.name + " object failed", failureCallback); var konySyncProgressCallback = kony.sdk.OfflineObjects.createKonySyncProgressCallback("Sync Progresss Callback Called", progressCallback); var sdkObjectSync = knyObj.getSdkObjectSync(); sdkObjectSync.startSyncOnSuccessOnFailureOnProgress(syncConfig, syncCallback.onSuccess, syncCallback.onFailure, konySyncProgressCallback.onProgress); }; kony.sdk.KNYObj.create = function(knyObj, record, options, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.KNYObj.create"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Creating record in " + knyObj.name + " object success", successCallback, "Creating record in " + knyObj.name + " object failed", failureCallback); var sdkObjectSync = knyObj.getSdkObjectSync(); sdkObjectSync.createOptionsOnSuccessOnFailure(record, options, syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.KNYObj.updateByPK = function(knyObj, record, options, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.KNYObj.updateByPK"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Updating record in " + knyObj.name + " object success", successCallback, "Updating record in " + knyObj.name + " object failed", failureCallback); var sdkObjectSync = knyObj.getSdkObjectSync(); sdkObjectSync.updateByPKOptionsOnSuccessOnFailure(record, options, syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.KNYObj.deleteByPK = function(knyObj, options, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.KNYObj.deleteByPK"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Deleting record in " + knyObj.name + " object success", successCallback, "Deleting record in " + knyObj.name + " object failed", failureCallback); var sdkObjectSync = knyObj.getSdkObjectSync(); sdkObjectSync.deleteByPKOnSuccessOnFailure(options, syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.KNYObj.get = function(knyObj, options, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.KNYObj.get"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Retrieving record from " + knyObj.name + " object success", successCallback, "Retrieving record from " + knyObj.name + " object failed", failureCallback); var sdkObjectSync = knyObj.getSdkObjectSync(); sdkObjectSync.getOnSuccessOnFailure(options, syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.KNYObj.rollback = function(knyObj, primaryKeyValueMap, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.KNYObj.rollback"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Rollback on " + knyObj.name + " object success", successCallback, "Rollback on " + knyObj.name + " object failed", failureCallback); var sdkObjectSync = knyObj.getSdkObjectSync(); sdkObjectSync.rollbackOnSuccessOnFailure(primaryKeyValueMap, syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.KNYObj.getBinary = function(knyObj, options, fileDownloadStartedCompletionBlock, chunkDownloadCompletedCompletionBlock, streamDownloadCompletionBlock, fileDownloadCompletedCompletionBlock, downloadFailureCompletionBlock) { var LOG_PREFIX = "kony.sdk.KNYObj.getBinary"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var binaryCallback = kony.sdk.OfflineObjects.createKonyBinaryDownloadCallback("Get binary on " + knyObj.name + " object started", fileDownloadStartedCompletionBlock, "Get binary on " + knyObj.name + " object: chunk download completed", chunkDownloadCompletedCompletionBlock, "Get binary on " + knyObj.name + " object: stream download completed", streamDownloadCompletionBlock, "Get binary on " + knyObj.name + " object: file download completed", fileDownloadCompletedCompletionBlock, "Get binary on " + knyObj.name + " object failed", downloadFailureCompletionBlock); var sdkObjectSync = knyObj.getSdkObjectSync(); sdkObjectSync.getBinaryDownloadStartedHandlerChunkDownloadCompletedHandlerStreamDownloadCompletedHandlerFileDownloadCompletedHandlerDownloadFailureHandler(options, binaryCallback.onFileDownloadStarted, binaryCallback.onChunkDownloadCompleted, binaryCallback.onStreamDownloadCompleted, binaryCallback.onFileDownloadCompleted, binaryCallback.onDownloadFailure); }; kony.sdk.KNYObj.getBinaryStatus = function(knyObj, options, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.KNYObj.getBinaryStatus"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("getBinaryStatus on " + knyObj.name + " object success", successCallback, "getBinaryStatus on " + knyObj.name + " object failed", failureCallback); var sdkObjectSync = knyObj.getSdkObjectSync(); sdkObjectSync.getBinaryStatusOnSuccessOnFailure(options, syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.KNYObj.markForUpload = function(knyObj, options, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.KNYObj.markForUpload"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("MarkForUpload on " + knyObj.name + " object success", successCallback, "Mark For Upload on " + knyObj.name + " object failed", failureCallback); var sdkObjectSync = knyObj.getSdkObjectSync(); sdkObjectSync.markForUploadOnSuccessOnFailure(options, syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.KNYObj.getUploadDeferredRecordKeys = function(knyObj, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.KNYObj.getUploadDeferredRecordKeys"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Retrieving deffered record primary keys from " + knyObj.name + " object success", successCallback, "Retrieving deferred record primary keys from " + knyObj.name + " object failed", failureCallback); var sdkObjectSync = knyObj.getSdkObjectSync(); sdkObjectSync.getUploadDeferredRecordKeysOnFailure(syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.KNYObj.cancelSync = function(knyObj, options, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.knyObj.cancelSync"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("CancelSync on " + knyObj.name + " object success", successCallback, "CancelSync on " + knyObj.name + " object failed", failureCallback); var sdkObjectSync = knyObj.getSdkObjectSync(); sdkObjectSync.cancelSyncOnFailure(syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.KNYObjSvc.createSDKObjectServiceSync = function(name) { var LOG_PREFIX = "kony.sdk.KNYObjSvc.createSDKObjectServiceSync"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncV2Classes = kony.sdk.SyncV2Classes.import(); var err = {}; var sdkObjectServiceSync = syncV2Classes.SDKObjectServiceSync.alloc().initWithNameError(name, err); if (err.error) { var exception = new Exception(err.error.code, err.error.localizedDescription); if (err.error.domain) { exception.domain = err.error.domain; } if (err.error.userInfo && err.error.userInfo.callStack) { exception.callStack = err.error.userInfo.callStack; } throw exception; } return sdkObjectServiceSync; }; kony.sdk.KNYObjSvc.startSync = function(knyObjSvc, syncConfig, successCallback, failureCallback, progressCallback) { var LOG_PREFIX = "kony.sdk.KNYObjSvc.startSync"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Syncing " + knyObjSvc.name + " object service success", successCallback, "Syncing " + knyObjSvc.name + " object service failed", failureCallback); var konySyncProgressCallback = kony.sdk.OfflineObjects.createKonySyncProgressCallback("Sync Progresss Callback Called", progressCallback); var sdkObjectServiceSync = knyObjSvc.getSdkObjectServiceSync(); sdkObjectServiceSync.startSyncOnSuccessOnFailureOnProgress(syncConfig, syncCallback.onSuccess, syncCallback.onFailure, konySyncProgressCallback.onProgress); }; kony.sdk.KNYObjSvc.rollback = function(knyObjSvc, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.KNYObjSvc.rollback"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Rollback on " + knyObjSvc.name + " object service success", successCallback, "Rollback on " + knyObjSvc.name + " object service failed", failureCallback); var sdkObjectServiceSync = knyObjSvc.getSdkObjectServiceSync(); sdkObjectServiceSync.rollbackOnFailure(syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.KNYObjSvc.cancelSync = function(knyObjSvc, options, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.KNYObjSvc.cancelSync"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("CancelSync on " + knyObjSvc.name + " object service success", successCallback, "CancelSync on " + knyObjSvc.name + " object service failed", failureCallback); var sdkObjectServiceSync = knyObjSvc.getSdkObjectServiceSync(); sdkObjectServiceSync.cancelSyncOnFailure(syncCallback.onSuccess, syncCallback.onFailure); }; kony.sdk.KNYObjSvc.clearOfflineData = function(knyObjSvc, options, successCallback, failureCallback) { var LOG_PREFIX = "kony.sdk.KNYObjSvc.clearOfflineData"; kony.sdk.logsdk.trace("Entering " + LOG_PREFIX); var syncCallback = kony.sdk.OfflineObjects.createSyncCallback("Successfully cleared offline data in " + knyObjSvc.name + " object service.", successCallback, "Failed to clear offline data in " + knyObjSvc.name + " object service.", failureCallback); var sdkObjectServiceSync = knyObjSvc.getSdkObjectServiceSync(); sdkObjectServiceSync.clearDataWithOptionsOnSuccessOnFailure(options, syncCallback.onSuccess, syncCallback.onFailure); }; kony.logger = kony.logger || {}; kony.logger.createNewLogger = function(loggerName, loggerConfig) { parseConfig = function(loggerConfig) { //private methods if (loggerConfig === null || typeof(loggerConfig) === 'undefined') { loggerConfig = {}; } else { loggerConfig = loggerConfig.getLoggerConfig(); } if (typeof(appConfig) != 'undefined') { appDetails = { appID: appConfig.appId, appVersion: appConfig.appVersion, sessionID: kony.license.getSessionId() }; //appInfo loggerConfig.appInfo = appDetails; } return loggerConfig; }; logMessage = function(loggerObj, logLevel, msg, params) { logMessageInFFI = function(NativeLoggerObject, logLevel, message) { switch (logLevel) { case kony.logger.logLevel.TRACE: NativeLoggerObject.logTrace(message); break; case kony.logger.logLevel.DEBUG: NativeLoggerObject.logDebug(message); break; case kony.logger.logLevel.INFO: NativeLoggerObject.logInfo(message); break; case kony.logger.logLevel.PERF: NativeLoggerObject.logPerf(message); break; case kony.logger.logLevel.WARN: NativeLoggerObject.logWarning(message); break; case kony.logger.logLevel.ERROR: NativeLoggerObject.logError(message); break; case kony.logger.logLevel.FATAL: NativeLoggerObject.logFatal(message); break; default: kony.print("Implementation not found for the specified log level " + logLevel); return; } }; formatLineInfo = function(callerInformation) { if (callerInformation.length == 3) { return callerInformation[1]; } // MFSDK-3910 // Temporary Fix to send line number as null if not present instead of undefined(<null>) return ""; }; formatFileInfo = function(callerInformation) { if (callerInformation.length >= 1) { callerInformation = callerInformation[callerInformation.length - 1]; callerInformation = callerInformation.split(":"); if (callerInformation.length == 3) { return callerInformation[0]; } } }; formatMethodInformation = function(callerInformation) { if (callerInformation.length > 1) return callerInformation[callerInformation.length - 2]; }; formatCallerInformation = function(callerInformation) { //JSCore syntax: <methodName>@<fileName>:<row>:<col> //V8 syntax: at <methodName> (<fileName>:<row>:<col>) //Chakra syntax: at (<methodURL> <fileURL>:<row>:<col>) if (callerInformation !== null) { var seperator = " "; seperator = "@"; formattedCallerInformation = callerInformation.split(seperator); return formattedCallerInformation; } return []; }; getCallerInformationFromCallStack = function(callStack, indirectionLevel) { var index = 5; index = 4; index += indirectionLevel; if (callStack.length >= index) return callStack[index]; return null; }; generateCallerInformation = function(indirectionLevel) { var errorObject = new Error(); var callStack; // In IE, Error object doesn't contain stack information, hence can't provide caller info if (errorObject.hasOwnProperty("stack")) { callStack = errorObject.stack.split("\n"); } else { callStack = []; } var callerInformation = getCallerInformationFromCallStack(callStack, indirectionLevel); return formatCallerInformation(callerInformation); }; parseMessage = function(loggerObj, logLevel, msg, params) { var logLevelVal = (kony.logger.isNativeLoggerAvailable()) ? KonyLogger.getLogLevel() : kony.logger.currentLogLevel.value; if (logLevel.value >= logLevelVal) { var metaData = {}; params = (typeof(params) === "undefined") ? "" : params; //Stringify object if (kony.logger.isValidJSTable(params)) { params = JSON.stringify(params, null, " "); } metaData.message = msg + params; metaData.callerInformation = generateCallerInformation(loggerObj.getIndirectionLevel()); metaData.methodName = formatMethodInformation(metaData.callerInformation); metaData.fileName = formatFileInfo(metaData.callerInformation); metaData.lineNo = formatLineInfo(metaData.callerInformation); if (kony.logger.isNativeLoggerAvailable()) { if (!loggerObj.NativeLoggerObject) { loggerObj.NativeLoggerObject = new KonyLogger.InitializeLogger(loggerObj.loggerName); KonyLogger.setConfig(loggerObj.config); } if (loggerObj.NativeLoggerObject) { logMessageInFFI(loggerObj.NativeLoggerObject, logLevel, metaData); } else { var date = new Date().toLocaleDateString(); var time = new Date().toLocaleTimeString(); var level = logLevel.code; var formattedMessage = "[" + loggerObj.loggerName + "][" + level + "][" + date + " " + time + "][" + metaData.fileName + "][" + metaData.methodName + "][" + metaData.lineNo + "] : " + metaData.message; kony.print(formattedMessage); } } else { var date = new Date().toLocaleDateString(); var time = new Date().toLocaleTimeString(); var level = logLevel.code; var formattedMessage = "[" + loggerObj.loggerName + "][" + level + "][" + date + " " + time + "][" + metaData.fileName + "][" + metaData.methodName + "][" + metaData.lineNo + "] : " + metaData.message; kony.print(formattedMessage); } } }; parseMessage(loggerObj, logLevel, msg, params); }; //Exposed object and it's methods var loggerObj = kony.logger.createLoggerObject(loggerName, loggerConfig); //Native object creation if (kony.logger.isNativeLoggerAvailable()) { loggerObj.NativeLoggerObject = new KonyLogger.InitializeLogger(loggerName); KonyLogger.setConfig(loggerObj.config); } return loggerObj; } kony.logger["appLogger"] = kony.logger.appLoggerInitialisation(); /** * MFSDK * Created by KH2204. * Copyright © 2018 Kony. All rights reserved. */ /** * Method to create the integration service instance with the provided service name. * @param {string} serviceName - Name of the service * @returns {IntegrationService} Integration service instance */ kony.sdk.prototype.getIntegrationService = function(serviceName) { if (!kony.sdk.isInitialized) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, kony.sdk.constants.INIT_FAILURE_MESSAGE + "integration service :" + serviceName); } var konyRef = kony.sdk.getCurrentInstance(); if (!kony.sdk.skipAnonymousCall && !this.currentClaimToken && !konyRef.isAnonymousProvider) { throw new Exception(kony.sdk.errorConstants.AUTH_FAILURE, "Valid claims token is not found, login using identity service before performing an operation on this integration service :" + serviceName); } if (this.integsvc != null) { if (this.integsvc[serviceName] != null) { kony.sdk.logsdk.debug("found integration service" + this.integsvc[serviceName]); return new IntegrationService(this, serviceName); } } throw new Exception(kony.sdk.errorConstants.INTEGRATION_FAILURE, "Integration service is not found or invalid :" + serviceName); }; /** * Method should not be called by developer. * @class * @classdesc Integration service instance for invoking the integration services. */ function IntegrationService(konyRef, serviceName) { var serviceUrl = ""; var svcObj = konyRef.integsvc[serviceName]; if (typeof(svcObj) === "object") { serviceUrl = svcObj["url"]; } else { serviceUrl = svcObj; } var networkProvider = new konyNetworkProvider(); if (kony.sdk.util.isNullOrEmptyString(serviceName) || kony.sdk.util.isNullOrEmptyString(serviceUrl)) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, "Invalid serviceUrl and serviceName"); } serviceUrl = stripTrailingCharacter(serviceUrl, "/"); this.getUrl = function() { return serviceUrl; }; /** * Integration service success callback method. * @callback integrationSuccessCallback * @param {json} response - Integration service response */ /** * Integration service failure callback method. * @callback integrationFailureCallback * @param {json} error - Error information */ /** * invoke the specified operation * @param {string} operationName - Name of the operation * @param {object} headers - Input headers for the operation * @param {object} data - Input data for the operation * @param {integrationSuccessCallback} successCallback - Callback method on success * @param {integrationFailureCallback} failureCallback - Callback method on failure * @param {object} options - XMLHttpRequest options like withCredentials value. */ this.invokeOperation = function(operationName, headers, data, successCallback, failureCallback, options) { function invokeOperationHandler() { _invokeOperation(operationName, headers, data, true, successCallback, failureCallback, options); } if (kony.sdk.skipAnonymousCall) { invokeOperationHandler(); } else { kony.sdk.claimsRefresh(invokeOperationHandler, failureCallback); } }; /** * Integration service API to upload binaries based on adapter template * @param {string} operationName - Name of the operation * @param {Object} uploadParams - InputContext or template variables * @param {callback} fileUploadStartedCallback - Callback which is invoked on start of file upload * @param {callback} chunkUploadCompletedCallback - Callback which is invoked on chunk upload * @param {callback} fileUploadCompletedCallback - Callback which is invoked on complete of file upload * @param {callback} fileUploadFailureCallback - Callback which is invoked in case of error during upload * @param {Object} options - Provision for user to send additional options */ this.uploadBinaryData = function(operationName, uploadParams, fileUploadStartedCallback, chunkUploadCompletedCallback, fileUploadCompletedCallback, fileUploadFailureCallback, options) { var errorObj = kony.sdk.binary.validateUploadParams(uploadParams); if (errorObj) { kony.sdk.verifyAndCallClosure(fileUploadFailureCallback, errorObj); return; } // if rawbytes are provided, converting to base64 string as can only receive base datatypes if (!kony.sdk.isNullOrUndefined(uploadParams[kony.sdk.constants.RAW_BYTES])) { var base64String = kony.convertToBase64(uploadParams[kony.sdk.constants.RAW_BYTES]); uploadParams[kony.sdk.constants.RAW_BYTES] = base64String; } function uploadBinaryDataHandler() { var uploadOptions = {}; uploadOptions["URL"] = serviceUrl + "/" + operationName; var headers = {}; if (!kony.sdk.skipAnonymousCall) { headers[kony.sdk.constants.KONY_AUTHORIZATION_HEADER] = kony.sdk.getCurrentInstance().currentClaimToken; } uploadOptions["headers"] = headers; //Extracting Mandatory Params from uploadParams before fetching template if (uploadParams[kony.sdk.constants.FILE_PATH]) { uploadOptions[kony.sdk.constants.FILE_PATH] = uploadParams[kony.sdk.constants.FILE_PATH]; delete uploadParams[kony.sdk.constants.FILE_PATH]; } else if (uploadParams[kony.sdk.constants.RAW_BYTES]) { uploadOptions[kony.sdk.constants.RAW_BYTES] = uploadParams[kony.sdk.constants.RAW_BYTES]; delete uploadParams[kony.sdk.constants.RAW_BYTES]; } else if (uploadParams[kony.sdk.constants.FILE_OBJECT]) { uploadOptions[kony.sdk.constants.FILE_OBJECT] = uploadParams[kony.sdk.constants.FILE_OBJECT]; delete uploadParams[kony.sdk.constants.FILE_OBJECT] } uploadOptions["uploadParams"] = uploadParams; kony.sdk.binary.uploadBinaryData(uploadOptions, fileUploadStartedCallback, chunkUploadCompletedCallback, fileUploadCompletedCallback, fileUploadFailureCallback, options); } if (kony.sdk.skipAnonymousCall) { uploadBinaryDataHandler(); } else { kony.sdk.claimsRefresh(uploadBinaryDataHandler, fileUploadFailureCallback); } }; /** * Integration service API to download binaries based on adapter template * @param {string} operationName - Name of the operation * @param {Object} fileparams - InputContext or template variables * @param {boolean} streaming - Boolean value to determine, whether chunks need to be saved to file or sent in callbacks * @param {Object} headers - Provision for custom headers * @param {callback} fileDownloadStartedCallback - Callback which is invoked on start of file download * @param {callback} chunkDownloadCompletedCallback - Callback which is invoked on stream/chunk download * @param {callback} fileDownloadCompletedCallback - Callback which is invoked on complete of file download * @param {callback} downloadFailureCallback - Callback which is invoked in case of error during download * @param {Object} options - Provision for user to send additional options */ this.getBinaryData = function(operationName, fileparams, streaming, headers, fileDownloadStartedCallback, chunkDownloadCompletedCallback, fileDownloadCompletedCallback, downloadFailureCallback, options) { function getBinaryDataHandler() { _invokeOperation(operationName, headers, fileparams, true, function(downloadConfig) { if (kony.sdk.isNullOrUndefined(downloadConfig)) { downloadConfig = {}; } if (options && options["ChunkSize"]) { downloadConfig.ChunkSize = options["ChunkSize"]; } if (headers) { if (kony.sdk.isNullOrUndefined(downloadConfig.headers)) { downloadConfig.headers = {}; } for (var header in headers) { if (headers.hasOwnProperty(header)) { downloadConfig.headers[header] = headers[header]; } } } kony.sdk.binary.getBinaryData(fileparams, streaming, downloadConfig, fileDownloadStartedCallback, chunkDownloadCompletedCallback, fileDownloadCompletedCallback, downloadFailureCallback, options); }, downloadFailureCallback, options); } if (kony.sdk.skipAnonymousCall) { // Check to find if the service is public or not, in case of public service anonymous login is not required. getBinaryDataHandler(); } else { kony.sdk.claimsRefresh(getBinaryDataHandler, downloadFailureCallback); } }; function invokeOperationRetry(operationName, headers, data, successCallback, failureCallback, options) { function invokeOperationRetryHandler() { _invokeOperation(operationName, headers, data, false, successCallback, failureCallback, options); } if (kony.sdk.skipAnonymousCall) { invokeOperationRetryHandler(); } else { kony.sdk.claimsAndProviderTokenRefresh(invokeOperationRetryHandler, failureCallback); } } function retryServiceCall(errorResponse) { if (errorResponse[kony.sdk.constants.MF_CODE]) { // check for the mfcode for which, // retry should be done. } else { if (errorResponse[kony.sdk.constants.HTTP_STATUS_CODE] && errorResponse[kony.sdk.constants.HTTP_STATUS_CODE] === 401) { kony.sdk.logsdk.debug("### IntegrationService::retryServiceCall received 401 from fabric, trying to refresh backend token"); return true; } } } function _invokeOperation(operationName, headers, data, isRetryNeeded, successCallback, failureCallback, options) { var requestData = kony.sdk.getPayload(konyRef); requestData.svcid = operationName; var sessionID = kony.sdk.dataStore.getItem(kony.sdk.constants.KONYUUID); if (!kony.sdk.isNullOrUndefined(sessionID)) { requestData.rsid = sessionID; } else { kony.sdk.logsdk.warn("sessionId is either empty,null or undefined"); } var dataToSend = {}; if (kony.sdk.metric) { if (kony.sdk.metric.reportEventBufferBackupArray.length === 0) { kony.sdk.metric.readFromDS(); } kony.sdk.metric.pushEventsToBufferArray(); requestData.events = kony.sdk.metric.reportEventBufferBackupArray; } for (var key in data) { if (data.hasOwnProperty(key)) { dataToSend[key] = data[key]; } } var defaultHeaders = {}; defaultHeaders[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; defaultHeaders["X-Kony-ReportingParams"] = JSON.stringify(requestData); if (!kony.sdk.skipAnonymousCall) { // Check to find if the service is public or not, in case of public service no token is required. var token = konyRef.currentClaimToken; if (!token) { token = kony.sdk.getCurrentInstance().currentClaimToken; } defaultHeaders[kony.sdk.constants.KONY_AUTHORIZATION_HEADER] = token; } var deviceId = kony.sdk.getDeviceId(); if (!kony.sdk.isNullOrUndefined(deviceId)) { defaultHeaders["X-Kony-DeviceId"] = deviceId; } if (typeof(svcObj) === 'object' && svcObj.version) { defaultHeaders["X-Kony-API-Version"] = svcObj.version; } // if the user has defined his own headers, use them if (!kony.sdk.isNullOrUndefined(headers)) { if ((Object.keys(headers)).length !== 0 && typeof(headers) === "object") { var defaultKeys = Object.keys(defaultHeaders); var lowerCaseHeaders = defaultKeys.map(function(x) { return x.toLowerCase() }); for (var header in headers) { var headerConst = header; if (lowerCaseHeaders.indexOf(headerConst.toLowerCase()) !== -1) { for (var i = 0; i < defaultKeys.length; i++) { var tempKey = defaultKeys[i]; if (tempKey.toLowerCase() === headerConst.toLowerCase()) { defaultHeaders[tempKey] = headers[header]; } } } else { defaultHeaders[header] = headers[header]; } } } } // If useCache is enabled and cacheID is present then network call will be skipped and cached response will be returned. if (options && options["useCache"] && options["cacheID"]) { var cacheResponse = new kony.sdk.ClientCache().get(options["cacheID"]); if (cacheResponse) { kony.sdk.logsdk.debug("Key found in hash, returning cached response."); kony.sdk.verifyAndCallClosure(successCallback, cacheResponse); return; } } function networkSuccessCallback(res) { if (kony.sdk.metric) { kony.sdk.metric.clearBufferEvents(); } // If useCache is enabled then the response is cached and returned. if (options && options["useCache"]) { cacheResponseForKey(options, serviceUrl + "/" + operationName, requestData, res); } kony.sdk.verifyAndCallClosure(successCallback, res); } function networkFailureCallback(xhr, status, err) { if (xhr && !(status && err)) { err = xhr; } if (isRetryNeeded === true && retryServiceCall(err) === true) { kony.sdk.logsdk.debug("errorCallback, retrying the operation: " + operationName); invokeOperationRetry(operationName, headers, data, successCallback, failureCallback); return; } kony.sdk.processIntegrationErrorResponse(err, true, failureCallback); } networkProvider.post(serviceUrl + "/" + operationName, dataToSend, defaultHeaders, networkSuccessCallback, networkFailureCallback, null, options); } kony.sdk.processIntegrationErrorResponse = function(err, isAsync, callBack) { if (kony.sdk.metric) { if (kony.sdk.metric.errorCodeMap[err.opstatus]) { kony.sdk.metric.saveInDS(); } } if (err[kony.sdk.constants.MF_CODE]) { //clear the cache if the error code related to session/token expiry if (kony.sdk.isSessionOrTokenExpired(err[kony.sdk.constants.MF_CODE])) { kony.sdk.logsdk.info("###IntegrationService::invokeOperationFailure Session/Token expired. Authenticate and Try again"); //TODO: Start a conversation with Suhas and Krishna regarding the scenario wherein one auth session expired and other is still valid. } } if (!isAsync) { return kony.sdk.error.getIntegrationErrObj(err); } else if (callBack) { kony.sdk.verifyAndCallClosure(callBack, kony.sdk.error.getIntegrationErrObj(err)); } }; //This is an internal api to invoke an service synchronously this.invokeOperationSync = function(operationName, headers, data) { var res = null; res = kony.sdk.claimsRefreshSync(); if (res && res.message && res.message === "success") { return _invokeOperationSync(operationName, headers, data); } else { return res; } }; function _invokeOperationSync(operationName, headers, data) { var requestData = {}; var konyRef = kony.sdk.getCurrentInstance(); var reportingData = kony.sdk.getPayload(konyRef); var sessionId = kony.ds.read(kony.sdk.constants.KONYUUID); if (sessionId) { reportingData.rsid = sessionId[0]; } if (!reportingData.rsid) { kony.sdk.logsdk.info("rsid is either empty,null or undefined"); } if (kony.sdk.metric) { if (kony.sdk.metric.reportEventBufferBackupArray.length === 0) { kony.sdk.metric.readFromDS(); } kony.sdk.metric.pushEventsToBufferArray(); reportingData.events = kony.sdk.metric.reportEventBufferBackupArray; } for (var key in data) { if (data.hasOwnProperty(key)) { requestData[key] = data[key]; } } reportingData.svcid = operationName; var token; for (var tempToken in konyRef.tokens) { if (konyRef.tokens.hasOwnProperty(tempToken) && typeof(tempToken) !== 'function') { token = konyRef.tokens[tempToken]; break; } } requestData[kony.sdk.constants.REPORTING_PARAMS] = JSON.stringify(reportingData); var defaultHeaders = {} defaultHeaders[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; defaultHeaders[kony.sdk.constants.KONY_AUTHORIZATION_HEADER] = konyRef.currentClaimToken; if (typeof(svcObj) === 'object' && svcObj.version) { defaultHeaders["X-Kony-API-Version"] = svcObj.version; } // if the user has defined his own headers, use them if ((Object.keys(headers)).length !== 0) { var defaultKeys = []; defaultKeys = Object.keys(defaultHeaders); var defaultkeyLower = {}; defaultkeyLower = defaultKeys.map(function(x) { return x.toLowerCase() }); for (var header in headers) { var headerConst = header; if (defaultkeyLower.indexOf(headerConst.toLowerCase()) !== -1) { for (var i = 0; i < defaultKeys.length; i++) { var tempKey = defaultKeys[i]; if (tempKey.toLowerCase() === headerConst.toLowerCase()) { defaultHeaders[tempKey] = headers[header]; } } } else { defaultHeaders[header] = headers[header]; } } } var res = null; res = networkProvider.postSync(serviceUrl + "/" + operationName, requestData, defaultHeaders); if (res.opstatus == 0) { if (kony.sdk.metric) { kony.sdk.metric.clearBufferEvents(); } return res; } else { return kony.sdk.processIntegrationErrorResponse(res, false); } } } kony.sdk.claimsRefreshSync = function() { var konyRef = kony.sdk.getCurrentInstance(); var networkProvider = new konyNetworkProvider(); var loginWithAnonymousProvider = function() { var identityObject = konyRef.getIdentityService("$anonymousProvider"); var res = identityObject.anonymousLoginSync(null); if (res && JSON.stringify(res) == "{}") { return { "message": "success" }; } else { return kony.sdk.error.getAuthErrObj(res); } }; if (konyRef.currentClaimToken === null) { kony.sdk.logsdk.info("claims Token is Unavialable"); if (konyRef.isAnonymousProvider) { return loginWithAnonymousProvider(); } else { return kony.sdk.error.getNullClaimsTokenErrObj(); } } else if (konyRef.claimTokenExpiry && new Date().getTime() > konyRef.claimTokenExpiry) { if (konyRef.isAnonymousProvider) { return loginWithAnonymousProvider(); } else { kony.sdk.logsdk.info("claims token has expired. fetching new token.."); var _serviceUrl = stripTrailingCharacter(konyRef.rec.url, "/"); var _url = _serviceUrl + "/claims"; kony.sdk.logsdk.debug("service url is " + _url); if (konyRef.currentRefreshToken === null) { return kony.sdk.error.getNullRefreshTokenErrObj(); } else { var headers = {}; headers[kony.sdk.constants.AUTHORIZATION_HEADER] = konyRef.currentRefreshToken; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; var data = networkProvider.postSync(_url, {}, headers); if (data.opstatus == 0) { kony.sdk.logsdk.info("refresh success..acquiring new tokens"); return kony.sdk.processClaimsSuccessResponse(data, konyRef, false); } else { kony.sdk.logsdk.info("failed to acquire refresh token"); return kony.sdk.processClaimsErrorResponse(data, konyRef, false); } } } } else { return { "message": "success" }; } }; /** * Method to create the messaging service instance. * @returns {MessagingService} Messaging service instance */ kony.sdk.prototype.getMessagingService = function() { if (!kony.sdk.isInitialized) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, kony.sdk.constants.INIT_FAILURE_MESSAGE + " Messaging service."); } return new MessagingService(this); }; /** * Should not be called by the developer. * @class * @classdesc Messaging service instance for invoking the Messaging services. * @param konyRef - reference to kony object */ function MessagingService(konyRef) { var homeUrl = konyRef.messagingsvc.url; var appId = konyRef.messagingsvc.appId; var networkProvider = new konyNetworkProvider(); var dsKey_KSID = appId + "_KSID"; var dsKey_authToken = appId + "_AUTHTOKEN"; var currentObject = this; var geoBoundaryData; var KSID; var AUTHTOKEN; this.getUrl = function() { return homeUrl; }; this.setKSID = function(ksid) { kony.sdk.dataStore.setItem(dsKey_KSID, ksid); KSID = ksid; }; this.getKSID = function() { if (!KSID) { KSID = kony.sdk.dataStore.getItem(dsKey_KSID); } return KSID; }; this.setAuthToken = function(authToken) { kony.sdk.dataStore.setItem(dsKey_authToken, authToken); AUTHTOKEN = authToken }; this.getAuthToken = function(options) { if (options && options[kony.sdk.constants.AUTH_TOKEN]) { AUTHTOKEN = options[kony.sdk.constants.AUTH_TOKEN]; } else { //retrieving from local store if user given token is null AUTHTOKEN = kony.sdk.dataStore.getItem(dsKey_authToken); } return AUTHTOKEN; }; var setGeoBoundaryData = function(data) { kony.sdk.dataStore.setItem("geoBoundaryData", data); geoBoundaryData = data; }; var getGeoBoundaryDataForBoundaryId = function(boundaryId) { if (!geoBoundaryData) { geoBoundaryData = kony.sdk.dataStore.getItem("geoBoundaryData") } return geoBoundaryData[boundaryId]; }; this.setKmsAppId = function(id) { appId = id; }; this.getKmsAppId = function() { return appId; }; KSID = currentObject.getKSID(); AUTHTOKEN = currentObject.getAuthToken(); var registerForMessagingService = function(osType, deviceId, pnsToken, email, authToken, successCallback, failureCallback) { var uri = homeUrl + "/subscribers"; var subscribeParamsJson = { "sid": pnsToken, "appId": appId, "ufid": email, "osType": osType, "deviceId": deviceId }; if (authToken != undefined && authToken != null) { subscribeParamsJson[kony.sdk.constants.AUTH_TOKEN] = authToken; } var jsonParam = { "subscriptionService": { "subscribe": subscribeParamsJson } }; var headers = {}; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_JSON; var payload = { postdata: JSON.stringify(jsonParam) }; var networkOptions = {}; networkOptions["disableIntegrity"] = true; networkProvider.post(uri, payload, headers, function(data) { currentObject.setKSID(data.id); currentObject.setAuthToken(authToken); kony.sdk.verifyAndCallClosure(successCallback, data); }, function(data, status, error) { kony.sdk.logsdk.error("ERROR: Failed to register device for KMS"); var errorObj = {}; errorObj.data = data; errorObj.status = status; errorObj.error = error; kony.sdk.verifyAndCallClosure(failureCallback, errorObj); }, null, networkOptions); }; var subscribeAudienceOrUpdate = function(firstName, lastName, emailId, mobileNumber, country, state, options, successCallback, failureCallback) { var uri = homeUrl + kony.sdk.constants.SUBSCRIBE_AUDIENCE; var subscribeAudienceJson = { "ksid": KSID, "firstName": firstName, "lastName": lastName, "email": emailId, "mobileNumber": mobileNumber, "country": country, "state": state }; var currentdate = new Date(); //toLocaleString gives current time in below format //6/25/2018, 12:38:21 PM var datetime = currentdate.toLocaleString('en-US', { timeZone: 'UTC' }); //remove , in the current UTC time datetime = datetime.replace(",", ""); subscribeAudienceJson[kony.sdk.constants.LAST_ACTIVE_DATE] = datetime; if (!kony.sdk.isNullOrUndefined(options)) { for (var key in options) { if (options.hasOwnProperty(key)) { if (key === kony.sdk.constants.AUTH_TOKEN) { subscribeAudienceJson[key] = currentObject.getAuthToken(options); } else { subscribeAudienceJson[key] = options[key]; } } } } var headers = {}; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_JSON; var payload = { postdata: JSON.stringify(subscribeAudienceJson) }; var networkOptions = {}; networkOptions[kony.sdk.constants.DISABLE_INTEGRITY] = true; networkProvider.post(uri, payload, headers, function(data) { //override data store auth token with user given token overrideAuthToken(options); kony.sdk.verifyAndCallClosure(successCallback, data); }, function(data, status, error) { kony.sdk.logsdk.error("ERROR: Failed to create or update audience", errorObj); var errorObj = {}; errorObj.data = data; errorObj.status = status; errorObj.error = error; kony.sdk.verifyAndCallClosure(failureCallback, errorObj); }, null, networkOptions); }; /** * register to messaging service * @param {string} osType - Type of the operating system * @param {string} deviceId - Device Id * @param {string} pnsToken - Token value * @param {string} ufid - UFID can be email-id,mobile number or any dynamic attribute configured as reconciliation key in Engagement console * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure * @param {dictionary} options - {authToken: <Auth Token>} */ this.register = function(osType, deviceId, pnsToken, ufid, successCallback, failureCallback, options) { var authToken = null; if (kony.sdk.isNullOrUndefined(pnsToken)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid pnsToken/sId, it cannot be null"); } if (kony.sdk.isNullOrUndefined(osType)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid osType, it cannot be null"); } if (kony.sdk.isNullOrUndefined(deviceId)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid deviceId, it cannot be null"); } if (kony.sdk.isNullOrUndefined(ufid)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid email, it cannot be null"); } authToken = currentObject.getAuthToken(options); registerForMessagingService(osType, deviceId, pnsToken, ufid, authToken, function(data) { //override data store auth token with user given token overrideAuthToken(options); kony.sdk.verifyAndCallClosure(successCallback, data); }, function(errorObj) { kony.sdk.logsdk.error("Register :: Register for messaging service failed with error", errorObj); kony.sdk.verifyAndCallClosure(failureCallback, errorObj); }); }; /** * register to messaging service * @param {string} osType - Type of the operating system * @param {string} deviceId - Device Id * @param {string} authToken - Authorization Token * @param {string} pnsToken - Token value * @param {string} email - email * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure */ /** * @deprecated This method is deprecated because authToken can be given as input through options param of * register method. */ this.registerWithAuthToken = function(osType, deviceId, pnsToken, email, authToken, successCallback, failureCallback) { if (kony.sdk.isNullOrUndefined(pnsToken)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid pnsToken/sId,it cannot be null"); } if (kony.sdk.isNullOrUndefined(osType)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid osType, it cannot be null"); } if (kony.sdk.isNullOrUndefined(deviceId)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid deviceId, it cannot be null"); } if (kony.sdk.isNullOrUndefined(email)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid email, it cannot be null"); } if (kony.sdk.isNullOrUndefined(authToken)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid authToken, it cannot be null"); } registerForMessagingService(osType, deviceId, pnsToken, email, authToken, function(data) { kony.sdk.verifyAndCallClosure(successCallback, data) }, function(errorObj) { kony.sdk.verifyAndCallClosure(failureCallback, errorObj); }); }; var unregisterFromMessagingService = function(authToken, successCallback, failureCallback) { var uri = homeUrl + "/subscribers"; var unsubscribeObj = { "ksid": currentObject.getKSID() }; if (authToken != undefined && authToken != null) { unsubscribeObj[kony.sdk.constants.AUTH_TOKEN] = authToken; } var inp = { "subscriptionService": { "unsubscribe": unsubscribeObj } }; var headers = {}; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_JSON; var payload = { postdata: JSON.stringify(inp) }; kony.sdk.logsdk.info("unsubscribe uri:" + uri); var networkOptions = {}; networkOptions[kony.sdk.constants.DISABLE_INTEGRITY] = true; networkProvider.post(uri, payload, headers, function(data) { kony.sdk.dataStore.removeItem(dsKey_KSID); kony.sdk.dataStore.removeItem(dsKey_authToken); kony.sdk.verifyAndCallClosure(successCallback, data); }, function(data, status, error) { kony.sdk.logsdk.error("ERROR: Failed to unregister device for KMS"); var errorObj = {}; errorObj.data = data; errorObj.status = status; errorObj.error = error; kony.sdk.verifyAndCallClosure(failureCallback, errorObj); }, null, networkOptions); }; /** * unregister to messaging service * @param {dictionary} options - {authToken: <Auth Token>} * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure */ this.unregister = function(successCallback, failureCallback, options) { var tempKSID = currentObject.getKSID(); var authToken = null; if (typeof(tempKSID) === 'undefined' || tempKSID === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "KSID not available, Register and try again."); } authToken = currentObject.getAuthToken(options); unregisterFromMessagingService(authToken, successCallback, failureCallback); }; /** * unregister to messaging service * @param {string} authToken - Authorization Token * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure */ /** * @deprecated This method is deprecated because authToken can be given as input through options param of * unregister method. */ this.unregisterWithAuthToken = function(authToken, successCallback, failureCallback) { var tempKSID = currentObject.getKSID(); if (typeof(tempKSID) === 'undefined' || tempKSID === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "KSID not available, Register and try again."); } if (typeof(authToken) === 'undefined' || authToken === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid authToken."); } unregisterFromMessagingService(authToken, successCallback, failureCallback); }; /** * Fetch all messages * @param {number} startIndex - starting index * @param {number} pageSize - page size * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure * @param {dictionary} options - {authToken: <Auth Token>} */ this.fetchAllMessages = function(startIndex, pageSize, successCallback, failureCallback, options) { var tempKSID = currentObject.getKSID(); if (typeof(tempKSID) === 'undefined' || tempKSID === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "KSID not available, Register and try again."); } var uri = homeUrl + "/messages/fetch"; var data = { "ksid": tempKSID, "startElement": startIndex, "elementsPerPage": pageSize }; data[kony.sdk.constants.AUTH_TOKEN] = currentObject.getAuthToken(options); var headers = {}; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_JSON; var payload = { postdata: JSON.stringify(data) }; var networkOptions = {}; networkOptions[kony.sdk.constants.DISABLE_INTEGRITY] = true; networkProvider.post(uri, payload, headers, function(data) { overrideAuthToken(options); kony.sdk.verifyAndCallClosure(successCallback, data); }, function(errorObj) { kony.sdk.logsdk.error("FetchAllMessages :: FetchAllMessages for messaging service failed with error", errorObj); kony.sdk.verifyAndCallClosure(failureCallback, errorObj); }, null, networkOptions); }; var updateGeoLocationForMessagingService = function(latitude, longitude, locationName, authToken, successCallback, failureCallback) { var uri = homeUrl + "/location"; var data = { "ksid": currentObject.getKSID(), "latitude": latitude, "longitude": longitude }; if (typeof(locationName) === "string") { data["locname"] = locationName; } if (authToken != null && authToken != undefined) { data[kony.sdk.constants.AUTH_TOKEN] = authToken; } var headers = {}; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_JSON; var payload = { postdata: JSON.stringify(data) }; var networkOptions = {}; networkOptions[kony.sdk.constants.DISABLE_INTEGRITY] = true; networkProvider.post(uri, payload, headers, function(data) { //override data store auth token with user given token currentObject.setAuthToken(authToken); kony.sdk.verifyAndCallClosure(successCallback, data); }, function(errorObj) { kony.sdk.logsdk.error("UpdateGeoLocation :: UpdateGeoLocation for messaging service failed with error", errorObj); kony.sdk.verifyAndCallClosure(failureCallback, errorObj); }, null, networkOptions); }; /** * Update the location * @param {string} latitude - Latitude value * @param {string} longitude - Longitude value * @param {string} locationName - Location name * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure * @param {dictionary} options - {authToken: <Auth Token>} */ this.updateGeoLocation = function(latitude, longitude, locationName, successCallback, failureCallback, options) { var tempKSID = currentObject.getKSID(); var authToken = null; if (typeof(tempKSID) === 'undefined' || tempKSID === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "KSID not available, Register and try again."); } if (typeof(latitude) === 'undefined' || latitude === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid latitude."); } if (typeof(longitude) === 'undefined' || longitude === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid longitude."); } authToken = currentObject.getAuthToken(options); updateGeoLocationForMessagingService(latitude, longitude, locationName, authToken, successCallback, failureCallback); }; /** * Update the location * @param {string} latitude - Latitude value * @param {string} longitude - Longitude value * @param {string} locationName - Location name * @param {string} authToken - Authorization Token * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure */ /** * @deprecated This method is deprecated because authToken can be given as a input through options param of * updateGeoLocation method */ this.updateGeoLocationWithAuthToken = function(latitude, longitude, locationName, authToken, successCallback, failureCallback) { var tempKSID = currentObject.getKSID(); if (typeof(tempKSID) === 'undefined' || tempKSID === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "KSID not available, Register and try again."); } if (typeof(latitude) === 'undefined' || latitude === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid latitude."); } if (typeof(longitude) === 'undefined' || longitude === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid longitude."); } if (typeof(authToken) === 'undefined' || authToken === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid authToken."); } updateGeoLocationForMessagingService(latitude, longitude, locationName, authToken, successCallback, failureCallback); }; /** * Mark the message as read for a given message id * @param {string} fetchId - Message id * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure * @param {dictionary} options - {authToken: <Auth Token>} */ this.markMessageRead = function(fetchId, successCallback, failureCallback, options) { if (typeof(fetchId) === 'undefined' || fetchId === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid FetchId, it cannot be null"); } var headers = {}; headers["X-HTTP-Method-Override"] = "get"; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_JSON; var uri = homeUrl + "/messages/open/" + fetchId; headers[kony.sdk.constants.DEVICE_AUTHTOKEN_HEADER] = currentObject.getAuthToken(options); var networkOptions = {}; networkOptions[kony.sdk.constants.DISABLE_INTEGRITY] = true; networkProvider.get(uri, null, headers, function(data) { //override data store auth token with user given token overrideAuthToken(options); kony.sdk.verifyAndCallClosure(successCallback, data); }, function(errorObj) { kony.sdk.logsdk.error("MarkMessageRead :: MarkMessageRead for messaging service failed with error", errorObj); kony.sdk.verifyAndCallClosure(failureCallback, errorObj); }, null, networkOptions); }; /** * Fetches the message conetent for a given message id * @param {string} fetchId - Message id * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure * @param {dictionary} options - {authToken: <Auth Token>} */ this.fetchMessageContent = function(fetchId, successCallback, failureCallback, options) { if (typeof(fetchId) === 'undefined' || fetchId === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid FetchId, it cannot be null"); } var uri = homeUrl + "/messages/content/" + fetchId; var headers = {}; headers[kony.sdk.constants.DEVICE_AUTHTOKEN_HEADER] = currentObject.getAuthToken(options); var networkOptions = {}; networkOptions[kony.sdk.constants.DISABLE_INTEGRITY] = true; networkProvider.get(uri, null, headers, function(data) { //override data store auth token with user given token overrideAuthToken(options) kony.sdk.verifyAndCallClosure(successCallback, data); }, function(errorObj) { kony.sdk.logsdk.error("FetchMessageContent :: FetchMessageContent for messaging service failed with error", errorObj); kony.sdk.verifyAndCallClosure(failureCallback, errorObj); }, null, networkOptions); }; /** * subscribeAudience to create a audience for subscribed device * @param {string} firstName - audience firstName * @param {string} lastName - audience lastName * @param {string} emailId - audience emailId * @param {string} mobileNumber - audience mobileNumber * @param {string} country - country * @param {string} state - state * @param {Object] options - {authToken: <Auth Token>} and user defined attributes like PAN no,SSN. * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure */ this.subscribeAudience = function(firstName, lastName, emailId, mobileNumber, country, state, successCallback, failureCallback, options) { if (kony.sdk.isNullOrUndefined(KSID)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Register for messaging service before creating or updating"); } if (kony.sdk.isNullOrUndefined(firstName)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid first name, it cannot be null"); } if (kony.sdk.isNullOrUndefined(lastName)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid last name, it cannot be null"); } if (kony.sdk.isNullOrUndefined(mobileNumber)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid mobile number, it cannot be null"); } if (kony.sdk.isNullOrUndefined(emailId)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid email Id, it cannot be null"); } if (kony.sdk.isNullOrUndefined(country)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid country, it cannot be null"); } subscribeAudienceOrUpdate(firstName, lastName, emailId, mobileNumber, country, state, options, successCallback, failureCallback); }; /** * delete subscribed audience * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure * @param {dictionary} options - {authToken: <Auth Token>} **/ this.unSubscribeAudience = function(successCallback, failureCallback, options) { if (kony.sdk.isNullOrUndefined(KSID)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Register for messaging service before unsubscribe audience"); } var uri = homeUrl + kony.sdk.constants.SUBSCRIBE_AUDIENCE + "/" + KSID; var headers = {}; headers[kony.sdk.constants.HTTP_OVERRIDE_HEADER] = kony.sdk.constants.HTTP_METHOD_DELETE; headers[kony.sdk.constants.DEVICE_AUTHTOKEN_HEADER] = currentObject.getAuthToken(options); var networkOptions = {}; networkOptions[kony.sdk.constants.DISABLE_INTEGRITY] = true; networkProvider.post(uri, null, headers, function(data) { //override data store auth token with user given token overrideAuthToken(options); kony.sdk.verifyAndCallClosure(successCallback, data); }, function(err) { kony.sdk.logsdk.error("### MessagingService::unSubscribeAudience failed to unsubscribe audience", err); kony.sdk.verifyAndCallClosure(failureCallback, err); }, null, networkOptions); }; /* * get subscribed audience details * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure * @param {dictionary} options - {authToken: <Auth Token>} */ this.getSubscribedAudienceDetails = function(successCallback, failureCallback, options) { if (kony.sdk.isNullOrUndefined(KSID)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Register for messaging service before get subscribed audience details"); } var uri = homeUrl + kony.sdk.constants.SUBSCRIBE_AUDIENCE + "/" + KSID; var headers = {}; headers[kony.sdk.constants.HTTP_OVERRIDE_HEADER] = kony.sdk.constants.HTTP_METHOD_GET; headers[kony.sdk.constants.DEVICE_AUTHTOKEN_HEADER] = currentObject.getAuthToken(options); var networkOptions = {}; networkOptions[kony.sdk.constants.DISABLE_INTEGRITY] = true; networkProvider.get(uri, null, headers, function(data) { //override data store auth token with user given token overrideAuthToken(options); kony.sdk.verifyAndCallClosure(successCallback, data); }, function(err) { kony.sdk.logsdk.error("### MessagingService::getSubscribedAudienceDetails failed to get audience details", err); kony.sdk.verifyAndCallClosure(failureCallback, err); }, null, networkOptions); } /* * get rich push content * @param pushId {string} - pushId for getting rich push content.Which we get after registering * for push notifications. * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure * @param {dictionary} options - {authToken: <Auth Token>} */ this.getRichPushContent = function(pushId, successCallback, failureCallback, options) { if (kony.sdk.isNullOrUndefined(KSID)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Register for messaging service to get rich push content"); } if (kony.sdk.isNullOrUndefined(pushId)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid PushId,it cannot be null"); } var uri = homeUrl + kony.sdk.constants.RICH_PUSH_MESSAGE + pushId; var headers = {}; headers[kony.sdk.constants.HTTP_OVERRIDE_HEADER] = kony.sdk.constants.HTTP_METHOD_GET; headers[kony.sdk.constants.DEVICE_AUTHTOKEN_HEADER] = currentObject.getAuthToken(options); var networkOptions = {}; networkOptions[kony.sdk.constants.DISABLE_INTEGRITY] = true; networkProvider.get(uri, null, headers, function(data) { //override data store auth token with user given token overrideAuthToken(options); kony.sdk.verifyAndCallClosure(successCallback, data); }, function(err) { kony.sdk.logsdk.error("MESSAGING SERVICE :: getRichPushContent failed to get rich content with error", err); kony.sdk.verifyAndCallClosure(failureCallback, err); }, null, networkOptions); }; /* * Update the list of beacons * @param {string} uuId - Universally Unique Identifier to identify a beacon in a network * @param {string} major - major id to identity and distinguish a group * @param {string} minor - distinguishing individual beacons within a group of beacons assigned a major value. * @param {function} successCallback - Callback method called on success. * @param {function} failureCallback - Callback method called on failure. * @param {object} options - options which accepts optional parameters such as ufid,appid and {authToken: <Auth Token>} */ this.updateListOfBeacons = function(uuId, major, minor, successCallback, failureCallback, options) { if (kony.sdk.isNullOrUndefined(KSID)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Register for messaging service before updating list of beacons"); } if (kony.sdk.isNullOrUndefined(uuId)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid UUID,it cannot be null"); } if (kony.sdk.isNullOrUndefined(major)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid major,it cannot be null"); } if (kony.sdk.isNullOrUndefined(minor)) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Invalid minor,it cannot be null"); } var uri = homeUrl + kony.sdk.constants.BEACON_UPDATE; var payload = {}; payload[kony.sdk.constants.KSID] = KSID; var beaconsList = {}; //beacon object has beacon details like uuid,major and minor var beacon = {}; beacon["uuid"] = uuId; beacon["major"] = major; beacon["minor"] = minor; beaconsList["beacon"] = beacon; payload["beacons"] = beaconsList; payload[kony.sdk.constants.AUTH_TOKEN] = currentObject.getAuthToken(options); //appid and ufid are optional if (options && options["ufid"]) { payload["ufid"] = options["ufid"]; } if (options && options["appid"]) { payload["appid"] = options["appid"]; } var payload = { postdata: JSON.stringify(payload) } var headers = {}; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_JSON; var networkOptions = {}; networkOptions[kony.sdk.constants.DISABLE_INTEGRITY] = true; networkProvider.post(uri, payload, headers, function(data) { //override data store auth token with user given token overrideAuthToken(options); kony.sdk.verifyAndCallClosure(successCallback, data); }, function(err) { kony.sdk.logsdk.error("MESSAGING SERVICE :: updateListOfBeacons failed to update with error", err); kony.sdk.verifyAndCallClosure(failureCallback, err); }, null, networkOptions); }; /* * Utility method to override datastore authtoken with user given auth token. */ var overrideAuthToken = function(options) { var authToken; if (options && options[kony.sdk.constants.AUTH_TOKEN]) { currentObject.setAuthToken(options[kony.sdk.constants.AUTH_TOKEN]); } }; var manageGeoBoundariesCallback = function(data) { if (data.state.toLocaleUpperCase() === "ENTRY" || data.state.toLocaleUpperCase() === "ENTER") { if (data.geofenceID !== "refreshBoundary") { var action = getGeoBoundaryDataForBoundaryId(parseInt(data.geofenceID)); if (action && action.clientAction === "notifyEngagementServer") { currentObject.updateGeoLocation(data.lat, data.lon, action.locationName, function(res) { kony.sdk.logsdk.info("### MessagingService::manageGeoBoundariesCallback successfully notified KMS"); }, function(err) { kony.sdk.logsdk.error("### MessagingService::manageGeoBoundariesCallback error in notifying KMS"); }); } else if (action && action.clientAction === "localNotification") { try { //Setting time to invoke after 1 second var date = new Date().getTime() + 1000; var dateString; var format; if (kony.sdk.getPlatformName() === kony.sdk.constants.PLATFORM_WINDOWS) { dateString = new Date(date).toString().slice(4, 24); format = "MMM dd yyyy HH:mm:ss"; } else { dateString = new Date(date).toString().slice(4, 24) + " " + new Date().toString().match(/([-\+][0-9]+)\s/)[1]; format = "MMM dd yyyy HH:mm:ss Z"; } kony.sdk.logsdk.trace("### MessagingService::manageGeoBoundariesCallback invoking local notification"); kony.localnotifications.create({ "id": date.toString(), "dateTime": { "date": dateString, "format": format }, "message": action.message, "title": appId.toString(), "categoryId": "geoBoundary" }); } catch (e) { kony.sdk.logsdk.error("Exception while creating localNotification " + e); } } else if (action && action.clientAction === "customLogic") { if (!kony.sdk.isNullOrUndefined(currentObject.geoBoundaryOptions["customLogicCallback"]) && typeof(currentObject.geoBoundaryOptions["customLogicCallback"]) == "function") { kony.sdk.logsdk.info("### MessagingService::manageGeoBoundariesCallback invoking customLogicCallback defined by user"); //Appending current location to the kms data obtained from the server action["CurrentLocation"] = { "latitude": data.lat, "longitude": data.lon }; kony.sdk.verifyAndCallClosure(currentObject.geoBoundaryOptions["customLogicCallback"], action); } else { kony.sdk.logsdk.info("### MessagingService::manageGeoBoundariesCallback customLogicCallback is not defined by user"); } } } } else if (data.state.toLocaleUpperCase() === "EXIT") { var options = {}; options[kony.sdk.constants.AUTH_TOKEN] = currentObject.getAuthToken(); if (data.geofenceID === "refreshBoundary") { currentObject.updateGeoLocation(data.lat, data.lon, data.geofenceID, function(res) { kony.sdk.logsdk.info("### MessagingService::manageGeoBoundariesCallback successfully notified KMS"); getAndRefreshBoundaries(currentObject.geoBoundaryOptions, function(res1) { kony.sdk.logsdk.info("### MessagingService::manageGeoBoundariesCallback successfully refreshed geoBoundaries"); }, function(err1) { kony.sdk.logsdk.error("### MessagingService::manageGeoBoundariesCallback failed to refresh geoBoundaries"); kony.sdk.verifyAndCallClosure(currentObject.refreshBoundariesFailuresCallback, err1); }, options); }, function(err) { kony.sdk.logsdk.error("### MessagingService::manageGeoBoundariesCallback error in notifying KMS"); }); } } }; var getAndRefreshBoundaries = function(geoBoundaryOptions, successCallback, failureCallback, options) { function formGeoBoundariesInput(id, latitude, longitude, distance) { return { "geofenceID": id.toString(), "lat": latitude, "lon": longitude, "radius": Number(distance.toFixed(4)) } } var url = homeUrl + "/geolocations/nearest/" + KSID; var flag = true; if (!kony.sdk.isNullOrUndefined(geoBoundaryOptions["radius"]) && typeof(geoBoundaryOptions["radius"]) == "number") { if (flag) { url = url + "?radius=" + geoBoundaryOptions["radius"]; flag = false; } else { url = url + "&radius=" + geoBoundaryOptions["radius"]; } } if (!kony.sdk.isNullOrUndefined(geoBoundaryOptions["pageSize"]) && typeof(geoBoundaryOptions["pageSize"]) == "number") { if (flag) { url = url + "?pageSize=" + geoBoundaryOptions["pageSize"]; flag = false; } else { url = url + "&pageSize=" + geoBoundaryOptions["pageSize"]; } } if (!kony.sdk.isNullOrUndefined(geoBoundaryOptions["tags"])) { if (flag) { url = url + "?tags=" + encodeURI(geoBoundaryOptions["tags"]); flag = false; } else { url = url + "&tags=" + encodeURI(geoBoundaryOptions["tags"]); } } var headers = {}; headers[kony.sdk.constants.DEVICE_AUTHTOKEN_HEADER] = currentObject.getAuthToken(options); kony.sdk.logsdk.info("### MessagingService::getAndRefreshBoundaries invoking refreshGeoBoundaries with url: " + url); var networkOptions = {}; networkOptions[kony.sdk.constants.DISABLE_INTEGRITY] = true; networkProvider.get(url, null, headers, function(res) { var geoBoundaries = []; var boundaryActions = {}; var boundariesLimit; //override data store auth token with user given token overrideAuthToken(options); if (!kony.sdk.isNullOrUndefined(geoBoundaryOptions["pageSize"]) && typeof(geoBoundaryOptions["pageSize"]) == "number") { boundariesLimit = geoBoundaryOptions["pageSize"]; } else { if (kony.sdk.getPlatformName() == kony.sdk.constants.PLATFORM_ANDROID) { boundariesLimit = 99; } else { boundariesLimit = 19; } } geoBoundaries.push(formGeoBoundariesInput("refreshBoundary", res["refreshBoundary"].latitude, res["refreshBoundary"].longitude, Math.abs(res["refreshBoundary"].distance * 1609.34))); var locations = res["locations"]; for (var i = 0; i < locations.length && i < boundariesLimit; i++) { var boundaryid = locations[i].id; geoBoundaries.push(formGeoBoundariesInput(boundaryid, locations[i].latitude, locations[i].longitude, Math.abs(locations[i].radius * 1609.34))); boundaryActions[boundaryid] = locations[i]; } setGeoBoundaryData(boundaryActions); kony.sdk.logsdk.debug("### MessagingService::getAndRefreshBoundaries registering " + geoBoundaries.length + " boundaries with frameworks for monitoring."); kony.location.setGeofencesCallback(manageGeoBoundariesCallback); kony.location.createGeofences(geoBoundaries); kony.sdk.verifyAndCallClosure(successCallback, res); }, function(err) { kony.sdk.logsdk.error("### MessagingService::getAndRefreshBoundaries failed to get geoBoundaries from KMS"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getMessagingError("Failed to get geoBoundaries from KMS")); }, null, networkOptions); }; /** * Register for registerGeoBoundaries with given radius * @param {object} options - JSON Object with radius, pageSize, tags and customLogicCallback * @param {function} successCallback - Callback method on success * @param {function} failureCallback - Callback method on failure of registerGeoBoundary and refreshGeoBoundariesFailure */ this.registerGeoBoundaries = function(options, successCallback, failureCallback) { var tempKSID = currentObject.getKSID(); var geoBoundaryOptions = {}; if (!kony.sdk.isNullOrUndefined(options)) { if (!kony.sdk.isNullOrUndefined(options["radius"])) { geoBoundaryOptions["radius"] = options["radius"]; } if (!kony.sdk.isNullOrUndefined(options["pageSize"])) { geoBoundaryOptions["pageSize"] = options["pageSize"]; } if (!kony.sdk.isNullOrUndefined(options["tags"]) && options["tags"] instanceof Array) { geoBoundaryOptions["tags"] = options["tags"]; } if (!kony.sdk.isNullOrUndefined(options["customLogicCallback"]) && typeof(failureCallback) == "function") { geoBoundaryOptions["customLogicCallback"] = options["customLogicCallback"]; } else { kony.sdk.logsdk.warn("### MessagingService::registerGeoBoundaries customLogicCallback not provided by user"); } } currentObject.geoBoundaryOptions = geoBoundaryOptions; if (typeof(tempKSID) === 'undefined' || tempKSID === null) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "KSID not available, Register and try again."); } if (!typeof(failureCallback) == "function") { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "failureCallback is not provided"); } else { currentObject.refreshBoundariesFailuresCallback = failureCallback; } kony.location.getCurrentPosition(function(res) { if (kony.sdk.getPlatformName() !== kony.sdk.constants.PLATFORM_WINDOWS) { var accept = kony.notificationsettings.createAction({ "id": kony.sdk.constants.HTTP_REQUEST_HEADER_ACCEPT, "label": kony.sdk.constants.HTTP_REQUEST_HEADER_ACCEPT, "pspConfig": { "activationMode": kony.notificationsettings.ACTIVATION_MODE_FORWARDS, "authenticationRequired": true, "destructive": false } }); var reject = kony.notificationsettings.createAction({ "id": "Reject", "label": "Reject", "pspConfig": { "activationMode": kony.notificationsettings.ACTIVATION_MODE_BACKWARDS, "authenticationRequired": false, "destructive": false } }); var categoryObj = kony.notificationsettings.createCategory({ "categoryId": "geoBoundary", "actions": [accept, reject], "pspConfig": { "minimalActions": [accept, reject] } }); var categoryArr = [categoryObj]; kony.notificationsettings.registerCategory({ "categories": categoryArr, "pspConfig": { "types": [0, 1, 2] } }); } var currentLocation = res.coords; var authToken = null; authToken = currentObject.getAuthToken(options); updateGeoLocationForMessagingService(currentLocation.latitude, currentLocation.longitude, "fetchBoundaries", authToken, function(res) { kony.sdk.logsdk.trace("### MessagingService::registerGeoBoundaries updated current location, fetching geoBoundaries from server."); getAndRefreshBoundaries(currentObject.geoBoundaryOptions, successCallback, failureCallback, options); }, function(err) { kony.sdk.logsdk.error("### MessagingService::registerGeoBoundaries Failed to update current location with KMS."); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getMessagingError("Failed to update current location with KMS")); }); }, function(err) { if (err.code == 1) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Permission to access location is not enabled"); } else if (err.code == 2) { throw new Exception(kony.sdk.errorConstants.MESSAGING_FAILURE, "Enable location and try again"); } else if (err.code == 3) { kony.sdk.logsdk.error("### MessagingService::registerGeoBoundaries Unable to retrieve current location."); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getMessagingError("Unable to retrieve current location")); } }); } } /** * Method to create the Metrics service instance with the provided service name. * @returns {MetricsService} Metrics service instance */ kony.sdk.prototype.getMetricsService = function() { if (!kony.sdk.isInitialized) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, kony.sdk.constants.INIT_FAILURE_MESSAGE + " Metrics service."); } if (!kony.sdk.isLicenseUrlAvailable) { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "metrics is not enabled"); } //var metricsServiceObject = null; if (this.metricsServiceObject) { return this.metricsServiceObject; } if (this.internalSdkObject) { //framework implementation this.metricsServiceObject = this.internalSdkObject.getMetricsService(); } else { //sdk local implementation this.metricsServiceObject = new MetricsService(this); } return this.metricsServiceObject; }; /** * Should not be called by the developer. * @class * @classdesc Metrics service instance for invoking the Metrics services. */ function MetricsService(konyRef) { var url = konyRef.customReportingURL; if (typeof(url) === 'undefined') { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "reporting url is undefined"); } var networkProvider = new konyNetworkProvider(); /** * invoke the getUserId operation */ this.getUserId = function() { return konyRef.getUserId(); }; //start of event api var eventFlowTag = ""; var eventBufferMaxValue = 1000; var eventBufferAutoFlushValue = 15; var characterLengthLimit = 256; var eventConfig = { "confType": "BUFFER", "eventBufferAutoFlushCount": eventBufferAutoFlushValue, "eventBufferMaxCount": eventBufferMaxValue }; var reportEventBufferArray = []; var reportEventBufferBackupArray = []; var retrievedDS = false; var eventBufferCount = 0; var eventTypeMap = { "formentry": "FormEntry", "formexit": "FormExit", "touch": "Touch", "servicerequest": "ServiceRequest", "serviceresponse": "ServiceResponse", "gesture": "Gesture", "orientation": "Orientation", "error": "Error", "exception": "Exception", "crash": "Crash", "custom": "Custom", "servicecall": "ServiceCall", "apptransition": "AppTransition", "appload": "AppLoad", "component": "Component" }; var errorCodeMap = { "1000": true, "1011": true, "1012": true, "1014": true, "1015": true, "1016": true }; var currentSessionId = ""; /** * This method will take the a String to set a Flow Tag for the reported events. * @param {string} flowTag - sets flow tag for reporting the events. */ this.setFlowTag = function(flowTag) { if (kony.sdk.isNullOrUndefined(flowTag)) { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Invalid value for event flow tag"); } else if (flowTag.length <= characterLengthLimit) { eventFlowTag = flowTag; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Length exceeded, Maximum length of event flow tag is " + characterLengthLimit + " characters"); } }; /** * This method will clear the flow tag set by the user previously. */ this.clearFlowTag = function() { eventFlowTag = ""; }; /** * This method will return the a String to set a Flow Tag for the reported events. * @return {string} flowTag - flow tag set by the user for reporting the events. */ this.getFlowTag = function() { return eventFlowTag; }; /** * This method will take the required values to set the event Configuration values. * @param {string} confType - sets the Current Configuration Type * possible values BUFFER or INSTANT. * @param {number} eventBufferAutoFlushCount - event buffer count to auto flush the events * possible values any positive integer * Default value 15 * @param {number} eventBufferMaxCount - Maximum event buffer count to store the events * possible values any positive integer * Default value 1000 */ this.setEventConfig = function(confType, eventBufferAutoFlushCount, eventBufferMaxCount) { if (kony.sdk.isNullOrUndefined(confType)) { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Config Type can not be null"); } else { confType = confType.toUpperCase(); } if (confType === "BUFFER") { eventConfig["confType"] = confType; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Invalid value for config type"); } if (!kony.sdk.isNullOrUndefined(eventBufferMaxCount) && typeof(eventBufferMaxCount) === "number" && eventBufferMaxCount > 0) { eventConfig["eventBufferMaxCount"] = eventBufferMaxCount; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "eventBufferMaxCount has to be a Number and greater than 0"); } if (!kony.sdk.isNullOrUndefined(eventBufferAutoFlushCount) && typeof(eventBufferAutoFlushCount) === "number" && eventBufferAutoFlushCount > 0 && eventBufferAutoFlushCount <= eventBufferMaxCount) { eventConfig["eventBufferAutoFlushCount"] = eventBufferAutoFlushCount; } else if (eventBufferAutoFlushCount >= eventBufferMaxCount) { eventConfig["eventBufferMaxCount"] = 1000; throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "eventBufferAutoFlushCount can not be greater than eventBufferMaxCount"); } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "eventBufferAutoFlushCount has to be a Number and greater than 0"); } }; /** * This method takes the event details from the developer and schedule it for sending to server as per Configuration values set by the developer. * @param {string} evttype - Event Type for the reported event. * @param {string} evtSubType - string literal for eventSubType(max 256 Chars) * @param {string} formID - string literal for formID(max 256 Chars) * @param {string} widgetID - string literal for widgetID(max 256 Chars) * @param {string} flowTag - string literal to override flow tag (max 256 Chars) * @param {string} metaData - string to describe metaData * @throws Exception */ this.sendEvent = function(evttype, evtSubType, formID, widgetID, flowTag, metaData) { if (reportEventBufferBackupArray.length === 0) { this.readFromDS(); } eventBufferCount = reportEventBufferBackupArray.length + reportEventBufferArray.length; if (eventBufferCount === eventConfig["eventBufferMaxCount"]) { throw new Exception(kony.sdk.errorConstants.DATA_STORE_EXCEPTION, "Reached maximum limit to store events"); } var reportEventMap = {}; reportEventMap.ts = kony.sdk.formatCurrentDate(new Date()); evttype = evttype.toLowerCase(); if (kony.sdk.isNullOrUndefined(eventTypeMap[evttype])) { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Invalid value for event type"); } else { reportEventMap["evttype"] = eventTypeMap[evttype]; } if (kony.sdk.isNullOrUndefined(evtSubType)) { reportEventMap["evtSubType"] = ""; } else if (evtSubType.length <= characterLengthLimit) { reportEventMap["evtSubType"] = evtSubType; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Length exceeded, Maximum length of event evtSubType is " + characterLengthLimit + " characters"); } if (kony.sdk.isNullOrUndefined(formID)) { reportEventMap["formID"] = kony.application.getCurrentForm().id; } else if (formID.length <= characterLengthLimit) { reportEventMap["formID"] = formID; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Length exceeded, Maximum length of event formID is " + characterLengthLimit + " characters"); } if (kony.sdk.isNullOrUndefined(widgetID)) { reportEventMap["widgetID"] = ""; } else if (widgetID.length <= characterLengthLimit) { reportEventMap["widgetID"] = widgetID; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Length exceeded, Maximum length of event widgetID is " + characterLengthLimit + " characters"); } if (kony.sdk.isNullOrUndefined(flowTag)) { reportEventMap["flowTag"] = this.getFlowTag(); } else if (flowTag.length <= characterLengthLimit) { reportEventMap["flowTag"] = flowTag; } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Length exceeded, Maximum length of event flowTag is " + characterLengthLimit + " characters"); } reportEventMap.SID = currentSessionId; reportEventMap.metaData = metaData; //checking each event data is a proper json or not // throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Invalid json string passed for events data"); // } reportEventBufferArray.push(reportEventMap); if (reportEventBufferArray.length % eventConfig["eventBufferAutoFlushCount"] === 0) { this.flushEvents(); } }; /** * This method will send the buffered events to the server at once. */ this.flushEvents = function() { var ref = this; if (reportEventBufferBackupArray.length === 0) { ref.readFromDS(); } if (reportEventBufferBackupArray.length === 0 && reportEventBufferArray.length === 0) { kony.sdk.logsdk.warn("There are no events to flush"); return; } var payload = kony.sdk.getPayload(kony.sdk.getCurrentInstance()); var params = {}; if (reportEventBufferArray.length !== 0) { ref.pushEventsToBufferArray(); } var headers = {}; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; payload.events = reportEventBufferBackupArray; payload.svcid = "SendEvents"; payload.rsid = reportEventBufferBackupArray[0].SID; params[kony.sdk.constants.REPORTING_PARAMS] = JSON.stringify(payload); var options = {}; options["disableIntegrity"] = true; networkProvider.post(url, params, headers, flushSuccessCallback, flushErrorCallback, null, options); function flushSuccessCallback(response) { if (response.opstatus == 0) { ref.clearBufferEvents(); } else if (errorCodeMap[response.opstatus]) { ref.saveInDS(); } else { ref.clearBufferEvents(); } } function flushErrorCallback(response) { kony.sdk.logsdk.error("Unable to flush events"); ref.saveInDS(); } }; /*Stores event data in Data Store on failure of service Call*/ this.saveInDS = function() { var eventsToSave = []; eventsToSave.push(JSON.stringify(reportEventBufferBackupArray)); kony.ds.save(eventsToSave, "konyMetricsBuffer"); reportEventBufferBackupArray = []; }; /*Clearing events sent to server */ this.clearBufferEvents = function() { reportEventBufferBackupArray = []; kony.ds.remove("konyMetricsBuffer"); }; /*Reading any pending events from Data Store */ this.readFromDS = function() { var eventsFromDS = kony.ds.read("konyMetricsBuffer"); if (eventsFromDS !== null) { var pushToArray = []; pushToArray.push(JSON.parse(eventsFromDS[0])); reportEventBufferBackupArray.push.apply(reportEventBufferBackupArray, pushToArray); } }; /*Pushes events received from user to BufferBackupArray which will be flushed to server */ this.pushEventsToBufferArray = function() { reportEventBufferBackupArray.push.apply(reportEventBufferBackupArray, reportEventBufferArray); reportEventBufferArray = []; }; /** * This method will return the a List of the buffered events. * @return {object} events - list of events stored in buffer. */ this.getEventsInBuffer = function() { var eventsFromDS = kony.ds.read("konyMetricsBuffer"); var eventsToReturn = []; if (!kony.sdk.isNullOrUndefined(eventsFromDS)) { eventsToReturn.push(JSON.parse(eventsFromDS[0])); } if (reportEventBufferArray.length !== 0) { eventsToReturn.push.apply(eventsToReturn, reportEventBufferArray); } if (eventsToReturn.length !== 0) { return eventsToReturn; } else { return null; } }; /** * invoke the sendCustomMetrics operation * @param {string} reportingGroupID - reporting Group ID * @param {object} metrics - metrics being reported */ this.sendCustomMetrics = function(reportingGroupID, metrics) { if (typeof(metrics) !== "object") { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Invalid type for metrics data."); } var sessionID = currentSessionId; var reportData = kony.sdk.dataStore.getItem("konyCustomReportData"); if (!reportData) { reportData = []; } else { reportData = JSON.parse(reportData); } kony.sdk.dataStore.removeItem("konyCustomReportData"); var currentData = {}; currentData.ts = kony.sdk.formatCurrentDate(new Date().toString()); currentData.fid = reportingGroupID; currentData.metrics = metrics; currentData.rsid = sessionID; reportData.push(currentData); //nyRef.getDataStore().setItem("konyCustomReportData",JSON.stringify(reportData)); var payload = kony.sdk.getPayload(konyRef); if (kony.sdk.metric) { if (kony.sdk.metric.reportEventBufferBackupArray.length === 0) { kony.sdk.metric.readFromDS(); } kony.sdk.metric.pushEventsToBufferArray(); payload.events = kony.sdk.metric.reportEventBufferBackupArray; } payload.reportData = reportData; payload.rsid = sessionID; payload.svcid = "CaptureKonyCustomMetrics"; // if (!kony.sdk.isJson(payload)) { // throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Invalid json string passed for custom metrics"); // } var newData = {}; newData[kony.sdk.constants.REPORTING_PARAMS] = JSON.stringify(payload); var options = {}; options["disableIntegrity"] = true; var headers = {}; headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; networkProvider.post(url, newData, headers, function(res) { //successcallback //konyRef.getDataStore().removeItem("konyCustomReportData"); if (kony.sdk.metric) { kony.sdk.metric.clearBufferEvents(); } kony.sdk.logsdk.info("metric data successfully sent" + JSON.stringify(res)); }, function(res) { var storeData = kony.sdk.dataStore.getItem("konyCustomReportData"); if (!storeData) { storeData = reportData; } else { storeData = JSON.parse(storeData); reportData.forEach(function(e) { storeData.push(e); }); } if (kony.sdk.metric) { if (kony.sdk.metric.errorCodeMap[res.opstatus]) { kony.sdk.metric.saveInDS(); } } kony.sdk.dataStore.setItem("konyCustomReportData", JSON.stringify(storeData)); kony.sdk.logsdk.error("Unable to send metric report" + JSON.stringify(res)); }, true, options); }; /** * This method takes the event details from the developer and schedule it for sending to server as per Configuration values set by the developer. * @param {string} errorCode - errorCode of the reported error. Can be empty if not applicable * @param {string} errorType - errorType of the reported error. Can be empty if not applicable * @param {string} errorMessage - errorMessage of the reported error. Can be empty if not applicable * @param {json} errorDetails - errorDetails of the reported error as a json string that can have key-value pairs for the following keys errfile, errmethod, errline, errstacktrace, formID, widgetID, flowTag. * @throws Exception */ this.reportError = function(errorCode, errorType, errorMessage, errorDetails) { var metaData = {}; metaData.errorcode = errorCode ? errorCode : ""; metaData.errmsg = errorMessage ? errorMessage : ""; if (errorDetails && kony.sdk.isJson(errorDetails)) { metaData.errfile = errorDetails.errfile ? errorDetails.errfile : ""; metaData.errmethod = errorDetails.errmethod ? errorDetails.errmethod : ""; metaData.errline = errorDetails.errline ? errorDetails.errline : ""; metaData.errstacktrace = errorDetails.errstacktrace ? errorDetails.errstacktrace : ""; metaData.errcustommsg = errorDetails.errcustommsg ? errorDetails.errcustommsg : ""; var formID = errorDetails.formID ? errorDetails.formID : ""; var widgetID = errorDetails.widgetID ? errorDetails.widgetID : ""; var flowTag = errorDetails.flowTag ? errorDetails.flowTag : ""; var evtSubType = errorType ? errorType : ""; this.sendEvent("Error", evtSubType, formID, widgetID, flowTag, metaData); } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Invalid json string passed for error details."); } }; /** * This method takes the event details from the developer and schedule it for sending to server as per Configuration values set by the developer. * @param {string} exceptionCode - Code for the reported exception. Can be empty if not applicable * @param {string} exceptionType - Type of the reported exception. Can be empty if not applicable * @param {string} exceptionMessage - Message of the reported exception. Can be empty if not applicable * @param {json} exceptionDetails - Details of the reported exception as a JSON string that can have key-value pairs for the following keys exceptioncode, exceptionfile, exceptionmethod, exceptionline, exceptionstacktrace, formID, widgetID, flowTag. * @throws Exception */ this.reportHandledException = function(exceptionCode, exceptionType, exceptionMessage, exceptionDetails) { var metaData = {}; metaData.exceptioncode = exceptionCode ? exceptionCode : ""; metaData.exceptionmsg = exceptionMessage ? exceptionMessage : ""; if (exceptionDetails && kony.sdk.isJson(exceptionDetails)) { metaData.errfile = exceptionDetails.errfile ? exceptionDetails.errfile : ""; metaData.errmethod = exceptionDetails.errmethod ? exceptionDetails.errmethod : ""; metaData.errline = exceptionDetails.errline ? exceptionDetails.errline : ""; metaData.errstacktrace = exceptionDetails.errstacktrace ? exceptionDetails.errstacktrace : ""; metaData.errcustommsg = exceptionDetails.errcustommsg ? exceptionDetails.errcustommsg : ""; var formID = exceptionDetails.formID ? exceptionDetails.formID : ""; var widgetID = exceptionDetails.widgetID ? exceptionDetails.widgetID : ""; var flowTag = exceptionDetails.flowTag ? exceptionDetails.flowTag : ""; var evtSubType = exceptionType ? exceptionType : ""; this.sendEvent("Exception", evtSubType, formID, widgetID, flowTag, metaData); } else { throw new Exception(kony.sdk.errorConstants.METRICS_FAILURE, "Invalid json string passed for exception details."); } }; /** * sets the current sessionId * @param {string} sessionId */ this.setSessionId = function(sessionId) { if (sessionId) { currentSessionId = sessionId; } }; /** * get the current sessionID * */ this.getSessionId = function() { return currentSessionId; }; /** * stub method used for event tracking * */ this.setEventTracking = function(eventTypes) { // Stub. This is implemented in native->js binding } } kony.sdk.initiateSession = function() {}; /** * Method which returns the offline enabled ObjectService object * @param konyRef * @param serviceName * @constructor */ kony.sdk.OfflineEnabledObjectService = function(konyRef, serviceName) { this.serviceName = serviceName; this.konyRef = konyRef; /** * This method is used to fetch records on the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject)} * @param successCallback * @param failureCallback */ this.fetch = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineEnabledObjectService.fetch"); if (!areOptionsValid(options, failureCallback)) { return; } try { var dataObject = options[kony.sdk.constants.ObjectServiceConstants.DATAOBJECT]; var objectName = dataObject.getObjectName(); function fetchHandler(objMetadata) { var obj = new kony.sdk.KNYObj(objectName); var readOptions = dataObject.getOfflineObjectsOptions(); /* If read options are not supplied, caller such as fetchDataForColumns model API would provide a select query object and some callers provide query params. * We parse the select query or queryParams to suite offline objects read API. */ if (!readOptions || Object.keys(readOptions).length == 0) { var selectQueryObject = dataObject.getSelectQueryObject(); var queryParams = options[kony.sdk.constants.ObjectServiceConstants.QUERYPARAMS]; if (selectQueryObject) { readOptions.projectionColumns = []; var columns = selectQueryObject.getColumns(); for (var column in columns) { readOptions.projectionColumns.push(columns[column].getName()); } var criteriaList = selectQueryObject.getCriterias(); var primaryKeys = {}; for (var criteria in criteriaList) { var colObj = criteriaList[criteria].getColumn(); if (colObj) { primaryKeys[colObj.getName()] = criteriaList[criteria].getValue(); } } readOptions.primaryKeys = primaryKeys; } else if (queryParams) { var primaryKeys = {}; if (objMetadata.primaryKey != null && objMetadata.primaryKey != undefined) { for (var indx = 0; indx < objMetadata.primaryKey.length; indx++) { var pKey = objMetadata.primaryKey[indx]; var pKeyValue = queryParams[pKey]; if (pKeyValue == null || pKeyValue == undefined || pKeyValue == "") { kony.sdk.logsdk.error("### OfflineEnabledObjectService:: fetch Error: Primarykey details missing so unable to fetch"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } primaryKeys[pKey] = pKeyValue; } readOptions.primaryKeys = primaryKeys; } else { kony.sdk.logsdk.error("### OfflineEnabledObjectService:: fetch Error: Primarykey details missing so unable to fetch"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } } } function fetchSuccessHandler(res) { var response = {}; response.records = res; successCallback(response); } obj.get(readOptions, fetchSuccessHandler, failureCallback); } this.getMetadataOfObject(objectName, {}, fetchHandler, failureCallback); } catch (error) { kony.sdk.logsdk.error("Fetch on offline enabled object failed with error: " + error); kony.sdk.verifyAndCallClosure(failureCallback, error); } }; /** * This method is used to create a record on the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject)} * @param successCallback * @param failureCallback */ this.create = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineEnabledObjectService.create"); if (!areOptionsValid(options, failureCallback)) { return; } try { var dataObject = options[kony.sdk.constants.ObjectServiceConstants.DATAOBJECT]; var objectName = dataObject.getObjectName(); var obj = new kony.sdk.KNYObj(objectName); var records = dataObject.getRecord(); obj.create(records, {}, successCallback, failureCallback); } catch (error) { kony.sdk.logsdk.error("Create on offline enabled object failed with error: " + error); kony.sdk.verifyAndCallClosure(failureCallback, error); } }; /** * This method is used to update a record on the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject)} * @param successCallback * @param failureCallback */ this.update = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineEnabledObjectService.update"); if (!areOptionsValid(options, failureCallback)) { return; } try { var dataObject = options[kony.sdk.constants.ObjectServiceConstants.DATAOBJECT]; var objectName = dataObject.getObjectName(); function updateHandler(objMetadata) { var obj = new kony.sdk.KNYObj(objectName); var updateOptions = dataObject.getOfflineObjectsOptions(); var records = dataObject.getRecord(); // If primary keys are not supplied through options, they are picked from the user supplied record. if (!updateOptions || Object.keys(updateOptions).length == 0 || !updateOptions['primaryKeys']) { if (records) { var primaryKeys = {}; if (objMetadata.primaryKey != null && objMetadata.primaryKey != undefined) { for (var indx = 0; indx < objMetadata.primaryKey.length; indx++) { var pKey = objMetadata.primaryKey[indx]; var pKeyValue = records[pKey]; if (pKeyValue == null || pKeyValue == undefined || pKeyValue == "") { kony.sdk.logsdk.error("### OfflineEnabledObjectService:: Update Error: Primarykey details missing so unable to update"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } primaryKeys[pKey] = pKeyValue; } updateOptions.primaryKeys = primaryKeys; } else { kony.sdk.logsdk.error("### OfflineEnabledObjectService:: Update Error: Primarykey details missing so unable to update"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } } else { kony.sdk.logsdk.error("Update Failed: primaryKeys key missing. Please use dataObject setOfflineObjectsOptions to set primaryKeys for update operation."); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } } obj.updateByPK(records, updateOptions, successCallback, failureCallback); } this.getMetadataOfObject(objectName, {}, updateHandler, failureCallback); } catch (error) { kony.sdk.logsdk.error("Update on offline enabled object failed with error: " + error); kony.sdk.verifyAndCallClosure(failureCallback, error); } }; /** * This method is used to delete a record on the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject)} * @param successCallback * @param failureCallback */ this.deleteRecord = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineEnabledObjectService.deleteRecord"); if (!areOptionsValid(options, failureCallback)) { return; } try { var dataObject = options[kony.sdk.constants.ObjectServiceConstants.DATAOBJECT]; var objectName = dataObject.getObjectName(); function deleteHandler(objMetadata) { var obj = new kony.sdk.KNYObj(objectName); var deleteOptions = dataObject.getOfflineObjectsOptions(); // If primary keys are not supplied through options, they are picked from the user supplied record if (!deleteOptions || Object.keys(deleteOptions).length == 0 || !deleteOptions['primaryKeys']) { var records = dataObject.getRecord(); if (records) { var primaryKeys = {}; if (objMetadata.primaryKey != null && objMetadata.primaryKey != undefined) { for (var indx = 0; indx < objMetadata.primaryKey.length; indx++) { var pKey = objMetadata.primaryKey[indx]; var pKeyValue = records[pKey]; if (pKeyValue == null || pKeyValue == undefined || pKeyValue == "") { kony.sdk.logsdk.error("### OfflineEnabledObjectService:: Delete Error: Primarykey details missing so unable to delete"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } primaryKeys[pKey] = pKeyValue; } deleteOptions.primaryKeys = primaryKeys; } else { kony.sdk.logsdk.error("### OfflineEnabledObjectService:: Delete Error: Primarykey details missing so unable to delete"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } } else { kony.sdk.logsdk.error("Delete Failed: primaryKeys key missing. Please use dataObject setOfflineObjectsOptions to set primaryKeys for delte operation."); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } } obj.deleteByPK(deleteOptions, successCallback, failureCallback); } this.getMetadataOfObject(objectName, {}, deleteHandler, failureCallback); } catch (error) { kony.sdk.logsdk.error("Delete on offline enabled object failed with error: " + error); kony.sdk.verifyAndCallClosure(failureCallback, error); } }; /** * This method is used to retrieve metadata of all objects * @param options * @param successCallback * @param failureCallback */ this.getMetadataOfAllObjects = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineEnabledObjectService.getMetadataOfAllObjects"); _getMetadataForObjectsOrServiceOnlineUtil(konyRef, serviceName, null, options, successCallback, failureCallback); kony.sdk.logsdk.trace("EXiting kony.sdk.OfflineEnabledObjectService.getMetadataOfAllObjects"); }; /** * This method is used to retrive metadata of a specific object * @param objectName * @param options * @param successCallback * @param failureCallback */ this.getMetadataOfObject = function(objectName, options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineEnabledObjectService.getMetadataOfObject"); _getMetadataForObjectsOrServiceOnlineUtil(konyRef, serviceName, objectName, options, successCallback, failureCallback); kony.sdk.logsdk.trace("Exiting kony.sdk.OfflineEnabledObjectService.getMetadataOfObject"); }; /** * This method is used to validate options * @param options * @param failureCallback */ function areOptionsValid(options, failureCallback) { if (options == null || options == undefined) { kony.sdk.logsdk.error("### OfflineEnabledObjectService:: Options Validity check: options null or undefined"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return false; } if (!(options[kony.sdk.constants.ObjectServiceConstants.DATAOBJECT] instanceof kony.sdk.dto.DataObject)) { kony.sdk.logsdk.error("### OfflineEnabledObjectService:: Options Validity check: invalid data object"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return false; } var dataObject = options[kony.sdk.constants.ObjectServiceConstants.DATAOBJECT]; var objectName = dataObject.getObjectName(); if (objectName == null || objectName == undefined) { kony.sdk.logsdk.error("### OfflineEnabledObjectService:: Options Validity check: objectname null or undefined"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "objectName" + kony.sdk.errormessages.null_or_undefined)); return false; } return true; }; }; /** * Method which returns the offline ObjectService object * @param konyRef * @param serviceName * @constructor */ kony.sdk.OfflineObjectService = function(konyRef, serviceName) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineObjectService"); this.konyRef = konyRef; this.serviceName = serviceName; /** * This method is used to create a record on the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject)} * @param successCallback * @param failureCallback */ this.create = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineObjectService.create"); if (options == null || options == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } if (!(options["dataObject"] instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } var dataObject = options["dataObject"]; function createHandler(objMetadata) { _invokeOfflineCreate(dataObject, successCallback, failureCallback, options); } this.getMetadataOfObject(dataObject.getObjectName(), {}, createHandler, failureCallback); }; /** * This method is used to fetch records from the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject)} * @param successCallback * @param failureCallback */ this.fetch = function(options, successCallback, failureCallback) { throw "This method is not implemented.Instead use executeSelectQuery"; }; /** * This method is used to update a record in the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject)} * @param successCallback * @param failureCallback */ this.update = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineObjectService.update"); if (options == null || options == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } if (!(options["dataObject"] instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } var dataObject = options["dataObject"]; function updateHandler(objMetadata) { function updateSuccessCallback(response) { kony.sdk.verifyAndCallClosure(successCallback, response); } function updateFailureCallback(error) { if (error != null && error != undefined) { //if the errorcode is equivalent to transaction failed then giving some generic error message to the client. if (error["errorCode"] == 7010) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.transaction_failed, kony.sdk.errormessages.transaction_failed)); return; } } kony.sdk.verifyAndCallClosure(failureCallback, error); } _invokeOfflineUpdate(dataObject, updateSuccessCallback, updateFailureCallback, options); } this.getMetadataOfObject(dataObject.getObjectName(), {}, updateHandler, failureCallback); }; /** * This method is used to delete a record in the object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject)} * @param successCallback * @param failureCallback */ this.deleteRecord = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineObjectService.deleteRecord"); if (options == null || options == undefined) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } if (!(options["dataObject"] instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } var dataObject = options["dataObject"]; function deleteHandler(objMetadata) { function deleteSuccessCallback(response) { //verifying delete response contains deleted records count as 0 if (response != null && response != undefined) { if (response["rowsdeleted"] == 0) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.norecords_to_delete, kony.sdk.errormessages.norecords_to_delete)); return; } } kony.sdk.verifyAndCallClosure(successCallback, response); } function deleteFailureCallback(error) { kony.sdk.verifyAndCallClosure(failureCallback, error); } _invokeOfflineDelete(dataObject, deleteSuccessCallback, deleteFailureCallback, options); } this.getMetadataOfObject(dataObject.getObjectName(), {}, deleteHandler, failureCallback); }; /** * This method is used to retrieve metadata of all objects * @param options * @param successCallback * @param failureCallback */ this.getMetadataOfAllObjects = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineObjectService.getMetadataOfAllObjects"); _getMetadataForObjectsOrServiceOnlineUtil(konyRef, serviceName, null, options, successCallback, failureCallback); kony.sdk.logsdk.trace("Exiting kony.sdk.OfflineObjectService.getMetadataOfAllObjects"); }; /** * This method is used to retrive metadata of a specific object * @param objectName * @param options * @param successCallback * @param failureCallback */ this.getMetadataOfObject = function(objectName, options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineObjectService.getMetadataOfObject"); _getMetadataForObjectsOrServiceOnlineUtil(konyRef, serviceName, objectName, options, successCallback, failureCallback); kony.sdk.logsdk.trace("Exiting kony.sdk.OfflineObjectService.getMetadataOfObject"); }; /** * This method is used to execute an sql query * @param queryStr * @param successCallback * @param failureCallback */ this.executeSelectQuery = function(queryStr, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineObjectService.executeSelectQuery"); function selctSuccess(response) { kony.sdk.logsdk.debug("### OfflineObjectService::executeSelectQuery::selectSuccess Response:", response); kony.sdk.verifyAndCallClosure(successCallback, response); } function selectError(error) { kony.sdk.logsdk.error("### OfflineObjectService::executeSelectQuery::selectError Error:", error); kony.sdk.verifyAndCallClosure(failureCallback, error); } kony.sync.single_select_execute(kony.sdk.util.getSyncDbName(), queryStr, null, selctSuccess, selectError); }; /** * Helps to get the binary content of the specified column on the Object * @param {map} options - includes {"dataObject":(@link kony.sdk.dto.DataObject), "responsetype":"base64string/filepath(Default)", "binaryAttrName":columnName} * @param successCallback * @param failureCallback */ this.getBinaryContent = function(options, successCallback, failureCallback) { kony.sdk.logsdk.trace("Entering kony.sdk.OfflineObjectService.getBinaryContenttion"); if (kony.sdk.isNullOrUndefined(options)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.null_or_undefined, "options" + kony.sdk.errormessages.null_or_undefined)); return; } var dataObject = options["dataObject"]; if (!(dataObject instanceof kony.sdk.dto.DataObject)) { kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.invalid_dataobject_instance, kony.sdk.errormessages.invalid_dataobject_instance)); return; } var binaryColName = options["binaryAttrName"]; if (kony.sdk.isNullOrUndefined(binaryColName)) { kony.sdk.logsdk.error("### OfflineObjectService::getBinaryContent Error: Please provide column name to fetch binary content"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj("90000", "Please provide column name to fetch binary content")); return; } var getBase64 = options["responsetype"] === "base64string" ? true : false; var config = options["config"]; function getBinaryDataHandler(objMetadata) { function selectSuccessCallback(response) { kony.sdk.logsdk.debug("### OfflineObjectService::getBinaryContent::selectSuccessCallback Response", response); var result; if (getBase64) { //get base64 from response var tempFile = new kony.io.File(response["FilePath"]); if (!kony.sdk.isNullOrUndefined(tempFile) && tempFile.exists() && tempFile.readable) { var tempRawBytes = tempFile.read(); result = kony.convertToBase64(tempRawBytes); } else { kony.sdk.logsdk.error("Error in reading binary file from filepath ", response["FilePath"]); var errorCode = kony.sdk.errorcodes.invalid_blob; var errorMessage = kony.sdk.errormessages.invalid_blob; kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(errorCode, errorMessage)); } } else { //get filepath from response result = response["FilePath"]; } kony.sdk.verifyAndCallClosure(successCallback, result); } function selectErrorCallback(error) { kony.sdk.logsdk.error("### OfflineObjectService::getBinaryContent::selectErrorCallback Error:", error); _invokeOfflineErrorCallback(failureCallback, error); } var dbName = kony.sdk.util.getSyncDbName(); var objName = dataObject.getObjectName(); var columnValues = kony.sdk.util.populateColumnValues(dataObject.getRecord(), null); var colMeta = kony.sdk.util.getMetadataOfColumn(objMetadata, binaryColName); if (kony.sdk.isNullOrUndefined(colMeta)) { kony.sdk.logsdk.warn("### OfflineObjectService::getBinaryContent Error: Invalid binary attribute name."); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj("90000", "Invalid binary attribute name.")); return; } if (colMeta["datatype"] !== kony.sdk.constants.BINARY_DATATYPE) { kony.sdk.logsdk.warn("### OfflineObjectService::getBinaryContent Error: Datatype is not binary for the specified binary attribute name"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj("90000", "Datatype is not binary for the specified binary attribute name")); return; } var pkTable = kony.sdk.util.getPkTableForBinary(objMetadata, columnValues, failureCallback); kony.sync.getBinary(dbName, objName, binaryColName, pkTable, config, selectSuccessCallback, selectErrorCallback); } this.getMetadataOfObject(dataObject.getObjectName(), {}, getBinaryDataHandler, failureCallback); }; function _invokeOfflineErrorCallback(failureCallback, errorObject) { //call the failureCallback after adding opstatus to the errorObject. var errorCode, errorMessage; if (errorObject) { errorCode = (errorObject.hasOwnProperty("errorCode")) ? errorObject["errorCode"] : kony.sdk.errorcodes.transaction_failed; errorMessage = (errorObject.hasOwnProperty("errorMessage")) ? errorObject["errorMessage"] : kony.sdk.errormessages.transaction_failed; } else { errorCode = kony.sdk.errorcodes.transaction_failed; errorMessage = kony.sdk.errormessages.transaction_failed; } kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(errorCode, errorMessage)); } function _invokeOfflineCreate(dataObject, successCallback, failureCallback, options) { var dbname = kony.sdk.util.getSyncDbName(); kony.sync.single_insert_execute(dbname, dataObject.getObjectName(), dataObject.getRecord(), successCallback, function(err) { _invokeOfflineErrorCallback(failureCallback, err); }, true, options); } function _invokeOfflineUpdate(dataObject, successCallback, failureCallback, options) { var objectName = dataObject.getObjectName(); var columnValues = dataObject.getRecord(); var objMetadata = kony.sdk.ObjectServiceUtil.getCachedObjectMetadata(serviceName, objectName); var pkTable = {}; var whereClause = []; if (objMetadata.primaryKey != null && objMetadata.primaryKey != undefined) { for (var indx = 0; indx < objMetadata.primaryKey.length; indx++) { var pKey = objMetadata.primaryKey[indx]; var pKeyValue = columnValues[pKey]; if (pKeyValue == null || pKeyValue == undefined || pKeyValue == "") { //TODO change to error object kony.sdk.logsdk.error("### OfflineObjectService::_invokeOfflineUpdate Error: Primarykey details missing so unable to update"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } pkTable.pKey = { "key": pKey, "value": pKeyValue }; var condition = {}; condition.key = pKey; condition.value = pKeyValue; whereClause.push(condition); } } else { //TODO change to error object kony.sdk.logsdk.error("### OfflineObjectService::_invokeOfflineUpdate Error: Primarykey details missing so unable to update"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } var dbName = kony.sdk.util.getSyncDbName(); kony.sync.single_update_execute(dbName, objectName, columnValues, whereClause, successCallback, function(err) { _invokeOfflineErrorCallback(failureCallback, err); }, false, true, null, options); } function _invokeOfflineDelete(dataObject, successCallback, failureCallback, options) { var isError = false; var markForUpload = false; var tbname = dataObject.getObjectName(); var errMsg = null; var wcs = []; var objMetadata = kony.sdk.ObjectServiceUtil.getCachedObjectMetadata(serviceName, dataObject.getObjectName()); var dbName = kony.sdk.util.getSyncDbName(); var srcAttributes = kony.sdk.util.getPrimarykeysFromMetadata(objMetadata); if (srcAttributes != null && srcAttributes != undefined) { var pkLen = Object.keys(srcAttributes).length; for (var indx = 0; indx < pkLen; indx++) { var pKey = Object.keys(srcAttributes)[indx]; var pKeyValue = dataObject.getRecord()[pKey]; if (pKeyValue == null || pKeyValue == undefined || pKeyValue == "") { //TODO //throw error kony.sdk.logsdk.error("### _invokeOfflineDelete:: Error Primarykey details missing so unable to delete"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } var whereClause = {}; whereClause.key = pKey; whereClause.value = pKeyValue; kony.table.insert(wcs, whereClause); } } else { //TODO //throw error kony.sdk.logsdk.error("### _invokeOfflineDelete:: Error Primarykey details missing so unable to delete"); kony.sdk.verifyAndCallClosure(failureCallback, kony.sdk.error.getClientErrObj(kony.sdk.errorcodes.primarykey_unavailable, kony.sdk.errormessages.primarykey_unavailable)); return; } kony.sync.single_delete_execute(dbName, tbname, wcs, successCallback, function(err) { _invokeOfflineErrorCallback(failureCallback, err); }, false, false, true, options); } }; //Utils specific to MVVM/MDA/MVC SDK // This function is responsible for checking if the array contains the object based on object's name property. // returns the array element if the object matches kony.sdk.util.getExtendedFieldsFromArray = function(array, object) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.getExtendedFieldsFromArray"); if (array instanceof Array) { for (var i = 0; i < array.length; i++) { if (array[i] instanceof kony.sdk.dto.FieldMetadata && object instanceof kony.sdk.dto.Column) { if (kony.sdk.util.matchIgnoreCase(array[i].name, object.getName()) && kony.sdk.util.matchIgnoreCase(array[i].type, "extendedfield")) { return array[i]; } } } return null; } }; /** * This Object represent picklist values * @constructor */ kony.sdk.dto.PickList = function() { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.PickList"); this.id = null; this.active = null; this.label = null; this.value = null; this.validFor = null; this.defaultValue = null; this.fieldMappingId = null; this.setId = function(id) { this.id = id; } this.getId = function() { return this.id; } this.setActive = function(active) { this.active = active; } this.isActive = function() { return this.active; } this.setLabel = function(label) { this.label = label; } this.getLabel = function() { return this.label; } this.setValue = function(value) { this.value = value; } this.getValue = function() { return this.value; } this.setValidFor = function(validFor) { this.validFor = validFor; } this.getValidFor = function() { return this.validFor; } this.setDefaultValue = function(defaultValue) { this.defaultValue = defaultValue; } this.getDefaultValue = function() { return this.defaultValue; } this.setFieldMappingId = function(fieldMappingId) { this.fieldMappingId = fieldMappingId; } this.getFieldMappingId = function() { return this.fieldMappingId; } } /** * The structure of Object Metadata obtained from server * @constructor */ kony.sdk.dto.ObjectMetadata = function() { //variables to store metadata of the object. this.custom; this.customizable; this.displayName; this.entityTypeID; this.columns; this.junction; this.name; this.primaryKey; this.relationshipList; this.sourceEntityName; this.updateable; this.uniqueKeys; } /** * The structure of Field Metadata obtained from server * @constructor */ kony.sdk.dto.FieldMetadata = function() { this.auditColumn; this.createable; this.custom; this.customizable; this.type; this.defaultValue; this.displayName; this.fieldMappingId; this.hasIndex; this.name; this.nameField; this.nullable; this.primaryKey; this.sourceFieldName; this.table; this.updateable; // array of picklistValueDto objects to hold the pick list values. This will be populated only when the data type is of picklist type this.pickListValues; } /** * The structure of Object Relationship in metadata obtained from server * @constructor */ kony.sdk.dto.ObjectRelationship = function() { this.entityName; this.entityPageTemplateId; this.id; this.junctionTableName; this.operationType; this.relatedEntity; this.relationshipFields; this.relationshipName; this.relationshipType; this.custom; } /** * The Object used to define select query object, in order to fetch data * @param serviceName * @param tableObj {@link kony.sdk.dto.Table} * @constructor */ kony.sdk.dto.SelectQuery = function(serviceName, tableObj) { this.tables = []; this.columnList = []; this.criteriaList = []; this.isDistinct = false; this.orderList = []; this.joinList = []; this.groupList = []; this.limit = null; this.skip = null; this.oDataURL = null; if (tableObj instanceof kony.sdk.dto.Table) { this.tables.push(tableObj); } /** * This function is used to set Limit value * @param val */ this.setLimit = function(val) { this.limit = val; }; /** * This function is used to set Skip value * @param val */ this.setSkip = function(val) { this.skip = val; }; /** * This function is used to get the Limit Value * @returns {integer} limit */ this.getLimit = function() { return this.limit; }; /** * This function is used to get the Skip Value * @returns {integer} skip */ this.getSkip = function() { return this.skip; }; /** * This function is used to add a column object into the select query * @param columnObj {@Link kony.sdk.dto.Column} * @returns {Array} */ this.addColumn = function(columnObj) { if (columnObj instanceof kony.sdk.dto.Column) { this.columnList.push(columnObj); return this.columnList; } }; /** * This function is used to add a criteria object to the select query * @param criteriaObj * @returns {Array} */ this.addCriteria = function(criteriaObj) { if (kony.sdk.util.validateCriteriaObject(criteriaObj)) { this.criteriaList.push(criteriaObj); return this.criteriaList; } }; /** * This function is used to add a group object to select query * @param groupObj */ this.addGroup = function(groupObj) { if (groupObj instanceof kony.sdk.dto.Group) { this.groupList.push(groupObj); for (var i = 0; i < this.tables.length; i++) { if (this.tables[i].getName().toUpperCase() === groupObj.getColumn().getTable().getName().toUpperCase()) { return; } } this.tables.push(groupObj.getColumn().getTable()); } }; /** * This function is used to add a join object * @param joinObj */ this.addJoin = function(joinObj) { if (joinObj instanceof kony.sdk.dto.Join) { this.joinList.push(joinObj); for (var i = 0; i < this.tables.length; i++) { if (this.tables[i].getName().toUpperCase() === joinObj.getTable().getName().toUpperCase()) { if (this.tables[i].getAlias() != null || joinObj.getTable().getAlias() != null || this.tables[i].getAlias() != undefined || joinObj.getTable().getAlias() != undefined) { if (this.tables[i].getAlias().toUpperCase() === joinObj.getTable().getAlias().toUpperCase()) { return; } else { this.tables.push(joinObj.getTable()); return; } } else { return; } } } this.tables.push(joinObj.getTable()); } }; /** * This function is used to add order object to a select query * @param orderObj */ this.addOrder = function(orderObj) { var currentobject = this; if (orderObj instanceof kony.sdk.dto.Order) { this.orderList.push(arguments[0]); for (var i = 0; i < this.tables.length; i++) { if (this.tables[i].getName().toUpperCase() === arguments[0].getColumn().getTable().getName().toUpperCase()) { return; } } this.tables.push(orderObj.getColumn().getTable()); } }; /** * This function is used to return tables in select query * @returns {Array} Tables */ this.getTables = function() { return this.tables; }; /** * This function is used to get isDistinct flag * @returns {boolean} */ this.getDistinct = function() { return this.isDistinct; }; /** * This function is used to return columns in select query * @returns {Array} Columns */ this.getColumns = function() { return this.columnList; }; /** * This function is used to get criteria objects in the select query * @returns {Array} Criterias */ this.getCriterias = function() { return this.criteriaList; }; /** * This function is used to get the group objects in the select query * @returns {Array} GroupObjs */ this.getGroups = function() { return this.groupList; }; /** * This function is used to get the Join objects in the select query * @returns {Array} Joins */ this.getJoins = function() { return this.joinList; }; /** * This function is used to get the Order Objects in the select query * @returns {Array} OrderObjs */ this.getOrders = function() { return this.orderList; }; /** * This function is used to remove columnobject set in select query * @param columnObj {@link kony.sdk.dto.Column} */ this.removeColumn = function(columnObj) { if (columnObj instanceof kony.sdk.dto.Column) { this.columnList.splice(this.columnList.indexOf(columnObj), 1); } }; /** * This function is used to remove criteriaObject from select query * @param criteriaObj */ this.removeCriteria = function(criteriaObj) { if (criteriaObj instanceof Criteria) { this.criteriaList.splice(this.criteriaList.indexOf(criteriaObj), 1); } }; /** * This function is used to remove group set from select query * @param groupObj */ this.removeGroup = function(groupObj) { if (groupObj instanceof kony.sdk.dto.Group) { this.groupList.splice(this.groupList.indexOf(groupObj), 1); } }; /** * This function is used to remove Join set in select query * @param joinObj */ this.removeJoin = function(joinObj) { if (joinObj instanceof kony.sdk.dto.Criteria) { this.joinList.splice(this.joinList.indexOf(joinObj), 1); } }; /** * This function is used to remove OrderObj set in SelectQuery * @param orderObj */ this.removeOrder = function(orderObj) { if (orderObj instanceof kony.sdk.dto.Order) { this.orderList.splice(this.orderList.indexOf(orderObj), 1); } }; /** * This function is used to set isDistinct * @param isDistinct */ this.setDistinct = function(isDistinct) { this.isDistinct = isDistinct; }; /** * This function is used to get the select query in the form of a string * @returns {string} */ this.toString = function() { var selectQueryDto = this; var query = ""; query = query + "SELECT "; if (this.getDistinct() == true || this.getDistinct() == "true") { query = query + " DISTINCT "; } // Fetch the metadata for the base table and see if there are any extended fields associated with it // If there are any, create a join between the base table and the corresponding parent table and fetch it var columns = this.columnList; var extendedFields = []; var columnsArr = []; var extendedJoins = []; var baseTable = this.getTables()[0]; var objectMetadata = kony.sdk.ObjectServiceUtil.getCachedObjectMetadata(serviceName, baseTable.getName()); if (columns.length !== 0) { var field = null; for (var colIndex = 0; colIndex < columns.length; colIndex++) { field = kony.sdk.util.getExtendedFieldsFromArray(objectMetadata.columns, columns[colIndex]); if (field !== null && field !== undefined) { selectQueryDto.columnList[colIndex].dataType = field.type; selectQueryDto.columnList[colIndex].parentFieldName = field.parentFieldName; extendedFields.push(field); field = null; } else { columnsArr.push(columns[colIndex]); } } } else { var col = null; var field = null; for (var colIndex = 0; colIndex < objectMetadata.columns.length; colIndex++) { field = objectMetadata.columns[colIndex]; col = new kony.sdk.dto.Column(baseTable, field.name); col.dataType = field.type; col.parentFieldName = field.parentFieldName; selectQueryDto.columnList.push(col); if (field !== null && field !== undefined && kony.sdk.util.matchIgnoreCase(field.type, "extendedfield")) { extendedFields.push(field); field = null; } else { columnsArr.push(columns[colIndex]); } } } var columnStr = selectQueryDto.appendListToQuery(columnsArr, ", ", 0); if (columnStr !== null && columnStr !== "") { query = query + columnStr; } //TODO have to modify the code based on latest metadata if (extendedFields !== null && extendedFields !== undefined && extendedFields.length !== 0) { var join = null; var table = null; var srcCol = null; var destCol = null; var joinType = kony.sdk.constants.JoinType.LEFT; var col = null; var colList = []; var extendedTablesAdded = {}; for (var extIndex = 0; extIndex < extendedFields.length; extIndex++) { if (extendedTablesAdded !== null && extendedTablesAdded.hasOwnProperty(extendedFields[extIndex].parentTableName)) { extendedTablesAdded["" + extendedFields[extIndex].parentTableName] = ++extendedTablesAdded["" + extendedFields[extIndex].parentTableName]; } else { extendedTablesAdded["" + extendedFields[extIndex].parentTableName] = 0; } table = new kony.sdk.dto.Table(extendedFields[extIndex].parentTableName); // Now add all extended field columns to the query col = new kony.sdk.dto.Column(table, extendedFields[extIndex].parentFieldName); colList.push(col); // Need to fetch the source table's primary key name from the metadata. For now hard coding it to 'id' //TODO srcCol = new kony.sdk.dto.Column(baseTable, extendedFields[extIndex].foreignKeyFieldName); destCol = new kony.sdk.dto.Column(table, extendedFields[extIndex].referencedField || "id"); join = new kony.sdk.dto.Join(table, srcCol, destCol, joinType); if (join !== null && join !== undefined && extendedTablesAdded["" + extendedFields[extIndex].parentTableName] === 0) { extendedJoins.push(join); } } var extColStr = ""; for (var i = 0; i < colList.length; i++) { extColStr = extColStr + colList[i].toString(); if (i < colList.length - 1) { extColStr = extColStr + ","; } } if (extColStr !== null && extColStr !== "") { query = query + "," + extColStr; } if (extendedJoins !== null && extendedJoins !== undefined) { for (var joinIndex = 0; joinIndex < extendedJoins.length; joinIndex++) { selectQueryDto.addJoin(extendedJoins[joinIndex]); } } } query = query + " FROM "; query = query + selectQueryDto.getTables()[0].toString(); if (selectQueryDto.getJoins().length !== 0) { var joinStr = selectQueryDto.appendListToQuery(selectQueryDto.joinList, " ", -1); query = query + joinStr; } if (!(selectQueryDto.criteriaList.length == 0)) { query = query + " WHERE "; query = query + selectQueryDto.appendListToQuery(selectQueryDto.criteriaList, " AND ", -1); } if (!(selectQueryDto.groupList.length == 0)) { query = query + " GROUP BY "; query = query + selectQueryDto.appendListToQuery(selectQueryDto.groupList, ", ", -1); } if (!(selectQueryDto.orderList.length == 0)) { query = query + " ORDER BY "; query = query + selectQueryDto.appendListToQuery(selectQueryDto.orderList, " ,", -1); } if (selectQueryDto.limit !== null && selectQueryDto.limit !== undefined && kony.sdk.util.isValidNumberType(selectQueryDto.limit) && selectQueryDto.limit !== 0) { query = query + " LIMIT " + selectQueryDto.limit; } if (selectQueryDto.skip !== null && selectQueryDto.skip !== undefined && kony.sdk.util.isValidNumberType(selectQueryDto.skip) && selectQueryDto.skip !== 0) { query = query + " OFFSET " + selectQueryDto.skip; } return query; }; this.appendListToQuery = function(objectList, seperator, mode) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.appendListToQuery"); var listBuffer = ""; for (var i = 0; i < objectList.length; i++) { var obj = objectList[i]; if (mode > -1) { if (obj !== null) { if (obj instanceof kony.sdk.dto.Column) { listBuffer = listBuffer.concat(obj.toString()); } else { listBuffer = listBuffer.concat(obj.toString()); } } } else if (obj !== null && obj !== undefined) { listBuffer = listBuffer.concat(obj.toString()); } if (i < objectList.length - 1) { listBuffer = listBuffer.concat(seperator); } } return listBuffer; }; }; /** * This function is the Table constructor. * @param tableName * @param tableAlias * @param junctionType * @constructor */ kony.sdk.dto.Table = function(tableName, tableAlias, junctionType) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.Table"); this.name = tableName; this.alias = tableAlias; this.isjunction = junctionType; this.getAlias = function() { return this.alias; }; /** * This function is used to set alias. * * @param alias */ this.setAlias = function(alias) { this.alias = alias; }; this.getName = function() { return this.name; }; /** * This function is used to set name. * * @param name */ this.setName = function(name) { this.name = name; }; /** * This function is used to check object equality. * * @param obj * @return Boolean */ this.equals = function(obj) { var areObjectsEqual = false; if (obj === null || obj === undefined) { areObjectsEqual = false; } else if (typeof(this) === typeof(obj)) { areObjectsEqual = true; if (this.hasAlias() && obj.hasAlias()) { areObjectsEqual = this.getAlias() === obj.getAlias(); } else { areObjectsEqual = this.getName() === obj.getName(); } } else { areObjectsEqual = false; } return areObjectsEqual; }; this.getColumn = function(columnName) { return new kony.sdk.dto.Column(this, columnName); }; /** * This function is used to check if alias is present or not. * * @return Boolean */ this.hasAlias = function() { return (this.alias !== null && this.alias !== undefined); }; /** * This function is used to convert to String. * * @return string */ this.toString = function() { return this.getName() + (this.hasAlias() ? " " + this.getAlias() : ""); }; /** * This function is used to return if the table is a junction table. * * @return boolean */ this.isJunction = function() { return (this.isjunction && this.isjunction == true); }; /** * This function is used to set the type of table junction/non-junction table. * * @param junctionType */ this.setJunction = function(junctionType) { this.isjunction = junctionType; }; }; /** * This function is a Column constructor * @param tableObj {@link kony.sdk.dto.Table} * @param colName * @constructor */ kony.sdk.dto.Column = function(tableObj, colName) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.Column"); if (tableObj instanceof kony.sdk.dto.Table) { this.aggregation = null; this.alias = null; this.dataType = null; this.name = null; this.table = null; if (colName !== undefined && colName !== null && typeof(colName) === "string") { this.name = colName; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Column:: Error: colName is undefined"); } this.table = tableObj; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Column:: Error: tableObj is not an instance of kony.sdk.dto.Table"); } this.getAggregation = function() { return this.aggregation; }; this.setAggregation = function(aggregation) { this.aggregation = aggregation; }; this.getAlias = function() { return this.alias; }; this.setAlias = function(alias) { this.alias = alias; }; this.getDataType = function() { return this.dataType; }; this.setDataType = function(dataType) { this.dataType = dataType; }; this.isComputedField = function() { return this.fieldComputed; }; this.setComputedField = function(fieldComputed) { this.fieldComputed = fieldComputed; }; this.getName = function() { return this.name; }; this.setName = function(name) { if (name !== undefined && name !== null && typeof(name) === "string") { this.name = name; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Column::setName:: Error: name is undefined"); } }; this.getTable = function() { return this.table; }; this.setTable = function(table) { if (table instanceof kony.sdk.dto.Table) { this.table = table; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Column:: Error: setTable is undefined"); } }; this.toStringByMode = function(mode) { var tableName = (this.getTable().getAlias() !== null && this.getTable().getAlias() !== undefined) ? this.getTable().getAlias() : this.getTable().getName(); var constructedColumn = null; var constructDataType = null; var constructAlias = null; var constructAggregation = null; switch (mode) { case 0: if (this.getDataType() !== null && this.getDataType() !== undefined) { if (kony.sdk.util.matchIgnoreCase(this.getDataType(), "Integer")) { constructDataType = "CAST (" + tableName + "." + this.getName() + " AS INTEGER)"; } else if (kony.sdk.util.matchIgnoreCase(this.getDataType(), "Numeric")) { constructDataType = "CAST (" + tableName + "." + this.getName() + " AS NUMERIC)"; } else if (kony.sdk.util.matchIgnoreCase(this.getDataType(), "Date")) { constructDataType = "date(" + tableName + "." + this.getName() + ")"; } else { constructDataType = tableName + "." + this.getName(); } } else { constructDataType = tableName + "." + this.getName(); } constructAlias = (this.getAlias() !== null && this.getAlias() !== undefined && this.getAlias() !== "") ? " AS " + this.getAlias() : ""; constructAggregation = (this.getAggregation() === kony.sdk.constants.Aggregation.NONE || (this.getAggregation() === null || this.getAggregation() === undefined)) ? constructDataType : (this.isComputedField() ? this.getAggregation() : this.getAggregation() + "(" + constructDataType + ")"); constructedColumn = constructAggregation + constructAlias; break; case 1: if (this.getDataType() !== null && this.getDataType() !== undefined) { if (kony.sdk.util.matchIgnoreCase(this.getDataType(), "STRING")) this.setDataType("text"); } constructDataType = (this.getDataType() !== null && this.getDataType() !== undefined) ? "CAST (" + tableName + "." + this.getName() + " AS " + this.getDataType() + ")" : tableName + "." + this.getName(); constructAggregation = (this.getAggregation() === kony.sdk.constants.Aggregation.NONE || (this.getAggregation() === null || this.getAggregation() === undefined)) ? constructDataType : (this.isComputedField() ? this.getAggregation() : this.getAggregation() + "(" + constructDataType + ")"); constructedColumn = constructAggregation; break; case 2: constructedColumn = this.getName(); break; case 3: constructedColumn = this.getName(); break; default: if (this.getDataType() !== null && this.getDataType() !== undefined) { if (kony.sdk.util.matchIgnoreCase(this.getDataType(), "STRING")) this.setDataType("text"); } constructDataType = (this.getDataType() !== null && this.getDataType() !== undefined) ? "CAST (" + tableName + "." + this.getName() + " AS " + this.getDataType() + ")" : tableName + "." + this.getName(); constructAlias = (this.getAlias() !== null && this.getAlias() !== undefined) ? " AS " + this.getAlias() : ""; constructAggregation = (this.getAggregation() === kony.sdk.constants.Aggregation.NONE || (this.getAggregation() === null || this.getAggregation() === undefined)) ? constructDataType : (this.isComputedField() ? this.getAggregation() : this.getAggregation() + "(" + constructDataType + ")"); constructedColumn = constructAggregation + constructAlias; break; } return constructedColumn; }; this.toString = function() { // To be removed later from here if (this.getDataType() !== null && this.getDataType() !== undefined) { if (kony.sdk.util.matchIgnoreCase(this.getDataType(), "STRING")) dataType = "text"; } var tableName = (this.getTable().getAlias() !== null && this.getTable().getAlias() !== undefined && this.getTable().getAlias() !== "") ? this.getTable().getAlias() : this.getTable().getName(); var constructedColumn = null; var constructDataType = null; var constructAggregation = null; if (this.getDataType() !== null && this.getDataType() !== undefined) { if (kony.sdk.util.matchIgnoreCase(this.getDataType(), "Integer")) { constructDataType = "CAST (" + tableName + "." + this.getName() + " AS INTEGER)"; } else if (kony.sdk.util.matchIgnoreCase(this.getDataType(), "Numeric")) { constructDataType = "CAST (" + tableName + "." + this.getName() + " AS NUMERIC)"; } else if (kony.sdk.util.matchIgnoreCase(this.getDataType(), "Date")) { constructDataType = "date(" + tableName + "." + this.getName() + ")"; } else { if (!this.isComputedField()) constructDataType = tableName + "." + this.getName(); } } else { if (!this.isComputedField()) constructDataType = tableName + "." + this.getName(); } var constructAlias = (this.getAlias() !== null && this.getAlias() !== undefined && this.getAlias() !== "") ? " AS " + this.getAlias() : ""; constructAggregation = (this.getAggregation() === kony.sdk.constants.Aggregation.NONE || (this.getAggregation() === null || this.getAggregation() === undefined)) ? constructDataType : (this.isComputedField() ? this.getAggregation() : this.getAggregation() + "(" + constructDataType + ")"); constructedColumn = constructAggregation + constructAlias; return constructedColumn; }; this.toStringByTablePrefix = function(includeTablePrefix) { if (includeTablePrefix) { return this.toString(); } else { return this.getName(); } } }; /** * This Object represents a groupby clause in select query * @param columnObj {@link kony.sdk.dto.Column} * @constructor */ kony.sdk.dto.Group = function(columnObj) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.Group"); if (columnObj instanceof kony.sdk.dto.Column) { this.column = columnObj; } this.getColumn = function() { return this.column; }; this.setColumn = function(column) { if (column instanceof kony.sdk.dto.Column) { this.column = column; } }; this.toString = function() { var tableName = (this.column.getTable().getAlias() !== null && this.column.getTable().getAlias() !== undefined) ? this.column.getTable().getAlias() : this.column.getTable().getName(); return tableName + "." + this.column.getName(); }; }; /** * This Object represents JOINS used in kony.sdk.dto.SelectQuery * @constructor */ kony.sdk.dto.Join = function() { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.Join"); this.criteria; this.table; this.joinType; var currentObject = this; if (arguments.length === 3) { getJoinByTableCriteriaAndJoinType(arguments[0], arguments[1], arguments[2]); } else if (arguments.length === 4) { getJoinByDestTableAndSrcColumnAndDestColumnAndJoinType(arguments[0], arguments[1], arguments[2], arguments[3]); } /** * This function is the Join constructor which has 3 arguments. * * @param table * @param criteria * @param joinType */ function getJoinByTableCriteriaAndJoinType(table, criteria, joinType) { kony.sdk.logsdk.trace("Entering into getJoinByTableCriteriaAndJoinType"); if (table instanceof kony.sdk.dto.Table && kony.sdk.util.validateCriteriaObject(criteria) && joinType !== null && joinType !== undefined && (joinType === kony.sdk.constants.JoinType.INNER || joinType === kony.sdk.constants.JoinType.LEFT)) { currentObject.table = table; currentObject.joinType = joinType; currentObject.criteria = criteria; return currentObject; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Join::getJoinByTableCriteriaAndJoinType:: Error: Validation error at getJoinByTableCriteriaAndJoinType"); } } /** * This function is the Join constructor which has 4 arguments. * * @param destTable * @param srcColumn * @param destColumn * @param joinTypeObj */ function getJoinByDestTableAndSrcColumnAndDestColumnAndJoinType(destTable, srcColumn, destColumn, joinTypeObj) { kony.sdk.logsdk.trace("Entering into getJoinByDestTableAndSrcColumnAndDestColumnAndJoinType"); if (destTable instanceof kony.sdk.dto.Table && srcColumn instanceof kony.sdk.dto.Column && destColumn instanceof kony.sdk.dto.Column && joinTypeObj !== null && joinTypeObj !== undefined && joinTypeObj !== '' && (joinTypeObj === kony.sdk.constants.JoinType.INNER || joinTypeObj === kony.sdk.constants.JoinType.LEFT)) { currentObject.table = destTable; currentObject.joinType = joinTypeObj; var criteria = new kony.sdk.dto.Match(srcColumn, kony.sdk.constants.MatchType.EQUALS, destColumn); currentObject.criteria = criteria; return currentObject; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Join::getJoinByDestTableAndSrcColumnAndDestColumnAndJoinType:: Error: Validation error at getJoinByDestTableAndSrcColumnAndDestColumnAndJoinType"); } } this.getCriteria = function() { return this.criteria; }; this.setCriteria = function(criteria) { if (kony.sdk.util.validateCriteriaObject(criteria)) { this.criteria = criteria; } }; this.getTable = function() { return this.table; }; this.setTable = function(table) { if (table instanceof kony.sdk.dto.Table) { this.table = table; } }; this.getJoinType = function() { return this.joinType; }; this.setJoinType = function(joinType) { if (joinType !== null) { this.joinType = joinType; } }; this.initCriteria = function(srcColumn, destColumn) { if ((srcColumn instanceof kony.sdk.dto.Column) && (destColumn instanceof kony.sdk.dto.Column)) { var criteria = new kony.sdk.dto.Match(srcColumn, kony.sdk.constants.MatchType.EQUALS, destColumn); this.setCriteria(criteria); } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Join::initCriteria:: Error: srcColumn or destColumn is not an isntanceof kony.sdk.dto.Column"); } }; this.toString = function() { var returnString = null; var temp = null; var join; if (kony.sdk.constants.JoinType.INNER == this.getJoinType()) { join = "INNER"; } else if (kony.sdk.constants.JoinType.LEFT == this.getJoinType()) { join = "LEFT"; } else if (kony.sdk.constants.JoinType.RIGHT == this.getJoinType()) { join = "RIGHT"; } returnString = " " + join + " JOIN " + this.getTable().toString() + " ON "; temp = this.getCriteria().toString(); returnString = returnString + temp; return returnString; }; }; /** * This function is the Order constructor. * @param columnObj * @param orderTypeObj */ kony.sdk.dto.Order = function(columnObj, orderTypeObj) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.Order"); if ((columnObj instanceof kony.sdk.dto.Column) && (orderTypeObj == kony.sdk.constants.OrderType.ASCENDING || orderTypeObj == kony.sdk.constants.OrderType.DESCENDING)) { this.column = columnObj; this.type = orderTypeObj; return this; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Order:: Error: Validation error") } this.getColumn = function() { return this.column; }; /** * This function is used to set column. * * @param column */ this.setColumn = function(column) { if (column instanceof kony.sdk.dto.Column) { this.column = column; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Order::setColumn: Error: column is not an instance of kony.sdk.dto.Column"); } }; this.getType = function() { return this.type; }; /** * This function is used to set type. * * @param type */ this.setType = function(type) { this.type = type; }; /** * This function is used to convert to String. * * @return string */ this.toString = function() { return this.column.toString() + " " + (this.type); }; }; /** * This function is used to check the range of values of columnObj * @param columnObj {@link kony.sdk.dto.Column} * @param colRange * @constructor */ kony.sdk.dto.Between = function(columnObj, colRange) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.Between"); this.column; this.range; if (columnObj instanceof kony.sdk.dto.Column && (colRange instanceof kony.sdk.dto.DateRange || colRange instanceof kony.sdk.dto.StringRange || colRange instanceof kony.sdk.dto.IntegerRange || colRange instanceof kony.sdk.dto.FloatRange)) { this.column = columnObj; this.range = colRange; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Between:: Error: Vaildation error"); } this.quote = function(str) { if (kony.sdk.util.isNull(str)) { return "null"; } // var str1 = new String(str); var strBuf = []; strBuf.push('\''); for (var index = 0; index < str.length; index++) { var charItem = str.charAt(index); if (charItem == '\\' || charItem == '\"' || charItem == '\'') { // strBuf.concat('\\'); strBuf.push('\\'); } strBuf.push(charItem); } strBuf.push('\''); return strBuf.join(""); }; this.setColumn = function(column) { if (column instanceof kony.sdk.dto.Column) { this.column = column; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Between::setColumn: Error:column is not an instance of kony.sdk.dto.Column"); } }; this.setRange = function(range) { if (range instanceof kony.sdk.dto.DateRange || range instanceof kony.sdk.dto.StringRange || range instanceof kony.sdk.dto.IntegerRange || range instanceof kony.sdk.dto.FloatRange) { this.range = range; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Between::setRange: Error: Validation Error"); } }; this.getColumn = function() { return this.column; }; this.getRange = function() { return this.range; }; this.toString = function() { var returnStr = ""; returnStr = this.getColumn().toString() + " Between " + this.getRange().toString(); return returnStr; }; }; /** * This function is the DateRange constructor. * @param startDate * @param endDate */ kony.sdk.dto.DateRange = function() { this.end; this.start; if (arguments.length === 2) { var startDate = arguments[0]; var endDate = arguments[1]; if (startDate instanceof Date && endDate instanceof Date) { this.start = startDate; this.end = endDate; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.DataRange:: Error: startDate or endDate is not an instance of Date"); } } else if (arguments.length === 1) { var dateType = arguments[0]; if (kony.sdk.util.validateDateTypeInput(dateType)) { var range = kony.sdk.util.getDateRange(dateType); if (range.length !== 2 || range[0] === 0 || range[1] === 0) { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.DateRange:: Error: Validation Error"); } else { this.start = range[0]; this.end = range[1]; } } } this.getEnd = function() { return this.end; }; /** * This function is used to set End value. * * @param end */ this.setEnd = function(end) { if (end instanceof Date) { var month = end.getMonth() + 1; var date = end.getDate(); var hr = end.getHours(); var min = end.getMinutes(); var sec = end.getSeconds(); if (month < 10) { month = "0" + month; } if (date < 10) { date = "0" + date; } if (hr < 10) { hr = "0" + hr; } if (min < 10) { min = "0" + min; } if (sec < 10) { sec = "0" + sec; } var endDate = end.getFullYear() + "-" + month + "-" + date + " " + hr + ":" + min + ":" + sec; this.end = endDate; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.DateRange::setEnd:: Error: end is not an instance of Date"); } }; this.getStart = function() { return this.start; }; /** * This function is used to set start value. * * @param start */ this.setStart = function(start) { if (start instanceof Date) { var month = start.getMonth() + 1; var date = start.getDate(); var hr = start.getHours(); var min = start.getMinutes(); var sec = start.getSeconds(); if (month < 10) { month = "0" + month; } if (date < 10) { date = "0" + date; } if (hr < 10) { hr = "0" + hr; } if (min < 10) { min = "0" + min; } if (sec < 10) { sec = "0" + sec; } var startDate = start.getFullYear() + "-" + month + "-" + date + " " + hr + ":" + min + ":" + sec; this.start = startDate; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.DateRange::setStart:: Error: start is not an instance of Date"); } }; /** * This function is used to convert to String. * * @return string */ this.toString = function() { var returnString = null; returnString = "'" + this.start + "'" + " AND " + "'" + this.end + "'"; return returnString; }; }; /** * This function is the DecimalRange constructor. * @param startDecimal * @param endDecimal */ kony.sdk.dto.DecimalRange = function(startDecimal, endDecimal) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.DecimalRange"); if ((endDecimal !== null && endDecimal !== undefined && typeof endDecimal === 'number') && (startDecimal !== null && startDecimal !== undefined && typeof startDecimal === 'number')) { this.end = endDecimal; this.start = startDecimal; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.DecimalRange:: Error: Validation Error"); } this.getEnd = function() { return this.end; }; /** * This function is used to set End value. * * @param end */ this.setEnd = function(end) { if (end !== null && end !== undefined && typeof end === 'number') { this.end = end; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.DecimalRange::setEnd:: Error: Validation Error"); } }; this.getStart = function() { return this.start; }; /** * This function is used to set start value. * * @param start */ this.setStart = function(start) { if (start !== null && start !== undefined && typeof start === 'number') { this.start = start; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.DecimalRange::setStart:: Error: Validation Error"); } }; /** * This function is used to convert to String. * * @return string */ this.toString = function() { var returnString = null; returnString = this.start + " AND " + this.end; return returnString; }; }; /** * This function is the FloatRange constructor. * @param startFloat * @param endFloat */ kony.sdk.dto.FloatRange = function(startFloat, endFloat) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.FloatRange"); this.end = endFloat; this.start = startFloat; this.getEnd = function() { return this.end; }; /** * This function is used to set End value. * * @param end */ this.setEnd = function(end) { if (end !== null && end !== undefined && typeof end === 'number') { this.end = end; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.FloatRange::setEnd:: Error: Validation Error"); } }; this.getStart = function() { return this.start; }; /** * This function is used to set start value. * * @param start */ this.setStart = function(start) { if (start !== null && start !== undefined && typeof start === 'number') { this.start = start; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.FloatRange::setStart:: Error: Validation Error"); } }; /** * This function is used to convert to String. * * @return string */ this.toString = function() { var returnString = null; returnString = this.start + " AND " + this.end; return returnString; }; }; /** * This function is the IntegerRange constructor. * @param startInt * @param endInt */ kony.sdk.dto.IntegerRange = function(startInt, endInt) { if ((endInt !== null && endInt !== undefined && typeof endInt === 'number') && (startInt !== null && startInt !== undefined && typeof startInt === 'number')) { this.end = endInt; this.start = startInt; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.IntegerRange:: Error: Validation Error"); } this.getEnd = function() { return this.end; }; /** * This function is used to set End value. * * @param end */ this.setEnd = function(end) { if (end !== null && end !== undefined && typeof end === 'number') { this.end = end; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.IntegerRange::setEnd:: Error: Validation Error"); } }; this.getStart = function() { return this.start; }; /** * This function is used to set start value. * * @param start */ this.setStart = function(start) { if (start !== null && start !== undefined && typeof start === 'number') { this.start = start; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.IntegerRange::setStart:: Error: Validation Error"); } }; /** * This function is used to convert to String. * * @return string */ this.toString = function() { var returnString = null; returnString = this.start.toFixed() + " AND " + this.end.toFixed(); return returnString; }; }; /** * This function is the StringRange constructor. * @param startString * @param endString */ kony.sdk.dto.StringRange = function(startString, endString) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.StringRange"); if ((endString !== null && endString !== undefined && typeof endString === 'string') && (startString !== null && startString !== undefined && typeof startString === 'string')) { this.end = endString; this.start = startString; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.StringRange:: Error: Validation Error"); } this.getEnd = function() { return this.end; }; /** * This function is used to set End value. * * @param end */ this.setEnd = function(end) { if (end !== null && end !== undefined && typeof end === 'string') { this.end = end; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.StringRange::setEnd:: Error: Validation Error"); } }; this.getStart = function() { return this.start; }; /** * This function is used to set start value. * * @param start */ this.setStart = function(start) { if (start !== null && start !== undefined && typeof start === 'string') { this.start = start; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.StringRange::setStart:: Error: Validation Error"); } }; /** * This function is used to convert to String. * * @return string */ this.toString = function() { var returnString = null; var crit = new kony.sdk.dto.Criteria(); returnString = crit.quote(this.start) + " AND " + crit.quote(this.end); return returnString; }; }; /** * This function helps in preparing And {@link kony.sdk.dto.And} and Or {@Link kony.sdk.dto.Or} clauses * @param operatorLg * @param leftOp * @param rightOp * @constructor */ kony.sdk.dto.LogicGroup = function(operatorLg, leftOp, rightOp) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.LogicGroup"); this.left = leftOp; this.operator = operatorLg; this.right = rightOp; /** * This function is used to initialize LogicGroup. * * @param operator * @param left * @param right */ this.initializeLogicGroup = function(operator, left, right) { this.left = left; this.operator = operator; this.right = right; }; this.getLeft = function() { return this.left; }; /** * This function is used to set left. * * @param val */ this.setLeft = function(val) { this.val = val; }; this.getOperator = function() { return this.operator; }; /** * This function is used to set Operator. * * @param val */ this.setOperator = function(val) { this.operator = val; }; this.getRight = function() { return this.right; }; /** * This function is used to set Right. * * @param val */ this.setRight = function(val) { this.right = val; }; /** * This function is used to convert to String. * * @return string */ this.toString = function() { var leftOperator = (this.getLeft() !== null && this.getLeft !== undefined) ? this.getLeft().toString() : ""; var rightOperator = (this.getRight() !== null && this.getRight() !== undefined) ? this.getRight().toString() : ""; return "(" + leftOperator + " " + this.getOperator() + " " + rightOperator + ")"; }; }; /** * This function is the And constructor. * * @param left * @param right */ kony.sdk.dto.And = function(left, right) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.And"); if (arguments.length !== 2) { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.And:: Error: invalid number of arguments, expected are left and right"); } if ((right !== null && left !== null && right !== undefined && left !== undefined && kony.sdk.util.validateCriteriaObject(left) && kony.sdk.util.validateCriteriaObject(right))) { kony.sdk.dto.LogicGroup.call(this, 'AND', left, right); } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.And:: Error: Validation Error"); } this.initializeAnd = function(left, right) { kony.sdk.dto.LogicGroup.call(this, 'AND', left, right); }; }; /** * This function is the Or constructor. * * @param left * @param right */ kony.sdk.dto.Or = function(left, right) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.Or"); if (arguments.length !== 2) { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Or:: Error: invalid number of arguments, expected are left and right"); } if ((right !== null && left !== null && right !== undefined && left !== undefined && kony.sdk.util.validateCriteriaObject(left) && kony.sdk.util.validateCriteriaObject(right))) { kony.sdk.dto.LogicGroup.call(this, 'OR', left, right); } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Or:: Error: Validation Error"); } this.initializeOr = function(left, right) { kony.sdk.dto.LogicGroup.call(this, 'OR', left, right); }; }; /** * This function is the Not constructor. * * @param right */ kony.sdk.dto.Not = function(right) { if (arguments.length !== 1) { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Not:: Error: invalid number of arguments, expected right"); } if (right !== null && right !== undefined && kony.sdk.util.validateCriteriaObject(right)) { kony.sdk.dto.LogicGroup.call(this, 'NOT', null, right); } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Not:: Error: Validation Error"); } this.initializeNot = function(right) { kony.sdk.dto.LogicGroup.call(this, 'NOT', null, right); }; }; /** * This function is a constructor for Expression Object * @constructor */ kony.sdk.dto.Expression = function() { this.term; this.operator; this.expression; var currentExpObj = this; if (arguments.length === 1) { if (kony.sdk.util.validateCriteriaObject(arguments[0])) { setTerm(arguments[0]); } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Expression:: Error: Validation Error"); } } else if (arguments.length === 2) { initExpression(arguments[0], arguments[1]); } else if (arguments.length === 3) { initExpressionByExpression(arguments[0], arguments[1], arguments[2]); } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Expression:: Error: invalid number of arguments, atleast 'term' is expected"); } /** * Recursively generates a Expression from a given list of * criteria and an infix operator to join each criteria with the * next in the list. Operator AND or Operator OR that joins each * criteria term with the next in the list. * * @param criterias * the list of criteria terms from which the * constructor generates the new criteria expression. * @param operator * the infix operator */ function initExpression(criterias, operator) { if (operator === kony.sdk.constants.Operator.OR) { setOperator(kony.sdk.constants.Operator.OR); } else if (operator === kony.sdk.constants.Operator.AND) { setOperator(kony.sdk.constants.Operator.AND); } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Expression::initExpression:: Error: Invalid Operator"); } if (criterias !== null && criterias !== undefined && criterias instanceof Array && criterias.length > 0) { if (kony.sdk.util.validateCriteriaObject(criterias[0])) { setTerm(criterias[0]); } if (criterias.length > 1) { var tmpOperator = operator; criterias.shift(); setExpression(new kony.sdk.dto.Expression(criterias, tmpOperator)); } } else { if (kony.sdk.util.validateCriteriaObject(criterias)) { setTerm(criterias); // return currentExpObj; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Expression::initExpression:: Error: Validation Error"); } } } function setExpression(expression) { if (expression instanceof kony.sdk.dto.Expression) { currentExpObj.expression = expression; // return currentExpObj; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Expression::setExpression:: Error: expression not an instance of kony.sdk.do.Expression"); } } function setTerm(term) { if (kony.sdk.util.validateCriteriaObject(term)) { currentExpObj.term = term; // return currentExpObj; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Expression::setTerm:: Error: Validation Error"); } } /** * Initializes a Expression with an initial criteria term, an * operator, and a another trailing criteria expression. * * @param criterias * the starting criteria to assign to the new * criteria expression. * @param operator * the infix operator * @param expression * the trailing expression to assign to the new * criteria expression. */ function initExpressionByExpression(criterias, operator, expression) { if (operator === kony.sdk.constants.Operator.OR) { initExpression(criterias, kony.sdk.constants.Operator.OR); } else if (operator === kony.sdk.constants.Operator.AND) { initExpression(criterias, kony.sdk.constants.Operator.AND); } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Expression::initExpressionByExpression:: Error: Invalid Operator"); } setExpression(expression); // return currentExpObj; } function setOperator(operator) { currentExpObj.operator = operator; } this.getTerm = function() { return this.term; }; this.getOperator = function() { return this.operator; }; this.getExpression = function() { return this.expression; }; this.toString = function() { var returnString = null; if ((this.getTerm() === null || this.getTerm() === undefined) && (this.getExpression() === null || this.getExpression() === undefined)) { returnString = ""; } else if (this.getExpression() === null || this.getExpression() === undefined) { returnString = this.getTerm().toString(); } else if (this.getOperator() === kony.sdk.constants.Operator.AND) { returnString = (new kony.sdk.dto.And(this.getTerm(), this.getExpression())).toString(); } else if (this.getOperator() === kony.sdk.constants.Operator.OR) { returnString = (new kony.sdk.dto.Or(this.getTerm(), this.getExpression())).toString(); } return returnString; } }; /** * This function is a constructor for InCriteria Object * @constructor */ kony.sdk.dto.InCriteria = function() { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.InCriteria"); this.column; this.values; var currentInCriteriaObj = this; if (arguments.length === 2) { getInCriteriaByColumnAndCollection(arguments[0], arguments[1]); } else if (arguments.length === 3) { getInCriteriaByTableAndCollection(arguments[0], arguments[1], arguments[2]); } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.InCriteria:: Error: invalid number of arguments, atleast column,values are expected"); } /** * This function is the InCriteria constructor which has 3 * arguments. * * @param table * @param columnname * @param values */ function getInCriteriaByTableAndCollection(table, columnname, values) { kony.sdk.logsdk.trace("Entering into getInCriteriaByTableAndCollection"); if (table instanceof kony.sdk.dto.Table) { currentInCriteriaObj.column = new kony.sdk.dto.Column(table, columnname); currentInCriteriaObj.values = values; return currentInCriteriaObj; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.InCriteria::getInCriteriaByTableAndCollection:: Error: table is not an instance of kony.sdk.dto.Table"); } } /** * This function is the InCriteria constructor which has 2 * arguments. * * @param column * @param values */ function getInCriteriaByColumnAndCollection(column, values) { kony.sdk.logsdk.trace("Entering into getInCriteriaByColumnAndCollection"); if (column instanceof kony.sdk.dto.Column && values instanceof Array && values.length > 0) { currentInCriteriaObj.column = column; currentInCriteriaObj.values = values; return currentInCriteriaObj; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.InCriteria::getInCriteriaByColumnAndCollection:: Error: Validation Error"); } } this.getColumnForTable = function(table, columnName) { if (table instanceof kony.sdk.dto.Table) { var column = new kony.sdk.dto.Column(table, columnName); return column; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.InCriteria::getColumnForTable:: Error: table not an instance of kony.sdk.dto.Table"); } }; this.getColumn = function() { return this.column; }; this.setColumn = function(column) { if (column instanceof kony.sdk.dto.Column) { this.column = column; } }; this.setValues = function(valuesCollection) { this.values = valuesCollection; }; this.getValues = function() { return this.values; }; this.toString = function() { var result = ""; result = this.column.toString() + " IN ("; if (this.values !== null && this.values !== undefined && this.values.length > 0) { for (var index = 0; index < this.values.length; index++) { var value; var criteria = new kony.sdk.dto.Criteria(); if (typeof(this.values[index]) === "string") { value = criteria.quote(this.values[index]); } else { value = this.values[index]; } result = result + value; if (index !== (this.values.length - 1)) { result = result + ", "; } } } /* * else if (this.subSelect !== null && this.subSelect !== * undefined) { result = result + this.subSelect; } */ result = result + ")"; return result; }; }; /** * This function is used to in set Exists param in select query * @param subSelectQuery {@link kony.sdk.dto.SelectQuery} * @constructor */ kony.sdk.dto.Exists = function(subSelectQuery) { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.Exists"); if (subSelectQuery instanceof kony.sdk.dto.SelectQuery) { this.subSelect = subSelectQuery; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Exists:: Error: subSelectQuery is not an instance of kony.sdk.dto.SelectQuery"); } this.getSubSelect = function() { return this.subSelect; }; this.setSubSelect = function(subSelect) { if (subSelect instanceof kony.sdk.dto.SelectQuery) { this.subSelect = subSelect; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Exists::subSelectQuery:: Error: subSelectQuery is not an instance of kony.sdk.dto.SelectQuery"); } }; this.toString = function() { return "EXISTS ( " + this.subSelect.toString() + " )"; }; }; /** * This is Interface to define where clauses * @constructor */ kony.sdk.dto.Criteria = function() { kony.sdk.logsdk.trace("Entering into kony.sdk.dto.Criteria"); this.quote = function(str) { if (str === null || str === undefined) { return "null"; } // var str1 = new String(str); var strBuf = []; strBuf.push('\''); for (var index = 0; index < str.length; index++) { var charItem = str.charAt(index); if (charItem == '\\' || charItem == '\"' || charItem == '\'') { // strBuf.concat('\\'); strBuf.push('\\'); } strBuf.push(charItem); } strBuf.push('\''); return strBuf.join(""); }; }; /** * This function is used to define where clause * @constructor */ kony.sdk.dto.Match = function() { this.column; this.matchType; this.value; var currentMatchObj = this; if (arguments.length === 3) { initMatchByColumn(arguments[0], arguments[1], arguments[2]); } else if (arguments.length === 4) { initMatchByTableAndColName(arguments[0], arguments[1], arguments[2], arguments[3]); } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Match:: Error: Invalid number of arguments, atleast columnObj,matchType,value is required") } /** * This function is the Match constructor which has 3 arguments. * * @param columnObj * @param matchType * @param value */ function initMatchByColumn(columnObj, matchType, value) { if (columnObj instanceof kony.sdk.dto.Column) { currentMatchObj.column = columnObj; if (matchType !== kony.sdk.constants.MatchType.EQUALS && matchType !== kony.sdk.constants.MatchType.GREATER && matchType !== kony.sdk.constants.MatchType.GREATEREQUAL && matchType !== kony.sdk.constants.MatchType.LESS && matchType !== kony.sdk.constants.MatchType.LESSEQUAL && matchType !== kony.sdk.constants.MatchType.STARTSWITH && matchType !== kony.sdk.constants.MatchType.CONTAINS && matchType !== kony.sdk.constants.MatchType.LIKE && matchType !== kony.sdk.constants.MatchType.ENDSWITH && matchType !== kony.sdk.constants.MatchType.NOTEQUAL && matchType !== kony.sdk.constants.MatchType.ISNULL && matchType !== kony.sdk.constants.MatchType.ISNOTNULL) { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Match::initMatchByColumn:: Error: Invalid MatchType"); } else { if (matchType !== kony.sdk.constants.MatchType.ISNULL && matchType !== kony.sdk.constants.MatchType.ISNOTNULL) { // check if the value is passed or not except // for NULL and NOT NULL cases. if (value !== null && value !== undefined) { if (value instanceof Array && value.length <= 0) { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Match::initMatchByColumn:: Error: value is undefined ,null or empty object"); } currentMatchObj.value = value; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Match::initMatchByColumn:: Error: Invalid MatchType"); } } currentMatchObj.matchType = matchType; return currentMatchObj; } } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Match::initMatchByColumn:: Error: columnObj is not an instance of kony.sdk.dto.Column"); } } /** * This function is the Match constructor which has 4 arguments. * * @param tableObj * @param columnName * @param matchType * @param value */ function initMatchByTableAndColName(tableObj, columnName, matchType, value) { // check for validity of tableObj if (tableObj instanceof kony.sdk.dto.Table) { // columnName should not empty or null or undefined. if (columnName !== null && columnName !== undefined && typeof(columnName) === 'string' && columnName.trim().length > 0) { currentMatchObj.column = tableObj.getColumn(columnName); if (matchType !== kony.sdk.constants.MatchType.EQUALS && matchType !== kony.sdk.constants.MatchType.GREATER && matchType !== kony.sdk.constants.MatchType.GREATEREQUAL && matchType !== kony.sdk.constants.MatchType.LESS && matchType !== kony.sdk.constants.MatchType.LESSEQUAL && matchType !== kony.sdk.constants.MatchType.STARTSWITH && matchType !== kony.sdk.constants.MatchType.CONTAINS && matchType !== kony.sdk.constants.MatchType.LIKE && matchType !== kony.sdk.constants.MatchType.ENDSWITH && matchType !== kony.sdk.constants.MatchType.NOTEQUAL && matchType !== kony.sdk.constants.MatchType.ISNULL && matchType !== kony.sdk.constants.MatchType.ISNOTNULL) { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Match::initMatchByTableAndColName:: Error: Invalid MatchType"); } else { if (matchType !== kony.sdk.constants.MatchType.ISNULL && matchType !== kony.sdk.constants.MatchType.ISNOTNULL) { // check if the value is passed or not // except for NULL and NOT NULL cases. if (value !== null && value !== undefined) { currentMatchObj.value = value; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Match::initMatchByTableAndColName:: Error: value is undefined ,null or empty object"); } } currentMatchObj.matchType = matchType; } return currentMatchObj; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Match::initMatchByTableAndColName:: Error: Invalid MatchType"); } } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Match:: Error: columnObj is not an instance of kony.sdk.dto.Column"); } } this.getColumn = function() { if (this.column !== null && this.column !== undefined) { return this.column; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Match::getColumn:: Error: column is null or undefined"); } }; this.getMatchType = function() { if (this.matchType !== null && this.matchType !== undefined) { return this.matchType; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Match::getMatchType:: Error: matchType is null or undefined"); } }; /** * This function is used to set match type. * * @param matchType */ this.setMatchType = function(matchType) { this.matchType = matchType; }; this.getValue = function() { return this.value; }; /* * quote=function(value){ return "'"+value+"'"; } */ /** * This function is used to convert to String. * * @return string */ this.toString = function() { if (this.matchType !== null && this.matchType !== undefined && this.column !== null && this.column !== undefined) { var constructedMatch = null; var constructedValue = null; var type = this.matchType; var val = this.matchType.name; if (this.value instanceof Date) { var dateStr = ""; var month = this.getValue().getMonth() + 1; var date = this.getValue().getDate(); if (month < 10) { month = "0" + month; } if (date < 10) { date = "0" + date; } dateStr = this.getValue().getFullYear() + "-" + month + "-" + date; constructedMatch = "date(substr(" + this.getColumn().toString() + ",0,11)) " + this.getMatchType().value + "'" + dateStr + "'"; return constructedMatch; } if (typeof(this.getValue()) === 'boolean') { if (this.getValue() === true) { return "(" + this.getColumn().toString() + " = 'true' OR " + this.getColumn().toString() + " = 1)"; } else if (this.getValue() === false) { return "(" + this.getColumn().toString() + " = 'false' OR " + this.getColumn().toString() + " = 0)"; } else { this.value = "'" + this.value + "'"; } } constructedMatch = this.getColumn().toString() + " " + this.getMatchType().value + " "; if (typeof(this.getValue()) === 'string') { constructedValue = kony.sdk.util.replaceAll(this.getValue(), "'", ""); if (kony.sdk.util.matchIgnoreCase(type.name, "STARTSWITH")) { constructedValue = constructedValue + "%"; } else if (kony.sdk.util.matchIgnoreCase(type.name, "CONTAINS")) { constructedValue = "%" + constructedValue + "%"; } else if (kony.sdk.util.matchIgnoreCase(type.name, "ENDSWITH")) { constructedValue = "%" + constructedValue; } else if (kony.sdk.util.matchIgnoreCase(type.name, "ISNULL")) { return "(lower(" + this.getColumn().toString() + ") = 'null' OR " + this.getColumn().toString() + " IS NULL)"; } else if (kony.sdk.util.matchIgnoreCase(type.name, "ISNOTNULL")) { return "(lower(" + this.getColumn().toString() + ") != 'null' OR " + this.getColumn().toString() + " IS NOT NULL)"; } constructedValue = new kony.sdk.dto.Criteria().quote(constructedValue); } else { if (kony.sdk.util.matchIgnoreCase(type.name, "ISNULL")) { return "(lower(" + this.getColumn().toString() + ") = 'null' OR " + this.getColumn().toString() + " IS NULL)"; } else if (kony.sdk.util.matchIgnoreCase(type.name, "ISNOTNULL")) { return "(lower(" + this.getColumn().toString() + ") != 'null' OR " + this.getColumn().toString() + " IS NOT NULL)"; } constructedValue = this.getValue().toString(); } if (!(kony.sdk.util.matchIgnoreCase(type.name, "ISNULL") || kony.sdk.util.matchIgnoreCase(type.name, "ISNOTNULL"))) { constructedMatch = constructedMatch + constructedValue; } return constructedMatch; } else { //TODO //throw error kony.sdk.logsdk.error("### kony.sdk.dto.Match::toString:: Error: matchType is undefined"); } } }; /** * Method to create the sync service instance. * @returns {SyncService} sync service instance */ kony.sdk.prototype.getSyncService = function() { if (!kony.sdk.isInitialized) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, kony.sdk.constants.INIT_FAILURE_MESSAGE + " Sync service."); } return new konySdkSyncService(this); } function konySdkSyncService(konyRef) { var SyncProvider = konyRef.sync; if (kony.sdk.isNullOrUndefined(kony.sdk.syncService)) { kony.sdk.syncService = sync; } var syncServiceHandler = kony.sdk.syncService; if (!SyncProvider) { throw new Exception(kony.sdk.errorConstants.SYNC_FAILURE, "invalid sync provider in serviceDoc"); } //mapping the sync logger to mbaassyncservice logger this.log = syncServiceHandler.log; //generic apis this.init = function(initSuccess, initFailure) { syncServiceHandler.init(initSuccess, initFailure); }; this.reset = function(resetSuccess, resetFailure) { syncServiceHandler.reset(resetSuccess, resetFailure); }; this.cancelPendingChunkRequests = function(successCallback, errorCallback) { syncServiceHandler.cancelPendingChunkRequests(successCallback, errorCallback); }; this.stopSession = function(successCallback) { syncServiceHandler.stopSession(successCallback); }; this.rollbackPendingLocalChanges = function(successCallback, errorCallback) { syncServiceHandler.rollbackPendingLocalChanges(successCallback, errorCallback); }; this.getPendingAcknowledgement = function(successCallback, errorCallback) { syncServiceHandler.getPendingAcknowledgement(successCallback, errorCallback); }; this.getPendingUpload = function(successCallback, errorCallback) { syncServiceHandler.getPendingUpload(successCallback, errorCallback); }; this.getDeferredUpload = function(successCallback, errorCallback) { syncServiceHandler.getDeferredUpload(successCallback, errorCallback); }; this.getAllPendingUploadInstances = function(retrieveOnlyCount, successcallback, errorcallback) { syncServiceHandler.getAllPendingUploadInstances(retrieveOnlyCount, successcallback, errorcallback); }; this.executeSelectQuery = function(query, successcallback, errorcallback) { syncServiceHandler.executeSelectQuery(query, successcallback, errorcallback); }; //adding the binary apis this.getFailedBinaryRecords = function(isDownload, tablename, columnname, successCallback, errorCallback) { syncServiceHandler.getFailedBinaryRecords(isDownload, tablename, columnname, successCallback, errorCallback); }; this.getStatusForBinary = function(tbname, columnName, pks, successCallback, errorCallback) { syncServiceHandler.getStatusForBinary(tbname, columnName, pks, successCallback, errorCallback); }; this.getBinaryBase64 = function(tbname, columnName, pks, config, successCallback, errorCallback) { syncServiceHandler.getBinaryBase64(tbname, columnName, pks, config, successCallback, errorCallback); }; this.getBinaryFilepath = function(tbname, columnName, pks, config, successCallback, errorCallback) { syncServiceHandler.getBinaryFilepath(tbname, columnName, pks, config, successCallback, errorCallback); }; //binary chunking apis this.createDownloadTask = function(tbname, columnName, pks, config, successCallback, errorCallback) { syncServiceHandler.createDownloadTask(tbname, columnName, pks, config, successCallback, errorCallback); }; this.startDownload = function(downloadID, successCallback, errorCallback) { syncServiceHandler.startDownload(downloadID, successCallback, errorCallback); }; this.pauseDownload = function(downloadID, successCallback, errorCallback) { syncServiceHandler.pauseDownload(downloadID, successCallback, errorCallback); }; this.resumeDownload = function(downloadID, successCallback, errorCallback) { syncServiceHandler.resumeDownload(downloadID, successCallback, errorCallback); }; this.getBinaryDataFilePath = function(tbname, columnName, pks, successCallback, errorCallback) { syncServiceHandler.getBinaryDataFilePath(tbname, columnName, pks, successCallback, errorCallback); }; this.getBinary = function(tableName, binaryColumnName, primaryKeyTable, config, successCallback, errorCallback) { syncServiceHandler.getBinary(tableName, binaryColumnName, primaryKeyTable, config, successCallback, errorCallback); }; this.deleteBinaryObject = function(tableName, binaryColumnName, primaryKeyTable, options, successCallback, errorCallback) { syncServiceHandler.deleteBinaryObject(tableName, binaryColumnName, primaryKeyTable, options, successCallback, errorCallback); }; var syncServiceAppid = SyncProvider["appId"]; var syncServiceUrl = SyncProvider["url"] + "/"; function genericErrorCallback(res) { kony.sdk.logsdk.error("error occurred in refreshing claims token.. Please call login again " + JSON.stringify(res)); } //modified api this.startSession = function(config) { var errorCallback; if (config.onsyncerror) { errorCallback = config.onsyncerror; } else { errorCallback = genericErrorCallback; } kony.sdk.claimsRefresh(sdkStartSession, errorCallback); function sdkStartSession() { config = processConfig(config); syncServiceHandler.startSession(config); } } this.performUpgrade = function(config) { var errorCallback; if (config.onperformupgradeerror) { errorCallback = config.onperformupgradeerror; } else { errorCallback = genericErrorCallback; } kony.sdk.claimsRefresh(sdkPerformUpgrade, errorCallback); function sdkPerformUpgrade() { config = processConfig(config); syncServiceHandler.performUpgrade(config); } } this.isUpgradeRequired = function(config) { var errorCallback; if (config.isupgraderequirederror) { errorCallback = config.isupgraderequirederror; } else { errorCallback = genericErrorCallback; } kony.sdk.claimsRefresh(sdkIsUpgradeRequired, errorCallback); function sdkIsUpgradeRequired() { config = processConfig(config); syncServiceHandler.isUpgradeRequired(config); } } function processConfig(config) { var tempConfig = config; tempConfig.serverurl = syncServiceUrl; tempConfig.appid = syncServiceAppid; tempConfig.authtoken = konyRef.currentClaimToken; return tempConfig; } this.startReconciliation = function(config) { if (!syncServiceHandler.startReconciliation) throw new Exception(kony.sdk.errorConstants.SYNC_FAILURE, "sync provider doesnot support reconciliation"); syncServiceHandler.startReconciliation(config); } } function OAuthHandler(serviceUrl, providerName, appkey, callback, type, options, isMFVersionCompatible) { var urlType = "/" + type + "/"; var isSuccess = true; var isLogout = false; // This will make sure the scheduler to request tokens will be instantiated only once in the method handleRequestCallback. // In case of Google OAuth changes Identity returns the success_url, so page gets refreshed twice which will fail in instantiating the scheduler twice. var isLoginCallbackInvoked = false; if (options && options.hasOwnProperty("logout") && options["logout"] === true) { isLogout = true; } var slo = false; if (options && options.hasOwnProperty("slo") && options["slo"] === true) { slo = options["slo"]; } var customQueryParamsForOAuth; if (options && options.hasOwnProperty("customQueryParamsForOAuth")) { customQueryParamsForOAuth = kony.sdk.util.objectToQueryParams(options["customQueryParamsForOAuth"]); } var requestUrl; function appendCustomOAuthParamsToURL(url) { if (!kony.sdk.util.isNullOrEmptyString(customQueryParamsForOAuth)) { url = url + "&" + customQueryParamsForOAuth; } return url; } function constructURLIE11(crossPlatformBaseURL, identityOAuthUrl) { //Identity Server will route the final result be it success or error to Injected callback page identityOAuthUrl = identityOAuthUrl + "&" + kony.sdk.constants.OAUTH_REDIRECT_SUCCESS_URL + "=" + encodeURIComponent(crossPlatformBaseURL + "/" + kony.sdk.constants.KNY_OAUTH_CALLBACK_HTML); //Invoking the identity through the injected Redirect Page to overcome IE imposed cross domain security restrictions. var finalRequestUrl = crossPlatformBaseURL + "/" + kony.sdk.constants.KNY_OAUTH_REDIRECT_HTML + "?" + kony.sdk.constants.KNY_OAUTH_REDIRECT_URL + "=" + encodeURIComponent(identityOAuthUrl); return finalRequestUrl; } if (typeof(XMLHttpRequest) !== 'undefined') { var _window = window; var _popup = null; var _listener = function(event) { var _contents = event.data; /** MFSDK-3431 - Recieving post message event from other endpoints. This is a short term fix. Currently Identity sends us only string in post message event, later on they have to send json with some more keys giving us the knowledge of source */ if (kony.sdk.util.isValidString(_contents) && !kony.sdk.isJson(_contents)) { _popup.close(); _detachEvent(); try { kony.sdk.logsdk.debug("### OAuthHandler::_listener received authorization code as " + _contents); var headers = {}; if (type === "oauth2" || type === "saml") { headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED } callback(urlType + "token", { code: _contents }, headers); } catch (err) { kony.sdk.logsdk.error("exception ::" + err); failureCallback(); } } else if (kony.sdk.isJson(_contents) || kony.sdk.util.isJsonObject(_contents)) { kony.sdk.logsdk.debug("### OAuthHandler::_listener received event.data in unknown format as " + JSON.stringify(_contents)); //TODO - After Identity changes check for desired key in the json. } }; var _attachEvent = function() { if (_window.addEventListener) { _window.addEventListener('message', _listener, false); } else if (_window.attachEvent) { _window.attachEvent('message', _listener); } else { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, "environment doesn't support event attaching"); } }; var _detachEvent = function() { if (_window.detachEvent) { _window.detachEvent('message', _listener); } else if (_window.removeEventListener) { _window.removeEventListener('message', _listener); } else { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, "environment doesn't support detaching an event"); } }; _attachEvent(); if (isLogout) { requestUrl = serviceUrl + urlType + "logout?provider=" + providerName + "&appkey=" + appkey + "&slo=" + slo; } else { requestUrl = serviceUrl + urlType + "login?provider=" + providerName + "&appkey=" + appkey; requestUrl = appendCustomOAuthParamsToURL(requestUrl); //Checking whether server is compatable to redirect to user defined callback url //Changes to support OAuth on IE11, MFSDK-3657 if (isMFVersionCompatible && kony.sdk.util.checkForIE11() && kony.sdk.util.isJsonObject(options) && options.hasOwnProperty(kony.sdk.constants.IE11_CROSS_DOMAIN_OAUTH_BASE_URL)) { requestUrl = constructURLIE11(stripTrailingCharacter(options[kony.sdk.constants.IE11_CROSS_DOMAIN_OAUTH_BASE_URL], "/"), requestUrl); } } _popup = _window.open(requestUrl); } else { var browserSF = null; var userDefined = false; if (kony.sdk.util.hasBrowserWidget(options)) { browserSF = options[kony.sdk.constants.BROWSER_WIDGET]; userDefined = true; } else if (options && options["UseDeviceBrowser"] && isMFVersionCompatible) { kony.sdk.util.OAuthCallback = callback; kony.sdk.util.OAuthType = type; } else { var formBasic = { id: "popUp", skin: null, isModal: false, transparencyBehindThePopup: 80, "needAppMenu": false }; var formLayout = { containerWeight: 100, padding: [5, 5, 5, 5], "paddingInPixel": true }; var formPSP = { "titleBar": true, "titleBarConfig": { "renderTitleText": true, "prevFormTitle": false, "titleBarLeftSideView": "button", "labelLeftSideView": "Back", "titleBarRightSideView": "none" }, "titleBarSkin": "slTitleBar" }; //to do.. this is a workaround for android browser issue.. need to refactor this code browserSF = new kony.ui.Browser({ "id": "browserSF", "text": "Browser", "isVisible": true, "detectTelNumber": true, "screenLevelWidget": true, "enableZoom": false }, { "margin": [0, 0, 0, 0], "marginInPixel": true, "paddingInPixel": true, "containerWeight": 100 }, {}); var prevForm = kony.application.getCurrentForm(); var oauthForm = new kony.ui.Form2(formBasic, formLayout, formPSP); oauthForm.add(browserSF); oauthForm.show(); } var urlConf; var headersConf = {}; if (!kony.sdk.isNullOrUndefined(konyRef.currentClaimToken)) { headersConf[kony.sdk.constants.KONY_AUTHORIZATION_HEADER] = konyRef.currentClaimToken; } konyRef.appendGlobalHeaders(headersConf); requestUrl = serviceUrl + urlType; if (isLogout) { requestUrl += "logout?provider=" + providerName + "&appkey=" + appkey + "&slo=" + slo; } else { requestUrl += "login?provider=" + providerName + "&appkey=" + appkey; } if (!kony.sdk.isNullOrUndefined(kony.sdk.getFabricAppVersion())) { requestUrl += "&app_version=" + kony.sdk.getFabricAppVersion(); } if (isLogout) { browserSF.onSuccess = handleOAuthLogoutSuccessCallback; browserSF.onFailure = handleOAuthLogoutFailureCallback; } else { if (options && options["success_url"] && isMFVersionCompatible) requestUrl += "&success_url=" + options["success_url"]; if (options && options["UseDeviceBrowser"] && isMFVersionCompatible) { kony.application.openURL(requestUrl); return; } else { isLoginCallbackInvoked = false; browserSF.handleRequest = handleRequestCallback; requestUrl = appendCustomOAuthParamsToURL(requestUrl); } } urlConf = { URL: requestUrl, requestMethod: constants.BROWSER_REQUEST_METHOD_GET }; if (Object.keys(headersConf).length > 0) { urlConf["headers"] = headersConf; } browserSF.requestURLConfig = urlConf; function handleOAuthLogoutSuccessCallback() { if (!userDefined) { var prevFormPostShow = prevForm.postShow; function postShowOverride() { oauthForm.destroy(); if (prevFormPostShow) { prevFormPostShow(); } prevForm.postShow = prevFormPostShow; } prevForm.postShow = postShowOverride; prevForm.show(); } callback(isSuccess); } function handleOAuthLogoutFailureCallback() { isSuccess = false; } function handleRequestCallback(browserWidget, params) { var originalUrl = params["originalURL"]; if (!isLoginCallbackInvoked && typeof(params.queryParams) !== "undefined" && typeof(params.queryParams.code) !== "undefined") { if (!userDefined) { var prevFormPostShow = prevForm.postShow; prevForm.postShow = postShowOverride; function postShowOverride() { oauthForm.destroy(); if (prevFormPostShow) { prevFormPostShow(); } prevForm.postShow = prevFormPostShow; } prevForm.show(); } var headers = {}; if (type === "oauth2" || type === "saml") { headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; } if (!isLoginCallbackInvoked) { // make request for tokens kony.timer.schedule(new Date().getTime().toString(), function(url, callback, code, headers) { return function() { callback(url, { code: code }, headers); }; }(urlType + "token", callback, decodeURIComponent(params.queryParams.code), headers), 1, false); isLoginCallbackInvoked = true; } } return false; } } } /** * Handles the deeplink callback, this needs to be called once deep link redirection is done. * @param {json} params parameters from Identity service - "code": HashValue */ function handleDeeplinkCallback(params) { if (params && kony.sdk.isValidDeeplinkCallback(params)) { var headers = {}; var requestUrl; if (kony.sdk.util.OAuthType === "oauth2" || kony.sdk.util.OAuthType === "saml") { headers[kony.sdk.constants.HTTP_CONTENT_HEADER] = kony.sdk.constants.CONTENT_TYPE_FORM_URL_ENCODED; } if (kony.sdk.util.OAuthType === "oauth2") { requestUrl = "/oauth2/token"; } else if (kony.sdk.util.OAuthType === "saml") { requestUrl = "/saml/token"; } else { requestUrl = "/login"; } // make request for tokens kony.sdk.util.OAuthCallback(requestUrl, { code: decodeURIComponent(params.launchparams.code) }, headers); } } if (kony.sdk) { kony.sdk.offline = {}; } //defined constants related to offline authentication. kony.sdk.offline.isOfflineEnabled = false; kony.sdk.offline.persistToken = false; kony.sdk.constants.iterations = 1024; kony.sdk.constants.keyLength = 256; function getOfflineLoginDBKeyForProvider(providerName) { return "userCredentials" + providerName; } /** * This Utility API to be used for the user to be able to login offline into the application. */ kony.sdk.offline.loginOffline = function(providerName, successCallback, errorCallback) { //retrieving the temporarily stored encrypted username. var tempUserIdBase64 = kony.sdk.dataStore.getItem("tempUserCredentials"); if (tempUserIdBase64 != null && tempUserIdBase64 != undefined) { var storedBase64 = kony.sdk.dataStore.getItem(getOfflineLoginDBKeyForProvider(providerName)); if (tempUserIdBase64 == storedBase64) { var authResponseStr = kony.sdk.offline.getUserAuthInformation("authResponse"); if (authResponseStr) successCallback(JSON.parse(authResponseStr)); else { errorCallback(kony.sdk.error.getMFcodeErrObj(kony.sdk.errorcodes.offline_auth_failed, kony.sdk.errormessages.offline_auth_failed)); } } else { errorCallback(kony.sdk.error.getMFcodeErrObj(kony.sdk.errorcodes.offline_auth_failed, kony.sdk.errormessages.offline_auth_failed)) } } }; /** * This API is to be used to store the user login success response to the device and read it in the offline auth success scenario. */ kony.sdk.offline.saveUserAuthInformation = function(dbKey, authResponse) { //validating arguments if (kony.sdk.isNullOrUndefined(dbKey) || typeof(dbKey) != "string" || dbKey.length === 0 || kony.sdk.isNullOrUndefined(authResponse) || typeof(authResponse) != "object" || Object.keys(authResponse).length === 0) { kony.sdk.logsdk.warn("### kony.sdk.offline.saveUserAuthInformation invalid arguments passed, returning"); return; } var stringifiedResponse = JSON.stringify(authResponse); // Encryption and saving authInformation // kony.sdk.getDeviceId() + appKey + appSecret is used as the secure key to encrypt / decrypt sensitive information saved into the local store var encryptedAuthResponse = kony.sdk.encryptText(stringifiedResponse, [kony.sdk.getDeviceId(), konyRef.mainRef.appKey, konyRef.mainRef.appSecret], "aes"); kony.sdk.dataStore.setItem(dbKey, encryptedAuthResponse); kony.sdk.logsdk.info("saved auth info from the login success response"); }; /** * This API is to be used to retrieve the user login success response to the device and read it in the offline auth success scenario. */ kony.sdk.offline.getUserAuthInformation = function(dbKey) { var decryptedAuthResponse = null; var encryptedAuthResponse; if (!kony.sdk.isNullOrUndefined(dbKey) && typeof(dbKey) == "string") encryptedAuthResponse = kony.sdk.dataStore.getItem(dbKey); if (!kony.sdk.isNullOrUndefined(encryptedAuthResponse)) { //Decrypting the saved response decryptedAuthResponse = kony.sdk.decryptText(encryptedAuthResponse, [kony.sdk.getDeviceId(), konyRef.mainRef.appKey, konyRef.mainRef.appSecret], "aes"); if (kony.sdk.isNullOrUndefined(decryptedAuthResponse) || decryptedAuthResponse === '') { // Backward compatibility. Since we didnt encrypt with deviceID decryption will fail. Decrypt with old key "ssoencryption". Encrypting with deviceID & persisting response. decryptedAuthResponse = kony.sdk.decryptText(encryptedAuthResponse, [konyRef.mainRef.appKey, konyRef.mainRef.appSecret], "aes"); if (!kony.sdk.isNullOrUndefined(decryptedAuthResponse) && decryptedAuthResponse !== '') { kony.sdk.offline.saveUserAuthInformation(dbKey, JSON.parse(decryptedAuthResponse)); } } } return decryptedAuthResponse; }; /** * This api saves the temporary user credentials to the device store. This is to be called only if the app is offline auth enabled. */ kony.sdk.offline.saveTempUserCredentials = function(options) { var op = { "algo": kony.sdk.constants.HASHING_ALGORITHM, "userid": options["userid"], "password": options["password"], "iterations": kony.sdk.constants.iterations, "keyLength": kony.sdk.constants.keyLength }; var key = kony.sdk.offline.getKey(op); var encrypteduserid = kony.crypto.encrypt("aes", key, options["userid"], {}); var base64userid = kony.convertToBase64(encrypteduserid); kony.sdk.dataStore.setItem("tempUserCredentials", base64userid); }; /** * This Util method reads the temporarily stored user credentials and updates the actual store of user credentials. This should be called on successful onlnine login. */ kony.sdk.offline.updateSuccessUserCredentials = function(providerName) { var tempUserObj = kony.sdk.dataStore.getItem("tempUserCredentials"); if (tempUserObj != null && tempUserObj != undefined) kony.sdk.dataStore.setItem(getOfflineLoginDBKeyForProvider(providerName), tempUserObj); kony.sdk.dataStore.removeItem("tempUserCredentials"); }; /** * This API generates the PBKDF2 key by reading the options passed as argument. */ kony.sdk.offline.getKey = function(options) { var userid = options["userid"]; var password = options["password"]; var salt = userid + password; var iterations = options["iterations"]; var klen = options["keyLength"]; var key = kony.crypto.createPBKDF2Key(options["algo"], options["password"], salt, iterations, klen); return key; }; /** * This Utility API is to enable the developer read the claims token when the device is in offline mode. */ kony.sdk.offline.getClaimsToken = function() { var userAuthInfoStr = kony.sdk.offline.getUserAuthInformation("authResponse"); if (userAuthInfoStr != null && userAuthInfoStr != undefined) { var userAuthInfo = JSON.parse(userAuthInfoStr); return userAuthInfo.claims_token; } return null; }; /** * This Utility API is to update the the claims token. */ kony.sdk.offline.updateAuthToken = function(data) { var userAuthInfoStr = kony.sdk.offline.getUserAuthInformation("authResponse"); if (userAuthInfoStr != null && userAuthInfoStr != undefined) { kony.sdk.offline.saveUserAuthInformation("authResponse", data); } }; /** * This Utility API is to update the the backend token. */ kony.sdk.offline.updatePersistedToken = function(data) { var userAuthInfoStr = kony.sdk.offline.getUserAuthInformation("persistedAuthResponse"); if (userAuthInfoStr != null && userAuthInfoStr != undefined) { kony.sdk.offline.saveUserAuthInformation("persistedAuthResponse", data); } }; /** * This API removes the user credentials from the device store. */ kony.sdk.offline.removeUserCredentials = function(providerName) { kony.sdk.dataStore.removeItem(getOfflineLoginDBKeyForProvider(providerName)); kony.sdk.dataStore.removeItem("tempUserCredentials"); }; /** * Removes the user auth information from device store. */ kony.sdk.offline.removeUserAuthInformation = function() { kony.sdk.dataStore.removeItem("authResponse"); }; kony.sdk.offline.removePersistedUserAuthInformation = function() { kony.store.removeItem("persistedAuthResponse"); }; /** * Created by Tharalika Palakurthy */ //SSO FFI functions kony.sdk.util.saveSSOToken = function(SSOToken) { if (typeof(SSOFFI) !== "undefined") { kony.sdk.logsdk.trace("Entering into kony.sdk.util.saveSSOToken"); var encryptedToken = kony.sdk.util.encryptSSOToken(SSOToken); return SSOFFI.saveToken(encryptedToken, "TokenKey"); } else { return null; } }; kony.sdk.util.getSSOToken = function() { if (typeof(SSOFFI) !== "undefined") { kony.sdk.logsdk.trace("Entering into kony.sdk.util.getSSOToken"); var decryptedToken = SSOFFI.getToken("TokenKey"); return kony.sdk.util.decrpytSSOToken(decryptedToken); } else { return null; } }; kony.sdk.util.deleteSSOToken = function() { if (typeof(SSOFFI) !== "undefined") { kony.sdk.logsdk.trace("Entering into kony.sdk.util.deleteSSOToken"); return SSOFFI.deleteToken("TokenKey"); } else { return null; } }; /** * Returns a unique identifier for device to encrypt/decrypt sso token. * Android & iOS SDK is generating a UUID if not exist and share accross multiple applications. * This UUID is used as a secure key for encrypting/decrypting tokens. * @return {string} * @private */ function _getUUIDForClientApps() { var deviceUUID = SSOFFI.getToken(kony.sdk.constants.KEY_DEVICE_ID); if (kony.sdk.isNullOrUndefined(deviceUUID) || deviceUUID === "") { deviceUUID = kony.license.generateUUID().toString(); SSOFFI.saveToken(deviceUUID, kony.sdk.constants.KEY_DEVICE_ID); } return deviceUUID; } kony.sdk.util.encryptSSOToken = function(ssotoken) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.encryptSSOToken"); return kony.sdk.encryptText(ssotoken, [_getUUIDForClientApps()], "aes"); }; kony.sdk.util.decrpytSSOToken = function(encryptedtoken) { kony.sdk.logsdk.trace("Entering into kony.sdk.util.decrpytSSOToken"); if (encryptedtoken == null || encryptedtoken == "" || encryptedtoken == undefined) return encryptedtoken; var decryptedToken = kony.sdk.decryptText(encryptedtoken, [_getUUIDForClientApps()], "aes"); if (kony.sdk.isNullOrUndefined(decryptedToken) || decryptedToken === '') { // Backward compatibility. Since we didnt encrypt with deviceID decryption will fail. Decrypt with old key "ssoencryption". Encrypting with deviceID & persisting response. decryptedToken = kony.sdk.decryptText(encryptedtoken, ["ssoencryption"], "aes"); if (!kony.sdk.isNullOrUndefined(decryptedToken) && decryptedToken !== '') { kony.sdk.util.saveSSOToken(decryptedToken); } } return decryptedToken; }; var KNYMobileFabric = null; var KNYMetricsService = null; kony.setupsdks = function(initConfig, successCallBack, errorCallBack) { var dsAppMetaData = null; var AppServiceDoc = null; var dsAppData; var dsAppServiceDoc; var serviceDocTimerId = null; var getServiceDocNonMFApp = function(initConfig) { var serviceDoc = new kony.sdk.serviceDoc(); serviceDoc.setAppId(initConfig.appConfig.appId); serviceDoc.setBaseId(initConfig.appConfig.appId); serviceDoc.setAppName(initConfig.appConfig.appName); serviceDoc.setReportingService(kony.sdk.constants.reportingType.session, getLicenseUrl(initConfig.appConfig)); serviceDoc.setReportingService(kony.sdk.constants.reportingType.custom, getMetricsUrl(initConfig.appConfig)); return serviceDoc.toJSON(); }; // Comparing the older etag vs current etag sent by tools, if mismatch considering the service doc from tools is latest. if (initConfig.appConfig.svcDoc && initConfig.appConfig.svcDoc.service_doc_etag) { var currentToolsEtag = initConfig.appConfig.svcDoc.service_doc_etag; var cachedToolsEtag = kony.sdk.dataStore.getItem("tools_etagID"); if (currentToolsEtag !== cachedToolsEtag) { kony.print("New etag set from the app/visulizer"); kony.sdk.dataStore.setItem("tools_etagID", currentToolsEtag); kony.sdk.dataStore.setItem(appConfig.appId + "_mobileFabricServiceDoc", JSON.stringify(initConfig.appConfig.svcDoc)); } } dsAppData = kony.sdk.dataStore.getItem(appConfig.appId); if (!kony.sdk.isNullOrUndefined(dsAppData)) { dsAppMetaData = JSON.parse(dsAppData); } dsAppServiceDoc = kony.sdk.dataStore.getItem(appConfig.appId + "_mobileFabricServiceDoc"); if (!kony.sdk.isNullOrUndefined(dsAppServiceDoc)) { AppServiceDoc = JSON.parse(dsAppServiceDoc); } var getLicenseUrl = function(appConfig) { var url = ""; if (appConfig.isturlbase) { url = appConfig.isturlbase + "/IST"; } else if (appConfig.secureurl) { url = getFromServerUrl(appConfig.secureurl, "IST"); } else if (appConfig.url) { url = getFromServerUrl(appConfig.url, "IST"); } return url; }; var getMetricsUrl = function(appConfig) { var url = ""; if (appConfig.isturlbase) { url = appConfig.isturlbase + "/CMS"; } else if (appConfig.secureurl) { url = getFromServerUrl(appConfig.secureurl, "CMS"); } else if (appConfig.url) { url = getFromServerUrl(appConfig.url, "CMS"); } return url; }; var getFromServerUrl = function(url, path) { // ServerURL for non-mf has /mwservlet appended after the context path. // We need to remove it to get the base server url //url = url.replace(/mwservlet\/*$/i, ""); //return url + path; var newUrl = ""; var exactSubString = url.match(/mwservlet/i); if (exactSubString) { var exactSubStringLength = "mwservlet".length; var lastSubStringIndex = url.lastIndexOf(exactSubString); var subString = url.slice(0, lastSubStringIndex); var index = (lastSubStringIndex + exactSubStringLength); var subString2 = url.slice(index, url.length); var has = /[a-zA-Z0-9]/.test(subString2); if (!has) { newUrl = subString; } else { newUrl = url; } } else { newUrl = url; } return newUrl + path; }; var konyAPMSuccessCallBack = function(metricsObject, initConfig) { kony.print("Initializing event tracking"); KNYMetricsService = metricsObject; if (KNYMetricsService) { KNYMetricsService.setEventTracking(initConfig.eventTypes); } }; var initKNYMobileFabric = function(initConfig) { KNYMobileFabric = new kony.sdk(); clientParams = {}; clientParams.aid = appConfig.appId; clientParams.aname = appConfig.appName; KNYMobileFabric.setClientParams(clientParams); }; var sdkInit = function(initConfig, successcallback, failurecallback) { var isInvalidConfig = false; var networkProvider = new konyNetworkProvider(); if (!kony.sdk.isNullOrUndefined(dsAppMetaData) && !kony.sdk.isNullOrUndefined(dsAppServiceDoc)) { if (dsAppMetaData.appId === appConfig.appId && dsAppMetaData.appVersion === appConfig.appVersion) { appConfig.appKey = dsAppMetaData.appKey; appConfig.appSecret = dsAppMetaData.appSecret; appConfig.serviceUrl = dsAppMetaData.serviceUrl; var reportingServiceUrl = dsAppMetaData.licenseUrl; appConfig.isturlbase = reportingServiceUrl.replace("/IST", ""); appConfig.svcDoc = AppServiceDoc; sdkInitConfig.appKey = dsAppMetaData.appKey; sdkInitConfig.appSecret = dsAppMetaData.appSecret; sdkInitConfig.serviceUrl = dsAppMetaData.serviceUrl; } } var refreshServiceDoc = function() { var networkProvider = new konyNetworkProvider(); if (!kony.sdk.isNullOrUndefined(dsAppMetaData) && !kony.sdk.isNullOrUndefined(dsAppServiceDoc)) { if (dsAppMetaData.appId === appConfig.appId && dsAppMetaData.appVersion === appConfig.appVersion) { initConfig.appKey = dsAppMetaData.appKey; initConfig.appSecret = dsAppMetaData.appSecret; initConfig.serviceUrl = dsAppMetaData.serviceUrl; } } var headers = {}; headers[kony.sdk.constants.APP_KEY_HEADER] = initConfig.appKey; headers[kony.sdk.constants.APP_SECRET_HEADER] = initConfig.appSecret; networkProvider.get(initConfig.serviceUrl, null, headers, function(data) { kony.sdk.dataStore.setItem(appConfig.appId + "_mobileFabricServiceDoc", JSON.stringify(data)); }, function(data) { kony.sdk.logsdk.warn("Refresh of serviceDoc failed:" + data); }); }; if (KNYMobileFabric == null) { initKNYMobileFabric(initConfig); } if (initConfig && initConfig.appConfig && (getLicenseUrl(initConfig.appConfig) === "")) { if (kony.license && kony.license.setIsLicenseUrlAvailable) { kony.license.setIsLicenseUrlAvailable(false); kony.sdk.isLicenseUrlAvailable = false; } } if (kony.sdk.isLicenseUrlAvailable && kony.license && kony.license.createSession) { kony.license.createSession(); } if (!initConfig.isMFApp) { initWithServiceDocHelper(initConfig, successcallback, failurecallback, getServiceDocNonMFApp(initConfig)); } else { if (!initConfig.appConfig.svcDocRefresh) { if (initConfig.appConfig.svcDoc) { initWithServiceDocHelper(initConfig, successcallback, failurecallback, initConfig.appConfig.svcDoc); } else { isInvalidConfig = true; } } if (isInvalidConfig || initConfig.appConfig.svcDocRefresh) { var cachedServiceDoc = kony.sdk.dataStore.getItem(appConfig.appId + "_mobileFabricServiceDoc"); if (cachedServiceDoc) { try { cachedServiceDoc = JSON.parse(cachedServiceDoc); } catch (err) { cachedServiceDoc = ""; kony.sdk.logsdk.error("cached service doc corrupted:" + err); } } //Todo: Dead code, remove this refresh service doc logic. (MFSDK-2084) var headers = {}; headers[kony.sdk.constants.APP_KEY_HEADER] = initConfig.appKey; headers[kony.sdk.constants.APP_SECRET_HEADER] = initConfig.appSecret; if (initConfig.appConfig.svcDocRefreshTimeSecs && !isInvalidConfig) { if (cachedServiceDoc || initConfig.appConfig.svcDoc) { var offlineServiceDoc = cachedServiceDoc ? cachedServiceDoc : initConfig.appConfig.svcDoc; initWithServiceDocHelper(initConfig, successcallback, failurecallback, offlineServiceDoc); serviceDocTimerId = Date.now().toString(); kony.timer.schedule(serviceDocTimerId, refreshServiceDoc, initConfig.appConfig.svcDocRefreshTimeSecs, true); } else { networkProvider.get(initConfig.serviceUrl, null, headers, function(res) { res = kony.sdk.formatSuccessResponse(res); initWithServiceDocHelper(initConfig, successcallback, failurecallback, res); }, function(res) { failurecallback(res); }); } } else { networkProvider.get(initConfig.serviceUrl, null, headers, function(res) { res = kony.sdk.formatSuccessResponse(res); initWithServiceDocHelper(initConfig, successcallback, failurecallback, res); }, function(res) { if (cachedServiceDoc || initConfig.appConfig.svcDoc) { var offlineServiceDoc = cachedServiceDoc ? cachedServiceDoc : initConfig.appConfig.svcDoc; initWithServiceDocHelper(initConfig, successcallback, failurecallback, offlineServiceDoc); } else { failurecallback(res); } }); } } } }; var initWithServiceDocHelper = function(initConfig, successcallback, failurecallback, serviceDoc) { try { if (!kony.sdk.isNullOrUndefined(initConfig) && !kony.sdk.isNullOrUndefined(initConfig["appMetadata"])) { kony.sdk.util.setPackagedMetadata(initConfig["appMetadata"]); } KNYMobileFabric.initWithServiceDoc(initConfig.appKey, initConfig.appSecret, serviceDoc); var MetricsService = null; if (kony.sdk.isLicenseUrlAvailable) { MetricsService = KNYMobileFabric.getMetricsService(); } if (initConfig.isMFApp) { konyRef.isAnonymousProvider = true; } if (successcallback) { successcallback(MetricsService, initConfig); } } catch (error) { if (failurecallback) failurecallback(error); } }; /* * isMFApp -- boolean to indicate app is being built for MFapp as backend or plain Konyserver * appConfig -- set to appConfig of startup.js * * --MF Parameters-- * serviceUrl -- mf appconfig url * appKey -- set to App Key for MF app scenario * appSecret -- set to App Secret for MF app scenario * * -- For APM -- * eventTypes -- This should be set to comma separated values chosen in the IDE for events chosen for automatic tracking * * Examples * var sdkInitConfigForMF = { * "isMFApp": true, "appConfig" : appconfig, "appKey" :"<appkey fetched from MF>", "appSecret":"<appsecret fetched from MF>", "serviceUrl" : "<appconfig url of the form https://100000013.auth.sit2-konycloud.com/appconfig>", "eventTypes" : ["FormEntry","FormExit","Touch","ServiceRequest","ServiceResponse","Gesture","Orientation","Error","Crash"] } * var sdkInitConfigForNonMF = { "isMFApp": false, "appConfig" : appconfig "eventTypes" : ["FormEntry","FormExit","Touch","ServiceRequest","ServiceResponse","Gesture","Orientation","Error","Crash"] } */ sdkInit(initConfig, function(metricsObject, initConfig) { kony.print("sdk initialization done"); konyAPMSuccessCallBack(metricsObject, initConfig); if (successCallBack) successCallBack(KNYMobileFabric); }, function(errorObj) { var errorMsg = errorObj ? errorObj.toString() : ""; kony.print("Error in setup " + errorMsg); if (errorCallBack) errorCallBack(errorObj); }); }; kony.sdk.util = kony.sdk.util || {}; function konyLogger() { this.log = function(text) { if (kony.sdk.isDebugEnabled) { kony.print(text); } } } /** * Flag used to override the network availability api for automation testing. * @type {boolean} */ overrideNetworkFlag = false; /** * Utility Method for the application to check the network availability. */ kony.sdk.isNetworkAvailable = function() { //Check the network flag if set for testing. This would mandate the application to be offline if device has network connectivity. if (overrideNetworkFlag !== undefined && overrideNetworkFlag !== null && overrideNetworkFlag && overrideNetworkFlag === true) return false; return kony.net.isNetworkAvailable(constants.NETWORK_TYPE_ANY); }; /** * Utility method to set the network flag for offline testing. */ kony.sdk.overrideNetworkFlag = function() { overrideNetworkFlag = true; }; /** * Utility method to reset the network flag set for offline testing. */ kony.sdk.resetNetworkFlag = function() { overrideNetworkFlag = false; overrideNetworkFlag = undefined; }; kony.sdk.overrideAnonymousLoginFlag = function() { kony.sdk.skipAnonymousCall = true; }; kony.sdk.resetAnonymousLoginFlag = function() { kony.sdk.skipAnonymousCall = false; }; function konyNetworkProvider() { this.post = function(url, params, headers, successCallback, failureCallback, konyContentType, options) { if (kony.sdk.util.isNullOrEmptyString(url)) { kony.sdk.verifyAndCallClosure(failureCallback, "url cannot be null or empty"); return; } //Appending global params if (kony.sdk.isNullOrUndefined(params)) { params = {}; } if (!kony.sdk.isNullOrUndefined(kony.sdk.currentInstance)) { url = kony.sdk.currentInstance.appendGlobalParams(url, headers, params); } konyNetHttpRequest(url, params, headers, "POST", konyContentType, successCallback, failureCallback, options); }; this.put = function(url, params, headers, successCallback, failureCallback, konyContentType, options) { if (kony.sdk.util.isNullOrEmptyString(url)) { kony.sdk.verifyAndCallClosure(failureCallback, "url cannot be null or empty"); return; } //Appending global params if (kony.sdk.isNullOrUndefined(params)) { params = {}; } if (!kony.sdk.isNullOrUndefined(kony.sdk.currentInstance)) { url = kony.sdk.currentInstance.appendGlobalParams(url, headers, params); } konyNetHttpRequest(url, params, headers, "PUT", konyContentType, successCallback, failureCallback, options); }; this.invokeDeleteRequest = function(url, params, headers, successCallback, failureCallback, konyContentType, options) { if (kony.sdk.util.isNullOrEmptyString(url)) { kony.sdk.verifyAndCallClosure(failureCallback, "url cannot be null or empty"); return; } //Appending global params if (kony.sdk.isNullOrUndefined(params)) { params = {}; } if (!kony.sdk.isNullOrUndefined(kony.sdk.currentInstance)) { url = kony.sdk.currentInstance.appendGlobalParams(url, headers, params); } konyNetHttpRequest(url, params, headers, "DELETE", konyContentType, successCallback, failureCallback, options); }; //postSync will only work for Richclients like Android,IOS this.postSync = function(url, params, headers) { if (kony.sdk.util.isNullOrEmptyString(url)) { kony.sdk.verifyAndCallClosure(failureCallback, "url cannot be null or empty"); return; } //Appending global params if (kony.sdk.isNullOrUndefined(params)) { params = {}; } if (!kony.sdk.isNullOrUndefined(kony.sdk.currentInstance)) { url = kony.sdk.currentInstance.appendGlobalParams(url, headers, params); } return konyNetHttpRequestSync(url, params, headers); }; this.get = function(url, params, headers, successCallback, failureCallback, konyContentType, options) { if (kony.sdk.util.isNullOrEmptyString(url)) { kony.sdk.verifyAndCallClosure(failureCallback, "url cannot be null or empty"); return; } //Appending global params if (kony.sdk.isNullOrUndefined(params)) { params = {}; } if (!kony.sdk.isNullOrUndefined(kony.sdk.currentInstance)) { url = kony.sdk.currentInstance.appendGlobalParams(url, headers, params); } konyNetHttpRequest(url, null, headers, "GET", konyContentType, successCallback, failureCallback, options); } } function konyNetHttpRequest(url, params, headers, httpMethod, konyContentType, successCallback, failureCallback, options) { var paramsTable = null; var httpRequest; if (options && options["httpRequestOptions"] && options["httpRequestOptions"] instanceof Object) { httpRequest = new kony.net.HttpRequest(options["httpRequestOptions"]); } else { httpRequest = new kony.net.HttpRequest(); } // check for the deprecated property if set in appmiddlewaresecureinvokerasync() API if (options && options["httpconfig_old"]) { if (options["httpconfig_old"]["timeout"]) { httpRequest.timeout = options["httpconfig_old"]["timeout"] * 1000; } } if (options && options["httpRequestOptions"] && options["httpRequestOptions"] instanceof Object && options["httpRequestOptions"]["timeoutIntervalForRequest"]) { httpRequest.timeout = options["httpRequestOptions"]["timeoutIntervalForRequest"] * 1000; } if (options && options["httpRequestOptions"] && options["httpRequestOptions"] instanceof Object && options["httpRequestOptions"]["enableBackgroundTransfer"] === true) { httpRequest.backgroundTransfer = true; } // As older versions of IE doesn't have xmlHttpRequest2, and it doesn't support "withCredentials" property // We put a check to handle a crash. Cookies will not be transferred in CORS request for IE due to this restriction if (typeof(XMLHttpRequest) !== "undefined" && "withCredentials" in (new XMLHttpRequest()) && options && options["xmlHttpRequestOptions"] && options["xmlHttpRequestOptions"]["enableWithCredentials"] === true) { httpRequest.enableWithCredentials = true; } var isInvalidResponse = false; //if httpmethod is not provided falling back to POST if (!httpMethod) { httpMethod = constants.HTTP_METHOD_POST; } httpRequest.open(httpMethod, url); function localRequestCallback(result) { var readyState = Number(httpRequest.readyState.toString()); var status = Number(httpRequest.status.toString()); var response = {}; if (readyState === 4) { //If option "passthrough" is enabled then SDK will not parse the result from backend. if (options && options[kony.sdk.constants.PASSTHROUGH]) { response.rawResponse = result.response; } else { //parseHttpResponse parse response based on the content-type response header var parsedResp = parseHttpResponse(httpRequest); if (parsedResp.isRawResponse) { response.rawResponse = parsedResp.response; } else { response = parsedResp.response; } isInvalidResponse = parsedResp.isInvalidResponse; } kony.sdk.setLogLevelFromServerResponse(httpRequest.getAllResponseHeaders()); if (response && !isInvalidResponse) { response.httpresponse = {}; response.httpresponse.headers = httpRequest.getAllResponseHeaders(); response.httpresponse.url = url; response.httpresponse.responsecode = status; } if (isInvalidResponse || (!response && status >= 200 && status < 300)) { var errorMessage = {}; errorMessage.httpresponse = {}; errorMessage[kony.sdk.constants.MF_OPSTATUS] = kony.sdk.errorcodes.invalid_json_code; errorMessage[kony.sdk.constants.MF_ERROR_MSG] = kony.sdk.errormessages.invalid_json_message; errorMessage[kony.sdk.constants.MF_ERROR_CODE] = kony.sdk.errorcodes.invalid_json_code; errorMessage[kony.sdk.constants.HTTP_STATUS_CODE] = status; errorMessage.httpresponse["response"] = parsedResp.response; errorMessage.httpresponse.headers = httpRequest.getAllResponseHeaders(); errorMessage.httpresponse.url = url; errorMessage.httpresponse.responsecode = status; failureCallback(errorMessage); } else if (status >= 200 && status < 300) { if (!response.opstatus) { response.opstatus = 0; } if (response.opstatus == 0 || (response.opstatus >= 500100 && response.opstatus <= 500200)) { if (options && (options[kony.sdk.constants.DISABLE_INTEGRITY] || options[kony.sdk.constants.PASSTHROUGH])) { successCallback(response); } else { if (typeof(konyRef) !== "undefined" && konyRef && konyRef.mainRef.integrityKey === true) { if (response.httpresponse.headers.hasOwnProperty(kony.sdk.constants.INTEGRITY_HEADER) || response.httpresponse.headers.hasOwnProperty(kony.sdk.constants.INTEGRITY_HEADER.toLowerCase())) { if (!(kony.sdk.isNullOrUndefined(httpRequest.integrityStatus))) { var integrityStatus = parseInt(httpRequest["integrityStatus"].toString()); switch (integrityStatus) { case constants.HTTP_INTEGRITY_CHECK_NOT_DONE: failureCallback(kony.sdk.error.getIntegrityErrorMessage(httpRequest, url)); break; case constants.HTTP_INTEGRITY_CHECK_SUCCESSFUL: successCallback(response); break; case constants.HTTP_INTEGRITY_CHECK_FAILED: failureCallback(kony.sdk.error.getIntegrityErrorMessage(httpRequest, url)); break; } } else { failureCallback(kony.sdk.error.getIntegrityErrorMessage(httpRequest, url)); } } else if (options && options != null && options["ignoreintegrity"]) { successCallback(response); } else { failureCallback(kony.sdk.error.getIntegrityErrorMessage(httpRequest, url)); } } else { successCallback(response); } } } else { failureCallback(response); } } else { var resultTable = {}; if (response) { resultTable = response; } else { resultTable[kony.sdk.constants.MF_OPSTATUS] = kony.sdk.errorcodes.connectivity_error_code; resultTable[kony.sdk.constants.MF_ERROR_CODE] = kony.sdk.errorcodes.connectivity_error_code; resultTable[kony.sdk.constants.MF_ERROR_MSG] = kony.sdk.errormessages.connectivity_error_message; } if (!kony.sdk.isNullOrUndefined(httpRequest.status)) { resultTable.httpStatusCode = httpRequest.status; } failureCallback(resultTable); } } } if (konyContentType === "application/json") { if (params) { paramsTable = JSON.stringify(params); } } else if (konyContentType == undefined || konyContentType == null || konyContentType != 'formdata') { //preparing params for other than object services var firstKey = true; for (var key in params) { if (firstKey) { paramsTable = new kony.net.FormData(); firstKey = false; } if (typeof(params[key]) != "undefined") { if (typeof(params[key]) !== "string") { params[key] = JSON.stringify(params[key]); } paramsTable.append((key), (params[key])); } } } else if (konyContentType == "formdata") { //for specific requests like object services we will send formdata through form encoding mechanism. if (params) { //for object services we are getting kony.net.FormData so using the same. paramsTable = params; } } if (headers) { for (var key in headers) { httpRequest.setRequestHeader(key, headers[key]); } } else { httpRequest.setRequestHeader(kony.sdk.constants.HTTP_CONTENT_HEADER, kony.sdk.constants.CONTENT_TYPE_JSON); } httpRequest.onReadyStateChange = localRequestCallback; if (options && (options[kony.sdk.constants.DISABLE_INTEGRITY] || options[kony.sdk.constants.PASSTHROUGH])) { //mesasging service and pass through enabled integration svc doesn't support http message body integrity //if integrity is enabled earlier,remove integrity //check is for windows 8.x and Kiosk platforms,which doesn't support integrity if (kony.sdk.constants.REMOVE_INTEGRITY_CHECK in kony.net) { kony.net.removeIntegrityCheck(); } if (paramsTable) { httpRequest.send(paramsTable); } else { httpRequest.send(); } } else { if (typeof(konyRef) !== "undefined" && konyRef && konyRef.mainRef.integrityKey === true) { var properties = konyRef.mainRef.integrityParams; try { //check is for windows 8.x and Kiosk platforms,which doesn't support integrity if (kony.sdk.constants.SET_INTEGRITY_CHECK in kony.net) { kony.net.setIntegrityCheck(properties); } } catch (e) { kony.sdk.logsdk.warn("Invalid Integrity properties received"); throw "Invalid Integrity properties received"; } } else { //check is for windows 8.x and Kiosk platforms,which doesn't support integrity if (kony.sdk.constants.REMOVE_INTEGRITY_CHECK in kony.net) { kony.net.removeIntegrityCheck(); } } if (paramsTable) { httpRequest.send(paramsTable); } else { httpRequest.send(); } } } function konyNetHttpRequestSync(url, params, headers) { var paramsTable = null; var httpRequest = new kony.net.HttpRequest(); var isInvalidJSON = false; httpRequest.open(constants.HTTP_METHOD_POST, url, false); var firstKey = true; for (var key in params) { if (firstKey) { paramsTable = new kony.net.FormData(); firstKey = false; } if (typeof(params[key]) != "undefined") { if (typeof(params[key]) !== "string") { params[key] = JSON.stringify(params[key]); } paramsTable.append((key), (params[key])); } } if (headers) { for (var key in headers) { httpRequest.setRequestHeader(key, headers[key]); } } else { httpRequest.setRequestHeader(kony.sdk.constants.HTTP_CONTENT_HEADER, kony.sdk.constants.CONTENT_TYPE_JSON); } //httpRequest.onReadyStateChange = localRequestCallback; httpRequest.send(paramsTable); var response = null; var status = Number(httpRequest.status.toString()); kony.sdk.setLogLevelFromServerResponse(httpRequest.getAllResponseHeaders()); if (httpRequest.response) { response = httpRequest.response; } if (response && typeof(response) === 'string') { if (kony.sdk.isJson(response)) { response = JSON.parse(response); } else { isInvalidJSON = true; } } if (response && !(isInvalidJSON)) { response.httpresponse = {}; response.httpresponse.headers = httpRequest.getAllResponseHeaders(); response.httpresponse.url = url; response.httpresponse.responsecode = status; } if (isInvalidJSON || (!response && status >= 200 && status < 300)) { var errorMessage = {}; errorMessage.httpresponse = {}; errorMessage[kony.sdk.constants.MF_OPSTATUS] = kony.sdk.errorcodes.invalid_json_code; errorMessage[kony.sdk.constants.MF_ERROR_MSG] = kony.sdk.errormessages.invalid_json_message; errorMessage[kony.sdk.constants.MF_ERROR_CODE] = kony.sdk.errorcodes.invalid_json_code; errorMessage[kony.sdk.constants.HTTP_STATUS_CODE] = status; errorMessage.httpresponse["response"] = response; errorMessage.httpresponse.headers = httpRequest.getAllResponseHeaders(); errorMessage.httpresponse.url = url; errorMessage.httpresponse.responsecode = status; return errorMessage; } else if (status >= 200 && status < 300) { if (!response.opstatus) { response.opstatus = 0; } return response; } else { var resultTable = {}; if (response) { resultTable = response; resultTable.httpStatusCode = httpRequest.status.toString(); } else { resultTable[kony.sdk.constants.MF_OPSTATUS] = kony.sdk.errorcodes.connectivity_error_code; resultTable[kony.sdk.constants.MF_ERROR_CODE] = kony.sdk.errorcodes.connectivity_error_code; resultTable[kony.sdk.constants.MF_ERROR_MSG] = kony.sdk.errormessages.connectivity_error_message; } return resultTable; } } function konyDataStore() { //kony.sdk.logsdk.trace("Setting konyDataStore"); this.setItem = function(key, value) { if (typeof(key) !== "string") { throw new Exception(kony.sdk.errorConstants.DATA_STORE_EXCEPTION, "Invalid Key"); } else { try { key = key.replace(/\//gi, ""); kony.store.setItem(key, value); } catch (e) { kony.sdk.logsdk.error("Failed to set item in dtastore:" + e); } } }; this.getItem = function(key) { kony.sdk.logsdk.debug("Getting item for key:" + key); if (typeof(key) !== "string") { throw new Exception(kony.sdk.errorConstants.DATA_STORE_EXCEPTION); } else { key = key.replace(/\//gi, ""); var value = kony.store.getItem(key); if (value === null || value === undefined) { kony.sdk.logsdk.debug("No value found with key:" + key); return null; } else { return value; } } }; this.removeItem = function(key) { kony.sdk.logsdk.debug("Removing item for key:" + key); if (typeof(key) !== "string") { throw new Exception(Error.DATA_STORE_EXCEPTION); } else { key = key.replace(/\//gi, ""); kony.store.removeItem(key); //If no item with that key exists, the method does not perform any action. Thus no need to check for key availablity. } }; this.destroy = function() { kony.sdk.logsdk.info("Destroying data store for this app"); kony.store.clear(); }; this.getAllItems = function() { kony.sdk.logsdk.info("Getting all item from data store"); var items = {}; var len = kony.store.length(); //get key length for (var i = 0; i < len; i++) { var key = kony.store.key(i); //get ith key var value = kony.store.getItem(key); //get value items[key] = value; //prepare itemset } return items; } } function parseHttpResponse(httpRequest) { var isInvalidResponse = false; var isJsonResponse = false; var parsedResponse = {}; parsedResponse.isRawResponse = false; var value = ""; var response = null; if (kony.sdk.isNullOrUndefined(httpRequest) || kony.sdk.isNullOrUndefined(httpRequest.response)) { kony.sdk.logsdk.warn("parseHttpResponse :: Null or Invalid response received"); } else { response = kony.sdk.cloneObject(httpRequest.response); kony.sdk.logsdk.debug("parseHttpResponse :: Network response :", response); //Defaulting to JSON format if (kony.sdk.util.isJsonObject(response)) { parsedResponse.response = response; isJsonResponse = true; } else if (kony.sdk.util.isValidString(response)) { if (kony.sdk.isJson(response)) { parsedResponse.response = JSON.parse(response); isJsonResponse = true; } } //Handling when response is not json if (!isJsonResponse) { if (kony.sdk.util.isValidString(httpRequest.response)) { parsedResponse.response = response; } else { parsedResponse.response = httpRequest.response; } var lowerCaseHeaders = kony.sdk.util.convertJsonKeysToLowerCase(httpRequest.getAllResponseHeaders()); //value variable contains response header in lower case if (!kony.sdk.isNullOrUndefined(lowerCaseHeaders)) { value = lowerCaseHeaders[kony.sdk.constants.HTTP_CONTENT_HEADER.trim().toLowerCase()]; } else { kony.sdk.logsdk.warn("parseHttpResponse :: received null response headers " + lowerCaseHeaders); } kony.sdk.logsdk.warn("parseHttpResponse :: content-type of response " + value); //MFSDK-3525 Adding an additional check to see if content type is present. if (kony.sdk.util.isValidString(value) && value.startsWith(kony.sdk.constants.CONTENT_TYPE_JSON)) { kony.sdk.logsdk.warn("parseHttpResponse :: Unhandled content received for content-type application/json"); isInvalidResponse = true; } else { parsedResponse.isRawResponse = true; } } } parsedResponse.isInvalidResponse = isInvalidResponse; return parsedResponse; } kony.sdk.getSdkType = function() { return kony.sdk.constants.SDK_TYPE_IDE; }; kony.sdk.getPayload = function(konyRef) { var payload = {}; payload.os = kony.os.deviceInfo().version + ""; payload.dm = kony.os.deviceInfo().model; payload.did = kony.sdk.getDeviceId(); payload.ua = kony.os.userAgent(); if (appConfig) { payload.aid = appConfig.appId; payload.aname = appConfig.appName; } else { var clientParams = konyRef.getClientParams(); payload.aid = clientParams.aid ? clientParams.aid : konyRef.mainRef.baseId; payload.aname = clientParams.aname ? clientParams.aname : konyRef.mainRef.name; } payload.chnl = kony.sdk.getChannelType(); payload.plat = kony.sdk.getPlatformName(); if (payload.plat === kony.sdk.constants.PLATFORM_IOS && kony.os.deviceInfo().name !== kony.sdk.constants.PLATFORM_SPA) { payload.did = getDeviceIdForIOSPlatform(); } if (payload.plat === kony.sdk.constants.PLATFORM_IOS && payload.dm.toLowerCase().indexOf("ipod") !== -1) { payload.chnl = "ipod"; } payload.aver = appConfig.appVersion; payload.atype = kony.sdk.getAType(); payload.stype = "b2c"; payload.kuid = konyRef.getUserId(); payload.mfaid = konyRef.mainRef.appId; payload.mfbaseid = konyRef.mainRef.baseId; payload.mfaname = konyRef.mainRef.name; payload.sdkversion = kony.sdk.version; payload.sdktype = kony.sdk.getSdkType(); if (kony.application.getCurrentForm()) { var fid = kony.application.getCurrentForm().id; if (fid) { payload.fid = fid; } } return payload; }; /** * Returns unique identifier for a device. * In case of Android & Windows the API kony.os.deviceInfo().deviceid is guaranteed to provide unique identifier for a device. * In case of iOS the API kony.os.deviceInfo().identifierForVendor is guaranteed to provide unique key per vendor. * A different value is returned for apps on the same device that come from different vendors, and for apps on different devices regardless of vendor * @return {string} */ kony.sdk.getDeviceId = function() { var name = kony.os.deviceInfo().name; if (name === kony.sdk.constants.PLATFORM_SPA) { var deviceID = kony.ds.read(kony.sdk.constants.KEY_DEVICE_ID); if (!deviceID) { deviceID = kony.license.generateUUID().toString(); kony.ds.save(deviceID, kony.sdk.constants.KEY_DEVICE_ID); } return deviceID; } else { return kony.os.deviceInfo().identifierForVendor; } }; kony.sdk.getChannelType = function() { var returnVal = ""; returnVal = "mobile"; return returnVal; }; kony.sdk.getPlatformName = function() { var returnVal = ""; returnVal = kony.sdk.constants.PLATFORM_IOS; return returnVal; }; kony.sdk.util.createSessionAndSendIST = function() { kony.license.createSession(); kony.license.captureKonyLicenseUsage(true); } kony.mbaas.invokeMbaasServiceFromKonyStudio = function(url, inputParam, serviceID, operationID, callBack, infoObject) { var currentInstance = kony.sdk.getCurrentInstance(); if (!currentInstance) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, kony.sdk.constants.INIT_FAILURE_MESSAGE + "this service."); } var integrationService = currentInstance.getIntegrationService(serviceID); var options = {}; if (inputParam && inputParam["httpconfig"]) { options["httpconfig_old"] = inputParam["httpconfig"]; delete inputParam["httpconfig"]; } if (inputParam && inputParam["httpRequestOptions"] && inputParam["httpRequestOptions"] instanceof Object) { options["httpRequestOptions"] = inputParam["httpRequestOptions"]; delete inputParam["httpRequestOptions"]; } var headers = null; if (inputParam && inputParam["httpheaders"]) { headers = inputParam["httpheaders"]; delete inputParam["httpheaders"]; } integrationService.invokeOperation(operationID, headers, inputParam, function(res) { if (typeof(callBack) === 'function') { callBack(400, res, infoObject); } }, function(res) { if (typeof(callBack) === 'function') { callBack(400, res, infoObject); } }, options); }; kony.mbaas.invokeMbaasServiceFromKonyStudioSync = function(url, inputParam, serviceID, operationID) { var currentInstance = kony.sdk.getCurrentInstance(); if (!currentInstance) { throw new Exception(kony.sdk.errorConstants.INIT_FAILURE, kony.sdk.constants.INIT_FAILURE_MESSAGE + "this service."); } var integrationService = currentInstance.getIntegrationService(serviceID); var headers = null; if (inputParam && inputParam["httpheaders"]) { headers = inputParam["httpheaders"]; delete inputParam["httpheaders"]; } return integrationService.invokeOperationSync(operationID, headers, inputParam); }; kony.mbaas.invokeMbaasServiceFromKonyStudioAsync = function(url, inputParam, serviceID, operationID, callBack, info) { kony.mbaas.invokeMbaasServiceFromKonyStudio(url, inputParam, serviceID, operationID, callBack, info); }; function getDeviceIdForIOSPlatform() { if (kony.os.deviceInfo().osversion >= 6.0) { return kony.os.deviceInfo().identifierForVendor; } return kony.os.deviceInfo().customdeviceid; } //Helps to prepare the input wrapped into kony.net.FormData kony.sdk.getFormData = function(payload) { var formData = new kony.net.FormData(); formData.append("jsondata", JSON.stringify(payload)); return formData; }; //Helps to update prepare the input wrapped into kony.net.FormData kony.sdk.updateFormData = function(formData, key, value) { formData.append(key, JSON.stringify(value)); return formData; }; //Helps to get the atype for Spa and DesktopWeb applications it would be kony.sdk.constants.SDK_ATYPE_SPA ,for android wear applications it would be "watch" and remaining it would be "native" kony.sdk.getAType = function() { var returnVal = kony.sdk.constants.SDK_ATYPE_NATIVE; return returnVal; }; kony.sdk.setLicenseCall = function(appKey, appSecret, data) { //checking if new MF app is connected var reportingServiceUrl = data.reportingsvc.session; if (typeof(appConfig) != "undefined") { if ((appKey === appConfig.appKey) && (appSecret === appConfig.appSecret) && (typeof(appConfig.svcDoc) !== "undefined" && reportingServiceUrl === appConfig.svcDoc.reportingsvc.session)) { return; //user is doing init on same environment and same MF-app } else { appConfig.isturlbase = reportingServiceUrl.replace("/IST", ""); appConfig.appKey = appKey; appConfig.appSecret = appSecret; appConfig.serviceUrl = data.selflink; appConfig.svcDoc = data; // IST is triggered with new sid and new MF app on the same or different IST server based on how isturlbase is populated kony.sdk.util.createSessionAndSendIST(); } } }; kony.sdk.saveMetadatainDs = function(appKey, appSecret, servConfig) { // Saving App metadata in storage for Persistence. kony.sdk.isLicenseUrlAvailable = true; var appId = { "appKey": appKey, "appSecret": appSecret, "serviceUrl": servConfig.selflink, "appVersion": appConfig.appVersion, "licenseUrl": servConfig.reportingsvc.session }; if (typeof(sdkInitConfig) !== "undefined") { sdkInitConfig.appKey = appKey; sdkInitConfig.appSecret = appSecret; sdkInitConfig.serviceUrl = servConfig.selflink; } kony.sdk.dataStore.setItem(appConfig.appId + "_mobileFabricServiceDoc", JSON.stringify(servConfig)); kony.sdk.dataStore.setItem(appConfig.appId, JSON.stringify(appId)); }; kony.sdk.deleteMetadatafromDs = function() { kony.sdk.dataStore.removeItem(appConfig.appId); }; /** * Validates the deeplink params. A valid deeplink redirection will contain params "code" & "launchmode" is 3. * @param {map} params - query parameters from the deeplink redirection */ kony.sdk.isValidDeeplinkCallback = function(params) { if (params && params.launchmode == kony.sdk.constants.LAUNCHMODE_DEEPLINK && params.launchparams.code) return true; else return false; }; kony.sdk.getReportingParamsForOfflineObjects = function() { var reportingData = kony.sdk.getPayload(konyRef); reportingData.xmode = "offline"; var sessionId = null; if (kony.ds) { sessionId = kony.ds.read(kony.sdk.constants.KONYUUID); } if (sessionId) { reportingData.rsid = sessionId[0]; } if (!reportingData.rsid) { kony.sdk.logsdk.warn("### kony.sdk.getReportingParamsForOfflineObjects:: rsid is either empty,null or undefined"); } return JSON.stringify(reportingData); }; var MFAppVersion; kony.sdk.setFabricAppVersion = function(version) { MFAppVersion = version; }; /** * Returns the default fabric application version. For auto init app version will be available in appConfig, * for manual init developer has to send fabric version explicitly. * * Fabric version in manual init has more priority over one specified in visualizer. * @return {*} */ kony.sdk.getFabricAppVersion = function() { if (!kony.sdk.isNullOrUndefined(MFAppVersion)) { return MFAppVersion; } else if (!kony.sdk.isNullOrUndefined(appConfig) && !kony.sdk.isNullOrUndefined(appConfig.runtimeAppVersion)) { return appConfig.runtimeAppVersion; } }; /** * Generates key to encrypt/decrypt any text. * @param salt {Array} * @returns string */ kony.sdk.generateSecureKeyFromText = function(salt) { var secureKey = ""; if (!kony.sdk.isNullOrUndefined(salt) && kony.sdk.isArray(salt)) { secureKey = kony.crypto.newKey("passphrase", 128, { passphrasetext: salt, subalgo: "aes", passphrasehashalgo: "md5" }); } else { throw new Exception(kony.sdk.errorConstants.CONFIGURATION_FAILURE, "Invalid param. salt cannot be null, should be of type Array"); } return secureKey; }; /** * Encrypts text with the given salt and encryptionAlgo. * @param text {string} * @param salt {Array} * @param encryptionAlgo {text} * @returns {string} */ kony.sdk.encryptText = function(text, salt, encryptionAlgo) { var encryptionKey = kony.sdk.generateSecureKeyFromText(salt); var encryptedText = kony.crypto.encrypt(encryptionAlgo, encryptionKey, text, {}); return kony.convertToBase64(encryptedText); }; /** * Decrypts text with the given salt and encryptionAlgo. * @param text {string} * @param salt {Array} * @param encryptionAlgo {text} * @returns {string} */ kony.sdk.decryptText = function(text, salt, decryptionAlgo) { var decryptionKey = kony.sdk.generateSecureKeyFromText(salt); var rawText = kony.convertToRawBytes(text) return kony.crypto.decrypt(decryptionAlgo, decryptionKey, rawText, {}); }; /** * Returns type of object * framework api kony.type is not supported by Phonegap and plain-js platforms * @return {*} */ kony.sdk.util.type = function(objectVar) { if (kony.sdk.getAType() === kony.sdk.constants.SDK_ATYPE_NATIVE) { return kony.type(objectVar) } else { return typeof(objectVar) } };
// The framer consists of two [Transform Stream][1] subclasses that operate in [object mode][2]: // the Serializer and the Deserializer // [1]: https://nodejs.org/api/stream.html#stream_class_stream_transform // [2]: https://nodejs.org/api/stream.html#stream_new_stream_readable_options var assert = require('assert'); var Transform = require('stream').Transform; exports.Serializer = Serializer; exports.Deserializer = Deserializer; var logData = (process !== 'undefined' && process.env !== 'undefined' && process.env.HTTP2_LOG_DATA); var MAX_PAYLOAD_SIZE = 16384; var WINDOW_UPDATE_PAYLOAD_SIZE = 4; // Serializer // ---------- // // Frame Objects // * * * * * * * --+--------------------------- // | | // v v Buffers // [] -----> Payload Ser. --[buffers]--> Header Ser. --> * * * * // empty adds payload adds header // array buffers buffer function Serializer(log) { this._log = log.child({ component: 'serializer' }); Transform.call(this, { objectMode: true }); } Serializer.prototype = Object.create(Transform.prototype, { constructor: { value: Serializer } }); // When there's an incoming frame object, it first generates the frame type specific part of the // frame (payload), and then then adds the header part which holds fields that are common to all // frame types (like the length of the payload). Serializer.prototype._transform = function _transform(frame, encoding, done) { this._log.trace({ frame: frame }, 'Outgoing frame'); assert(frame.type in Serializer, 'Unknown frame type: ' + frame.type); var buffers = []; Serializer[frame.type](frame, buffers); var length = Serializer.commonHeader(frame, buffers); assert(length <= MAX_PAYLOAD_SIZE, 'Frame too large!'); for (var i = 0; i < buffers.length; i++) { if (logData) { this._log.trace({ data: buffers[i] }, 'Outgoing data'); } this.push(buffers[i]); } done(); }; // Deserializer // ------------ // // Buffers // * * * * --------+------------------------- // | | // v v Frame Objects // {} -----> Header Des. --{frame}--> Payload Des. --> * * * * * * * // empty adds parsed adds parsed // object header properties payload properties function Deserializer(log, role) { this._role = role; this._log = log.child({ component: 'deserializer' }); Transform.call(this, { objectMode: true }); this._next(COMMON_HEADER_SIZE); } Deserializer.prototype = Object.create(Transform.prototype, { constructor: { value: Deserializer } }); // The Deserializer is stateful, and it's two main alternating states are: *waiting for header* and // *waiting for payload*. The state is stored in the boolean property `_waitingForHeader`. // // When entering a new state, a `_buffer` is created that will hold the accumulated data (header or // payload). The `_cursor` is used to track the progress. Deserializer.prototype._next = function(size) { this._cursor = 0; this._buffer = new Buffer(size); this._waitingForHeader = !this._waitingForHeader; if (this._waitingForHeader) { this._frame = {}; } }; // Parsing an incoming buffer is an iterative process because it can hold multiple frames if it's // large enough. A `cursor` is used to track the progress in parsing the incoming `chunk`. Deserializer.prototype._transform = function _transform(chunk, encoding, done) { var cursor = 0; if (logData) { this._log.trace({ data: chunk }, 'Incoming data'); } while(cursor < chunk.length) { // The content of an incoming buffer is first copied to `_buffer`. If it can't hold the full // chunk, then only a part of it is copied. var toCopy = Math.min(chunk.length - cursor, this._buffer.length - this._cursor); chunk.copy(this._buffer, this._cursor, cursor, cursor + toCopy); this._cursor += toCopy; cursor += toCopy; // When `_buffer` is full, it's content gets parsed either as header or payload depending on // the actual state. // If it's header then the parsed data is stored in a temporary variable and then the // deserializer waits for the specified length payload. if ((this._cursor === this._buffer.length) && this._waitingForHeader) { var payloadSize = Deserializer.commonHeader(this._buffer, this._frame); if (payloadSize <= MAX_PAYLOAD_SIZE) { this._next(payloadSize); } else { this.emit('error', 'FRAME_SIZE_ERROR'); return; } } // If it's payload then the the frame object is finalized and then gets pushed out. // Unknown frame types are ignored. // // Note: If we just finished the parsing of a header and the payload length is 0, this branch // will also run. if ((this._cursor === this._buffer.length) && !this._waitingForHeader) { if (this._frame.type) { var error = Deserializer[this._frame.type](this._buffer, this._frame, this._role); if (error) { this._log.error('Incoming frame parsing error: ' + error); this.emit('error', error); } else { this._log.trace({ frame: this._frame }, 'Incoming frame'); this.push(this._frame); } } else { this._log.error('Unknown type incoming frame'); // Ignore it other than logging } this._next(COMMON_HEADER_SIZE); } } done(); }; // [Frame Header](https://tools.ietf.org/html/rfc7540#section-4.1) // -------------------------------------------------------------- // // HTTP/2 frames share a common base format consisting of a 9-byte header followed by 0 to 2^24 - 1 // bytes of data. // // Additional size limits can be set by specific application uses. HTTP limits the frame size to // 16,384 octets by default, though this can be increased by a receiver. // // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Length (24) | // +---------------+---------------+---------------+ // | Type (8) | Flags (8) | // +-+-----------------------------+---------------+---------------+ // |R| Stream Identifier (31) | // +-+-------------------------------------------------------------+ // | Frame Data (0...) ... // +---------------------------------------------------------------+ // // The fields of the frame header are defined as: // // * Length: // The length of the frame data expressed as an unsigned 24-bit integer. The 9 bytes of the frame // header are not included in this value. // // * Type: // The 8-bit type of the frame. The frame type determines how the remainder of the frame header // and data are interpreted. Implementations MUST ignore unsupported and unrecognized frame types. // // * Flags: // An 8-bit field reserved for frame-type specific boolean flags. // // Flags are assigned semantics specific to the indicated frame type. Flags that have no defined // semantics for a particular frame type MUST be ignored, and MUST be left unset (0) when sending. // // * R: // A reserved 1-bit field. The semantics of this bit are undefined and the bit MUST remain unset // (0) when sending and MUST be ignored when receiving. // // * Stream Identifier: // A 31-bit stream identifier. The value 0 is reserved for frames that are associated with the // connection as a whole as opposed to an individual stream. // // The structure and content of the remaining frame data is dependent entirely on the frame type. var COMMON_HEADER_SIZE = 9; var frameTypes = []; var frameFlags = {}; var genericAttributes = ['type', 'flags', 'stream']; var typeSpecificAttributes = {}; Serializer.commonHeader = function writeCommonHeader(frame, buffers) { var headerBuffer = new Buffer(COMMON_HEADER_SIZE); var size = 0; for (var i = 0; i < buffers.length; i++) { size += buffers[i].length; } headerBuffer.writeUInt8(0, 0); headerBuffer.writeUInt16BE(size, 1); var typeId = frameTypes.indexOf(frame.type); // If we are here then the type is valid for sure headerBuffer.writeUInt8(typeId, 3); var flagByte = 0; for (var flag in frame.flags) { var position = frameFlags[frame.type].indexOf(flag); assert(position !== -1, 'Unknown flag for frame type ' + frame.type + ': ' + flag); if (frame.flags[flag]) { flagByte |= (1 << position); } } headerBuffer.writeUInt8(flagByte, 4); assert((0 <= frame.stream) && (frame.stream < 0x7fffffff), frame.stream); headerBuffer.writeUInt32BE(frame.stream || 0, 5); buffers.unshift(headerBuffer); return size; }; Deserializer.commonHeader = function readCommonHeader(buffer, frame) { if (buffer.length < 9) { return 'FRAME_SIZE_ERROR'; } var totallyWastedByte = buffer.readUInt8(0); var length = buffer.readUInt16BE(1); // We do this just for sanity checking later on, to make sure no one sent us a // frame that's super large. length += totallyWastedByte << 16; frame.type = frameTypes[buffer.readUInt8(3)]; if (!frame.type) { // We are required to ignore unknown frame types return length; } frame.flags = {}; var flagByte = buffer.readUInt8(4); var definedFlags = frameFlags[frame.type]; for (var i = 0; i < definedFlags.length; i++) { frame.flags[definedFlags[i]] = Boolean(flagByte & (1 << i)); } frame.stream = buffer.readUInt32BE(5) & 0x7fffffff; return length; }; // Frame types // =========== // Every frame type is registered in the following places: // // * `frameTypes`: a register of frame type codes (used by `commonHeader()`) // * `frameFlags`: a register of valid flags for frame types (used by `commonHeader()`) // * `typeSpecificAttributes`: a register of frame specific frame object attributes (used by // logging code and also serves as documentation for frame objects) // [DATA Frames](https://tools.ietf.org/html/rfc7540#section-6.1) // ------------------------------------------------------------ // // DATA frames (type=0x0) convey arbitrary, variable-length sequences of octets associated with a // stream. // // The DATA frame defines the following flags: // // * END_STREAM (0x1): // Bit 1 being set indicates that this frame is the last that the endpoint will send for the // identified stream. // * PADDED (0x08): // Bit 4 being set indicates that the Pad Length field is present. frameTypes[0x0] = 'DATA'; frameFlags.DATA = ['END_STREAM', 'RESERVED2', 'RESERVED4', 'PADDED']; typeSpecificAttributes.DATA = ['data']; Serializer.DATA = function writeData(frame, buffers) { buffers.push(frame.data); }; Deserializer.DATA = function readData(buffer, frame) { var dataOffset = 0; var paddingLength = 0; if (frame.flags.PADDED) { if (buffer.length < 1) { // We must have at least one byte for padding control, but we don't. Bad peer! return 'FRAME_SIZE_ERROR'; } paddingLength = (buffer.readUInt8(dataOffset) & 0xff); dataOffset = 1; } if (paddingLength) { if (paddingLength >= (buffer.length - 1)) { // We don't have enough room for the padding advertised - bad peer! return 'FRAME_SIZE_ERROR'; } frame.data = buffer.slice(dataOffset, -1 * paddingLength); } else { frame.data = buffer.slice(dataOffset); } }; // [HEADERS](https://tools.ietf.org/html/rfc7540#section-6.2) // -------------------------------------------------------------- // // The HEADERS frame (type=0x1) allows the sender to create a stream. // // The HEADERS frame defines the following flags: // // * END_STREAM (0x1): // Bit 1 being set indicates that this frame is the last that the endpoint will send for the // identified stream. // * END_HEADERS (0x4): // The END_HEADERS bit indicates that this frame contains the entire payload necessary to provide // a complete set of headers. // * PADDED (0x08): // Bit 4 being set indicates that the Pad Length field is present. // * PRIORITY (0x20): // Bit 6 being set indicates that the Exlusive Flag (E), Stream Dependency, and Weight fields are // present. frameTypes[0x1] = 'HEADERS'; frameFlags.HEADERS = ['END_STREAM', 'RESERVED2', 'END_HEADERS', 'PADDED', 'RESERVED5', 'PRIORITY']; typeSpecificAttributes.HEADERS = ['priorityDependency', 'priorityWeight', 'exclusiveDependency', 'headers', 'data']; // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // |Pad Length? (8)| // +-+-------------+---------------+-------------------------------+ // |E| Stream Dependency? (31) | // +-+-------------+-----------------------------------------------+ // | Weight? (8) | // +-+-------------+-----------------------------------------------+ // | Header Block Fragment (*) ... // +---------------------------------------------------------------+ // | Padding (*) ... // +---------------------------------------------------------------+ // // The payload of a HEADERS frame contains a Headers Block Serializer.HEADERS = function writeHeadersPriority(frame, buffers) { if (frame.flags.PRIORITY) { var buffer = new Buffer(5); assert((0 <= frame.priorityDependency) && (frame.priorityDependency <= 0x7fffffff), frame.priorityDependency); buffer.writeUInt32BE(frame.priorityDependency, 0); if (frame.exclusiveDependency) { buffer[0] |= 0x80; } assert((0 <= frame.priorityWeight) && (frame.priorityWeight <= 0xff), frame.priorityWeight); buffer.writeUInt8(frame.priorityWeight, 4); buffers.push(buffer); } buffers.push(frame.data); }; Deserializer.HEADERS = function readHeadersPriority(buffer, frame) { var minFrameLength = 0; if (frame.flags.PADDED) { minFrameLength += 1; } if (frame.flags.PRIORITY) { minFrameLength += 5; } if (buffer.length < minFrameLength) { // Peer didn't send enough data - bad peer! return 'FRAME_SIZE_ERROR'; } var dataOffset = 0; var paddingLength = 0; if (frame.flags.PADDED) { paddingLength = (buffer.readUInt8(dataOffset) & 0xff); dataOffset = 1; } if (frame.flags.PRIORITY) { var dependencyData = new Buffer(4); buffer.copy(dependencyData, 0, dataOffset, dataOffset + 4); dataOffset += 4; frame.exclusiveDependency = !!(dependencyData[0] & 0x80); dependencyData[0] &= 0x7f; frame.priorityDependency = dependencyData.readUInt32BE(0); frame.priorityWeight = buffer.readUInt8(dataOffset); dataOffset += 1; } if (paddingLength) { if ((buffer.length - dataOffset) < paddingLength) { // Not enough data left to satisfy the advertised padding - bad peer! return 'FRAME_SIZE_ERROR'; } frame.data = buffer.slice(dataOffset, -1 * paddingLength); } else { frame.data = buffer.slice(dataOffset); } }; // [PRIORITY](https://tools.ietf.org/html/rfc7540#section-6.3) // ------------------------------------------------------- // // The PRIORITY frame (type=0x2) specifies the sender-advised priority of a stream. // // The PRIORITY frame does not define any flags. frameTypes[0x2] = 'PRIORITY'; frameFlags.PRIORITY = []; typeSpecificAttributes.PRIORITY = ['priorityDependency', 'priorityWeight', 'exclusiveDependency']; // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // |E| Stream Dependency? (31) | // +-+-------------+-----------------------------------------------+ // | Weight? (8) | // +-+-------------+ // // The payload of a PRIORITY frame contains an exclusive bit, a 31-bit dependency, and an 8-bit weight Serializer.PRIORITY = function writePriority(frame, buffers) { var buffer = new Buffer(5); assert((0 <= frame.priorityDependency) && (frame.priorityDependency <= 0x7fffffff), frame.priorityDependency); buffer.writeUInt32BE(frame.priorityDependency, 0); if (frame.exclusiveDependency) { buffer[0] |= 0x80; } assert((0 <= frame.priorityWeight) && (frame.priorityWeight <= 0xff), frame.priorityWeight); buffer.writeUInt8(frame.priorityWeight, 4); buffers.push(buffer); }; Deserializer.PRIORITY = function readPriority(buffer, frame) { if (buffer.length < 5) { // PRIORITY frames are 5 bytes long. Bad peer! return 'FRAME_SIZE_ERROR'; } var dependencyData = new Buffer(4); buffer.copy(dependencyData, 0, 0, 4); frame.exclusiveDependency = !!(dependencyData[0] & 0x80); dependencyData[0] &= 0x7f; frame.priorityDependency = dependencyData.readUInt32BE(0); frame.priorityWeight = buffer.readUInt8(4); }; // [RST_STREAM](https://tools.ietf.org/html/rfc7540#section-6.4) // ----------------------------------------------------------- // // The RST_STREAM frame (type=0x3) allows for abnormal termination of a stream. // // No type-flags are defined. frameTypes[0x3] = 'RST_STREAM'; frameFlags.RST_STREAM = []; typeSpecificAttributes.RST_STREAM = ['error']; // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Error Code (32) | // +---------------------------------------------------------------+ // // The RST_STREAM frame contains a single unsigned, 32-bit integer identifying the error // code (see Error Codes). The error code indicates why the stream is being terminated. Serializer.RST_STREAM = function writeRstStream(frame, buffers) { var buffer = new Buffer(4); var code = errorCodes.indexOf(frame.error); assert((0 <= code) && (code <= 0xffffffff), code); buffer.writeUInt32BE(code, 0); buffers.push(buffer); }; Deserializer.RST_STREAM = function readRstStream(buffer, frame) { if (buffer.length < 4) { // RST_STREAM is 4 bytes long. Bad peer! return 'FRAME_SIZE_ERROR'; } frame.error = errorCodes[buffer.readUInt32BE(0)]; if (!frame.error) { // Unknown error codes are considered equivalent to INTERNAL_ERROR frame.error = 'INTERNAL_ERROR'; } }; // [SETTINGS](https://tools.ietf.org/html/rfc7540#section-6.5) // ------------------------------------------------------- // // The SETTINGS frame (type=0x4) conveys configuration parameters that affect how endpoints // communicate. // // The SETTINGS frame defines the following flag: // * ACK (0x1): // Bit 1 being set indicates that this frame acknowledges receipt and application of the peer's // SETTINGS frame. frameTypes[0x4] = 'SETTINGS'; frameFlags.SETTINGS = ['ACK']; typeSpecificAttributes.SETTINGS = ['settings']; // The payload of a SETTINGS frame consists of zero or more settings. Each setting consists of a // 16-bit identifier, and an unsigned 32-bit value. // // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Identifier(16) | Value (32) | // +-----------------+---------------------------------------------+ // ...Value | // +---------------------------------+ // // Each setting in a SETTINGS frame replaces the existing value for that setting. Settings are // processed in the order in which they appear, and a receiver of a SETTINGS frame does not need to // maintain any state other than the current value of settings. Therefore, the value of a setting // is the last value that is seen by a receiver. This permits the inclusion of the same settings // multiple times in the same SETTINGS frame, though doing so does nothing other than waste // connection capacity. Serializer.SETTINGS = function writeSettings(frame, buffers) { var settings = [], settingsLeft = Object.keys(frame.settings); definedSettings.forEach(function(setting, id) { if (setting.name in frame.settings) { settingsLeft.splice(settingsLeft.indexOf(setting.name), 1); var value = frame.settings[setting.name]; settings.push({ id: id, value: setting.flag ? Boolean(value) : value }); } }); assert(settingsLeft.length === 0, 'Unknown settings: ' + settingsLeft.join(', ')); var buffer = new Buffer(settings.length * 6); for (var i = 0; i < settings.length; i++) { buffer.writeUInt16BE(settings[i].id & 0xffff, i*6); buffer.writeUInt32BE(settings[i].value, i*6 + 2); } buffers.push(buffer); }; Deserializer.SETTINGS = function readSettings(buffer, frame, role) { frame.settings = {}; // Receipt of a SETTINGS frame with the ACK flag set and a length // field value other than 0 MUST be treated as a connection error // (Section 5.4.1) of type FRAME_SIZE_ERROR. if(frame.flags.ACK && buffer.length != 0) { return 'FRAME_SIZE_ERROR'; } if (buffer.length % 6 !== 0) { return 'PROTOCOL_ERROR'; } for (var i = 0; i < buffer.length / 6; i++) { var id = buffer.readUInt16BE(i*6) & 0xffff; var setting = definedSettings[id]; if (setting) { if (role == 'CLIENT' && setting.name == 'SETTINGS_ENABLE_PUSH') { return 'SETTINGS frame on client got SETTINGS_ENABLE_PUSH'; } var value = buffer.readUInt32BE(i*6 + 2); frame.settings[setting.name] = setting.flag ? Boolean(value & 0x1) : value; } } }; // The following settings are defined: var definedSettings = []; // * SETTINGS_HEADER_TABLE_SIZE (1): // Allows the sender to inform the remote endpoint of the size of the header compression table // used to decode header blocks. definedSettings[1] = { name: 'SETTINGS_HEADER_TABLE_SIZE', flag: false }; // * SETTINGS_ENABLE_PUSH (2): // This setting can be use to disable server push. An endpoint MUST NOT send a PUSH_PROMISE frame // if it receives this setting set to a value of 0. The default value is 1, which indicates that // push is permitted. definedSettings[2] = { name: 'SETTINGS_ENABLE_PUSH', flag: true }; // * SETTINGS_MAX_CONCURRENT_STREAMS (3): // indicates the maximum number of concurrent streams that the sender will allow. definedSettings[3] = { name: 'SETTINGS_MAX_CONCURRENT_STREAMS', flag: false }; // * SETTINGS_INITIAL_WINDOW_SIZE (4): // indicates the sender's initial stream window size (in bytes) for new streams. definedSettings[4] = { name: 'SETTINGS_INITIAL_WINDOW_SIZE', flag: false }; // * SETTINGS_MAX_FRAME_SIZE (5): // indicates the maximum size of a frame the receiver will allow. definedSettings[5] = { name: 'SETTINGS_MAX_FRAME_SIZE', flag: false }; // [PUSH_PROMISE](https://tools.ietf.org/html/rfc7540#section-6.6) // --------------------------------------------------------------- // // The PUSH_PROMISE frame (type=0x5) is used to notify the peer endpoint in advance of streams the // sender intends to initiate. // // The PUSH_PROMISE frame defines the following flags: // // * END_PUSH_PROMISE (0x4): // The END_PUSH_PROMISE bit indicates that this frame contains the entire payload necessary to // provide a complete set of headers. frameTypes[0x5] = 'PUSH_PROMISE'; frameFlags.PUSH_PROMISE = ['RESERVED1', 'RESERVED2', 'END_PUSH_PROMISE', 'PADDED']; typeSpecificAttributes.PUSH_PROMISE = ['promised_stream', 'headers', 'data']; // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // |Pad Length? (8)| // +-+-------------+-----------------------------------------------+ // |X| Promised-Stream-ID (31) | // +-+-------------------------------------------------------------+ // | Header Block Fragment (*) ... // +---------------------------------------------------------------+ // | Padding (*) ... // +---------------------------------------------------------------+ // // The PUSH_PROMISE frame includes the unsigned 31-bit identifier of // the stream the endpoint plans to create along with a minimal set of headers that provide // additional context for the stream. Serializer.PUSH_PROMISE = function writePushPromise(frame, buffers) { var buffer = new Buffer(4); var promised_stream = frame.promised_stream; assert((0 <= promised_stream) && (promised_stream <= 0x7fffffff), promised_stream); buffer.writeUInt32BE(promised_stream, 0); buffers.push(buffer); buffers.push(frame.data); }; Deserializer.PUSH_PROMISE = function readPushPromise(buffer, frame) { if (buffer.length < 4) { return 'FRAME_SIZE_ERROR'; } var dataOffset = 0; var paddingLength = 0; if (frame.flags.PADDED) { if (buffer.length < 5) { return 'FRAME_SIZE_ERROR'; } paddingLength = (buffer.readUInt8(dataOffset) & 0xff); dataOffset = 1; } frame.promised_stream = buffer.readUInt32BE(dataOffset) & 0x7fffffff; dataOffset += 4; if (paddingLength) { if ((buffer.length - dataOffset) < paddingLength) { return 'FRAME_SIZE_ERROR'; } frame.data = buffer.slice(dataOffset, -1 * paddingLength); } else { frame.data = buffer.slice(dataOffset); } }; // [PING](https://tools.ietf.org/html/rfc7540#section-6.7) // ----------------------------------------------- // // The PING frame (type=0x6) is a mechanism for measuring a minimal round-trip time from the // sender, as well as determining whether an idle connection is still functional. // // The PING frame defines one type-specific flag: // // * ACK (0x1): // Bit 1 being set indicates that this PING frame is a PING response. frameTypes[0x6] = 'PING'; frameFlags.PING = ['ACK']; typeSpecificAttributes.PING = ['data']; // In addition to the frame header, PING frames MUST contain 8 additional octets of opaque data. Serializer.PING = function writePing(frame, buffers) { buffers.push(frame.data); }; Deserializer.PING = function readPing(buffer, frame) { if (buffer.length !== 8) { return 'FRAME_SIZE_ERROR'; } frame.data = buffer; }; // [GOAWAY](https://tools.ietf.org/html/rfc7540#section-6.8) // --------------------------------------------------- // // The GOAWAY frame (type=0x7) informs the remote peer to stop creating streams on this connection. // // The GOAWAY frame does not define any flags. frameTypes[0x7] = 'GOAWAY'; frameFlags.GOAWAY = []; typeSpecificAttributes.GOAWAY = ['last_stream', 'error']; // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // |X| Last-Stream-ID (31) | // +-+-------------------------------------------------------------+ // | Error Code (32) | // +---------------------------------------------------------------+ // | Additional Debug Data (*) | // +---------------------------------------------------------------+ // // The last stream identifier in the GOAWAY frame contains the highest numbered stream identifier // for which the sender of the GOAWAY frame has received frames on and might have taken some action // on. // // The GOAWAY frame also contains a 32-bit error code (see Error Codes) that contains the reason for // closing the connection. Serializer.GOAWAY = function writeGoaway(frame, buffers) { var buffer = new Buffer(8); var last_stream = frame.last_stream; assert((0 <= last_stream) && (last_stream <= 0x7fffffff), last_stream); buffer.writeUInt32BE(last_stream, 0); var code = errorCodes.indexOf(frame.error); assert((0 <= code) && (code <= 0xffffffff), code); buffer.writeUInt32BE(code, 4); buffers.push(buffer); }; Deserializer.GOAWAY = function readGoaway(buffer, frame) { if (buffer.length < 8) { // GOAWAY must have at least 8 bytes return 'FRAME_SIZE_ERROR'; } frame.last_stream = buffer.readUInt32BE(0) & 0x7fffffff; frame.error = errorCodes[buffer.readUInt32BE(4)]; if (!frame.error) { // Unknown error types are to be considered equivalent to INTERNAL ERROR frame.error = 'INTERNAL_ERROR'; } // Read remaining data into "debug_data" // https://http2.github.io/http2-spec/#GOAWAY // Endpoints MAY append opaque data to the payload of any GOAWAY frame if (buffer.length > 8) { frame.debug_data = buffer.slice(8); } }; // [WINDOW_UPDATE](https://tools.ietf.org/html/rfc7540#section-6.9) // ----------------------------------------------------------------- // // The WINDOW_UPDATE frame (type=0x8) is used to implement flow control. // // The WINDOW_UPDATE frame does not define any flags. frameTypes[0x8] = 'WINDOW_UPDATE'; frameFlags.WINDOW_UPDATE = []; typeSpecificAttributes.WINDOW_UPDATE = ['window_size']; // The payload of a WINDOW_UPDATE frame is a 32-bit value indicating the additional number of bytes // that the sender can transmit in addition to the existing flow control window. The legal range // for this field is 1 to 2^31 - 1 (0x7fffffff) bytes; the most significant bit of this value is // reserved. Serializer.WINDOW_UPDATE = function writeWindowUpdate(frame, buffers) { var buffer = new Buffer(4); var window_size = frame.window_size; assert((0 < window_size) && (window_size <= 0x7fffffff), window_size); buffer.writeUInt32BE(window_size, 0); buffers.push(buffer); }; Deserializer.WINDOW_UPDATE = function readWindowUpdate(buffer, frame) { if (buffer.length !== WINDOW_UPDATE_PAYLOAD_SIZE) { return 'FRAME_SIZE_ERROR'; } frame.window_size = buffer.readUInt32BE(0) & 0x7fffffff; if (frame.window_size === 0) { return 'PROTOCOL_ERROR'; } }; // [CONTINUATION](https://tools.ietf.org/html/rfc7540#section-6.10) // ------------------------------------------------------------ // // The CONTINUATION frame (type=0x9) is used to continue a sequence of header block fragments. // // The CONTINUATION frame defines the following flag: // // * END_HEADERS (0x4): // The END_HEADERS bit indicates that this frame ends the sequence of header block fragments // necessary to provide a complete set of headers. frameTypes[0x9] = 'CONTINUATION'; frameFlags.CONTINUATION = ['RESERVED1', 'RESERVED2', 'END_HEADERS']; typeSpecificAttributes.CONTINUATION = ['headers', 'data']; Serializer.CONTINUATION = function writeContinuation(frame, buffers) { buffers.push(frame.data); }; Deserializer.CONTINUATION = function readContinuation(buffer, frame) { frame.data = buffer; }; // [ALTSVC](https://tools.ietf.org/html/rfc7838#section-4) // ------------------------------------------------------------ // // The ALTSVC frame (type=0xA) advertises the availability of an alternative service to the client. // // The ALTSVC frame does not define any flags. frameTypes[0xA] = 'ALTSVC'; frameFlags.ALTSVC = []; // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Origin-Len (16) | Origin? (*) ... // +-------------------------------+----------------+--------------+ // | Alt-Svc-Field-Value (*) ... // +---------------------------------------------------------------+ // // The ALTSVC frame contains the following fields: // // Origin-Len: An unsigned, 16-bit integer indicating the length, in // octets, of the Origin field. // // Origin: An OPTIONAL sequence of characters containing ASCII // serialisation of an origin ([RFC6454](https://tools.ietf.org/html/rfc6454), // Section 6.2) that the alternate service is applicable to. // // Alt-Svc-Field-Value: A sequence of octets (length determined by // subtracting the length of all preceding fields from the frame // length) containing a value identical to the Alt-Svc field value // defined in (Section 3)[https://tools.ietf.org/html/rfc7838#section-3] // (ABNF production "Alt-Svc"). typeSpecificAttributes.ALTSVC = ['maxAge', 'port', 'protocolID', 'host', 'origin']; function istchar(c) { return ('!#$&\'*+-.^_`|~1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.indexOf(c) > -1); } function hexencode(s) { var t = ''; for (var i = 0; i < s.length; i++) { if (!istchar(s[i])) { t += '%'; t += new Buffer(s[i]).toString('hex'); } else { t += s[i]; } } return t; } Serializer.ALTSVC = function writeAltSvc(frame, buffers) { var buffer = new Buffer(2); buffer.writeUInt16BE(frame.origin.length, 0); buffers.push(buffer); buffers.push(new Buffer(frame.origin, 'ascii')); var fieldValue = hexencode(frame.protocolID) + '="' + frame.host + ':' + frame.port + '"'; if (frame.maxAge !== 86400) { // 86400 is the default fieldValue += "; ma=" + frame.maxAge; } buffers.push(new Buffer(fieldValue, 'ascii')); }; function stripquotes(s) { var start = 0; var end = s.length; while ((start < end) && (s[start] === '"')) { start++; } while ((end > start) && (s[end - 1] === '"')) { end--; } if (start >= end) { return ""; } return s.substring(start, end); } function splitNameValue(nvpair) { var eq = -1; var inQuotes = false; for (var i = 0; i < nvpair.length; i++) { if (nvpair[i] === '"') { inQuotes = !inQuotes; continue; } if (inQuotes) { continue; } if (nvpair[i] === '=') { eq = i; break; } } if (eq === -1) { return {'name': nvpair, 'value': null}; } var name = stripquotes(nvpair.substring(0, eq).trim()); var value = stripquotes(nvpair.substring(eq + 1).trim()); return {'name': name, 'value': value}; } function splitHeaderParameters(hv) { return parseHeaderValue(hv, ';', splitNameValue); } function parseHeaderValue(hv, separator, callback) { var start = 0; var inQuotes = false; var values = []; for (var i = 0; i < hv.length; i++) { if (hv[i] === '"') { inQuotes = !inQuotes; continue; } if (inQuotes) { // Just skip this continue; } if (hv[i] === separator) { var newValue = hv.substring(start, i).trim(); if (newValue.length > 0) { newValue = callback(newValue); values.push(newValue); } start = i + 1; } } var newValue = hv.substring(start).trim(); if (newValue.length > 0) { newValue = callback(newValue); values.push(newValue); } return values; } function rsplit(s, delim, count) { var nsplits = 0; var end = s.length; var rval = []; for (var i = s.length - 1; i >= 0; i--) { if (s[i] === delim) { var t = s.substring(i + 1, end); end = i; rval.unshift(t); nsplits++; if (nsplits === count) { break; } } } if (end !== 0) { rval.unshift(s.substring(0, end)); } return rval; } function ishex(c) { return ('0123456789ABCDEFabcdef'.indexOf(c) > -1); } function unescape(s) { var i = 0; var t = ''; while (i < s.length) { if (s[i] != '%' || !ishex(s[i + 1]) || !ishex(s[i + 2])) { t += s[i]; } else { ++i; var hexvalue = ''; if (i < s.length) { hexvalue += s[i]; ++i; } if (i < s.length) { hexvalue += s[i]; } if (hexvalue.length > 0) { t += new Buffer(hexvalue, 'hex').toString(); } else { t += '%'; } } ++i; } return t; } Deserializer.ALTSVC = function readAltSvc(buffer, frame) { if (buffer.length < 2) { return 'FRAME_SIZE_ERROR'; } var originLength = buffer.readUInt16BE(0); if ((buffer.length - 2) < originLength) { return 'FRAME_SIZE_ERROR'; } frame.origin = buffer.toString('ascii', 2, 2 + originLength); var fieldValue = buffer.toString('ascii', 2 + originLength); var values = parseHeaderValue(fieldValue, ',', splitHeaderParameters); if (values.length > 1) { // TODO - warn that we only use one here } if (values.length === 0) { // Well that's a malformed frame. Just ignore it. return; } var chosenAltSvc = values[0]; frame.maxAge = 86400; // Default for (var i = 0; i < chosenAltSvc.length; i++) { if (i === 0) { // This corresponds to the protocolID="<host>:<port>" item frame.protocolID = unescape(chosenAltSvc[i].name); var hostport = rsplit(chosenAltSvc[i].value, ':', 1); frame.host = hostport[0]; frame.port = parseInt(hostport[1], 10); } else if (chosenAltSvc[i].name == 'ma') { frame.maxAge = parseInt(chosenAltSvc[i].value, 10); } // Otherwise, we just ignore this } }; // BLOCKED // ------------------------------------------------------------ // // The BLOCKED frame (type=0xB) indicates that the sender is unable to send data // due to a closed flow control window. // // The BLOCKED frame does not define any flags and contains no payload. frameTypes[0xB] = 'BLOCKED'; frameFlags.BLOCKED = []; typeSpecificAttributes.BLOCKED = []; Serializer.BLOCKED = function writeBlocked(frame, buffers) { }; Deserializer.BLOCKED = function readBlocked(buffer, frame) { }; // [Error Codes](https://tools.ietf.org/html/rfc7540#section-7) // ------------------------------------------------------------ var errorCodes = [ 'NO_ERROR', 'PROTOCOL_ERROR', 'INTERNAL_ERROR', 'FLOW_CONTROL_ERROR', 'SETTINGS_TIMEOUT', 'STREAM_CLOSED', 'FRAME_SIZE_ERROR', 'REFUSED_STREAM', 'CANCEL', 'COMPRESSION_ERROR', 'CONNECT_ERROR', 'ENHANCE_YOUR_CALM', 'INADEQUATE_SECURITY', 'HTTP_1_1_REQUIRED' ]; // Logging // ------- // [Bunyan serializers](https://github.com/trentm/node-bunyan#serializers) to improve logging output // for debug messages emitted in this component. exports.serializers = {}; // * `frame` serializer: it transforms data attributes from Buffers to hex strings and filters out // flags that are not present. var frameCounter = 0; exports.serializers.frame = function(frame) { if (!frame) { return null; } if ('id' in frame) { return frame.id; } frame.id = frameCounter; frameCounter += 1; var logEntry = { id: frame.id }; genericAttributes.concat(typeSpecificAttributes[frame.type]).forEach(function(name) { logEntry[name] = frame[name]; }); if (frame.data instanceof Buffer) { if (logEntry.data.length > 50) { logEntry.data = frame.data.slice(0, 47).toString('hex') + '...'; } else { logEntry.data = frame.data.toString('hex'); } if (!('length' in logEntry)) { logEntry.length = frame.data.length; } } if (frame.promised_stream instanceof Object) { logEntry.promised_stream = 'stream-' + frame.promised_stream.id; } logEntry.flags = Object.keys(frame.flags || {}).filter(function(name) { return frame.flags[name] === true; }); return logEntry; }; // * `data` serializer: it simply transforms a buffer to a hex string. exports.serializers.data = function(data) { return data.toString('hex'); };
/** * Construct a recursive tree from a list of class names. * * The class names are split on the '.' character. * * So, the list ["a.b.c", "a.b.d", "a.c.c"] would become become: * * - a * -b * -c * -d * -c * -c * * @param classNames * @param root */ export default function (classNames, root) { // Split up the class names by periods var splitNames = classNames.map( function (className) { return className.split('.'); } ); // Iterate through the split names, recursively adding to the root for (var i = 0; i < splitNames.length; i++) { var codeArray = splitNames[i]; var node = root; for (var j = 0; j < codeArray.length; j++) { node = node.getOrAppendChild(codeArray[j]); } } }
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import InputBuilder from '../base/InputBuilder'; const iconId = require('../../../assets/images/icons/icon-document.svg'); const iconIdLight = require('../../../assets/images/icons/icon-document-light.svg'); export default class InputCPFCNPJ extends PureComponent { static propTypes = { light: PropTypes.bool, }; validate = value => { if (!value) return { error: 'CPF/CNPJ deve ser preenchido' }; return { success: true }; }; mask = value => { const length = value.replace(/[^\d]/g, '').length; if (length > 11) { // CNPJ return [ /[0-9]/, /[0-9]/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, ]; } // CPF return [ /[0-9]/, /[0-9]/, /[0-9]/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/, ]; }; render() { const { light } = this.props; return ( <InputBuilder validate={this.validate} mask={this.mask} clearable field="cpfOrCnpj" placeholder="CPF ou CNPJ" icon={light ? iconIdLight : iconId} {...this.props} /> ); } }
var click = "click"; var keydown = "keydown"; var keypress = "keypress"; var keyup = "keyup"; var change = "change"; var MODELFLAG_PICKED = 1 << 1; var MODELFLAG_HIDDEN = 1 << 2; var MODELFLAG_LOCKED = 1 << 3; var MODELFLAG_FORCE_UPDATE = 1 << 4; function ArrayPushIfNotHas(arr, element) { if (arr && element && arr.indexOf(element) == -1) { arr.push(element); return true; } else return false; } function getParameterByName(name) { if (!location || !location.search) return undefined; return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null; } //# sourceURL=file://ui/global/constant.js
/*! * ${copyright} */ /*global history */ sap.ui.define([ "sap/ui/documentation/library", "sap/ui/core/Fragment", "sap/ui/core/mvc/Controller", "sap/ui/core/routing/History", "sap/ui/model/resource/ResourceModel", "sap/ui/Device", "sap/m/library", "sap/ui/documentation/sdk/controller/util/APIInfo", "sap/base/strings/formatMessage" ], function (library, Fragment, Controller, History, ResourceModel, Device, mobileLibrary, APIInfo, formatMessage) { "use strict"; // shortcut for sap.m.SplitAppMode var SplitAppMode = mobileLibrary.SplitAppMode; return Controller.extend("sap.ui.documentation.sdk.controller.BaseController", { // Prerequisites _oCore: sap.ui.getCore(), formatMessage: formatMessage, onInit: function() { var oMessageBundle = new ResourceModel({ bundleName: "sap.ui.documentation.messagebundle" }); this.setModel(oMessageBundle, "i18n"); // Load <code>versionInfo</code> to ensure the <code>versionData</code> model is loaded. if (Device.system.phone || Device.system.tablet) { this.getOwnerComponent().loadVersionInfo(); // for Desktop is always loaded in <code>Component.js</code> } }, hideMasterSide : function() { var splitApp = this.getSplitApp(); splitApp.setMode(SplitAppMode.HideMode); }, showMasterSide : function() { var splitApp = this.getSplitApp(); splitApp.setMode(SplitAppMode.ShowHideMode); }, getSplitApp: function() { return this.getView().getParent().getParent(); }, /** * Convenience method for accessing the router in every controller of the application. * @public * @returns {sap.ui.core.routing.Router} the router for this component */ getRouter : function () { return this.getOwnerComponent().getRouter(); }, /** * Convenience method for getting the view model by name in every controller of the application. * @public * @param {string} sName the model name * @returns {sap.ui.model.Model} the model instance */ getModel : function (sName) { return this.getView().getModel(sName); }, /** * Convenience method for setting the view model in every controller of the application. * @public * @param {sap.ui.model.Model} oModel the model instance * @param {string} sName the model name * @returns {sap.ui.mvc.View} the view instance */ setModel : function (oModel, sName) { return this.getView().setModel(oModel, sName); }, /** * Convenience method for getting the application configuration located in manifest.json. * @public * @returns {object} the configuration of the component */ getConfig : function () { return this.getOwnerComponent().getMetadata().getConfig(); }, /** * Event handler for navigating back. * It checks if there is a history entry. If yes, history.go(-1) will happen. * If not, it will replace the current entry of the browser history with the master route. * @public */ onNavBack : function(event) { var sPreviousHash = History.getInstance().getPreviousHash(); if (sPreviousHash !== undefined) { // The history contains a previous entry if (sPreviousHash.indexOf("search/") === 0) { this.getRouter().navTo("search", {searchParam: sPreviousHash.split("/")[1]}, false); } else { history.go(-1); } } else { var sCurrentHash = window.location.hash; if (sCurrentHash.indexOf("#/topic/") == 0) { this.getRouter().navTo("topic", {}, true); } else if (sCurrentHash.indexOf("#/api/") == 0) { this.getRouter().navTo("api", {}, true); } } }, searchResultsButtonVisibilitySwitch : function(oButton) { var sPreviousHash = History.getInstance().getPreviousHash(); if (sPreviousHash && sPreviousHash.indexOf("search/") === 0) { oButton.setVisible(true); } else { oButton.setVisible(false); } }, /** * Getter for the application root view * @return {sap.ui.core.mvc.View} Application root view */ getRootView: function () { var oComponent = this.getOwnerComponent(); return oComponent.byId(oComponent.getManifestEntry("/sap.ui5/rootView").id); }, /** * Opens a legal disclaimer for Links Popover. * @param {sap.ui.base.Event} oEvent: the <code>Image</code> press event * @public */ onDisclaimerLinkPress: function (oEvent) { var oSource = oEvent.getSource ? oEvent.getSource() : oEvent.target; if (!this.oDisclaimerPopover) { Fragment.load({ name: "sap.ui.documentation.sdk.view.LegalDisclaimerPopover" }).then(function (oPopover) { // connect dialog to the root view of this component (models, lifecycle) this.getView().addDependent(oPopover); this.oDisclaimerPopover = oPopover; oPopover.openBy(oSource); }.bind(this)); return; // We continue execution in the promise } else if (this.oDisclaimerPopover.isOpen()) { this.oDisclaimerPopover.close(); } this.oDisclaimerPopover.openBy(oSource); }, /** * Retrieves the actual component for the control. * @param {string} sControlName * @return {string} the actual component */ _getControlComponent: function (sControlName, oControlsData) { var oLibComponentModel = oControlsData.libComponentInfos, oLibInfo = library._getLibraryInfoSingleton(); return oLibInfo._getActualComponent(oLibComponentModel, sControlName); }, /** * Switches the maximum height of the phone image for optimal display in landscape mode * @param {sap.ui.base.Event} oEvent Device orientation change event * @private */ _onOrientationChange: function(oEvent) { var oImage = this.byId("phoneImage"); if (Device.system.phone && oImage) { oImage.toggleStyleClass("phoneHeaderImageLandscape", oEvent.landscape); } }, /** * Registers an event listener on device orientation change * @private */ _registerOrientationChange: function () { Device.orientation.attachHandler(this._onOrientationChange, this); }, /** * Deregisters the event listener for device orientation change * @private */ _deregisterOrientationChange: function () { Device.orientation.detachHandler(this._onOrientationChange, this); }, /** * Handles landing image load event and makes landing image headline visible * when the image has loaded. */ handleLandingImageLoad: function () { this.getView().byId("landingImageHeadline").setVisible(true); }, /** * Checks if a control has API Reference * @param {string} sControlName * @return {Promise} A promise that resolves to {boolean} */ getAPIReferenceCheckPromise: function (sControlName) { return APIInfo.getIndexJsonPromise().then(function (aData) { function findSymbol (a) { return a.some(function (o) { var bFound = o.name === sControlName; if (!bFound && o.nodes) { return findSymbol(o.nodes); } return bFound; }); } return findSymbol(aData); }); } }); } );
// Relative paths work! define(['./Shirt'], function(Shirt) { return { shirt: Shirt }; });
import React from "react"; import { View, Text, StyleSheet, TouchableOpacity, TextInput, Platform, ActivityIndicator, AsyncStorage, FlatList, PlatformColor, Appearance, useColorScheme, Modal, } from "react-native"; import emoji_datasource from "emoji-datasource"; const colorScheme = Appearance.getColorScheme(); export const Categories = { all: { symbol: null, name: "All", }, history: { symbol: "🕘", name: "Recently used", }, emotion: { symbol: "😀", name: "Smileys & Emotion", }, people: { symbol: "🧑", name: "People & Body", }, nature: { symbol: "🦄", name: "Animals & Nature", }, food: { symbol: "🍔", name: "Food & Drink", }, activities: { symbol: "⚾️", name: "Activities", }, places: { symbol: "✈️", name: "Travel & Places", }, objects: { symbol: "💡", name: "Objects", }, symbols: { symbol: "🔣", name: "Symbols", }, flags: { symbol: "🏳️‍🌈", name: "Flags", }, }; const charFromUtf16 = (utf16) => String.fromCodePoint(...utf16.split("-").map((u) => "0x" + u)); export const charFromEmojiObject = (obj) => charFromUtf16(obj.unified); const filteredEmojis = emoji_datasource.filter((e) => !e["obsoleted_by"]); const emojiByCategory = (category) => filteredEmojis.filter((e) => e.category === category); const sortEmoji = (list) => list.sort((a, b) => a.sort_order - b.sort_order); const categoryKeys = Object.keys(Categories); const TabBar = ({ theme, activeCategory, onPress, width, inActiveTabBorderColor, styles }) => { const categories = Object.keys(Categories); const tabSize = Math.min(width / categories.length, 56); const colorScheme = useColorScheme(); return categories.map((c) => { const category = Categories[c]; if (c !== "all") return ( <TouchableOpacity key={category.name} onPress={() => onPress(category)} activeOpacity={0.5} style={[ { height: tabSize, borderColor: category === activeCategory ? theme : inActiveTabBorderColor, }, styles.tab, ]} > <Text style={[{ fontSize: tabSize - 24 }, styles.tabInner]}> {category.symbol} </Text> </TouchableOpacity> ); }); }; const EmojiCell = ({ emoji, colSize, ...other }) => ( <TouchableOpacity activeOpacity={0.5} style={{ width: colSize, height: colSize, alignItems: "center", justifyContent: "center", }} {...other} > <Text style={{ color: "#FFFFFF", fontSize: colSize - 12 }}> {charFromEmojiObject(emoji)} </Text> </TouchableOpacity> ); // TODO: Move all these styles to defaultStyles and allow for overrides const VariationPicker = ({ emoji, onEmojiSelected, ...props }) => { const renderEmojis = () => { let { skin_variations } = emoji; let variants = Object.keys(skin_variations).map( (skin) => skin_variations[skin] ); return ( <View style={{ backgroundColor: PlatformColor("secondarySystemBackground"), width: 240, height: 176, padding: 24, borderRadius: 24, }} > <FlatList data={[].concat(emoji, variants)} renderItem={({ item }) => ( <EmojiCell key={item.key} emoji={item} colSize={64} onPress={() => onEmojiSelected(item)} /> )} keyExtractor={(item) => item.unified} horizontal={false} numColumns={3} /> </View> ); }; return ( <Modal animationType="fade" transparent={true} style={{ flex: 1, }} {...props} > <View style={{ flex: 1, height: "100%", flexDirection: "column", alignItems: "center", justifyContent: "center", }} > {emoji ? renderEmojis() : "..."} </View> </Modal> ); }; const storage_key = "@react-native-emoji-selector:HISTORY"; const EmojiSelector = ({ theme, category, columns, placeholder, placeholderTextColor, showHistory, showSearchBar, showSectionTitles, showTabs, onEmojiSelected, shouldInclude, inActiveTabBorderColor, overrideStyles = {}, ...other }) => { let [state, setState] = React.useState({ searchQuery: "", category: category ?? Categories.people, isReady: false, history: [], emojiList: null, colSize: 0, width: 0, }); let [selectedEmoji, setSelectedEmoji] = React.useState(null); let [showVariations, setShowVariations] = React.useState(false); const scrollviewRef = React.useRef(null); const styles = { ...defaultStyles, ...overrideStyles, }; const handleLayout = ({ nativeEvent: { layout } }) => { if (layout.width !== state.width) { setState({ ...state, width: layout.width, }); } }; const handleTabSelect = (category) => { if (state.isReady) { scrollviewRef.current?.scrollToOffset({ x: 0, y: 0, animated: false }); setState({ ...state, searchQuery: "", category, }); } }; const returnSectionData = () => { const { history, emojiList, searchQuery, category } = state; let emojiData = (function () { if (category === Categories.all && searchQuery === "") { //TODO: OPTIMIZE THIS let largeList = []; categoryKeys.forEach((c) => { const name = Categories[c].name; const list = name === Categories.history.name ? history : emojiList[name]; if (c !== "all" && c !== "history") largeList = largeList.concat(list); }); return largeList.map((emoji) => ({ key: emoji.unified, emoji })); } else { let list; const hasSearchQuery = searchQuery !== ""; const name = category.name; if (hasSearchQuery) { const filtered = emoji_datasource.filter((e) => { let display = false; e.short_names.forEach((name) => { if (name.includes(searchQuery.toLowerCase())) display = true; }); return display; }); list = sortEmoji(filtered); } else if (name === Categories.history.name) { list = history; } else { list = emojiList[name]; } return list.map((emoji) => ({ key: emoji.unified, emoji })); } })(); return shouldInclude ? emojiData.filter((e) => shouldInclude(e.emoji)) : emojiData; }; const prerenderEmojis = () => { let emojiList = {}; categoryKeys.forEach((c) => { let name = Categories[c].name; emojiList[name] = sortEmoji(emojiByCategory(name)); }); setState({ ...state, emojiList, colSize: Math.floor(state.width / columns), isReady: true, }); }; const handleEmojiSelect = (emoji) => { // TODO: Figure out history bullshit // if (showHistory) { // addToHistoryAsync(emoji); // } onEmojiSelected(charFromEmojiObject(emoji)); if (showVariations) { setShowVariations(false); } }; const handleEmojiLongPress = (emoji) => { if (emoji.skin_variations) { setSelectedEmoji(emoji); setShowVariations(true); } else { handleEmojiSelect(emoji); } }; const renderEmojiCell = ({ item }) => ( <EmojiCell key={item.key} emoji={item.emoji} onPress={() => handleEmojiSelect(item.emoji)} onLongPress={() => handleEmojiLongPress(item.emoji)} colSize={state.colSize} /> ); const handleSearch = (searchQuery) => { setState({ ...state, searchQuery }); }; React.useEffect(() => { if (state.width > 0) { prerenderEmojis(); } }, [state.width]); return ( <View style={styles.frame} {...other} onLayout={handleLayout}> <VariationPicker emoji={selectedEmoji} visible={showVariations} onEmojiSelected={handleEmojiSelect} onRequestClose={() => setShowVariations(false)} /> <View style={styles.tabBar}> {showTabs && ( <TabBar inActiveTabBorderColor={inActiveTabBorderColor} activeCategory={state.category} onPress={handleTabSelect} theme={theme} styles={styles} width={state.width} /> )} </View> <View style={{ flex: 1 }}> {showSearchBar && ( <View style={styles.searchContainer}> <TextInput placeholderTextColor={placeholderTextColor} style={styles.search} placeholder={placeholder} clearButtonMode="always" returnKeyType="done" autoCorrect={false} underlineColorAndroid={theme} value={state.searchQuery} onChangeText={handleSearch} /> </View> )} {state.isReady ? ( <View style={{ flex: 1 }}> <View style={styles.container}> {showSectionTitles && ( <Text style={styles.sectionHeader}> {state.searchQuery !== "" ? "Search Results" : state.category.name} </Text> )} <FlatList style={styles.scrollview} contentContainerStyle={{ paddingBottom: state.colSize }} data={returnSectionData()} renderItem={renderEmojiCell} horizontal={false} numColumns={columns} keyboardShouldPersistTaps={"always"} ref={scrollviewRef} removeClippedSubviews /> </View> </View> ) : ( <View style={styles.loader} {...other}> <ActivityIndicator size={"large"} color={Platform.OS === "android" ? theme : "#000000"} /> </View> )} </View> </View> ); }; EmojiSelector.defaultProps = { theme: PlatformColor("link") /* TODO: Android */, category: Categories.all, showTabs: true, showSearchBar: true, showHistory: false, showSectionTitles: true, columns: 6, placeholder: "Search...", placeholderTextColor: 'red', inActiveTabBorderColor: 'red', }; export const defaultStyles = StyleSheet.create({ frame: { flex: 1, width: "100%", overflow: "hidden", backgroundColor: PlatformColor("systemBackground") /*TODO: Android */, }, loader: { flex: 1, alignItems: "center", justifyContent: "center", }, tab: { flex: 1, borderBottomWidth: 2, alignItems: "center", justifyContent: "center", }, tabInner: { textAlign: "center", paddingBottom: 8, }, tabBar: { flexDirection: "row", }, scrollview: { flex: 1, }, searchContainer: { width: "100%", zIndex: 1, }, search: { ...Platform.select({ ios: { height: 36, paddingLeft: 8, borderRadius: 10, color: PlatformColor("label") /* TODO: Android */, backgroundColor: PlatformColor("systemGray6") /* TODO: Android */, }, }), margin: 8, }, container: { flex: 1, flexWrap: "wrap", flexDirection: "row", alignItems: "flex-start", }, sectionHeader: { margin: 8, fontSize: 17, width: "100%", color: PlatformColor("secondaryLabel") /* TODO: Android */, }, }); export default EmojiSelector;
'use strict'; const emitter = require('./events/emitter'); const isNil = require('ramda/src/isNil'); var gloo = function (hostname, port, ssl) { if ( isNil(hostname) || typeof hostname !== 'string' || hostname === '' ) { throw new Error("gloo constructor requires hostname to be specified<string>") } if ( isNil(port) || typeof port !== 'number' ) { throw new Error("gloo constructor requires port to be specified<string>") } return { emitter: emitter(hostname, port, ssl) } }; module.exports = gloo;
var searchData= [ ['fs_5fapplication_2ecpp_802',['fs_application.cpp',['../fs__application_8cpp.html',1,'']]], ['fs_5fapplication_2ehpp_803',['fs_application.hpp',['../fs__application_8hpp.html',1,'']]] ];
import { AIRPORT_DATABASE } from '@airport/air-control'; import { container, DI } from '@airport/di'; import { getFullApplicationName, STORE_DRIVER, } from '@airport/ground-control'; import { Actor, } from '@airport/holding-pattern'; import { APPLICATION_INITIALIZER } from '@airport/landing'; import { APPLICATION_DAO } from '@airport/airspace'; import { TRANSACTIONAL_SERVER } from '@airport/terminal-map'; import { DATABASE_MANAGER, INTERNAL_RECORD_MANAGER } from '../tokens'; import { BLUEPRINT } from '@airport/blueprint'; export class DatabaseManager { constructor() { this.initialized = false; } async initNoDb(context, ...applications) { await container(this).get(AIRPORT_DATABASE); const server = await container(this).get(TRANSACTIONAL_SERVER); server.tempActor = new Actor(); await this.installStarterApplication(true, false, context); const applicationInitializer = await container(this).get(APPLICATION_INITIALIZER); await applicationInitializer.stage(applications, context); server.tempActor = null; this.initialized = true; } async initWithDb(domainName, context) { await container(this).get(AIRPORT_DATABASE); const storeDriver = await container(this).get(STORE_DRIVER); const server = await container(this).get(TRANSACTIONAL_SERVER); server.tempActor = new Actor(); const hydrate = await storeDriver.doesTableExist(getFullApplicationName(BLUEPRINT[0]), 'PACKAGES', context); await this.installStarterApplication(false, hydrate, context); if (!hydrate) { const internalRecordManager = await container(this) .get(INTERNAL_RECORD_MANAGER); await internalRecordManager.initTerminal(domainName, context); } server.tempActor = null; this.initialized = true; } isInitialized() { return this.initialized; } async initFeatureApplications(context, jsonApplications) { const applicationDao = await container(this).get(APPLICATION_DAO); const applications = await applicationDao.findAllWithJson(); const existingApplicationMap = new Map(); for (const application of applications) { existingApplicationMap.set(application.fullName, application); } const applicationsToCreate = []; for (const jsonApplication of jsonApplications) { const existingApplication = existingApplicationMap.get(getFullApplicationName(jsonApplication)); if (existingApplication) { jsonApplication.lastIds = existingApplication.versions[0].jsonApplication.lastIds; } else { applicationsToCreate.push(jsonApplication); } } // if (applicationsToCreate.length) { const [applicationInitializer, server] = await container(this) .get(APPLICATION_INITIALIZER, TRANSACTIONAL_SERVER); server.tempActor = new Actor(); // await applicationInitializer.initialize(applicationsToCreate, context, existingApplicationsAreHydrated); await applicationInitializer.initialize(applicationsToCreate, existingApplicationMap, context, true); // } server.tempActor = null; } /* static async addDataStore( storeType: StoreType, terminalName: string ): Promise<void> { if (this.isInitialized(terminalName)) { throw new Error( `Database '${terminalName}' is already initialized`); } const newDataStore = await QDataStore.db(dbConst.DEFAULT_DB).save({ name: terminalName, storeType: storeType }); await TQ.init(storeType, terminalName); } private doEnsureInitialized( terminalName: string, resolve, reject, remainingTimeout: number ): void { if (this.isInitialized(terminalName)) { resolve() } if (remainingTimeout <= 0) { reject(`Timeout out waiting for initialization of DB: [${terminalName}]`) } remainingTimeout -= 100 setTimeout(() => { this.doEnsureInitialized(terminalName, resolve, reject, remainingTimeout) }, 100) } */ async installStarterApplication(stage, hydrate, context) { const blueprintFile = await import('@airport/blueprint'); const applicationInitializer = await container(this).get(APPLICATION_INITIALIZER); if (stage) { await applicationInitializer.stage(blueprintFile.BLUEPRINT, context); } else if (hydrate) { await applicationInitializer.hydrate(blueprintFile.BLUEPRINT, context); // Below appears to be not needed - hydrate gets all applications // const applicationDao = await container(this).get(APPLICATION_DAO) // const applications = await applicationDao.findAll() // const jsonApplicationNameSet: Set<string> = new Set() // blueprintFile.BLUEPRINT // .map(jsonApplication => getFullApplicationName(jsonApplication)) // // schemname contains both domain and application's actual name // .forEach(applicationName => { // jsonApplicationNameSet.add(applicationName) // }) // const jsonApplications = applications.filter(application => !jsonApplicationNameSet.has(application.fullName)) // .map(application => application.jsonApplication) // await applicationInitializer.hydrate(jsonApplications as any, context); } else { await applicationInitializer.initialize(blueprintFile.BLUEPRINT, new Map(), context, false); } } } DI.set(DATABASE_MANAGER, DatabaseManager); //# sourceMappingURL=DatabaseManager.js.map
import Element from '@flyskywhy/react-native-browser-polyfill/src/DOM/Element'; import GContext2D from '../context/2d/RenderingContext'; import GContextWebGL from '../context/webgl/RenderingContext'; import {PixelRatio} from 'react-native'; function sleepMs(ms) { for (var start = new Date(); new Date() - start <= ms; ) {} } export default class GCanvas extends Element { static GBridge = null; id = null; _renderLoopId = null; _context = null; _clientWidth = 100; _clientHeight = 150; _width = 100; _height = 150; _needRender = true; constructor(id, {isAutoClearRectBeforePutImageData, devicePixelRatio, disableAutoSwap, style}) { super('canvas'); this.id = id; this._isAutoClearRectBeforePutImageData = isAutoClearRectBeforePutImageData; if (devicePixelRatio !== undefined) { this._devicePixelRatio = parseInt(devicePixelRatio, 10); } this._disableAutoSwap = disableAutoSwap; this._swapBuffers = () => { this._context && this._context.flushJsCommands2CallNative(); }; this._clientWidth = style.width; this._clientHeight = style.height; this._width = style.width; this._height = style.height; } get clientWidth() { return this._clientWidth; } get clientHeight() { return this._clientHeight; } set clientWidth(value) { this._clientWidth = value; } set clientHeight(value) { this._clientHeight = value; } get width() { return this._width; } set width(value) { if (this._context && this._context.className === 'CanvasRenderingContext2D') { this._context.clearRect(0, 0, this._clientWidth, this._clientHeight); } this._width = value; GCanvas.GBridge.callResetGlViewport(this.id); this._context.drawingBufferWidth = this._clientWidth * PixelRatio.get(); } get height() { return this._height; } set height(value) { if (this._context && this._context.className === 'CanvasRenderingContext2D') { this._context.clearRect(0, 0, this._clientWidth, this._clientHeight); } this._height = value; GCanvas.GBridge.callResetGlViewport(this.id); this._context.drawingBufferHeight = this._clientHeight * PixelRatio.get(); } getContext(type) { if (type.match(/webgl/i)) { this._context = new GContextWebGL(this); this._context.drawingBufferWidth = this._clientWidth * PixelRatio.get(); this._context.drawingBufferHeight = this._clientHeight * PixelRatio.get(); this._context.componentId = this.id; GCanvas.GBridge.callSetContextType(this.id, 1); // 0 for 2d; 1 for webgl if (!this._disableAutoSwap) { const render = () => { if (this._needRender) { this._context.flushJsCommands2CallNative(); this._needRender = false; } }; setInterval(render, 16); } // On Android, need `sleepMs()` by `for(;;)` to wait enough (or wait until m_requestInitialize be true?) to // let `mProxy->SetClearColor` be invoked in renderLoop() of core/android/3d/view/grenderer.cpp // at the very first, otherwise can't `gl.clearColor` right away on canvas.getContext('webgl') // like https://github.com/flyskywhy/react-native-gcanvas/issues/24 sleepMs(100); if (__DEV__) { // https://github.com/flyskywhy/snakeRN/tree/v3.0.0 sometimes (1st load js on new installed debug apk) // will cause `Error: Invalid value of `0` passed to `checkMaxIfStatementsInShader` in // `node_modules/pixi.js/lib/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js` , // `sleepMs()` by `for(;;)` wait enough can fix it, don't know why. sleepMs(130); } if (this._devicePixelRatio > 0) { GCanvas.GBridge.callSetDevicePixelRatio(this.id, this._devicePixelRatio); } } else if (type.match(/2d/i)) { this._context = new GContext2D(this); this._context.drawingBufferWidth = this._clientWidth * PixelRatio.get(); this._context.drawingBufferHeight = this._clientHeight * PixelRatio.get(); this._context.componentId = this.id; GCanvas.GBridge.callSetContextType(this.id, 0); // need `sleepMs()` by `for(;;)` to let callSetDevicePixelRatio take effect sleepMs(100); if (this._devicePixelRatio > 0) { GCanvas.GBridge.callSetDevicePixelRatio(this.id, this._devicePixelRatio); } this._renderLoopId = requestAnimationFrame(this._renderLoop.bind(this)); } else { throw new Error('not supported context ' + type); } return this._context; } _renderLoop() { this._context.flushJsCommands2CallNative(); this._renderLoopId = requestAnimationFrame(this._renderLoop.bind(this)); } // default 0.92 comes from https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLCanvasElement/toDataURL toDataURL(type = 'image/png', encoderOptions = 0.92) { let quality = encoderOptions < 0.0 ? 0.0 : encoderOptions; quality = quality > 1.0 ? 1.0 : quality; return GCanvas.GBridge.callToDataURL(this.id, type, quality); } reset() { GCanvas.GBridge.callReset(this.id); } }
import { DisplayNews } from "./DisplayNews"; export default DisplayNews;
/* Closure é quando uma função é capaz de "lembrar" e acessar seu escopo léxico mesmo quando ela está sendo executada fora de seu escopo léxico. */ function imprimeNome() { let nome = 'Ayrton'; return function() { return nome; } } var func = imprimeNome(); console.log(func()) console.log(func()) /*Podemos ver que mesmo a let nome estando lá atras essa função ainda se lembra que la atrás ela foi declarada com um nome,isso é closures */ function minhaBiblioteca() { function auxiliar(valor) { return 10 + valor } return { add5() { return auxiliar(5); }, add7() { return auxiliar(7); } } } var biblioteca = minhaBiblioteca(); console.log(biblioteca) console.log(biblioteca.add5()) console.log(biblioteca.add7())
/**! * * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import simpleModel from '../processors/simpleModel' import { customTitleAndKeylabel, divideByOnlyMetric, renameMetric, onlyLatestValues, filterKeepSelectedMetrics, mapInstanceDomains, ceiling, cumulativeTransform, mathValuesSelective, filterAboveMaxInstanceValue, } from '../processors/transforms' import MultiTable from '../components/Charts/MultiTable.jsx' import SimpleTable from '../components/Charts/SimpleTable.jsx' import Heatmap from '../components/Charts/Heatmap.jsx' import HeatmapSettingsModal from '../components/SettingsModals/HeatmapSettingsModal.jsx' import { thresholds, colors } from '../components/Charts/cividis.js' export default function _charts(config) { if (!config.enableBcc) return [] return [ { chartId: 'bcc-biolatency', group: 'BCC/BPF', title: 'biolatency', tooltipText: 'block device I/O latency heatmap', processor: simpleModel, visualisation: Heatmap, metricNames: [ 'bcc.disk.all.latency' ], transforms: [ cumulativeTransform(), ceiling(), mapInstanceDomains('yAxisLabels'), filterAboveMaxInstanceValue(), ], settingsComponent: HeatmapSettingsModal, heatmap: { thresholds, colors }, }, { chartId: 'bcc-gclatency', group: 'BCC/BPF', title: 'gclatency', tooltipText: 'GC latency in several high-level languages', processor: simpleModel, visualisation: Heatmap, metricNames: [ 'bcc.proc.ugc.latency' ], transforms: [ cumulativeTransform(), ceiling(), mapInstanceDomains('yAxisLabels'), filterAboveMaxInstanceValue(), ], settingsComponent: HeatmapSettingsModal, heatmap: { thresholds, colors }, }, { chartId: 'bcc-runqlat', group: 'BCC/BPF', title: 'runqlat', tooltipText: 'run queue latency heatmap', processor: simpleModel, visualisation: Heatmap, metricNames: [ 'bcc.runq.latency' ], transforms: [ cumulativeTransform(), ceiling(), mapInstanceDomains('yAxisLabels'), filterAboveMaxInstanceValue(), ], settingsComponent: HeatmapSettingsModal, heatmap: { thresholds, colors }, }, { chartId: 'bcc-ext4lat', group: 'BCC/BPF', title: 'ext4dist', tooltipText: 'ext4 operation latencies (open, read, write, fsync)', processor: simpleModel, visualisation: Heatmap, metricNames: [ 'bcc.fs.ext4.latency.open', 'bcc.fs.ext4.latency.read', 'bcc.fs.ext4.latency.write', 'bcc.fs.ext4.latency.fsync', ], transforms: [ cumulativeTransform(), ceiling(), filterKeepSelectedMetrics('selectedMetrics'), mapInstanceDomains('yAxisLabels'), filterAboveMaxInstanceValue(), ], settingsComponent: HeatmapSettingsModal, heatmap: { thresholds, colors }, selectedMetrics: [ 'bcc.fs.ext4.latency.open', 'bcc.fs.ext4.latency.read', 'bcc.fs.ext4.latency.write', 'bcc.fs.ext4.latency.fsync', ], }, { chartId: 'bcc-xfslat', group: 'BCC/BPF', title: 'xfsdist', tooltipText: 'xfs operation latencies (open, read, write, fsync)', processor: simpleModel, visualisation: Heatmap, metricNames: [ 'bcc.fs.xfs.latency.open', 'bcc.fs.xfs.latency.read', 'bcc.fs.xfs.latency.write', 'bcc.fs.xfs.latency.fsync', ], transforms: [ cumulativeTransform(), ceiling(), filterKeepSelectedMetrics('selectedMetrics'), mapInstanceDomains('yAxisLabels'), filterAboveMaxInstanceValue(), ], settingsComponent: HeatmapSettingsModal, heatmap: { thresholds, colors }, selectedMetrics: [ 'bcc.fs.xfs.latency.open', 'bcc.fs.xfs.latency.read', 'bcc.fs.xfs.latency.write', 'bcc.fs.xfs.latency.fsync', ], }, { chartId: 'bcc-zfslat', group: 'BCC/BPF', title: 'zfsdist', tooltipText: 'zfs operation latencies (open, read, write, fsync)', processor: simpleModel, visualisation: Heatmap, metricNames: [ 'bcc.fs.zfs.latency.open', 'bcc.fs.zfs.latency.read', 'bcc.fs.zfs.latency.write', 'bcc.fs.zfs.latency.fsync', ], transforms: [ cumulativeTransform(), ceiling(), filterKeepSelectedMetrics('selectedMetrics'), mapInstanceDomains('yAxisLabels'), filterAboveMaxInstanceValue(), ], settingsComponent: HeatmapSettingsModal, heatmap: { thresholds, colors }, selectedMetrics: [ 'bcc.fs.zfs.latency.open', 'bcc.fs.zfs.latency.read', 'bcc.fs.zfs.latency.write', 'bcc.fs.zfs.latency.fsync', ], }, { chartId: 'bcc-tcplife', group: 'BCC/BPF', title: 'tcplife', tooltipText: 'TCP session life and data rates', processor: simpleModel, visualisation: MultiTable, metricNames: [ 'bcc.proc.io.net.tcp.pid', 'bcc.proc.io.net.tcp.comm', 'bcc.proc.io.net.tcp.laddr', 'bcc.proc.io.net.tcp.lport', 'bcc.proc.io.net.tcp.daddr', 'bcc.proc.io.net.tcp.dport', 'bcc.proc.io.net.tcp.tx', 'bcc.proc.io.net.tcp.rx', 'bcc.proc.io.net.tcp.duration', ], transforms: [ onlyLatestValues(), renameMetric({ 'bcc.proc.io.net.tcp.pid': 'PID', 'bcc.proc.io.net.tcp.comm': 'COMM', 'bcc.proc.io.net.tcp.laddr': 'LADDR', 'bcc.proc.io.net.tcp.lport': 'LPORT', 'bcc.proc.io.net.tcp.daddr': 'DADDR', 'bcc.proc.io.net.tcp.dport': 'DPORT', 'bcc.proc.io.net.tcp.tx': 'TX_KB', 'bcc.proc.io.net.tcp.rx': 'RX_KB', 'bcc.proc.io.net.tcp.duration': 'MS' }), divideByOnlyMetric(1024, [ 'TX_KB', 'RX_KB' ]), divideByOnlyMetric(1000, [ 'MS' ]), mathValuesSelective(Math.round, mi => ['TX_KB', 'RX_KB', 'MS'].includes(mi.metric)), ], }, { chartId: 'bcc-execsnoop', group: 'BCC/BPF', title: 'execsnoop', tooltipText: 'trace new process launches', processor: simpleModel, visualisation: MultiTable, metricNames: [ 'bcc.proc.exec.comm', 'bcc.proc.exec.pid', 'bcc.proc.exec.ppid', 'bcc.proc.exec.ret', 'bcc.proc.exec.args', ], transforms: [ onlyLatestValues(), renameMetric({ 'bcc.proc.exec.comm': 'COMM', 'bcc.proc.exec.pid': 'PID', 'bcc.proc.exec.ppid': 'PPID', 'bcc.proc.exec.ret': 'RET', 'bcc.proc.exec.args': 'ARGS', }), ], }, { chartId: 'bcc-tcpretrans', group: 'BCC/BPF', title: 'tcpretrans', tooltipText: 'TCP retransmit counts', processor: simpleModel, visualisation: SimpleTable, metricNames: [ 'bcc.io.net.tcp.retrans.count', ], transforms: [ mapInstanceDomains(), customTitleAndKeylabel((metric, instance) => instance), onlyLatestValues(), ], }, // TODO test biotop (could not get it working on my machine) { chartId: 'bcc-biotop', group: 'BCC/BPF', title: 'biotop', tooltipText: 'block device I/O "top"', processor: simpleModel, visualisation: MultiTable, metricNames: [ 'bcc.proc.io.perdev.pid', 'bcc.proc.io.perdev.comm', 'bcc.proc.io.perdev.direction', 'bcc.proc.io.perdev.major', 'bcc.proc.io.perdev.minor', 'bcc.proc.io.perdev.disk', 'bcc.proc.io.perdev.io', 'bcc.proc.io.perdev.bytes', 'bcc.proc.io.perdev.duration', ], transforms: [ onlyLatestValues(), renameMetric({ 'bcc.proc.io.perdev.pid': 'PID', 'bcc.proc.io.perdev.comm': 'COMM', 'bcc.proc.io.perdev.direction': 'D', 'bcc.proc.io.perdev.major': 'MAJ', 'bcc.proc.io.perdev.minor': 'MIN', 'bcc.proc.io.perdev.disk': 'DISK', 'bcc.proc.io.perdev.io': 'I/O', 'bcc.proc.io.perdev.bytes': 'Kbytes', // will be shortly 'bcc.proc.io.perdev.duration': 'AVGms', // will be shortly }), divideByOnlyMetric(1024, [ 'Kbytes' ]), divideByOnlyMetric(1000, [ 'AVGms' ]), mathValuesSelective(Math.round, mi => ['Kbytes', 'AVGms'].includes(mi.metric)), ], }, { chartId: 'bcc-tcptop', group: 'BCC/BPF', title: 'tcptop', tooltipText: 'tcp throughput "top"', processor: simpleModel, visualisation: MultiTable, metricNames: [ 'bcc.proc.io.net.tcptop.pid', 'bcc.proc.io.net.tcptop.comm', 'bcc.proc.io.net.tcptop.laddr', 'bcc.proc.io.net.tcptop.lport', 'bcc.proc.io.net.tcptop.daddr', 'bcc.proc.io.net.tcptop.dport', 'bcc.proc.io.net.tcptop.rx', 'bcc.proc.io.net.tcptop.tx', ], transforms: [ onlyLatestValues(), renameMetric({ 'bcc.proc.io.net.tcptop.pid': 'PID', 'bcc.proc.io.net.tcptop.comm': 'COMM', 'bcc.proc.io.net.tcptop.laddr': 'LADDR', 'bcc.proc.io.net.tcptop.lport': 'LPORT', 'bcc.proc.io.net.tcptop.daddr': 'DADDR', 'bcc.proc.io.net.tcptop.dport': 'DPORT', 'bcc.proc.io.net.tcptop.rx': 'RX_KB', 'bcc.proc.io.net.tcptop.tx': 'TX_KB', }), divideByOnlyMetric(1024, [ 'TX_KB', 'RX_KB' ]), mathValuesSelective(Math.round, mi => ['TX_KB', 'RX_KB'].includes(mi.metric)), ], }, { chartId: 'bcc-tracepoint-hits', group: 'BCC/BPF', title: 'tracepoint hits', tooltipText: 'kernel tracepoint hit counts', processor: simpleModel, visualisation: SimpleTable, metricNames: [ 'bcc.tracepoint.hits', ], transforms: [ mapInstanceDomains(), customTitleAndKeylabel((metric, instance) => instance), onlyLatestValues(), ], }, { chartId: 'bcc-usdt-hits', group: 'BCC/BPF', title: 'USDT hits', tooltipText: 'user-level statically defined tracepoint hit counts', processor: simpleModel, visualisation: SimpleTable, metricNames: [ 'bcc.usdt.hits', ], transforms: [ mapInstanceDomains(), customTitleAndKeylabel((metric, instance) => instance), onlyLatestValues(), ], }, { chartId: 'bcc-uprobe-hits', group: 'BCC/BPF', title: 'uprobe hits', tooltipText: 'uprobe hit counts', processor: simpleModel, visualisation: SimpleTable, metricNames: [ 'bcc.uprobe.hits', ], transforms: [ mapInstanceDomains(), customTitleAndKeylabel((metric, instance) => instance), onlyLatestValues(), ], }, ] }
/* v----- Do not change anything between here * (the DRIVERNAME placeholder will be automatically replaced during build) */ define('ui/components/machine/driver-%%DRIVERNAME%%/component', ['exports', 'ember', 'ui/mixins/driver'], function (exports, _ember, _uiMixinsDriver) { exports['default'] = _ember['default'].Component.extend(_uiMixinsDriver['default'], { /* ^--- And here */ // Write your component here, starting with setting 'model' to a machine with your config populated driverName: '%%DRIVERNAME%%', //state manage variables of static data. gotStaticData: false, //assign method systemStorageAssign: 'new', dataStorageAssign: 'new', //view control. systemStorageDisable: '', ibaDisable: 'disabled', restoreImageDisable: 'disabled', ibbDisable: 'disabled', dataStorageDisable: '', willRender() { if (!this.get('gotStaticData')) { let staticData = { "systemStorageType": { "types": [ { "label": "", "value": "" }, { "label": "S30GB/CentOS7 :64bit", "value": "S30GB_CENTOS7_64" }, { "label": "S30GB/CentOS6 :64bit", "value": "S30GB_CENTOS6_64" }, { "label": "S30GB/RHEL7 :64bit", "value": "S30GB_RHEL7_64" }, { "label": "S30GB/RHEL6 :64bit", "value": "S30GB_RHEL6_64" }, { "label": "S30GB/Ubuntu16 :64bit", "value": "S30GB_UBUNTU16_64" }, { "label": "S30GB/Ubuntu14 :64bit", "value": "S30GB_UBUNTU14_64" } ] }, "serverType": { "types": [ { "label": "", "value": "" }, { "label": "VB0-1", "value": "VB0-1" }, { "label": "VB1-2", "value": "VB1-2" }, { "label": "VB2-3", "value": "VB2-3" }, { "label": "VB4-6", "value": "VB4-6" }, { "label": "VB8-12", "value": "VB8-12" }, { "label": "VB12-24", "value": "VB12-24" }, { "label": "VB1-1", "value": "VB1-1" }, { "label": "VB2-2", "value": "VB2-2" }, { "label": "VB4-3", "value": "VB4-3" }, { "label": "VB8-6", "value": "VB8-6" }, { "label": "VB12-12", "value": "VB12-12" }, { "label": "VB0-2", "value": "VB0-2" }, { "label": "VB1-3", "value": "VB1-3" }, { "label": "VB2-6", "value": "VB2-6" }, { "label": "VB4-12", "value": "VB4-12" }, { "label": "VB8-24", "value": "VB8-24" }, { "label": "VD16-96-SSD", "value": "VD16-96-SSD" }, { "label": "VD16-192-FIPX", "value": "VD16-192-FIPX" }, { "label": "VG1-3", "value": "VG1-3" }, { "label": "VG2-6", "value": "VG2-6" }, { "label": "VG4-12", "value": "VG4-12" }, { "label": "VG6-24", "value": "VG6-24" }, { "label": "VG8-32", "value": "VG8-32" }, { "label": "VG12-48", "value": "VG12-48" }, { "label": "VG2-3", "value": "VG2-3" }, { "label": "VG4-6", "value": "VG4-6" }, { "label": "VG6-12", "value": "VG6-12" }, { "label": "VG8-24", "value": "VG8-24" }, { "label": "VG12-32", "value": "VG12-32" }, { "label": "VG1-6", "value": "VG1-6" }, { "label": "VG2-12", "value": "VG2-12" }, { "label": "VG4-24", "value": "VG4-24" }, { "label": "VG6-32", "value": "VG6-32" }, { "label": "VG8-48", "value": "VG8-48" } ] }, "serverGroup": { "groups": [ { "label": "", "value": "" }, { "label": "A", "value": "A" }, { "label": "B", "value": "B" } ] }, "dataStorageType": { "types": [ { "label": "", "value": "" }, { "label": "G100GB:IOPS1000", "value": "G100GB_IOPS1000" }, { "label": "G100GB:IOPS2000", "value": "G100GB_IOPS2000" }, { "label": "G300GB:IOPS1000", "value": "G300GB_IOPS1000" }, { "label": "G300GB:IOPS2000", "value": "G300GB_IOPS2000" }, { "label": "G300GB:IOPS3000", "value": "G300GB_IOPS3000" }, { "label": "G500GB:IOPS2000", "value": "G500GB_IOPS2000" }, { "label": "G500GB:IOPS3000", "value": "G500GB_IOPS3000" }, { "label": "G500GB:IOPS4000", "value": "G500GB_IOPS4000" }, { "label": "G1000GB:IOPS3000", "value": "G1000GB_IOPS3000" }, { "label": "G1000GB:IOPS4000", "value": "G1000GB_IOPS4000" }, { "label": "G1000GB:IOPS5000", "value": "G1000GB_IOPS5000" }, { "label": "B100GB", "value": "B100GB" }, { "label": "B300GB", "value": "B300GB" }, { "label": "B500GB", "value": "B500GB" }, { "label": "B1000GB", "value": "B1000GB" } ] }, "storageGroup": { "groups": [ { "label": "", "value": "" }, { "label": "Y", "value": "Y" }, { "label": "Z", "value": "Z" } ] } }; this.set('model.static', staticData); this.set('gotStaticData', true) } }, bootstrap: function () { let config = this.get('store').createRecord({ type: '%%DRIVERNAME%%Config', //Account gis: '', accessKey: '', secretKey: '', //Instance serverType: '', serverGroup: '', ivm: '', //dose not set value. //storage group storageGroup: '', //System Dtorage imageName: '',//NEW SYSTEM Image iba: '', //Attach Already existing storage customImage: '', //CustomeImgae ID(format iarXXXXX,nnnnn) iar:'', customImageId: '', //restoreId: '',//Restore //Data Storage ibb: '', dataStorage: '', //Network privateOnly: '', dockerPort: 2376, extraPorts: "500/udp,4500/udp", replyAnyArp: true }); let type = 'host'; if (!this.get('useHost')) { type = 'machine'; } this.set('model', this.get('store').createRecord({ type: type, '%%DRIVERNAME%%Config': config, })); }, // Add custom validation beyond what can be done from the config API schema validate() { // Get generic API validation errors this._super(); var errors = this.get('errors') || []; // Add more specific errors // mandatory if (!this.get('model.%%DRIVERNAME%%Config.gis')) { errors.push('Service Code is required'); } if (!this.get('model.%%DRIVERNAME%%Config.accessKey')) { errors.push('Access Key ID is required'); } if (!this.get('model.%%DRIVERNAME%%Config.secretKey')) { errors.push('Secret Key is required'); } var systemStorageAssignMethod = this.get('systemStorageAssign'); switch (systemStorageAssignMethod) { case 'new' : this.set('model.%%DRIVERNAME%%Config.iba', ''); this.set('model.%%DRIVERNAME%%Config.customImage', ''); this.set('model.%%DRIVERNAME%%Config.iar', ''); this.set('model.%%DRIVERNAME%%Config.customImageId', ''); break; case 'restore' : var chkError = false; if (!this.get('model.%%DRIVERNAME%%Config.iar')) { errors.push('Storage Archive Service Code is required'); chkError = true; } if (!this.get('model.%%DRIVERNAME%%Config.customImageId')) { errors.push('Storage Archive Image ID is required'); chkError = true; } if(chkError) { break; } this.set('model.%%DRIVERNAME%%Config.customImage', this.get('model.%%DRIVERNAME%%Config.iar') + "," +this.get('model.%%DRIVERNAME%%Config.customImageId')); this.set('model.%%DRIVERNAME%%Config.iba', ''); this.set('model.%%DRIVERNAME%%Config.imageName', ''); this.$('#systemStorageSB').each(function () { this.selectedIndex = 0; }); break; case 'assign' : if (!this.get('model.%%DRIVERNAME%%Config.iba')) { errors.push('System Storage Service Code is required'); break; } this.set('model.%%DRIVERNAME%%Config.imageName', ''); this.set('model.%%DRIVERNAME%%Config.customImage', ''); this.set('model.%%DRIVERNAME%%Config.iar', ''); this.set('model.%%DRIVERNAME%%Config.customImageId', ''); this.$('#systemStorageSB').each(function () { this.selectedIndex = 0; }); break; } var dataStorageAssignMethod = this.get('dataStorageAssign'); switch (dataStorageAssignMethod) { case 'new' : this.set('model.%%DRIVERNAME%%Config.ibb', ''); break; case 'assign' : if (!this.get('model.%%DRIVERNAME%%Config.ibb')) { errors.push('Data Storage Type is required'); break; } this.set('model.%%DRIVERNAME%%Config.imageName', ''); this.$('#dataStorageSB').each(function () { this.selectedIndex = 0; }); break; } //for debug console.debug('gis=' + this.get('model.%%DRIVERNAME%%Config.gis')); console.debug('accessKey=' + this.get('model.%%DRIVERNAME%%Config.accessKey')); console.debug('secretKey=' + this.get('model.%%DRIVERNAME%%Config.secretKey')); console.debug('serverType=' + this.get('model.%%DRIVERNAME%%Config.serverType')); console.debug('serverGroup=' + this.get('model.%%DRIVERNAME%%Config.serverGroup')); console.debug('ivm=' + this.get('model.%%DRIVERNAME%%Config.ivm')); console.debug('storageGroup=' + this.get('model.%%DRIVERNAME%%Config.storageGroup')); console.debug('imageName=' + this.get('model.%%DRIVERNAME%%Config.imageName')); console.debug('iba=' + this.get('model.%%DRIVERNAME%%Config.iba')); console.debug('customImage=' + this.get('model.%%DRIVERNAME%%Config.customImage')); console.debug('iar=' + this.get('model.%%DRIVERNAME%%Config.iar')); console.debug('customImageId=' + this.get('model.%%DRIVERNAME%%Config.customImageId')); console.debug('ibb=' + this.get('model.%%DRIVERNAME%%Config.ibb')); console.debug('dataStorage=' + this.get('model.%%DRIVERNAME%%Config.dataStorage')); console.debug('privateOnly=' + this.get('model.%%DRIVERNAME%%Config.privateOnly')); console.debug('iba=' + this.get('model.%%DRIVERNAME%%Config.iba')); console.debug('dockerPort=' + this.get('model.%%DRIVERNAME%%Config.dockerPort')); console.debug('extraPorts=' + this.get('model.%%DRIVERNAME%%Config.extraPorts')); console.debug('replyAnyArp=' + this.get('model.%%DRIVERNAME%%Config.replyAnyArp')); // Check something and add an error entry if it fails: if (parseInt(this.get('model.%%DRIVERNAME%%Config.size'), 10) < 1024) { errors.push('Size must be at least 1024 MB'); } // Set the array of errors for display, // and return true if saving should continue. if (errors.get('length')) { this.set('errors', errors); return false; } else { this.set('errors', null); return true; } }, actions: { selectStorageAttach: function (value) { switch (value) { case 'new': this.set('systemStorageAssign', value); this.set('systemStorageDisable', ''); this.set('ibaDisable', 'disabled'); this.set('restoreImageDisable', 'disabled'); break; case 'restore': this.set('systemStorageAssign', value); this.set('systemStorageDisable', 'disabled'); this.set('ibaDisable', 'disabled'); this.set('restoreImageDisable', ''); break; case 'assign': this.set('systemStorageAssign', value); this.set('systemStorageDisable', 'disabled'); this.set('ibaDisable', ''); this.set('restoreImageDisable', 'disabled'); break; } }, selectDataStorageAttach: function (value) { switch (value) { case 'new': this.set('dataStorageAssign', value); this.set('dataStorageDisable', ''); this.set('ibbDisable', 'disabled'); break; case 'assign': this.set('dataStorageAssign', value); this.set('dataStorageDisable', 'disabled'); this.set('ibbDisable', ''); break; } }, selectImageType: function (value) { console.debug('imageType=' + value); this.set('model.%%DRIVERNAME%%Config.imageName', value) }, selectServerType: function (value) { console.debug('serverType=' + value); this.set('model.%%DRIVERNAME%%Config.serverType', value) }, selectServerGroup: function (value) { //console.debug('serverGroup=' + value); this.set('model.%%DRIVERNAME%%Config.serverGroup', value) }, selectStorageGroup: function (value) { console.debug('storageGroup=' + value); this.set('model.%%DRIVERNAME%%Config.storageGroup', value) }, selectDataStorageType: function (value) { console.debug('dataStorageType=' + value); this.set('model.%%DRIVERNAME%%Config.dataStorage', value) } }, }); });
/* eslint-disable no-unused-expressions */ var expect = require('chai').expect; var m = require('mongoose'); var groupSchema = require('../../src/models/group'); describe('group.js', function () { var groupId = m.Types.ObjectId(); var memberId1 = m.Types.ObjectId(); var memberId2 = m.Types.ObjectId(); var memberId3 = m.Types.ObjectId(); var nonMember1 = m.Types.ObjectId(); it('should create a group', function (done) { groupSchema.create( { _id: groupId, name: 'Test Group', members: [memberId1, memberId2, memberId3], sendMailTo: [], }, function (err, group) { expect(err).to.not.exist; expect(group).to.be.a('object'); expect(group._doc).to.include.keys('_id', 'name', 'members', 'sendMailTo'); done(); } ); }); it('should get all groups', function (done) { groupSchema.getAllGroups(function (err, group) { expect(err).to.not.exist; expect(group).to.have.length(2); done(); }); }); it('should get group by id', function (done) { groupSchema.getGroupById(groupId, function (err, groups) { expect(err).to.not.exist; expect(groups).to.be.a('object'); done(); }); }); it('should add group member', function (done) { groupSchema.getGroupByName('Test Group', function (err, group) { expect(err).to.not.exist; expect(group).to.be.a('object'); group.addMember(nonMember1, function (err, success) { expect(err).to.not.exist; expect(success).to.equal(true); group.addMember(memberId1, function (err, success) { expect(err).to.not.exist; expect(success).to.equal(true); done(); }); }); }); }); it('should remove group member', function (done) { groupSchema.getGroupByName('Test Group', function (err, group) { expect(err).to.not.exist; expect(group).to.be.a('object'); var mem = { _id: memberId2, }; group.members = [mem]; group.removeMember(memberId2, function (err, success) { expect(err).to.not.exist; expect(success).to.equal(true); done(); }); }); }); });
export default { install: function (Vue, myGate, name = "$gate") { Object.defineProperty(Vue.prototype, name, {value: myGate}); } };
import colors from 'colors'; /* eslint-disable no-console */ console.log('Starting app in dev mode...'.green);
const getScripts = async () => { const package$ = await import("./package.json") return package$.scripts } const isOdd = n => !!(n % 2) const mapArgsToMap = args => { const res = args.map((n, i, arr) => { if (isOdd(i)) { console.log(arr[i - 1].match(/^-|^--/)) return [ arr[i - 1] .trim() .replace(/^--|^-/g, "") .trim(), n ] } }) return new Map(res.filter(Boolean)) } const argvMap = mapArgsToMap(process.argv.slice(2)) const scriptToRun = argvMap.get("s") const { exec } = require("child_process") getScripts().then(script => exec(script[scriptToRun]))
function Sandbox(url) { 'use strict'; function send(data) { source.postMessage(data, frameHost); } var iframe = document.createElement('iframe'); frameHost = location.origin, iframe.src = jsbin.root + '/sandbox.html?' + url, body = document.body, source = null, guid = +new Date(), callbacks = {}, queue = new Queue(send); iframe.style.display = 'none'; body.appendChild(iframe); window.addEventListener('message', function (event) { var result; if (event.origin === frameHost) { if (event.data === '__pong__') { source = event.source; queue.ready(); } else { result = JSON.parse(event.data); if (callbacks[result.guid]) { callbacks[result.guid](result.data); } } } }, false); iframe.onload = function () { iframe.contentWindow.postMessage('__ping__', frameHost); }; return { get: function (what, callback) { guid++; callbacks[guid] = callback; queue.push(JSON.stringify({ guid: guid, what: what })); } }; }
export class UserDataController { static get() { return axios.post("/user/data/getdata") } }
import { dist, resolve, src } from './conf'; import baseConfig from './webpack.config.base'; import { theme } from './theme'; import webpack from 'webpack'; import webpackMerge from 'webpack-merge'; const PORT = 4000; // 服务器端口 const HOST = '0.0.0.0'; export default webpackMerge(baseConfig, { entry: { index: resolve(src + '/index.js') // 主网站入口 }, module: { rules: [ { test: /\.(css|less)$/, include: resolve('../node_modules'), use: [ { loader: 'style-loader' }, { loader: 'css-loader', options: { sourceMap: true } }, { loader: 'postcss-loader', options: { sourceMap: true } }, { loader: 'less-loader', options: { sourceMap: true, javascriptEnabled: true, modifyVars: theme } } ] }, { test: /\.(css|less)$/, include: resolve(src), use: [ { loader: 'style-loader' }, { loader: 'css-loader', options: { sourceMap: true } }, { loader: 'postcss-loader', options: { sourceMap: true } }, { loader: 'less-loader', options: { sourceMap: true, javascriptEnabled: true, modifyVars: theme } } ] } ] }, devtool: 'cheap-module-eval-source-map', plugins: [ // 出错不终止插件 new webpack.NoEmitOnErrorsPlugin(), // 配置全局变量 new webpack.DefinePlugin({ __DEV__: true }), new webpack.HotModuleReplacementPlugin() //热加载插件 ], devServer: { // 服务器 host: HOST, port: PORT, inline: true, hot: true, // 热更新模式 historyApiFallback: true, // using html5 router. contentBase: resolve('../web') // 网站目录 // proxy: { // '/api': { // target: 'http://localhost:8080/api', // changeOrigin: true // } // } } });
class Vec3 { constructor(x, y, z) { this.x = x; this.y = y; this.z = z; } cross(v) { if (!(v instanceof Vec3)) { throw new Error('Input argument must be of type Vec3'); } const t = this; return new Vec3( (t.y * v.z) - (t.z * v.y), (t.z * v.x) - (t.x * v.z), (t.x * v.y) - (t.y * v.x) ); } mult(a) { return this.map(x => x * a); } neg() { return this.map(x => -x); } map(f) { return new Vec3(f(this.x), f(this.y), f(this.z)); } add(v) { if (v instanceof Vec3) { return new Vec3(this.x + v.x, this.y + v.y, this.z + v.z); } return this.map(x => x + v); } sub(v) { if (v instanceof Vec3) { return new Vec3(this.x - v.x, this.y - v.y, this.z - v.z); } return this.map(x => x - v); } dot(v) { return (this.x * v.x) + (this.y * v.y) + (this.z * v.z); } toString() { return `[${this.x}, ${this.y}, ${this.z}]`; } lengthSquared() { return this.dot(this); } length() { return Math.sqrt(this.lengthSquared()); } normalize() { return this.mult(1 / this.length()); } asArray() { return [this.x, this.y, this.z]; } round() { return this.map(Math.round); } } export default Vec3;
/** * Copyright 2020 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {ContextNode} from '../../../src/context/node'; import {deepScan, findParent} from '../../../src/context/scan'; import {domOrderComparator} from '../../../src/core/dom'; describes.realWin('ContextNode', {}, (env) => { let win, doc; let tree; let clock; let discoverWrapper; beforeEach(() => { win = env.win; doc = win.document; clock = env.sandbox.useFakeTimers(); tree = (() => { function createSubtree(id, children, depth) { const el = doc.createElement('div'); el.id = id; el.textContent = id; if (depth > 1) { for (let i = 0; i < children; i++) { const child = createSubtree(`${id}-${i + 1}`, children, depth - 1); el.appendChild(child); } } return el; } return createSubtree('T', 4, 4); })(); discoverWrapper = wrapper(ContextNode.prototype, 'discover_'); // Customize output of the ContextNode for easy debug. ContextNode.prototype.inspect = function () { const contextNode = this; return `ContextNode(${contextNode.node.id || contextNode.node.nodeName})`; }; }); afterEach(() => { delete ContextNode.prototype.inspect; }); function el(id) { if (id == 'T') { return tree; } const found = tree.querySelector(`#${id}`); if (!found) { throw new Error(`element not found ${id}`); } return found; } /** * @param {Object} obj * @param {string} name */ function wrapper(obj, name) { const original = obj[name]; const stub = env.sandbox.stub(ContextNode.prototype, name); const wrapperName = `__wrapper_${name}`; stub.callsFake(function (...args) { const obj = this; const resolvers = obj[wrapperName] ?? (obj[wrapperName] = []); const result = original.apply(this, args); const current = resolvers.slice(0); resolvers.length = 0; current.forEach((resolver) => resolver(result)); return result; }); return { spy: stub, waitFor: (obj) => { const resolvers = obj[wrapperName] ?? (obj[wrapperName] = []); return new Promise((resolve) => { resolvers.push(resolve); }); }, }; } function waitForDiscover(...nodesOrContextNodes) { const contextNodes = nodesOrContextNodes.map((arg) => arg.nodeType ? ContextNode.get(arg) : arg ); const promises = contextNodes.map((contextNode) => discoverWrapper.waitFor(contextNode) ); clock.tick(1); return Promise.all(promises); } function rediscover(...nodesOrContextNodes) { const contextNodes = nodesOrContextNodes.map((arg) => arg.nodeType ? ContextNode.get(arg) : arg ); contextNodes.forEach((cn) => cn.discover()); return waitForDiscover.apply(null, contextNodes); } function expectContext(nodeOrContext, spec) { const contextNode = nodeOrContext.nodeType ? ContextNode.get(nodeOrContext) : nodeOrContext; if (spec.isRoot !== undefined) { expect(contextNode.isRoot, 'isRoot').to.equal(spec.isRoot); } if (spec.root !== undefined) { const {root} = contextNode; expect((root && root.node) ?? null, 'root').to.equal(spec.root); } if (spec.discoverable !== undefined) { expect(contextNode.isDiscoverable(), 'discoverable').to.equal( spec.discoverable ); } if (spec.parent !== undefined) { const {parent} = contextNode; const parentNode = (parent && parent.node) ?? null; const specNode = ((spec.parent && spec.parent.node) || spec.parent) ?? null; expect(parentNode, 'parent').to.equal(specNode); } if (spec.children !== undefined) { const children = (contextNode.children || []).map((cn) => cn.node || cn); children.sort(domOrderComparator); const specChildren = spec.children.slice(0); specChildren.sort(domOrderComparator); expect(children, 'children').to.deep.equal(specChildren); } } describe('ContextNode.get', () => { it('should create an element node', () => { const el = doc.createElement('div'); const cn = ContextNode.get(el); expect(cn.node).to.equal(el); // Parent always starts as null. expectContext(cn, { parent: null, isRoot: false, root: null, children: [], discoverable: true, }); }); it('should create a fragment node', () => { const frag = doc.createDocumentFragment(); const cn = ContextNode.get(frag); expect(cn.node).to.equal(frag); // Parent always starts as null. expectContext(cn, { parent: null, isRoot: false, root: null, children: [], discoverable: true, }); }); it('should create a document node', () => { const cn = ContextNode.get(doc); expect(cn.node).to.equal(doc); // Parent always starts as null. expectContext(cn, { parent: null, isRoot: true, root: doc, children: [], discoverable: false, }); }); it('should create a node only once', () => { const el = doc.createElement('div'); const frag = doc.createDocumentFragment(); const cn1 = ContextNode.get(el); const cn2 = ContextNode.get(frag); const cn3 = ContextNode.get(doc); expect(cn1).to.equal(ContextNode.get(el)); expect(cn2).to.equal(ContextNode.get(frag)); expect(cn3).to.equal(ContextNode.get(doc)); }); }); describe('ContextNode.closest', () => { let element; let grandparent; beforeEach(() => { element = el('T-1-1-1'); grandparent = el('T-1'); }); it('should find itself', () => { const elementContext = ContextNode.get(element); expect(ContextNode.closest(element)).to.equal(elementContext); }); it('should skip itself', () => { ContextNode.get(element); const grandparentContext = ContextNode.get(grandparent); expect(ContextNode.closest(element, false)).to.equal(grandparentContext); expect(ContextNode.closest(grandparent, false)).to.be.null; }); it('should go up DOM tree', () => { const grandparentContext = ContextNode.get(grandparent); expect(ContextNode.closest(element)).to.equal(grandparentContext); }); it('should auto-create root when connected', () => { doc.body.appendChild(tree); expect(ContextNode.closest(element)).to.equal(ContextNode.get(doc)); expectContext(ContextNode.get(doc), {isRoot: true}); }); it('should auto-create root on a fragment', () => { const frag = doc.createDocumentFragment(); frag.appendChild(tree); expect(ContextNode.closest(element)).to.equal(ContextNode.get(frag)); expectContext(ContextNode.get(frag), { isRoot: false, root: null, parent: null, }); }); it('should auto-create a custom AMP element', () => { const ampElement = doc.createElement('amp-element'); ampElement.appendChild(tree); expect(ContextNode.closest(element)).to.equal( ContextNode.get(ampElement) ); expectContext(ContextNode.get(ampElement), { isRoot: false, root: null, parent: null, }); }); }); describe('discover', () => { let sibling1; let sibling2; let cousin1; let parent; let grandparent; beforeEach(() => { sibling1 = el('T-1-1-1'); sibling2 = el('T-1-1-2'); cousin1 = el('T-1-2-1'); parent = el('T-1-1'); grandparent = el('T-1'); }); it('should be created in an undiscovered mode', () => { expectContext(sibling1, {parent: null, discoverable: true}); expectContext(sibling2, {parent: null, discoverable: true}); expectContext(cousin1, {parent: null, discoverable: true}); }); describe('disconnected tree', () => { beforeEach(async () => { await waitForDiscover(sibling1, sibling2, cousin1); }); it('should not auto-discover an orphan', async () => { expectContext(sibling1, { parent: null, children: [], root: null, isRoot: false, discoverable: true, }); expectContext(sibling2, { parent: null, children: [], root: null, isRoot: false, discoverable: true, }); expectContext(cousin1, { parent: null, children: [], root: null, isRoot: false, discoverable: true, }); }); it('should auto-discover the grandparent', async () => { await waitForDiscover(grandparent); await rediscover(sibling1, sibling2, cousin1); expectContext(sibling1, { isRoot: false, root: null, parent: grandparent, children: [], discoverable: true, }); expectContext(sibling2, { isRoot: false, root: null, parent: grandparent, children: [], discoverable: true, }); expectContext(cousin1, { isRoot: false, root: null, parent: grandparent, children: [], discoverable: true, }); expectContext(grandparent, { isRoot: false, root: null, parent: null, children: [sibling1, sibling2, cousin1], discoverable: true, }); const element3 = el('T-1-1-3'); await waitForDiscover(element3); expectContext(element3, { isRoot: false, root: null, parent: grandparent, children: [], discoverable: true, }); expectContext(grandparent, { isRoot: false, root: null, parent: null, children: [sibling1, sibling2, cousin1, element3], discoverable: true, }); }); it('should insert an intermediary parent', async () => { await waitForDiscover(grandparent); await rediscover(sibling1, sibling2, cousin1); expectContext(sibling1, {parent: grandparent}); expectContext(sibling2, {parent: grandparent}); expectContext(cousin1, {parent: grandparent}); await waitForDiscover(parent); expectContext(sibling1, { parent, children: [], isRoot: false, root: null, discoverable: true, }); expectContext(sibling2, { parent, children: [], isRoot: false, root: null, discoverable: true, }); expectContext(parent, { parent: grandparent, children: [sibling1, sibling2], isRoot: false, root: null, discoverable: true, }); expectContext(grandparent, { parent: null, children: [parent, cousin1], isRoot: false, root: null, discoverable: true, }); }); it('should assign/unassign a slot', async () => { await waitForDiscover(grandparent, parent); await rediscover(sibling1, sibling2, cousin1); expectContext(sibling1, {parent}); expectContext(sibling2, {parent}); expectContext(cousin1, {grandparent}); expectContext(grandparent, {children: [parent, cousin1]}); expectContext(parent, {children: [sibling1, sibling2]}); // Slot cousin1 under parent. ContextNode.assignSlot(cousin1, el('T-1-1-3')); await rediscover(cousin1); expectContext(cousin1, {parent}); expectContext(grandparent, {children: [parent]}); expectContext(parent, {children: [sibling1, sibling2, cousin1]}); // Unslot cousin1. ContextNode.unassignSlot(cousin1, el('T-1-1-3')); await rediscover(cousin1); expectContext(cousin1, {parent: grandparent}); expectContext(grandparent, {children: [parent, cousin1]}); expectContext(parent, {children: [sibling1, sibling2]}); }); it('should assign/unassign a slot in Shadow DOM', async () => { if (Element.prototype.attachShadow) { return; } await waitForDiscover(grandparent, parent); const grandchild = doc.createElement('div'); sibling1.appendChild(grandchild); await waitForDiscover(grandchild); const shadowRoot = sibling1.attachShadow({mode: 'open'}); await waitForDiscover(shadowRoot); expectContext(grandchild, {parent: sibling1}); expectContext(sibling1, {children: [grandchild, shadowRoot]}); expectContext(shadowRoot, {children: [], parent: sibling1}); // Slot. const slot = doc.createElement('slot'); shadowRoot.appendChild(slot); await rediscover(grandchild); expectContext(grandchild, {parent: shadowRoot}); expectContext(sibling1, {children: [shadowRoot]}); expectContext(shadowRoot, {children: [grandchild], parent: sibling1}); // Unslot. shadowRoot.removeChild(slot); await rediscover(grandchild); expectContext(grandchild, {parent: sibling1}); expectContext(sibling1, {children: [grandchild, shadowRoot]}); expectContext(shadowRoot, {children: [], parent: sibling1}); }); it('should override the root', async () => { await waitForDiscover(grandparent, parent); await rediscover(sibling1, sibling2, cousin1); ContextNode.get(grandparent).setIsRoot(true); expectContext(grandparent, { parent: null, children: [parent, cousin1], isRoot: true, root: grandparent, discoverable: false, }); expectContext(parent, { parent: grandparent, children: [sibling1, sibling2], isRoot: false, root: grandparent, discoverable: true, }); expectContext(sibling1, { parent, children: [], isRoot: false, root: grandparent, discoverable: true, }); expectContext(sibling2, { parent, children: [], isRoot: false, root: grandparent, discoverable: true, }); expectContext(cousin1, { parent: grandparent, children: [], isRoot: false, root: grandparent, discoverable: true, }); }); it('should override the parent', async () => { await waitForDiscover(grandparent); await rediscover(sibling1, sibling2, cousin1); expectContext(sibling1, {parent: grandparent}); expectContext(sibling2, {parent: grandparent}); expectContext(cousin1, {parent: grandparent}); ContextNode.get(sibling2).setParent(sibling1); expectContext(sibling2, { parent: sibling1, children: [], discoverable: false, }); expectContext(sibling1, { parent: grandparent, children: [sibling2], discoverable: true, }); expectContext(grandparent, { children: [sibling1, cousin1], discoverable: true, }); }); }); describe('tree connected later', () => { beforeEach(async () => { await waitForDiscover(sibling1, sibling2, cousin1); }); function connectTree() { doc.body.appendChild(tree); return ContextNode.get(doc); } it('should configure the root', async () => { expectContext(connectTree(), { discoverable: false, isRoot: true, root: doc, parent: null, children: [], }); }); it('should auto-discover an orphan', async () => { expectContext(sibling1, {parent: null, root: null}); expectContext(sibling2, {parent: null, root: null}); expectContext(cousin1, {parent: null, root: null}); connectTree(); await rediscover(sibling1, sibling2, cousin1); expectContext(sibling1, { parent: doc, root: doc, children: [], isRoot: false, discoverable: true, }); expectContext(sibling2, { parent: doc, root: doc, children: [], isRoot: false, discoverable: true, }); expectContext(cousin1, { parent: doc, root: doc, children: [], isRoot: false, discoverable: true, }); expectContext(doc, { isRoot: true, root: doc, parent: null, children: [sibling1, sibling2, cousin1], }); }); it('should auto-discover the grandparent', async () => { await waitForDiscover(grandparent); await rediscover(sibling1, sibling2, cousin1); connectTree(); await rediscover(grandparent); expectContext(doc, { isRoot: true, root: doc, parent: null, children: [grandparent], discoverable: false, }); expectContext(grandparent, { isRoot: false, root: doc, parent: doc, children: [sibling1, sibling2, cousin1], discoverable: true, }); expectContext(sibling1, { isRoot: false, root: doc, parent: grandparent, children: [], discoverable: true, }); expectContext(sibling2, { isRoot: false, root: doc, parent: grandparent, children: [], discoverable: true, }); expectContext(cousin1, { isRoot: false, root: doc, parent: grandparent, children: [], discoverable: true, }); }); it('should insert an intermediary parent', async () => { await waitForDiscover(grandparent, parent); await rediscover(sibling1, sibling2, cousin1); connectTree(); await rediscover(grandparent); expectContext(doc, { parent: null, children: [grandparent], isRoot: true, root: doc, discoverable: false, }); expectContext(grandparent, { parent: doc, children: [parent, cousin1], isRoot: false, root: doc, discoverable: true, }); expectContext(parent, { parent: grandparent, children: [sibling1, sibling2], isRoot: false, root: doc, discoverable: true, }); expectContext(sibling1, { parent, children: [], isRoot: false, root: doc, discoverable: true, }); expectContext(sibling2, { parent, children: [], isRoot: false, root: doc, discoverable: true, }); expectContext(cousin1, { parent: grandparent, children: [], isRoot: false, root: doc, discoverable: true, }); }); }); describe('tree connected earlier', () => { beforeEach(async () => { doc.body.appendChild(tree); await waitForDiscover(sibling1, sibling2, cousin1); }); it('should configure root', () => { expectContext(doc, { root: doc, isRoot: true, parent: null, children: [sibling1, sibling2, cousin1], discoverable: false, }); }); it('should auto-discover an orphan', async () => { expectContext(sibling1, { parent: doc, root: doc, isRoot: false, children: [], discoverable: true, }); expectContext(sibling2, { parent: doc, root: doc, isRoot: false, children: [], discoverable: true, }); expectContext(cousin1, { parent: doc, root: doc, isRoot: false, children: [], discoverable: true, }); }); it('should auto-discover the grandparent', async () => { await waitForDiscover(grandparent); expectContext(doc, { isRoot: true, root: doc, parent: null, children: [grandparent], discoverable: false, }); expectContext(grandparent, { isRoot: false, root: doc, parent: doc, children: [sibling1, sibling2, cousin1], discoverable: true, }); expectContext(sibling1, { isRoot: false, root: doc, parent: grandparent, children: [], discoverable: true, }); expectContext(sibling2, { isRoot: false, root: doc, parent: grandparent, children: [], discoverable: true, }); expectContext(cousin1, { isRoot: false, root: doc, parent: grandparent, children: [], discoverable: true, }); }); it('should insert an intermediary parent', async () => { await waitForDiscover(grandparent, parent); expectContext(doc, { isRoot: true, root: doc, parent: null, children: [grandparent], discoverable: false, }); expectContext(grandparent, { parent: doc, children: [parent, cousin1], isRoot: false, root: doc, discoverable: true, }); expectContext(parent, { parent: grandparent, children: [sibling1, sibling2], isRoot: false, root: doc, discoverable: true, }); expectContext(sibling1, { parent, children: [], isRoot: false, root: doc, discoverable: true, }); expectContext(sibling2, { parent, children: [], isRoot: false, root: doc, discoverable: true, }); expectContext(cousin1, { parent: grandparent, children: [], isRoot: false, root: doc, discoverable: true, }); }); it('should move to new root', async () => { await waitForDiscover(grandparent, parent); const doc2 = document.implementation.createHTMLDocument(''); ContextNode.get(doc2); doc2.body.appendChild(tree); await rediscover(grandparent); expectContext(doc, { parent: null, children: [], isRoot: true, root: doc, discoverable: false, }); expectContext(doc2, { parent: null, children: [grandparent], isRoot: true, root: doc2, discoverable: false, }); expectContext(grandparent, { parent: doc2, children: [parent, cousin1], root: doc2, }); expectContext(parent, { parent: grandparent, children: [sibling1, sibling2], root: doc2, }); expectContext(sibling1, { parent, children: [], root: doc2, }); expectContext(sibling2, { parent, children: [], root: doc2, }); expectContext(cousin1, { parent: grandparent, children: [], root: doc2, }); }); it('should override the root', async () => { await waitForDiscover(grandparent, parent); ContextNode.get(grandparent).setIsRoot(true); expectContext(grandparent, { parent: doc, children: [parent, cousin1], isRoot: true, root: grandparent, discoverable: false, }); expectContext(parent, { parent: grandparent, children: [sibling1, sibling2], isRoot: false, root: grandparent, discoverable: true, }); expectContext(sibling1, { parent, children: [], isRoot: false, root: grandparent, discoverable: true, }); expectContext(sibling2, { parent, children: [], isRoot: false, root: grandparent, discoverable: true, }); expectContext(cousin1, { parent: grandparent, children: [], isRoot: false, root: grandparent, discoverable: true, }); }); }); }); describe('discover shadow DOM', () => { let sibling1; let sibling2; let parent; beforeEach(() => { sibling1 = el('T-1-1-1'); sibling2 = el('T-1-1-2'); parent = el('T-1-1'); }); it('should rediscover slots when shadow root is added', async () => { doc.body.appendChild(tree); await waitForDiscover(parent, sibling1, sibling2); const shadowRoot = parent.attachShadow({mode: 'open'}); ContextNode.get(shadowRoot).setParent(parent); const slot1 = doc.createElement('slot'); slot1.name = 'slot1'; sibling1.setAttribute('slot', 'slot1'); shadowRoot.appendChild(slot1); await waitForDiscover(shadowRoot, sibling1); // sibling1's parent is shadow root because it matches the slot. expectContext(sibling1, {parent: shadowRoot}); // sibling2's parent stays with "parent" because it's unslotted. expectContext(sibling2, {parent}); }); describe('shadow DOM exists from the start', () => { let shadowRoot; let slot1, slot1Parent; beforeEach(async () => { shadowRoot = parent.attachShadow({mode: 'open'}); ContextNode.get(shadowRoot).setParent(parent); slot1Parent = doc.createElement('div'); slot1Parent.id = 'slot1-parent'; shadowRoot.appendChild(slot1Parent); slot1 = doc.createElement('slot'); slot1.id = slot1.name = 'slot1'; sibling1.setAttribute('slot', 'slot1'); slot1Parent.appendChild(slot1); doc.body.appendChild(tree); await waitForDiscover(parent, shadowRoot, sibling1, sibling2); }); function awaitSlotChange() { return new Promise((resolve) => { shadowRoot.addEventListener('slotchange', resolve); }); } it('should assign shadow root as a parent via slot', () => { // sibling1's parent is shadow root because it matches the slot. expectContext(sibling1, {parent: shadowRoot}); // sibling2's parent stays with "parent" because it's unslotted. expectContext(sibling2, {parent}); }); it('should reassign when slots change', async () => { sibling1.removeAttribute('slot'); sibling2.setAttribute('slot', 'slot1'); await awaitSlotChange(); clock.runAll(); // sibling1's parent stays with "parent" because it's unslotted. expectContext(sibling1, {parent}); // sibling2's parent is shadow root because it matches the slot. expectContext(sibling2, {parent: shadowRoot}); }); it('should reassign when slots are removed', async () => { slot1Parent.removeChild(slot1); await waitForDiscover(sibling1); // Returns to parent. expectContext(sibling1, {parent}); }); it('should reassign to slot if it becomes a context node', async () => { const sibling1Wait = waitForDiscover(sibling1); await rediscover(slot1); await sibling1Wait; // slot belongs to the shadow root. expectContext(slot1, {parent: shadowRoot}); // sibling1's parent is slot now. expectContext(sibling1, {parent: slot1}); // Not changed: unslotted. expectContext(sibling2, {parent}); }); it('should reassign to slot parent becomes a context node', async () => { const sibling1Wait = waitForDiscover(sibling1); await rediscover(slot1Parent); await sibling1Wait; // slot belongs to the shadow root. expectContext(slot1Parent, {parent: shadowRoot}); // sibling1's parent is slot now. expectContext(sibling1, {parent: slot1Parent}); // Not changed: unslotted. expectContext(sibling2, {parent}); }); }); }); describe('discover groups', () => { let sibling1; let sibling2; let cousin1; let parent; let grandparent; beforeEach(async () => { sibling1 = el('T-1-1-1'); sibling2 = el('T-1-1-2'); cousin1 = el('T-1-2-1'); parent = el('T-1-1'); grandparent = el('T-1'); await waitForDiscover(grandparent, parent, sibling1, sibling2, cousin1); }); it('should rediscover children when a new group is added', async () => { const group1 = ContextNode.get(parent).addGroup( 'group1', (node) => node == sibling1, 0 ); await waitForDiscover(group1, sibling1); clock.runAll(); expect(group1.node).to.equal(parent); expectContext(group1, {parent, children: [sibling1]}); // sibling1 is reassigned to the group. expectContext(sibling1, {parent: group1}); // sibling2 stays stays unchanged. expectContext(sibling2, {parent}); }); it('should discover a new child', async () => { const sibling3 = el('T-1-1-3'); const group1 = ContextNode.get(parent).addGroup( 'group1', (node) => node == sibling3, 0 ); await waitForDiscover(group1); // Discover the new node. await rediscover(sibling3); expectContext(sibling3, {parent: group1}); }); it('should handle weight', async () => { const group1 = ContextNode.get(parent).addGroup( 'group1', (node) => node == sibling1, 0 ); await waitForDiscover(group1, sibling1); expectContext(sibling1, {parent: group1}); // A lower weight. const group2 = ContextNode.get(parent).addGroup( 'group1', (node) => node == sibling1, -1 ); await waitForDiscover(group2, sibling1); expectContext(sibling1, {parent: group1}); // A higher weight. const group3 = ContextNode.get(parent).addGroup( 'group1', (node) => node == sibling1, 1 ); await waitForDiscover(group3, sibling1); expectContext(sibling1, {parent: group3}); }); }); describe('scanners', () => { const EXCLUDE_SELF = false; let parent; let grandparent; let sibling1; let sibling2; let cousin1; beforeEach(async () => { grandparent = ContextNode.get(el('T-1')); parent = ContextNode.get(el('T-1-1')); sibling1 = ContextNode.get(el('T-1-1-1')); sibling2 = ContextNode.get(el('T-1-1-2')); cousin1 = ContextNode.get(el('T-1-2-1')); await waitForDiscover(grandparent, parent, sibling1, sibling2, cousin1); }); it('should find closest', () => { const any = () => true; expect(findParent(sibling1, any)).to.equal(sibling1); expect(findParent(sibling1, any, null, EXCLUDE_SELF)).to.equal(parent); const eq = (cn, arg) => cn === arg; expect(findParent(sibling1, eq, sibling1)).to.equal(sibling1); expect(findParent(sibling1, eq, sibling1, EXCLUDE_SELF)).to.be.null; expect(findParent(sibling1, eq, parent)).to.equal(parent); }); it('should scan the subtree completely', () => { const scanned = []; const scan = (cn, exclude) => { scanned.push(cn); if (exclude && exclude.indexOf(cn) != -1) { return false; } return true; }; // Scan all. scanned.length = 0; deepScan(grandparent, scan); expect(scanned).to.deep.equal([ grandparent, parent, sibling1, sibling2, cousin1, ]); // Scan subtree. scanned.length = 0; deepScan(grandparent, scan, null, true, EXCLUDE_SELF); expect(scanned).to.deep.equal([parent, sibling1, sibling2, cousin1]); // Scan some. scanned.length = 0; deepScan(grandparent, scan, [parent]); expect(scanned).to.deep.equal([grandparent, parent, cousin1]); }); }); });
import MongoClient from 'mongodb'; const url = "mongodb+srv://SydneyDevaney:YHfpLjWRea4J3qm5@cluster0.yuzwq.mongodb.net" class Database { constructor(){ this.connection = null; this.database = null; this.collection = null; } async connect(database, collection){ this.connection = await MongoClient.connect(url); this.database = this.connection.db(database); this.collection = this.database.collection(collection); } createOne(){ } readOne(){ } async updateOne(id, title, rating, review){ if (this.collection != null) { const result = await this.collection.updateOne({"id": id}, {$set: {"title": title}}); return{"title": title}; }else{ return null; } } async deleteOne(id){ if (this.collection != null) { const result = await this.collection.deleteOne({"id": id}); return{"deleted": result.deletedCount}; }else { return {"deleted": 0}; } } close(){ } } export default Database;
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require bootstrap //= require angular //= require angular-cookies //= require angular-ui-router //= require angular-bootstrap //= require angular-rails-templates //= require_tree . //= require_tree ../templates
'use strict'; /** * Module dependencies. */ var should = require('should'), mongoose = require('mongoose'), User = mongoose.model('User'), Thread = mongoose.model('Thread'), Message = mongoose.model('Message'), ReferenceThread = mongoose.model('ReferenceThread'); /** * Globals */ var user1, user2, message, thread, referenceThread; /** * Unit tests */ describe('Reference Thread Model Unit Tests:', function() { beforeEach(function(done) { user1 = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test1@test.com', username: 'username1', password: 'password123', provider: 'local' }); user2 = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test2@test.com', username: 'username2', password: 'password123', provider: 'local' }); message = { content: 'Lorem ipsum', notified: true, userTo: null, userFrom: null, read: true, created: new Date() }; thread = { message: null, userTo: null, userFrom: null, read: true, updated: new Date() }; referenceThread = { thread: null, userFrom: null, userTo: null, reference: 'yes', created: new Date() }; // Create users and reference user1.save(function(err, user1res) { referenceThread.userFrom = user1res._id; message.userFrom = user1res._id; thread.userFrom = user1res._id; user2.save(function(err, user2res) { referenceThread.userTo = user2res._id; message.userTo = user2res._id; thread.userTo = user2res._id; new Message(message).save(function(err, message2res) { thread.message = message2res._id; new Thread(thread).save(function(err, thread2res) { referenceThread.thread = thread2res._id; referenceThread = new ReferenceThread(referenceThread); return done(); }); }); }); }); }); describe('Method Save', function() { it('should be able to save without problems', function(done) { referenceThread.save(function(err) { should.not.exist(err); return done(); }); }); it('should be able to save without problems with reference text set to "no"', function(done) { referenceThread.reference = 'no'; referenceThread.save(function(err) { should.not.exist(err); return done(); }); }); it('should be able to show an error when try to save with reference text set to something else than "yes" or "no"', function(done) { referenceThread.reference = 'beer'; referenceThread.save(function(err) { should.exist(err); return done(); }); }); }); afterEach(function(done) { ReferenceThread.remove().exec(function() { User.remove().exec(done); }); }); });
/* istanbul instrument in package npmtest_mocha_phantomjs */ /*jslint bitwise: true, browser: true, maxerr: 8, maxlen: 96, node: true, nomen: true, regexp: true, stupid: true */ (function () { 'use strict'; var local; // run shared js-env code - pre-init (function () { // init local local = {}; // init modeJs local.modeJs = (function () { try { return typeof navigator.userAgent === 'string' && typeof document.querySelector('body') === 'object' && typeof XMLHttpRequest.prototype.open === 'function' && 'browser'; } catch (errorCaughtBrowser) { return module.exports && typeof process.versions.node === 'string' && typeof require('http').createServer === 'function' && 'node'; } }()); // init global local.global = local.modeJs === 'browser' ? window : global; // init utility2_rollup local = local.global.utility2_rollup || local; // init lib local.local = local.npmtest_mocha_phantomjs = local; // init exports if (local.modeJs === 'browser') { local.global.utility2_npmtest_mocha_phantomjs = local; } else { module.exports = local; module.exports.__dirname = __dirname; module.exports.module = module; } }()); }());
import React, { Component } from 'react' import { Typography } from '@material-ui/core' import { InitConfig } from 'components/Auth/context/ConfigContext' import 'echarts/theme/macarons' class CleanText extends Component { constructor(props) { super(props) this.state = { widgetTitle: '', dataValue: 0 } } componentDidMount() { const { widgetTitle, resourceId, dataId, dataValue, socket } = this.props this.setState({ widgetTitle: widgetTitle, dataValue: dataValue }) socket.on(`${resourceId}-${dataId}`, resData => { this.setState({ dataValue: resData.value }) }) } render() { return ( <div className="col-xs-12 col-md-12 p-1"> <div className="card box"> <div className="p-2"> <div className="row"> <div className="col-10 d-flex justify-content-start"> <Typography noWrap>{this.state.widgetTitle}</Typography> </div> <div className="col-12 d-flex"> <div className="w-100 align-self-center"> <div className="d-flex justify-content-center" style={{color: '#00BCD4'}}> <b> <h4>{this.state.dataValue}</h4> </b> </div> </div> </div> </div> </div> </div> </div> ) } } export default InitConfig(CleanText);
/** * @typedef {Object} TransferChangeType * @property {string} name * @property {string} description */ /** * @type {Array.<TransferChangeType>} */ const transferChangeTypes = [ { name: 'TOTAL_POINTS', description: 'How many points has this player scored so far this season', }, { name: 'NOW_COST', description: 'What\'s the current cost of this player', }, { name: 'SELECTED_BY_PERCENT', description: 'what percentage of fpl users have selected this player to 1 decimal place', }, { name: 'TRANSFERS_IN', description: 'how many time has this player been transferred in to a users team', }, { name: 'TRANSFERS_IN_EVENT', description: 'how many time has this player been transferred in to a users team during this gameweek', }, { name: 'TRANSFERS_OUT', description: 'how many time has this player been transferred out of a users team', }, { name: 'TRANSFERS_OUT_EVENT', description: 'how many time has this player been transferred out of a users team this gameweek', }, ]; module.exports = transferChangeTypes;
import React from 'react'; import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom'; import Header from './Header'; import Home from './Home'; import NotFound from './NotFound'; import Favorites from './Favorites'; import Recipe from './Recipe'; class App extends React.Component { constructor(props) { super(props); this.state = { recipes: [], favorites: [], }; } componentDidMount() { fetch(`${API_URL}/v1/recipes`) .then(res => res.json()) .then(recipes => { this.setState({ recipes }); }); } toggleFavorite = id => { this.setState(({ favorites, ...state }) => { const idx = favorites.indexOf(id); if (idx !== -1) { return { ...state, favorites: favorites.filter(f => f !== id) }; } return { ...state, favorites: [...favorites, id] }; }); }; render() { return ( <BrowserRouter> <main> <Header /> <Switch> <Redirect from="/home" to="/" /> <Route exact path="/" render={() => ( <Home state={this.state} toggleFavorite={this.toggleFavorite} /> )} /> <Route path="/favorites" render={() => ( <Favorites state={this.state} toggleFavorite={this.toggleFavorite} /> )} /> <Route path="/recipe/:id" component={Recipe} /> <Route component={NotFound} /> </Switch> </main> </BrowserRouter> ) } }; export default App;
import React from "react"; import { Route, Switch, useRouteMatch } from "react-router-dom"; import DetailUser from "./pages/detailUser"; import MainUser from "./pages/mainUser"; function UserPage() { const match = useRouteMatch(); return ( <Switch> <Route path={`${match.url}/`} exact component={MainUser} /> <Route path={`${match.url}/:id`} component={DetailUser} /> </Switch> ); } export default UserPage;
import Search from '..'; import { mount } from '../../../test/utils'; test('input event', () => { const onInput = jest.fn(); const wrapper = mount(Search, { context: { on: { input: onInput } } }); const input = wrapper.find('input'); input.element.value = '1'; input.trigger('input'); expect(onInput).toHaveBeenCalledWith('1'); }); test('cancel event', () => { const onInput = jest.fn(); const onCancel = jest.fn(); const wrapper = mount(Search, { propsData: { value: 'test', showAction: true }, context: { on: { input: onInput, cancel: onCancel } } }); const cancel = wrapper.find('.van-search__action div'); cancel.trigger('click'); expect(onInput).toHaveBeenCalledWith(''); expect(onCancel).toHaveBeenCalled(); }); test('search event', () => { const onSearch = jest.fn(); const onKeypress = jest.fn(); const wrapper = mount(Search, { context: { on: { search: onSearch, keypress: onKeypress } } }); const input = wrapper.find('input'); input.trigger('keypress.enter'); input.trigger('keypress.a'); expect(onSearch).toHaveBeenCalled(); expect(onKeypress).toHaveBeenCalled(); }); test('label slot', () => { const wrapper = mount(Search, { scopedSlots: { label() { return 'Custom Label'; } } }); expect(wrapper).toMatchSnapshot(); }); test('left-icon prop', () => { const wrapper = mount(Search, { propsData: { leftIcon: 'setting-o' } }); expect(wrapper).toMatchSnapshot(); }); test('right-icon prop', () => { const wrapper = mount(Search, { propsData: { rightIcon: 'setting-o' } }); expect(wrapper).toMatchSnapshot(); }); test('right-icon slot', () => { const wrapper = mount(Search, { scopedSlots: { 'right-icon': () => 'Custom Right Icon' } }); expect(wrapper).toMatchSnapshot(); });
import React, { Component } from 'react' import { AppContainer } from 'src/components' import { Flex, Text, Box } from 'serverless-design-system' import videoPosterImage from 'src/assets/images/home/video-loading-poster.png' import styled from 'styled-components' import featuresData from './FeaturesData' import ReactPlayer from 'react-player' require('./responsivePlayer.css') const HR = styled('hr')` width: 100%; margin-top: -69px; z-index: -2; ` //TODO: create a component for the below 2 const HoverableText = styled(Text)` &:hover { cursor: pointer; } ` const StyledSelect = styled('select')` width: 300px; height: 42px; border-radius: 4px; box-shadow: 2px 2px 8px 0 rgba(0, 0, 0, 0.08); border: solid 1px rgba(234, 234, 234, 0.3); background-color: white; font-size: 18px; line-height: 30px; letter-spacing: -0.28px; font-family: 'SoleilBk'; outline: none; margin-top: 25px; ` class HomeFeatureList extends Component { constructor(props) { super(props) this.state = { activeVideoId: 1, activeFeature: 'Intro', activeVideoUrl: featuresData.filter(f => f.name === 'Intro')[0].videoUrl, videoPlaying: true, isMobile: false, } this.updateActiveFeatureMobile = this.updateActiveFeatureMobile.bind(this) this.updateActiveFeature = this.updateActiveFeature.bind(this) this.autoPlayNextVideo = this.autoPlayNextVideo.bind(this) this.toggleVideoPlaying = this.toggleVideoPlaying.bind(this) } componentDidMount() { if (window) { const isMobile = window.innerWidth <= 420 ? true : false if (isMobile) { this.setState({ isMobile: true }) } } } updateActiveFeatureMobile(event) { const featureName = event.target.value const featureObj = featuresData.filter(f => f.name === featureName)[0] this.updateActiveFeature(featureObj) } updateActiveFeature(feature) { this.setState({ activeFeature: feature.name, activeVideoUrl: feature.videoUrl, videoPlaying: true, }) this.setState({ activeVideoId: feature.id }) } autoPlayNextVideo() { const nextId = this.state.activeVideoId === 6 ? 1 : this.state.activeVideoId + 1 const nextIdFeature = featuresData.filter(f => f.id === nextId)[0] this.updateActiveFeature(nextIdFeature) this.setState({ activeVideoId: nextId }) } toggleVideoPlaying() { if (!this.state.isMobile) { this.setState({ videoPlaying: !this.state.videoPlaying }) } } render() { return ( <Flex flexDirection={['column', 'column', 'column']} width={[1]} mt={[3, 3, 2, 2, 2]} alignItems='center' > <Box display={['none', 'none', 'block']} mb={52}> <Flex mb={67}> {featuresData.map(feature => ( <HoverableText key={feature.name} mx={[25]} fontSize={18} lineHeight={'30px'} letterSpacing={'-0.28px'} fontFamily='SoleilBk' pb={'12px'} style={ this.state.activeFeature === feature.name ? { borderBottom: '2px solid black', color: '#000' } : { color: '#8c8c8c' } } onClick={() => this.updateActiveFeature(feature)} > {feature.name} </HoverableText> ))} </Flex> <HR /> </Box> <Box display={['block', 'block', 'none']} mb={[45, 45, 32]}> <StyledSelect onChange={this.updateActiveFeatureMobile}> {featuresData.map(feature => ( <option value={feature.name} key={feature.name}> {feature.name} </option> ))} </StyledSelect> </Box> <AppContainer> <div className='homepage-video-player-wrapper'> <ReactPlayer url={this.state.activeVideoUrl} className='react-player' muted controls={this.state.isMobile ? true : false} width='100%' height='529px' onClick={() => this.toggleVideoPlaying()} onEnded={() => this.autoPlayNextVideo()} loop={false} playing={this.state.videoPlaying} config={{ file: { attributes: { poster: videoPosterImage, }, }, }} /> </div> </AppContainer> </Flex> ) } } export default HomeFeatureList
import Ember from 'ember'; export default Ember.Route.extend({ model: function() { var car1 = { name: 'Carrera', color: 'red' }; var car2 = { name: 'Veyron', color: 'red' }; var car3 = { name: 'Corvette', color: 'blue' }; var car4 = { name: 'Viper', color: 'blue' }; var car5 = { name: 'Cobra', color: 'green' }; var cars = [car1, car2, car3, car4, car5]; return cars; } });
export const getNameStore = store => store.name; export const getName = store => getNameStore(store) ? getNameStore(store).name : 'No Name';
//! moment.js locale configuration ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(that, (function (moment) { 'use strict'; var months = [ 'جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر' ]; var days = [ 'اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'ہفتہ' ]; var ur = moment.defineLocale('ur', { months : months, monthsShort : months, weekdays : days, weekdaysShort : days, weekdaysMin : days, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd، D MMMM YYYY HH:mm' }, meridiemParse: /صبح|شام/, isPM : function (input) { return 'شام' === input; }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return 'صبح'; } return 'شام'; }, calendar : { sameDay : '[آج بوقت] LT', nextDay : '[کل بوقت] LT', nextWeek : 'dddd [بوقت] LT', lastDay : '[گذشتہ روز بوقت] LT', lastWeek : '[گذشتہ] dddd [بوقت] LT', sameElse : 'L' }, relativeTime : { future : '%s بعد', past : '%s قبل', s : 'چند سیکنڈ', ss : '%d سیکنڈ', m : 'ایک منٹ', mm : '%d منٹ', h : 'ایک گھنٹہ', hh : '%d گھنٹے', d : 'ایک دن', dd : '%d دن', M : 'ایک ماہ', MM : '%d ماہ', y : 'ایک سال', yy : '%d سال' }, preparse: function (string) { return string.replace(/،/g, ','); }, postformat: function (string) { return string.replace(/,/g, '،'); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); return ur; })));
import { createMuiTheme } from "@material-ui/core/styles"; import BrandColors from "../Brand/BrandColors"; // Brand Colors const civicPrimary = BrandColors.primary.hex; const civicPlumLight = BrandColors.plumLight.hex; const civicMedium = BrandColors.medium.hex; const civicSubdued = BrandColors.subdued.hex; const civicAction = BrandColors.action.hex; const civicError = BrandColors.error.hex; // Typography const dataSanSerif = "Roboto Condensed, Helvetica Neue, Helvetica, sans-serif"; const sanSerif = "Rubik, Helvetica Neue, Helvetica, sans-serif"; // Animation const animationSpeed = 4; const MaterialTheme = createMuiTheme({ palette: { common: { black: "rgba(0, 0, 0, 1)", white: "#fff" }, background: { paper: "rgba(243, 242, 243, 1)", default: "rgba(255, 255, 255, 1)" }, primary: { light: civicPlumLight, main: civicPrimary, dark: civicPrimary, contrastText: "#fff" // must override emotion theme if link }, secondary: { light: civicAction, main: civicAction, dark: civicAction, contrastText: "#fff" }, error: { light: civicError, main: civicError, dark: civicError, contrastText: "#fff" }, text: { primary: civicPrimary, secondary: civicPrimary, disabled: civicSubdued, hint: civicMedium } }, shape: { borderRadius: 0 }, typography: { fontFamily: dataSanSerif, button: { fontFamily: sanSerif }, h6: { fontFamily: sanSerif } }, transitions: { duration: { shortest: 150 / animationSpeed, shorter: 200 / animationSpeed, short: 250 / animationSpeed, standard: 300 / animationSpeed, complex: 375 / animationSpeed, enteringScreen: 225 / animationSpeed, leavingScreen: 195 / animationSpeed } }, props: { MuiButtonBase: { disableRipple: true // No more ripple, on the whole application 💣! } }, overrides: { MuiMenuItem: { root: { minHeight: "unset", lineHeight: "unset" } } } }); export default MaterialTheme;
(function ($) { /** * Patch TOC list. * * Will mutate the underlying span to have a correct ul for nav. * * @param $span: Span containing nested UL's to mutate. * @param minLevel: Starting level for nested lists. (1: global, 2: local). */ var patchToc = function ($ul, minLevel) { var findA, patchTables, $localLi; // Find all a "internal" tags, traversing recursively. findA = function ($elem, level) { level = level || 0; var $items = $elem.find("> li > a.internal, > ul, > li > ul"); // Iterate everything in order. $items.each(function (index, item) { var $item = $(item), tag = item.tagName.toLowerCase(), $childrenLi = $item.children('li'), $parentLi = $($item.parent('li'), $item.parent().parent('li')); // Add dropdowns if more children and above minimum level. if (tag === 'ul' && level >= minLevel && $childrenLi.length > 0) { $parentLi .addClass('dropdown-submenu') .children('a').first().attr('tabindex', -1); $item.addClass('dropdown-menu'); } findA($item, level + 1); }); }; findA($ul); }; /** * Patch all tables to remove ``docutils`` class and add Bootstrap base * ``table`` class. */ patchTables = function () { $("table.docutils") .removeClass("docutils") .addClass("table") .attr("border", 0); }; $(window).load(function () { /* * Scroll the window to avoid the topnav bar * https://github.com/twitter/bootstrap/issues/1768 */ if ($("#navbar.navbar-fixed-top").length > 0) { var navHeight = $("#navbar").height(), shiftWindow = function() { scrollBy(0, -navHeight - 10); }; if (location.hash) { setTimeout(shiftWindow, 1); } window.addEventListener("hashchange", shiftWindow); } }); $(document).ready(function () { // Add styling, structure to TOC's. $(".dropdown-menu").each(function () { $(this).find("ul").each(function (index, item){ var $item = $(item); $item.addClass('unstyled'); }); }); // Global TOC. if ($("ul.globaltoc li").length) { patchToc($("ul.globaltoc"), 1); } else { // Remove Global TOC. $(".globaltoc-container").remove(); } // Local TOC. $(".bs-sidenav ul").addClass("nav nav-list"); $(".bs-sidenav > ul > li > a").addClass("nav-header"); // back to top setTimeout(function () { var $sideBar = $('.bs-sidenav'); $sideBar.affix({ offset: { top: function () { var offsetTop = $sideBar.offset().top; var sideBarMargin = parseInt($sideBar.children(0).css('margin-top'), 10); var navOuterHeight = $('#navbar').height(); return (this.top = offsetTop - navOuterHeight - sideBarMargin); } , bottom: function () { // add 25 because the footer height doesn't seem to be enough return (this.bottom = $('.footer').outerHeight(true) + 25); } } }); }, 100); // Local TOC. patchToc($("ul.localtoc"), 2); // Mutate sub-lists (for bs-2.3.0). $(".dropdown-menu ul").not(".dropdown-menu").each(function () { var $ul = $(this), $parent = $ul.parent(), tag = $parent[0].tagName.toLowerCase(), $kids = $ul.children().detach(); // Replace list with items if submenu header. if (tag === "ul") { $ul.replaceWith($kids); } else if (tag === "li") { // Insert into previous list. $parent.after($kids); $ul.remove(); } }); // Add divider in page TOC. $localLi = $("ul.localtoc li"); if ($localLi.length > 2) { $localLi.first().after('<li class="divider"></li>'); } // Manually add dropdown. // Appears unnecessary as of: // https://github.com/ryan-roemer/sphinx-bootstrap-theme/pull/90 // Remove next time around... // a.dropdown-toggle class needed in globaltoc.html //$('.dropdown-toggle').dropdown(); // Patch tables. patchTables(); // Add Note, Warning styles. (BS v2,3 compatible). $('.admonition').addClass('alert alert-info') .filter('.warning, .caution') .removeClass('alert-info') .addClass('alert-warning').end() .filter('.error, .danger') .removeClass('alert-info') .addClass('alert-danger alert-error').end(); // Inline code styles to Bootstrap style. $('tt.docutils.literal').not(".xref").each(function (i, e) { // ignore references if (!$(e).parent().hasClass("reference")) { $(e).replaceWith(function () { return $("<code />").html($(this).html()); }); }}); // Update sourcelink to remove outerdiv (fixes appearance in navbar). var $srcLink = $(".nav #sourcelink"); $srcLink.parent().html($srcLink.html()); }); }(window.$jqTheme || window.jQuery));
import { Fragment } from "react"; import { Form, Button } from "react-bootstrap"; import Loader from "../../components/Loader"; import Message from "../../components/Message"; import { useDispatch, useSelector } from "react-redux"; import { loginProfile } from "../../actions/authAction"; const ProfileScreen = (props) => { const { value, handleChange } = props; const { authInfo } = useSelector((state) => state); const { loading, error } = authInfo; const dispatch = useDispatch(); const Continue = async (e) => { e.preventDefault(); let data = { name: value.name, userName: value.userName, mobile: value.mobile, }; if (value.profilePic) { data.profilePic = value.profilePic; } dispatch(loginProfile(data)); }; return ( <Fragment> {loading ? ( <div className="loader-wrapper"> <Loader /> </div> ) : ( <div className="login-container d-flex align-items-center justify-content-center"> <Form className="login-form text-center"> {error && <Message variant="danger">{error.message}</Message>} <h2 className="mb-4 font-weight-normal "> {" "} <strong>Profile</strong> </h2> <div className="profile-pic"> <img src="./images/user.png" className=" rounded img-fluid" id="profilePic" alt="Profile" style={{ width: "160px", height: "160px" }} /> </div> { // <ButtonGroup aria-label="Basic example" className="mb-4 mt-4"> // <Button variant="danger">Delete</Button> // <Button variant="info"> // <span className="btn-info btn-file">Upload // <input type="file" name="profilePic" /> // </span> // </Button> // </ButtonGroup> } <Form.Group controlId="formBasicName"> <Form.Control name="name" type="text" placeholder="Name" onChange={(e) => handleChange(e.target.name, e.target.value)} value={value.name} /> </Form.Group> <Form.Group controlId="formBasicUsername"> <Form.Control name="userName" type="text" placeholder="Username" onChange={(e) => handleChange(e.target.name, e.target.value)} value={value.userName} /> </Form.Group> <Button type="submit" onClick={Continue} className="btn mt-5 btn-custom btn-primary btn-block text-uppercase rounded-pill btn-lg" > NEXT </Button> </Form> </div> )} </Fragment> ); }; export default ProfileScreen;
import BaseRenderer from 'diagram-js/lib/draw/BaseRenderer'; import PathMap from './PathMap.js' import { append as svgAppend, attr as svgAttr, classes as svgClasses, create as svgCreate } from 'tiny-svg'; import { getRoundRectPath } from 'bpmn-js/lib/draw/BpmnRenderUtil'; import { is, getBusinessObject } from 'bpmn-js/lib/util/ModelUtil'; const HIGH_PRIORITY = 1500, TASK_BORDER_RADIUS = 2, COLOR_GREEN = '#52B415', COLOR_YELLOW = '#ffc800', COLOR_RED = '#cc0000'; export default class CustomRenderer extends BaseRenderer { constructor(eventBus, bpmnRenderer) { super(eventBus, HIGH_PRIORITY); this.bpmnRenderer = bpmnRenderer; } canRender(element) { // ignore labels return !element.labelTarget; } drawShape(parentNode, element) { const shape = this.bpmnRenderer.drawShape(parentNode, element); if (is(element, 'dsgvo:UnrechtmaessigeVerarbeitung')) { const rect = drawRect(parentNode, 100, 80, TASK_BORDER_RADIUS); var x = 15; var y = 12; var pathData = this.getScaledPath('Unrechtmaessige_Verarbeitung', { abspos: { x: x, y: y } }); drawPath(pathData, { strokeWidth: 0.5, }); return shape; } return shape; } getShapePath(shape) { if (is(shape, 'bpmn:Task')) { return getRoundRectPath(shape, TASK_BORDER_RADIUS); } return this.bpmnRenderer.getShapePath(shape); } } CustomRenderer.$inject = [ 'eventBus', 'bpmnRenderer' ]; // helpers ////////// // copied from https://github.com/bpmn-io/bpmn-js/blob/master/lib/draw/BpmnRenderer.js function drawRect(parentNode, width, height, borderRadius, color) { const rect = svgCreate('rect'); svgAttr(rect, { width: width, height: height, rx: borderRadius, ry: borderRadius, stroke: color, strokeWidth: 2, fill: color }); svgAppend(parentNode, rect); return rect; } function drawPath(parentGfx, d, attrs) { attrs = computeStyle(attrs, [ 'no-fill' ], { strokeWidth: 2, stroke: 'black' }); var path = svgCreate('path'); svgAttr(path, { d: d }); svgAttr(path, attrs); svgAppend(parentGfx, path); return path; }
ShareDrop.App.FileField = Ember.TextField.extend({ type: 'file', classNames: ['invisible'], click: function (event) { event.stopPropagation(); }, change: function (event) { var input = event.target, files = input.files, file = files[0]; this.sendAction('action', { file: file }); }, // Hackish way to reset file input when sender cancels file transfer, // so if sender wants later to send the same file again, // the 'change' event is triggered correctly. fileDidChange: function () { if (!this.get('file')) { var field = this.$(); field.wrap('<form>').closest('form').get(0).reset(); field.unwrap(); } }.observes('file') });
/*! jQuery UI - v1.10.3 - 2013-05-03 * http://jqueryui.com * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.effect.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js, jquery.ui.menu.js, jquery.ui.position.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ (function(t,e){function i(e,i){var n,o,a,r=e.nodeName.toLowerCase();return"area"===r?(n=e.parentNode,o=n.name,e.href&&o&&"map"===n.nodeName.toLowerCase()?(a=t("img[usemap=#"+o+"]")[0],!!a&&s(a)):!1):(/input|select|textarea|button|object/.test(r)?!e.disabled:"a"===r?e.href||i:i)&&s(e)}function s(e){return t.expr.filters.visible(e)&&!t(e).parents().addBack().filter(function(){return"hidden"===t.css(this,"visibility")}).length}var n=0,o=/^ui-id-\d+$/;t.ui=t.ui||{},t.extend(t.ui,{version:"1.10.3",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),t.fn.extend({focus:function(e){return function(i,s){return"number"==typeof i?this.each(function(){var e=this;setTimeout(function(){t(e).focus(),s&&s.call(e)},i)}):e.apply(this,arguments)}}(t.fn.focus),scrollParent:function(){var e;return e=t.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(t.css(this,"position"))&&/(auto|scroll)/.test(t.css(this,"overflow")+t.css(this,"overflow-y")+t.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(t.css(this,"overflow")+t.css(this,"overflow-y")+t.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!e.length?t(document):e},zIndex:function(i){if(i!==e)return this.css("zIndex",i);if(this.length)for(var s,n,o=t(this[0]);o.length&&o[0]!==document;){if(s=o.css("position"),("absolute"===s||"relative"===s||"fixed"===s)&&(n=parseInt(o.css("zIndex"),10),!isNaN(n)&&0!==n))return n;o=o.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++n)})},removeUniqueId:function(){return this.each(function(){o.test(this.id)&&t(this).removeAttr("id")})}}),t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(i){return!!t.data(i,e)}}):function(e,i,s){return!!t.data(e,s[3])},focusable:function(e){return i(e,!isNaN(t.attr(e,"tabindex")))},tabbable:function(e){var s=t.attr(e,"tabindex"),n=isNaN(s);return(n||s>=0)&&i(e,!n)}}),t("<a>").outerWidth(1).jquery||t.each(["Width","Height"],function(i,s){function n(e,i,s,n){return t.each(o,function(){i-=parseFloat(t.css(e,"padding"+this))||0,s&&(i-=parseFloat(t.css(e,"border"+this+"Width"))||0),n&&(i-=parseFloat(t.css(e,"margin"+this))||0)}),i}var o="Width"===s?["Left","Right"]:["Top","Bottom"],a=s.toLowerCase(),r={innerWidth:t.fn.innerWidth,innerHeight:t.fn.innerHeight,outerWidth:t.fn.outerWidth,outerHeight:t.fn.outerHeight};t.fn["inner"+s]=function(i){return i===e?r["inner"+s].call(this):this.each(function(){t(this).css(a,n(this,i)+"px")})},t.fn["outer"+s]=function(e,i){return"number"!=typeof e?r["outer"+s].call(this,e):this.each(function(){t(this).css(a,n(this,e,!0,i)+"px")})}}),t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(t.fn.removeData=function(e){return function(i){return arguments.length?e.call(this,t.camelCase(i)):e.call(this)}}(t.fn.removeData)),t.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),t.support.selectstart="onselectstart"in document.createElement("div"),t.fn.extend({disableSelection:function(){return this.bind((t.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(t){t.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),t.extend(t.ui,{plugin:{add:function(e,i,s){var n,o=t.ui[e].prototype;for(n in s)o.plugins[n]=o.plugins[n]||[],o.plugins[n].push([i,s[n]])},call:function(t,e,i){var s,n=t.plugins[e];if(n&&t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType)for(s=0;n.length>s;s++)t.options[n[s][0]]&&n[s][1].apply(t.element,i)}},hasScroll:function(e,i){if("hidden"===t(e).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",n=!1;return e[s]>0?!0:(e[s]=1,n=e[s]>0,e[s]=0,n)}})})(jQuery),function(t,e){var i=0,s=Array.prototype.slice,n=t.cleanData;t.cleanData=function(e){for(var i,s=0;null!=(i=e[s]);s++)try{t(i).triggerHandler("remove")}catch(o){}n(e)},t.widget=function(i,s,n){var o,a,r,h,l={},c=i.split(".")[0];i=i.split(".")[1],o=c+"-"+i,n||(n=s,s=t.Widget),t.expr[":"][o.toLowerCase()]=function(e){return!!t.data(e,o)},t[c]=t[c]||{},a=t[c][i],r=t[c][i]=function(t,i){return this._createWidget?(arguments.length&&this._createWidget(t,i),e):new r(t,i)},t.extend(r,a,{version:n.version,_proto:t.extend({},n),_childConstructors:[]}),h=new s,h.options=t.widget.extend({},h.options),t.each(n,function(i,n){return t.isFunction(n)?(l[i]=function(){var t=function(){return s.prototype[i].apply(this,arguments)},e=function(t){return s.prototype[i].apply(this,t)};return function(){var i,s=this._super,o=this._superApply;return this._super=t,this._superApply=e,i=n.apply(this,arguments),this._super=s,this._superApply=o,i}}(),e):(l[i]=n,e)}),r.prototype=t.widget.extend(h,{widgetEventPrefix:a?h.widgetEventPrefix:i},l,{constructor:r,namespace:c,widgetName:i,widgetFullName:o}),a?(t.each(a._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,r,i._proto)}),delete a._childConstructors):s._childConstructors.push(r),t.widget.bridge(i,r)},t.widget.extend=function(i){for(var n,o,a=s.call(arguments,1),r=0,h=a.length;h>r;r++)for(n in a[r])o=a[r][n],a[r].hasOwnProperty(n)&&o!==e&&(i[n]=t.isPlainObject(o)?t.isPlainObject(i[n])?t.widget.extend({},i[n],o):t.widget.extend({},o):o);return i},t.widget.bridge=function(i,n){var o=n.prototype.widgetFullName||i;t.fn[i]=function(a){var r="string"==typeof a,h=s.call(arguments,1),l=this;return a=!r&&h.length?t.widget.extend.apply(null,[a].concat(h)):a,r?this.each(function(){var s,n=t.data(this,o);return n?t.isFunction(n[a])&&"_"!==a.charAt(0)?(s=n[a].apply(n,h),s!==n&&s!==e?(l=s&&s.jquery?l.pushStack(s.get()):s,!1):e):t.error("no such method '"+a+"' for "+i+" widget instance"):t.error("cannot call methods on "+i+" prior to initialization; "+"attempted to call method '"+a+"'")}):this.each(function(){var e=t.data(this,o);e?e.option(a||{})._init():t.data(this,o,new n(a,this))}),l}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(e,s){s=t(s||this.defaultElement||this)[0],this.element=t(s),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this.bindings=t(),this.hoverable=t(),this.focusable=t(),s!==this&&(t.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===s&&this.destroy()}}),this.document=t(s.style?s.ownerDocument:s.document||s),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:t.noop,_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(t.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:t.noop,widget:function(){return this.element},option:function(i,s){var n,o,a,r=i;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof i)if(r={},n=i.split("."),i=n.shift(),n.length){for(o=r[i]=t.widget.extend({},this.options[i]),a=0;n.length-1>a;a++)o[n[a]]=o[n[a]]||{},o=o[n[a]];if(i=n.pop(),s===e)return o[i]===e?null:o[i];o[i]=s}else{if(s===e)return this.options[i]===e?null:this.options[i];r[i]=s}return this._setOptions(r),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return this.options[t]=e,"disabled"===t&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!e).attr("aria-disabled",e),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(i,s,n){var o,a=this;"boolean"!=typeof i&&(n=s,s=i,i=!1),n?(s=o=t(s),this.bindings=this.bindings.add(s)):(n=s,s=this.element,o=this.widget()),t.each(n,function(n,r){function h(){return i||a.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof r?a[r]:r).apply(a,arguments):e}"string"!=typeof r&&(h.guid=r.guid=r.guid||h.guid||t.guid++);var l=n.match(/^(\w+)\s*(.*)$/),c=l[1]+a.eventNamespace,u=l[2];u?o.delegate(u,c,h):s.bind(c,h)})},_off:function(t,e){e=(e||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(e).undelegate(e)},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){t(e.currentTarget).addClass("ui-state-hover")},mouseleave:function(e){t(e.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){t(e.currentTarget).addClass("ui-state-focus")},focusout:function(e){t(e.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}})}(jQuery),function(t){var e=!1;t(document).mouseup(function(){e=!1}),t.widget("ui.mouse",{version:"1.10.3",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.bind("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).bind("click."+this.widgetName,function(i){return!0===t.data(i.target,e.widgetName+".preventClickEvent")?(t.removeData(i.target,e.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):undefined}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&t(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(i){if(!e){this._mouseStarted&&this._mouseUp(i),this._mouseDownEvent=i;var s=this,n=1===i.which,o="string"==typeof this.options.cancel&&i.target.nodeName?t(i.target).closest(this.options.cancel).length:!1;return n&&!o&&this._mouseCapture(i)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){s.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(i)&&this._mouseDelayMet(i)&&(this._mouseStarted=this._mouseStart(i)!==!1,!this._mouseStarted)?(i.preventDefault(),!0):(!0===t.data(i.target,this.widgetName+".preventClickEvent")&&t.removeData(i.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return s._mouseMove(t)},this._mouseUpDelegate=function(t){return s._mouseUp(t)},t(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),i.preventDefault(),e=!0,!0)):!0}},_mouseMove:function(e){return t.ui.ie&&(!document.documentMode||9>document.documentMode)&&!e.button?this._mouseUp(e):this._mouseStarted?(this._mouseDrag(e),e.preventDefault()):(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1,this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)),!this._mouseStarted)},_mouseUp:function(e){return t(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),!1},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})}(jQuery),function(t){t.widget("ui.draggable",t.ui.mouse,{version:"1.10.3",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"!==this.options.helper||/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(e){var i=this.options;return this.helper||i.disabled||t(e.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(e),this.handle?(t(i.iframeFix===!0?"iframe":i.iframeFix).each(function(){t("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>").css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(t(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(e){var i=this.options;return this.helper=this._createHelper(e),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),t.ui.ddmanager&&(t.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offsetParent=this.helper.offsetParent(),this.offsetParentCssPosition=this.offsetParent.css("position"),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},this.offset.scroll=!1,t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",e)===!1?(this._clear(),!1):(this._cacheHelperProportions(),t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this._mouseDrag(e,!0),t.ui.ddmanager&&t.ui.ddmanager.dragStart(this,e),!0)},_mouseDrag:function(e,i){if("fixed"===this.offsetParentCssPosition&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",e,s)===!1)return this._mouseUp({}),!1;this.position=s.position}return this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),!1},_mouseStop:function(e){var i=this,s=!1;return t.ui.ddmanager&&!this.options.dropBehaviour&&(s=t.ui.ddmanager.drop(this,e)),this.dropped&&(s=this.dropped,this.dropped=!1),"original"!==this.options.helper||t.contains(this.element[0].ownerDocument,this.element[0])?("invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||t.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?t(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",e)!==!1&&i._clear()}):this._trigger("stop",e)!==!1&&this._clear(),!1):!1},_mouseUp:function(e){return t("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),t.ui.ddmanager&&t.ui.ddmanager.dragStop(this,e),t.ui.mouse.prototype._mouseUp.call(this,e)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(e){return this.options.handle?!!t(e.target).closest(this.element.find(this.options.handle)).length:!0},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return s.parents("body").length||s.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s[0]===this.element[0]||/(fixed|absolute)/.test(s.css("position"))||s.css("position","absolute"),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.element.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;return n.containment?"window"===n.containment?(this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):"document"===n.containment?(this.containment=[0,0,t(document).width()-this.helperProportions.width-this.margins.left,(t(document).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):n.containment.constructor===Array?(this.containment=n.containment,undefined):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=t(n.containment),s=i[0],s&&(e="hidden"!==i.css("overflow"),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=i),undefined):(this.containment=null,undefined)},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent;return this.offset.scroll||(this.offset.scroll={top:n.scrollTop(),left:n.scrollLeft()}),{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top)*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)*s}},_generatePosition:function(e){var i,s,n,o,a=this.options,r="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=e.pageX,l=e.pageY;return this.offset.scroll||(this.offset.scroll={top:r.scrollTop(),left:r.scrollLeft()}),this.originalPosition&&(this.containment&&(this.relative_container?(s=this.relative_container.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,e.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),e.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),e.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),e.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),a.grid&&(n=a.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/a.grid[1])*a.grid[1]:this.originalPageY,l=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-a.grid[1]:n+a.grid[1]:n,o=a.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/a.grid[0])*a.grid[0]:this.originalPageX,h=i?o-this.offset.click.left>=i[0]||o-this.offset.click.left>i[2]?o:o-this.offset.click.left>=i[0]?o-a.grid[0]:o+a.grid[0]:o)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s]),"drag"===e&&(this.positionAbs=this._convertPositionTo("absolute")),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i){var s=t(this).data("ui-draggable"),n=s.options,o=t.extend({},i,{item:s.element});s.sortables=[],t(n.connectToSortable).each(function(){var i=t.data(this,"ui-sortable");i&&!i.options.disabled&&(s.sortables.push({instance:i,shouldRevert:i.options.revert}),i.refreshPositions(),i._trigger("activate",e,o))})},stop:function(e,i){var s=t(this).data("ui-draggable"),n=t.extend({},i,{item:s.element});t.each(s.sortables,function(){this.instance.isOver?(this.instance.isOver=0,s.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=this.shouldRevert),this.instance._mouseStop(e),this.instance.options.helper=this.instance.options._helper,"original"===s.options.helper&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",e,n))})},drag:function(e,i){var s=t(this).data("ui-draggable"),n=this;t.each(s.sortables,function(){var o=!1,a=this;this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(o=!0,t.each(s.sortables,function(){return this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this!==a&&this.instance._intersectsWith(this.instance.containerCache)&&t.contains(a.instance.element[0],this.instance.element[0])&&(o=!1),o})),o?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=t(n).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return i.helper[0]},e.target=this.instance.currentItem[0],this.instance._mouseCapture(e,!0),this.instance._mouseStart(e,!0,!0),this.instance.offset.click.top=s.offset.click.top,this.instance.offset.click.left=s.offset.click.left,this.instance.offset.parent.left-=s.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=s.offset.parent.top-this.instance.offset.parent.top,s._trigger("toSortable",e),s.dropped=this.instance.element,s.currentItem=s.element,this.instance.fromOutside=s),this.instance.currentItem&&this.instance._mouseDrag(e)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",e,this.instance._uiHash(this.instance)),this.instance._mouseStop(e,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),s._trigger("fromSortable",e),s.dropped=!1)})}}),t.ui.plugin.add("draggable","cursor",{start:function(){var e=t("body"),i=t(this).data("ui-draggable").options;e.css("cursor")&&(i._cursor=e.css("cursor")),e.css("cursor",i.cursor)},stop:function(){var e=t(this).data("ui-draggable").options;e._cursor&&t("body").css("cursor",e._cursor)}}),t.ui.plugin.add("draggable","opacity",{start:function(e,i){var s=t(i.helper),n=t(this).data("ui-draggable").options;s.css("opacity")&&(n._opacity=s.css("opacity")),s.css("opacity",n.opacity)},stop:function(e,i){var s=t(this).data("ui-draggable").options;s._opacity&&t(i.helper).css("opacity",s._opacity)}}),t.ui.plugin.add("draggable","scroll",{start:function(){var e=t(this).data("ui-draggable");e.scrollParent[0]!==document&&"HTML"!==e.scrollParent[0].tagName&&(e.overflowOffset=e.scrollParent.offset())},drag:function(e){var i=t(this).data("ui-draggable"),s=i.options,n=!1;i.scrollParent[0]!==document&&"HTML"!==i.scrollParent[0].tagName?(s.axis&&"x"===s.axis||(i.overflowOffset.top+i.scrollParent[0].offsetHeight-e.pageY<s.scrollSensitivity?i.scrollParent[0].scrollTop=n=i.scrollParent[0].scrollTop+s.scrollSpeed:e.pageY-i.overflowOffset.top<s.scrollSensitivity&&(i.scrollParent[0].scrollTop=n=i.scrollParent[0].scrollTop-s.scrollSpeed)),s.axis&&"y"===s.axis||(i.overflowOffset.left+i.scrollParent[0].offsetWidth-e.pageX<s.scrollSensitivity?i.scrollParent[0].scrollLeft=n=i.scrollParent[0].scrollLeft+s.scrollSpeed:e.pageX-i.overflowOffset.left<s.scrollSensitivity&&(i.scrollParent[0].scrollLeft=n=i.scrollParent[0].scrollLeft-s.scrollSpeed))):(s.axis&&"x"===s.axis||(e.pageY-t(document).scrollTop()<s.scrollSensitivity?n=t(document).scrollTop(t(document).scrollTop()-s.scrollSpeed):t(window).height()-(e.pageY-t(document).scrollTop())<s.scrollSensitivity&&(n=t(document).scrollTop(t(document).scrollTop()+s.scrollSpeed))),s.axis&&"y"===s.axis||(e.pageX-t(document).scrollLeft()<s.scrollSensitivity?n=t(document).scrollLeft(t(document).scrollLeft()-s.scrollSpeed):t(window).width()-(e.pageX-t(document).scrollLeft())<s.scrollSensitivity&&(n=t(document).scrollLeft(t(document).scrollLeft()+s.scrollSpeed)))),n!==!1&&t.ui.ddmanager&&!s.dropBehaviour&&t.ui.ddmanager.prepareOffsets(i,e)}}),t.ui.plugin.add("draggable","snap",{start:function(){var e=t(this).data("ui-draggable"),i=e.options;e.snapElements=[],t(i.snap.constructor!==String?i.snap.items||":data(ui-draggable)":i.snap).each(function(){var i=t(this),s=i.offset();this!==e.element[0]&&e.snapElements.push({item:this,width:i.outerWidth(),height:i.outerHeight(),top:s.top,left:s.left})})},drag:function(e,i){var s,n,o,a,r,h,l,c,u,d,p=t(this).data("ui-draggable"),f=p.options,g=f.snapTolerance,m=i.offset.left,v=m+p.helperProportions.width,_=i.offset.top,b=_+p.helperProportions.height;for(u=p.snapElements.length-1;u>=0;u--)r=p.snapElements[u].left,h=r+p.snapElements[u].width,l=p.snapElements[u].top,c=l+p.snapElements[u].height,r-g>v||m>h+g||l-g>b||_>c+g||!t.contains(p.snapElements[u].item.ownerDocument,p.snapElements[u].item)?(p.snapElements[u].snapping&&p.options.snap.release&&p.options.snap.release.call(p.element,e,t.extend(p._uiHash(),{snapItem:p.snapElements[u].item})),p.snapElements[u].snapping=!1):("inner"!==f.snapMode&&(s=g>=Math.abs(l-b),n=g>=Math.abs(c-_),o=g>=Math.abs(r-v),a=g>=Math.abs(h-m),s&&(i.position.top=p._convertPositionTo("relative",{top:l-p.helperProportions.height,left:0}).top-p.margins.top),n&&(i.position.top=p._convertPositionTo("relative",{top:c,left:0}).top-p.margins.top),o&&(i.position.left=p._convertPositionTo("relative",{top:0,left:r-p.helperProportions.width}).left-p.margins.left),a&&(i.position.left=p._convertPositionTo("relative",{top:0,left:h}).left-p.margins.left)),d=s||n||o||a,"outer"!==f.snapMode&&(s=g>=Math.abs(l-_),n=g>=Math.abs(c-b),o=g>=Math.abs(r-m),a=g>=Math.abs(h-v),s&&(i.position.top=p._convertPositionTo("relative",{top:l,left:0}).top-p.margins.top),n&&(i.position.top=p._convertPositionTo("relative",{top:c-p.helperProportions.height,left:0}).top-p.margins.top),o&&(i.position.left=p._convertPositionTo("relative",{top:0,left:r}).left-p.margins.left),a&&(i.position.left=p._convertPositionTo("relative",{top:0,left:h-p.helperProportions.width}).left-p.margins.left)),!p.snapElements[u].snapping&&(s||n||o||a||d)&&p.options.snap.snap&&p.options.snap.snap.call(p.element,e,t.extend(p._uiHash(),{snapItem:p.snapElements[u].item})),p.snapElements[u].snapping=s||n||o||a||d)}}),t.ui.plugin.add("draggable","stack",{start:function(){var e,i=this.data("ui-draggable").options,s=t.makeArray(t(i.stack)).sort(function(e,i){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(i).css("zIndex"),10)||0)});s.length&&(e=parseInt(t(s[0]).css("zIndex"),10)||0,t(s).each(function(i){t(this).css("zIndex",e+i)}),this.css("zIndex",e+s.length))}}),t.ui.plugin.add("draggable","zIndex",{start:function(e,i){var s=t(i.helper),n=t(this).data("ui-draggable").options;s.css("zIndex")&&(n._zIndex=s.css("zIndex")),s.css("zIndex",n.zIndex)},stop:function(e,i){var s=t(this).data("ui-draggable").options;s._zIndex&&t(i.helper).css("zIndex",s._zIndex)}})}(jQuery),function(t){function e(t,e,i){return t>e&&e+i>t}t.widget("ui.droppable",{version:"1.10.3",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var e=this.options,i=e.accept;this.isover=!1,this.isout=!0,this.accept=t.isFunction(i)?i:function(t){return t.is(i) },this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight},t.ui.ddmanager.droppables[e.scope]=t.ui.ddmanager.droppables[e.scope]||[],t.ui.ddmanager.droppables[e.scope].push(this),e.addClasses&&this.element.addClass("ui-droppable")},_destroy:function(){for(var e=0,i=t.ui.ddmanager.droppables[this.options.scope];i.length>e;e++)i[e]===this&&i.splice(e,1);this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(e,i){"accept"===e&&(this.accept=t.isFunction(i)?i:function(t){return t.is(i)}),t.Widget.prototype._setOption.apply(this,arguments)},_activate:function(e){var i=t.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),i&&this._trigger("activate",e,this.ui(i))},_deactivate:function(e){var i=t.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),i&&this._trigger("deactivate",e,this.ui(i))},_over:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",e,this.ui(i)))},_out:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",e,this.ui(i)))},_drop:function(e,i){var s=i||t.ui.ddmanager.current,n=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var e=t.data(this,"ui-droppable");return e.options.greedy&&!e.options.disabled&&e.options.scope===s.options.scope&&e.accept.call(e.element[0],s.currentItem||s.element)&&t.ui.intersect(s,t.extend(e,{offset:e.element.offset()}),e.options.tolerance)?(n=!0,!1):undefined}),n?!1:this.accept.call(this.element[0],s.currentItem||s.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",e,this.ui(s)),this.element):!1):!1},ui:function(t){return{draggable:t.currentItem||t.element,helper:t.helper,position:t.position,offset:t.positionAbs}}}),t.ui.intersect=function(t,i,s){if(!i.offset)return!1;var n,o,a=(t.positionAbs||t.position.absolute).left,r=a+t.helperProportions.width,h=(t.positionAbs||t.position.absolute).top,l=h+t.helperProportions.height,c=i.offset.left,u=c+i.proportions.width,d=i.offset.top,p=d+i.proportions.height;switch(s){case"fit":return a>=c&&u>=r&&h>=d&&p>=l;case"intersect":return a+t.helperProportions.width/2>c&&u>r-t.helperProportions.width/2&&h+t.helperProportions.height/2>d&&p>l-t.helperProportions.height/2;case"pointer":return n=(t.positionAbs||t.position.absolute).left+(t.clickOffset||t.offset.click).left,o=(t.positionAbs||t.position.absolute).top+(t.clickOffset||t.offset.click).top,e(o,d,i.proportions.height)&&e(n,c,i.proportions.width);case"touch":return(h>=d&&p>=h||l>=d&&p>=l||d>h&&l>p)&&(a>=c&&u>=a||r>=c&&u>=r||c>a&&r>u);default:return!1}},t.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,i){var s,n,o=t.ui.ddmanager.droppables[e.options.scope]||[],a=i?i.type:null,r=(e.currentItem||e.element).find(":data(ui-droppable)").addBack();t:for(s=0;o.length>s;s++)if(!(o[s].options.disabled||e&&!o[s].accept.call(o[s].element[0],e.currentItem||e.element))){for(n=0;r.length>n;n++)if(r[n]===o[s].element[0]){o[s].proportions.height=0;continue t}o[s].visible="none"!==o[s].element.css("display"),o[s].visible&&("mousedown"===a&&o[s]._activate.call(o[s],i),o[s].offset=o[s].element.offset(),o[s].proportions={width:o[s].element[0].offsetWidth,height:o[s].element[0].offsetHeight})}},drop:function(e,i){var s=!1;return t.each((t.ui.ddmanager.droppables[e.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&t.ui.intersect(e,this,this.options.tolerance)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(e,i){e.element.parentsUntil("body").bind("scroll.droppable",function(){e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)})},drag:function(e,i){e.options.refreshPositions&&t.ui.ddmanager.prepareOffsets(e,i),t.each(t.ui.ddmanager.droppables[e.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,n,o,a=t.ui.intersect(e,this,this.options.tolerance),r=!a&&this.isover?"isout":a&&!this.isover?"isover":null;r&&(this.options.greedy&&(n=this.options.scope,o=this.element.parents(":data(ui-droppable)").filter(function(){return t.data(this,"ui-droppable").options.scope===n}),o.length&&(s=t.data(o[0],"ui-droppable"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(e,i){e.element.parentsUntil("body").unbind("scroll.droppable"),e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)}}}(jQuery),function(t){function e(t){return parseInt(t,10)||0}function i(t){return!isNaN(parseInt(t,10))}t.widget("ui.resizable",t.ui.mouse,{version:"1.10.3",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_create:function(){var e,i,s,n,o,a=this,r=this.options;if(this.element.addClass("ui-resizable"),t.extend(this,{_aspectRatio:!!r.aspectRatio,aspectRatio:r.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:r.helper||r.ghost||r.animate?r.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(t("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.data("ui-resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=r.handles||(t(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),e=this.handles.split(","),this.handles={},i=0;e.length>i;i++)s=t.trim(e[i]),o="ui-resizable-"+s,n=t("<div class='ui-resizable-handle "+o+"'></div>"),n.css({zIndex:r.zIndex}),"se"===s&&n.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(n);this._renderAxis=function(e){var i,s,n,o;e=e||this.element;for(i in this.handles)this.handles[i].constructor===String&&(this.handles[i]=t(this.handles[i],this.element).show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(s=t(this.handles[i],this.element),o=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),e.css(n,o),this._proportionallyResize()),t(this.handles[i]).length},this._renderAxis(this.element),this._handles=t(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){a.resizing||(this.className&&(n=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),a.axis=n&&n[1]?n[1]:"se")}),r.autoHide&&(this._handles.hide(),t(this.element).addClass("ui-resizable-autohide").mouseenter(function(){r.disabled||(t(this).removeClass("ui-resizable-autohide"),a._handles.show())}).mouseleave(function(){r.disabled||a.resizing||(t(this).addClass("ui-resizable-autohide"),a._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var e,i=function(e){t(e).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_mouseCapture:function(e){var i,s,n=!1;for(i in this.handles)s=t(this.handles[i])[0],(s===e.target||t.contains(s,e.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(i){var s,n,o,a=this.options,r=this.element.position(),h=this.element;return this.resizing=!0,/absolute/.test(h.css("position"))?h.css({position:"absolute",top:h.css("top"),left:h.css("left")}):h.is(".ui-draggable")&&h.css({position:"absolute",top:r.top,left:r.left}),this._renderProxy(),s=e(this.helper.css("left")),n=e(this.helper.css("top")),a.containment&&(s+=t(a.containment).scrollLeft()||0,n+=t(a.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:s,top:n},this.size=this._helper?{width:h.outerWidth(),height:h.outerHeight()}:{width:h.width(),height:h.height()},this.originalSize=this._helper?{width:h.outerWidth(),height:h.outerHeight()}:{width:h.width(),height:h.height()},this.originalPosition={left:s,top:n},this.sizeDiff={width:h.outerWidth()-h.width(),height:h.outerHeight()-h.height()},this.originalMousePosition={left:i.pageX,top:i.pageY},this.aspectRatio="number"==typeof a.aspectRatio?a.aspectRatio:this.originalSize.width/this.originalSize.height||1,o=t(".ui-resizable-"+this.axis).css("cursor"),t("body").css("cursor","auto"===o?this.axis+"-resize":o),h.addClass("ui-resizable-resizing"),this._propagate("start",i),!0},_mouseDrag:function(e){var i,s=this.helper,n={},o=this.originalMousePosition,a=this.axis,r=this.position.top,h=this.position.left,l=this.size.width,c=this.size.height,u=e.pageX-o.left||0,d=e.pageY-o.top||0,p=this._change[a];return p?(i=p.apply(this,[e,u,d]),this._updateVirtualBoundaries(e.shiftKey),(this._aspectRatio||e.shiftKey)&&(i=this._updateRatio(i,e)),i=this._respectSize(i,e),this._updateCache(i),this._propagate("resize",e),this.position.top!==r&&(n.top=this.position.top+"px"),this.position.left!==h&&(n.left=this.position.left+"px"),this.size.width!==l&&(n.width=this.size.width+"px"),this.size.height!==c&&(n.height=this.size.height+"px"),s.css(n),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),t.isEmptyObject(n)||this._trigger("resize",e,this.ui()),!1):!1},_mouseStop:function(e){this.resizing=!1;var i,s,n,o,a,r,h,l=this.options,c=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),n=s&&t.ui.hasScroll(i[0],"left")?0:c.sizeDiff.height,o=s?0:c.sizeDiff.width,a={width:c.helper.width()-o,height:c.helper.height()-n},r=parseInt(c.element.css("left"),10)+(c.position.left-c.originalPosition.left)||null,h=parseInt(c.element.css("top"),10)+(c.position.top-c.originalPosition.top)||null,l.animate||this.element.css(t.extend(a,{top:h,left:r})),c.helper.height(c.size.height),c.helper.width(c.size.width),this._helper&&!l.animate&&this._proportionallyResize()),t("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",e),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(t){var e,s,n,o,a,r=this.options;a={minWidth:i(r.minWidth)?r.minWidth:0,maxWidth:i(r.maxWidth)?r.maxWidth:1/0,minHeight:i(r.minHeight)?r.minHeight:0,maxHeight:i(r.maxHeight)?r.maxHeight:1/0},(this._aspectRatio||t)&&(e=a.minHeight*this.aspectRatio,n=a.minWidth/this.aspectRatio,s=a.maxHeight*this.aspectRatio,o=a.maxWidth/this.aspectRatio,e>a.minWidth&&(a.minWidth=e),n>a.minHeight&&(a.minHeight=n),a.maxWidth>s&&(a.maxWidth=s),a.maxHeight>o&&(a.maxHeight=o)),this._vBoundaries=a},_updateCache:function(t){this.offset=this.helper.offset(),i(t.left)&&(this.position.left=t.left),i(t.top)&&(this.position.top=t.top),i(t.height)&&(this.size.height=t.height),i(t.width)&&(this.size.width=t.width)},_updateRatio:function(t){var e=this.position,s=this.size,n=this.axis;return i(t.height)?t.width=t.height*this.aspectRatio:i(t.width)&&(t.height=t.width/this.aspectRatio),"sw"===n&&(t.left=e.left+(s.width-t.width),t.top=null),"nw"===n&&(t.top=e.top+(s.height-t.height),t.left=e.left+(s.width-t.width)),t},_respectSize:function(t){var e=this._vBoundaries,s=this.axis,n=i(t.width)&&e.maxWidth&&e.maxWidth<t.width,o=i(t.height)&&e.maxHeight&&e.maxHeight<t.height,a=i(t.width)&&e.minWidth&&e.minWidth>t.width,r=i(t.height)&&e.minHeight&&e.minHeight>t.height,h=this.originalPosition.left+this.originalSize.width,l=this.position.top+this.size.height,c=/sw|nw|w/.test(s),u=/nw|ne|n/.test(s);return a&&(t.width=e.minWidth),r&&(t.height=e.minHeight),n&&(t.width=e.maxWidth),o&&(t.height=e.maxHeight),a&&c&&(t.left=h-e.minWidth),n&&c&&(t.left=h-e.maxWidth),r&&u&&(t.top=l-e.minHeight),o&&u&&(t.top=l-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_proportionallyResize:function(){if(this._proportionallyResizeElements.length){var t,e,i,s,n,o=this.helper||this.element;for(t=0;this._proportionallyResizeElements.length>t;t++){if(n=this._proportionallyResizeElements[t],!this.borderDif)for(this.borderDif=[],i=[n.css("borderTopWidth"),n.css("borderRightWidth"),n.css("borderBottomWidth"),n.css("borderLeftWidth")],s=[n.css("paddingTop"),n.css("paddingRight"),n.css("paddingBottom"),n.css("paddingLeft")],e=0;i.length>e;e++)this.borderDif[e]=(parseInt(i[e],10)||0)+(parseInt(s[e],10)||0);n.css({height:o.height()-this.borderDif[0]-this.borderDif[2]||0,width:o.width()-this.borderDif[1]-this.borderDif[3]||0})}}},_renderProxy:function(){var e=this.element,i=this.options;this.elementOffset=e.offset(),this._helper?(this.helper=this.helper||t("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize,s=this.originalPosition;return{left:s.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize,n=this.originalPosition;return{top:n.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},sw:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[e,i,s]))},ne:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},nw:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[e,i,s]))}},_propagate:function(e,i){t.ui.plugin.call(this,e,[i,this.ui()]),"resize"!==e&&this._trigger(e,i,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),t.ui.plugin.add("resizable","animate",{stop:function(e){var i=t(this).data("ui-resizable"),s=i.options,n=i._proportionallyResizeElements,o=n.length&&/textarea/i.test(n[0].nodeName),a=o&&t.ui.hasScroll(n[0],"left")?0:i.sizeDiff.height,r=o?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-a},l=parseInt(i.element.css("left"),10)+(i.position.left-i.originalPosition.left)||null,c=parseInt(i.element.css("top"),10)+(i.position.top-i.originalPosition.top)||null;i.element.animate(t.extend(h,c&&l?{top:c,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseInt(i.element.css("width"),10),height:parseInt(i.element.css("height"),10),top:parseInt(i.element.css("top"),10),left:parseInt(i.element.css("left"),10)};n&&n.length&&t(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",e)}})}}),t.ui.plugin.add("resizable","containment",{start:function(){var i,s,n,o,a,r,h,l=t(this).data("ui-resizable"),c=l.options,u=l.element,d=c.containment,p=d instanceof t?d.get(0):/parent/.test(d)?u.parent().get(0):d;p&&(l.containerElement=t(p),/document/.test(d)||d===document?(l.containerOffset={left:0,top:0},l.containerPosition={left:0,top:0},l.parentData={element:t(document),left:0,top:0,width:t(document).width(),height:t(document).height()||document.body.parentNode.scrollHeight}):(i=t(p),s=[],t(["Top","Right","Left","Bottom"]).each(function(t,n){s[t]=e(i.css("padding"+n))}),l.containerOffset=i.offset(),l.containerPosition=i.position(),l.containerSize={height:i.innerHeight()-s[3],width:i.innerWidth()-s[1]},n=l.containerOffset,o=l.containerSize.height,a=l.containerSize.width,r=t.ui.hasScroll(p,"left")?p.scrollWidth:a,h=t.ui.hasScroll(p)?p.scrollHeight:o,l.parentData={element:p,left:n.left,top:n.top,width:r,height:h}))},resize:function(e){var i,s,n,o,a=t(this).data("ui-resizable"),r=a.options,h=a.containerOffset,l=a.position,c=a._aspectRatio||e.shiftKey,u={top:0,left:0},d=a.containerElement;d[0]!==document&&/static/.test(d.css("position"))&&(u=h),l.left<(a._helper?h.left:0)&&(a.size.width=a.size.width+(a._helper?a.position.left-h.left:a.position.left-u.left),c&&(a.size.height=a.size.width/a.aspectRatio),a.position.left=r.helper?h.left:0),l.top<(a._helper?h.top:0)&&(a.size.height=a.size.height+(a._helper?a.position.top-h.top:a.position.top),c&&(a.size.width=a.size.height*a.aspectRatio),a.position.top=a._helper?h.top:0),a.offset.left=a.parentData.left+a.position.left,a.offset.top=a.parentData.top+a.position.top,i=Math.abs((a._helper?a.offset.left-u.left:a.offset.left-u.left)+a.sizeDiff.width),s=Math.abs((a._helper?a.offset.top-u.top:a.offset.top-h.top)+a.sizeDiff.height),n=a.containerElement.get(0)===a.element.parent().get(0),o=/relative|absolute/.test(a.containerElement.css("position")),n&&o&&(i-=a.parentData.left),i+a.size.width>=a.parentData.width&&(a.size.width=a.parentData.width-i,c&&(a.size.height=a.size.width/a.aspectRatio)),s+a.size.height>=a.parentData.height&&(a.size.height=a.parentData.height-s,c&&(a.size.width=a.size.height*a.aspectRatio))},stop:function(){var e=t(this).data("ui-resizable"),i=e.options,s=e.containerOffset,n=e.containerPosition,o=e.containerElement,a=t(e.helper),r=a.offset(),h=a.outerWidth()-e.sizeDiff.width,l=a.outerHeight()-e.sizeDiff.height;e._helper&&!i.animate&&/relative/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l}),e._helper&&!i.animate&&/static/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l})}}),t.ui.plugin.add("resizable","alsoResize",{start:function(){var e=t(this).data("ui-resizable"),i=e.options,s=function(e){t(e).each(function(){var e=t(this);e.data("ui-resizable-alsoresize",{width:parseInt(e.width(),10),height:parseInt(e.height(),10),left:parseInt(e.css("left"),10),top:parseInt(e.css("top"),10)})})};"object"!=typeof i.alsoResize||i.alsoResize.parentNode?s(i.alsoResize):i.alsoResize.length?(i.alsoResize=i.alsoResize[0],s(i.alsoResize)):t.each(i.alsoResize,function(t){s(t)})},resize:function(e,i){var s=t(this).data("ui-resizable"),n=s.options,o=s.originalSize,a=s.originalPosition,r={height:s.size.height-o.height||0,width:s.size.width-o.width||0,top:s.position.top-a.top||0,left:s.position.left-a.left||0},h=function(e,s){t(e).each(function(){var e=t(this),n=t(this).data("ui-resizable-alsoresize"),o={},a=s&&s.length?s:e.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];t.each(a,function(t,e){var i=(n[e]||0)+(r[e]||0);i&&i>=0&&(o[e]=i||null)}),e.css(o)})};"object"!=typeof n.alsoResize||n.alsoResize.nodeType?h(n.alsoResize):t.each(n.alsoResize,function(t,e){h(t,e)})},stop:function(){t(this).removeData("resizable-alsoresize")}}),t.ui.plugin.add("resizable","ghost",{start:function(){var e=t(this).data("ui-resizable"),i=e.options,s=e.size;e.ghost=e.originalElement.clone(),e.ghost.css({opacity:.25,display:"block",position:"relative",height:s.height,width:s.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass("string"==typeof i.ghost?i.ghost:""),e.ghost.appendTo(e.helper)},resize:function(){var e=t(this).data("ui-resizable");e.ghost&&e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})},stop:function(){var e=t(this).data("ui-resizable");e.ghost&&e.helper&&e.helper.get(0).removeChild(e.ghost.get(0))}}),t.ui.plugin.add("resizable","grid",{resize:function(){var e=t(this).data("ui-resizable"),i=e.options,s=e.size,n=e.originalSize,o=e.originalPosition,a=e.axis,r="number"==typeof i.grid?[i.grid,i.grid]:i.grid,h=r[0]||1,l=r[1]||1,c=Math.round((s.width-n.width)/h)*h,u=Math.round((s.height-n.height)/l)*l,d=n.width+c,p=n.height+u,f=i.maxWidth&&d>i.maxWidth,g=i.maxHeight&&p>i.maxHeight,m=i.minWidth&&i.minWidth>d,v=i.minHeight&&i.minHeight>p;i.grid=r,m&&(d+=h),v&&(p+=l),f&&(d-=h),g&&(p-=l),/^(se|s|e)$/.test(a)?(e.size.width=d,e.size.height=p):/^(ne)$/.test(a)?(e.size.width=d,e.size.height=p,e.position.top=o.top-u):/^(sw)$/.test(a)?(e.size.width=d,e.size.height=p,e.position.left=o.left-c):(e.size.width=d,e.size.height=p,e.position.top=o.top-u,e.position.left=o.left-c)}})}(jQuery),function(t){t.widget("ui.selectable",t.ui.mouse,{version:"1.10.3",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var e,i=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){e=t(i.options.filter,i.element[0]),e.addClass("ui-selectee"),e.each(function(){var e=t(this),i=e.offset();t.data(this,"selectable-item",{element:this,$element:e,left:i.left,top:i.top,right:i.left+e.outerWidth(),bottom:i.top+e.outerHeight(),startselected:!1,selected:e.hasClass("ui-selected"),selecting:e.hasClass("ui-selecting"),unselecting:e.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=e.addClass("ui-selectee"),this._mouseInit(),this.helper=t("<div class='ui-selectable-helper'></div>")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(e){var i=this,s=this.options;this.opos=[e.pageX,e.pageY],this.options.disabled||(this.selectees=t(s.filter,this.element[0]),this._trigger("start",e),t(s.appendTo).append(this.helper),this.helper.css({left:e.pageX,top:e.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=t.data(this,"selectable-item");s.startselected=!0,e.metaKey||e.ctrlKey||(s.$element.removeClass("ui-selected"),s.selected=!1,s.$element.addClass("ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",e,{unselecting:s.element}))}),t(e.target).parents().addBack().each(function(){var s,n=t.data(this,"selectable-item");return n?(s=!e.metaKey&&!e.ctrlKey||!n.$element.hasClass("ui-selected"),n.$element.removeClass(s?"ui-unselecting":"ui-selected").addClass(s?"ui-selecting":"ui-unselecting"),n.unselecting=!s,n.selecting=s,n.selected=s,s?i._trigger("selecting",e,{selecting:n.element}):i._trigger("unselecting",e,{unselecting:n.element}),!1):undefined}))},_mouseDrag:function(e){if(this.dragged=!0,!this.options.disabled){var i,s=this,n=this.options,o=this.opos[0],a=this.opos[1],r=e.pageX,h=e.pageY;return o>r&&(i=r,r=o,o=i),a>h&&(i=h,h=a,a=i),this.helper.css({left:o,top:a,width:r-o,height:h-a}),this.selectees.each(function(){var i=t.data(this,"selectable-item"),l=!1;i&&i.element!==s.element[0]&&("touch"===n.tolerance?l=!(i.left>r||o>i.right||i.top>h||a>i.bottom):"fit"===n.tolerance&&(l=i.left>o&&r>i.right&&i.top>a&&h>i.bottom),l?(i.selected&&(i.$element.removeClass("ui-selected"),i.selected=!1),i.unselecting&&(i.$element.removeClass("ui-unselecting"),i.unselecting=!1),i.selecting||(i.$element.addClass("ui-selecting"),i.selecting=!0,s._trigger("selecting",e,{selecting:i.element}))):(i.selecting&&((e.metaKey||e.ctrlKey)&&i.startselected?(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.$element.addClass("ui-selected"),i.selected=!0):(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.startselected&&(i.$element.addClass("ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",e,{unselecting:i.element}))),i.selected&&(e.metaKey||e.ctrlKey||i.startselected||(i.$element.removeClass("ui-selected"),i.selected=!1,i.$element.addClass("ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",e,{unselecting:i.element})))))}),!1}},_mouseStop:function(e){var i=this;return this.dragged=!1,t(".ui-unselecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");s.$element.removeClass("ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",e,{unselected:s.element})}),t(".ui-selecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");s.$element.removeClass("ui-selecting").addClass("ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",e,{selected:s.element})}),this._trigger("stop",e),this.helper.remove(),!1}})}(jQuery),function(t){function e(t,e,i){return t>e&&e+i>t}function i(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))}t.widget("ui.sortable",t.ui.mouse,{version:"1.10.3",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_create:function(){var t=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?"x"===t.axis||i(this.items[0].item):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_setOption:function(e,i){"disabled"===e?(this.options[e]=i,this.widget().toggleClass("ui-sortable-disabled",!!i)):t.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(e,i){var s=null,n=!1,o=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(e),t(e.target).parents().each(function(){return t.data(this,o.widgetName+"-item")===o?(s=t(this),!1):undefined}),t.data(e.target,o.widgetName+"-item")===o&&(s=t(e.target)),s?!this.options.handle||i||(t(this.options.handle,s).find("*").addBack().each(function(){this===e.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(e,i,s){var n,o,a=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,a.cursorAt&&this._adjustOffsetFromHelper(a.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),a.containment&&this._setContainment(),a.cursor&&"auto"!==a.cursor&&(o=this.document.find("body"),this.storedCursor=o.css("cursor"),o.css("cursor",a.cursor),this.storedStylesheet=t("<style>*{ cursor: "+a.cursor+" !important; }</style>").appendTo(o)),a.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",a.opacity)),a.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",a.zIndex)),this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",e,this._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(e),!0},_mouseDrag:function(e){var i,s,n,o,a=this.options,r=!1;for(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<a.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+a.scrollSpeed:e.pageY-this.overflowOffset.top<a.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-a.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<a.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+a.scrollSpeed:e.pageX-this.overflowOffset.left<a.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-a.scrollSpeed)):(e.pageY-t(document).scrollTop()<a.scrollSensitivity?r=t(document).scrollTop(t(document).scrollTop()-a.scrollSpeed):t(window).height()-(e.pageY-t(document).scrollTop())<a.scrollSensitivity&&(r=t(document).scrollTop(t(document).scrollTop()+a.scrollSpeed)),e.pageX-t(document).scrollLeft()<a.scrollSensitivity?r=t(document).scrollLeft(t(document).scrollLeft()-a.scrollSpeed):t(window).width()-(e.pageX-t(document).scrollLeft())<a.scrollSensitivity&&(r=t(document).scrollLeft(t(document).scrollLeft()+a.scrollSpeed))),r!==!1&&t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],n=s.item[0],o=this._intersectsWithPointer(s),o&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==n&&!t.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],n):!0)){if(this.direction=1===o?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break; this._rearrange(e,s),this._trigger("change",e,this._uiHash());break}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var s=this,n=this.placeholder.offset(),o=this.options.axis,a={};o&&"x"!==o||(a.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft)),o&&"y"!==o||(a.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,t(this.helper).animate(a,parseInt(this.options.revert,10)||500,function(){s._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("deactivate",null,this._uiHash(this)),this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",null,this._uiHash(this)),this.containers[e].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);i&&s.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!s.length&&e.key&&s.push(e.key+"="),s.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},i.each(function(){s.push(t(e.item||this).attr(e.attribute||"id")||"")}),s},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,o=t.left,a=o+t.width,r=t.top,h=r+t.height,l=this.offset.click.top,c=this.offset.click.left,u="x"===this.options.axis||s+l>r&&h>s+l,d="y"===this.options.axis||e+c>o&&a>e+c,p=u&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?p:e+this.helperProportions.width/2>o&&a>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(t){var i="x"===this.options.axis||e(this.positionAbs.top+this.offset.click.top,t.top,t.height),s="y"===this.options.axis||e(this.positionAbs.left+this.offset.click.left,t.left,t.width),n=i&&s,o=this._getDragVerticalDirection(),a=this._getDragHorizontalDirection();return n?this.floating?a&&"right"===a||"down"===o?2:1:o&&("down"===o?2:1):!1},_intersectsWithSides:function(t){var i=e(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),s=e(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),n=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return this.floating&&o?"right"===o&&s||"left"===o&&!s:n&&("down"===n&&i||"up"===n&&!i)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){return this._refreshItems(t),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){var i,s,n,o,a=[],r=[],h=this._connectWith();if(h&&e)for(i=h.length-1;i>=0;i--)for(n=t(h[i]),s=n.length-1;s>=0;s--)o=t.data(n[s],this.widgetFullName),o&&o!==this&&!o.options.disabled&&r.push([t.isFunction(o.options.items)?o.options.items.call(o.element):t(o.options.items,o.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),o]);for(r.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),i=r.length-1;i>=0;i--)r[i][0].each(function(){a.push(this)});return t(a)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var i=0;e.length>i;i++)if(e[i]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[],this.containers=[this];var i,s,n,o,a,r,h,l,c=this.items,u=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(n=t(d[i]),s=n.length-1;s>=0;s--)o=t.data(n[s],this.widgetFullName),o&&o!==this&&!o.options.disabled&&(u.push([t.isFunction(o.options.items)?o.options.items.call(o.element[0],e,{item:this.currentItem}):t(o.options.items,o.element),o]),this.containers.push(o));for(i=u.length-1;i>=0;i--)for(a=u[i][1],r=u[i][0],s=0,l=r.length;l>s;s++)h=t(r[s]),h.data(this.widgetName+"-item",a),c.push({item:h,instance:a,width:0,height:0,left:0,top:0})},refreshPositions:function(e){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,o;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?t(this.options.toleranceElement,s.item):s.item,e||(s.width=n.outerWidth(),s.height=n.outerHeight()),o=n.offset(),s.left=o.left,s.top=o.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)o=this.containers[i].element.offset(),this.containers[i].containerCache.left=o.left,this.containers[i].containerCache.top=o.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(e){e=e||this;var i,s=e.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=e.currentItem[0].nodeName.toLowerCase(),n=t("<"+s+">",e.document[0]).addClass(i||e.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tr"===s?e.currentItem.children().each(function(){t("<td>&#160;</td>",e.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(n)}):"img"===s&&n.attr("src",e.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(t,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10)))}}),e.placeholder=t(s.placeholder.element.call(e.element,e.currentItem)),e.currentItem.after(e.placeholder),s.placeholder.update(e,e.placeholder)},_contactContainers:function(s){var n,o,a,r,h,l,c,u,d,p,f=null,g=null;for(n=this.containers.length-1;n>=0;n--)if(!t.contains(this.currentItem[0],this.containers[n].element[0]))if(this._intersectsWith(this.containers[n].containerCache)){if(f&&t.contains(this.containers[n].element[0],f.element[0]))continue;f=this.containers[n],g=n}else this.containers[n].containerCache.over&&(this.containers[n]._trigger("out",s,this._uiHash(this)),this.containers[n].containerCache.over=0);if(f)if(1===this.containers.length)this.containers[g].containerCache.over||(this.containers[g]._trigger("over",s,this._uiHash(this)),this.containers[g].containerCache.over=1);else{for(a=1e4,r=null,p=f.floating||i(this.currentItem),h=p?"left":"top",l=p?"width":"height",c=this.positionAbs[h]+this.offset.click[h],o=this.items.length-1;o>=0;o--)t.contains(this.containers[g].element[0],this.items[o].item[0])&&this.items[o].item[0]!==this.currentItem[0]&&(!p||e(this.positionAbs.top+this.offset.click.top,this.items[o].top,this.items[o].height))&&(u=this.items[o].item.offset()[h],d=!1,Math.abs(u-c)>Math.abs(u+this.items[o][l]-c)&&(d=!0,u+=this.items[o][l]),a>Math.abs(u-c)&&(a=Math.abs(u-c),r=this.items[o],this.direction=d?"up":"down"));if(!r&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[g])return;r?this._rearrange(s,r,null,!0):this._rearrange(s,null,this.containers[g].element,!0),this._trigger("change",s,this._uiHash()),this.containers[g]._trigger("change",s,this._uiHash(this)),this.currentContainer=this.containers[g],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[g]._trigger("over",s,this._uiHash(this)),this.containers[g].containerCache.over=1}},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||t("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,t("document"===n.containment?document:window).width()-this.helperProportions.width-this.margins.left,(t("document"===n.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(e=t(n.containment)[0],i=t(n.containment).offset(),s="hidden"!==t(e).css("overflow"),this.containment=[i.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())*s}},_generatePosition:function(e){var i,s,n=this.options,o=e.pageX,a=e.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left),e.pageY-this.offset.click.top<this.containment[1]&&(a=this.containment[1]+this.offset.click.top),e.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((a-this.originalPageY)/n.grid[1])*n.grid[1],a=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((o-this.originalPageX)/n.grid[0])*n.grid[0],o=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){this.reverting=!1;var i,s=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(i in this._storedCSS)("auto"===this._storedCSS[i]||"static"===this._storedCSS[i])&&(this._storedCSS[i]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&s.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||s.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(s.push(function(t){this._trigger("remove",t,this._uiHash())}),s.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),s.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),i=this.containers.length-1;i>=0;i--)e||s.push(function(t){return function(e){t._trigger("deactivate",e,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over&&(s.push(function(t){return function(e){t._trigger("out",e,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,this.cancelHelperRemoval){if(!e){for(this._trigger("beforeStop",t,this._uiHash()),i=0;s.length>i;i++)s[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!1}if(e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null,!e){for(i=0;s.length>i;i++)s[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}})}(jQuery),function(t,e){var i="ui-effects-";t.effects={effect:{}},function(t,e){function i(t,e,i){var s=u[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:0>t?0:t>s.max?s.max:t)}function s(i){var s=l(),n=s._rgba=[];return i=i.toLowerCase(),f(h,function(t,o){var a,r=o.re.exec(i),h=r&&o.parse(r),l=o.space||"rgba";return h?(a=s[l](h),s[c[l].cache]=a[c[l].cache],n=s._rgba=a._rgba,!1):e}),n.length?("0,0,0,0"===n.join()&&t.extend(n,o.transparent),s):o[i]}function n(t,e,i){return i=(i+1)%1,1>6*i?t+6*(e-t)*i:1>2*i?e:2>3*i?t+6*(e-t)*(2/3-i):t}var o,a="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",r=/^([\-+])=\s*(\d+\.?\d*)/,h=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[t[1],t[2],t[3],t[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[2.55*t[1],2.55*t[2],2.55*t[3],t[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(t){return[t[1],t[2]/100,t[3]/100,t[4]]}}],l=t.Color=function(e,i,s,n){return new t.Color.fn.parse(e,i,s,n)},c={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},u={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},d=l.support={},p=t("<p>")[0],f=t.each;p.style.cssText="background-color:rgba(1,1,1,.5)",d.rgba=p.style.backgroundColor.indexOf("rgba")>-1,f(c,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),l.fn=t.extend(l.prototype,{parse:function(n,a,r,h){if(n===e)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=t(n).css(a),a=e);var u=this,d=t.type(n),p=this._rgba=[];return a!==e&&(n=[n,a,r,h],d="array"),"string"===d?this.parse(s(n)||o._default):"array"===d?(f(c.rgba.props,function(t,e){p[e.idx]=i(n[e.idx],e)}),this):"object"===d?(n instanceof l?f(c,function(t,e){n[e.cache]&&(u[e.cache]=n[e.cache].slice())}):f(c,function(e,s){var o=s.cache;f(s.props,function(t,e){if(!u[o]&&s.to){if("alpha"===t||null==n[t])return;u[o]=s.to(u._rgba)}u[o][e.idx]=i(n[t],e,!0)}),u[o]&&0>t.inArray(null,u[o].slice(0,3))&&(u[o][3]=1,s.from&&(u._rgba=s.from(u[o])))}),this):e},is:function(t){var i=l(t),s=!0,n=this;return f(c,function(t,o){var a,r=i[o.cache];return r&&(a=n[o.cache]||o.to&&o.to(n._rgba)||[],f(o.props,function(t,i){return null!=r[i.idx]?s=r[i.idx]===a[i.idx]:e})),s}),s},_space:function(){var t=[],e=this;return f(c,function(i,s){e[s.cache]&&t.push(i)}),t.pop()},transition:function(t,e){var s=l(t),n=s._space(),o=c[n],a=0===this.alpha()?l("transparent"):this,r=a[o.cache]||o.to(a._rgba),h=r.slice();return s=s[o.cache],f(o.props,function(t,n){var o=n.idx,a=r[o],l=s[o],c=u[n.type]||{};null!==l&&(null===a?h[o]=l:(c.mod&&(l-a>c.mod/2?a+=c.mod:a-l>c.mod/2&&(a-=c.mod)),h[o]=i((l-a)*e+a,n)))}),this[n](h)},blend:function(e){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=l(e)._rgba;return l(t.map(i,function(t,e){return(1-s)*n[e]+s*t}))},toRgbaString:function(){var e="rgba(",i=t.map(this._rgba,function(t,e){return null==t?e>2?1:0:t});return 1===i[3]&&(i.pop(),e="rgb("),e+i.join()+")"},toHslaString:function(){var e="hsla(",i=t.map(this.hsla(),function(t,e){return null==t&&(t=e>2?1:0),e&&3>e&&(t=Math.round(100*t)+"%"),t});return 1===i[3]&&(i.pop(),e="hsl("),e+i.join()+")"},toHexString:function(e){var i=this._rgba.slice(),s=i.pop();return e&&i.push(~~(255*s)),"#"+t.map(i,function(t){return t=(t||0).toString(16),1===t.length?"0"+t:t}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),l.fn.parse.prototype=l.fn,c.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e,i,s=t[0]/255,n=t[1]/255,o=t[2]/255,a=t[3],r=Math.max(s,n,o),h=Math.min(s,n,o),l=r-h,c=r+h,u=.5*c;return e=h===r?0:s===r?60*(n-o)/l+360:n===r?60*(o-s)/l+120:60*(s-n)/l+240,i=0===l?0:.5>=u?l/c:l/(2-c),[Math.round(e)%360,i,u,null==a?1:a]},c.hsla.from=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/360,i=t[1],s=t[2],o=t[3],a=.5>=s?s*(1+i):s+i-s*i,r=2*s-a;return[Math.round(255*n(r,a,e+1/3)),Math.round(255*n(r,a,e)),Math.round(255*n(r,a,e-1/3)),o]},f(c,function(s,n){var o=n.props,a=n.cache,h=n.to,c=n.from;l.fn[s]=function(s){if(h&&!this[a]&&(this[a]=h(this._rgba)),s===e)return this[a].slice();var n,r=t.type(s),u="array"===r||"object"===r?s:arguments,d=this[a].slice();return f(o,function(t,e){var s=u["object"===r?t:e.idx];null==s&&(s=d[e.idx]),d[e.idx]=i(s,e)}),c?(n=l(c(d)),n[a]=d,n):l(d)},f(o,function(e,i){l.fn[e]||(l.fn[e]=function(n){var o,a=t.type(n),h="alpha"===e?this._hsla?"hsla":"rgba":s,l=this[h](),c=l[i.idx];return"undefined"===a?c:("function"===a&&(n=n.call(this,c),a=t.type(n)),null==n&&i.empty?this:("string"===a&&(o=r.exec(n),o&&(n=c+parseFloat(o[2])*("+"===o[1]?1:-1))),l[i.idx]=n,this[h](l)))})})}),l.hook=function(e){var i=e.split(" ");f(i,function(e,i){t.cssHooks[i]={set:function(e,n){var o,a,r="";if("transparent"!==n&&("string"!==t.type(n)||(o=s(n)))){if(n=l(o||n),!d.rgba&&1!==n._rgba[3]){for(a="backgroundColor"===i?e.parentNode:e;(""===r||"transparent"===r)&&a&&a.style;)try{r=t.css(a,"backgroundColor"),a=a.parentNode}catch(h){}n=n.blend(r&&"transparent"!==r?r:"_default")}n=n.toRgbaString()}try{e.style[i]=n}catch(h){}}},t.fx.step[i]=function(e){e.colorInit||(e.start=l(e.elem,i),e.end=l(e.end),e.colorInit=!0),t.cssHooks[i].set(e.elem,e.start.transition(e.end,e.pos))}})},l.hook(a),t.cssHooks.borderColor={expand:function(t){var e={};return f(["Top","Right","Bottom","Left"],function(i,s){e["border"+s+"Color"]=t}),e}},o=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(jQuery),function(){function i(e){var i,s,n=e.ownerDocument.defaultView?e.ownerDocument.defaultView.getComputedStyle(e,null):e.currentStyle,o={};if(n&&n.length&&n[0]&&n[n[0]])for(s=n.length;s--;)i=n[s],"string"==typeof n[i]&&(o[t.camelCase(i)]=n[i]);else for(i in n)"string"==typeof n[i]&&(o[i]=n[i]);return o}function s(e,i){var s,n,a={};for(s in i)n=i[s],e[s]!==n&&(o[s]||(t.fx.step[s]||!isNaN(parseFloat(n)))&&(a[s]=n));return a}var n=["add","remove","toggle"],o={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};t.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(e,i){t.fx.step[i]=function(t){("none"!==t.end&&!t.setAttr||1===t.pos&&!t.setAttr)&&(jQuery.style(t.elem,i,t.end),t.setAttr=!0)}}),t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.effects.animateClass=function(e,o,a,r){var h=t.speed(o,a,r);return this.queue(function(){var o,a=t(this),r=a.attr("class")||"",l=h.children?a.find("*").addBack():a;l=l.map(function(){var e=t(this);return{el:e,start:i(this)}}),o=function(){t.each(n,function(t,i){e[i]&&a[i+"Class"](e[i])})},o(),l=l.map(function(){return this.end=i(this.el[0]),this.diff=s(this.start,this.end),this}),a.attr("class",r),l=l.map(function(){var e=this,i=t.Deferred(),s=t.extend({},h,{queue:!1,complete:function(){i.resolve(e)}});return this.el.animate(this.diff,s),i.promise()}),t.when.apply(t,l.get()).done(function(){o(),t.each(arguments,function(){var e=this.el;t.each(this.diff,function(t){e.css(t,"")})}),h.complete.call(a[0])})})},t.fn.extend({addClass:function(e){return function(i,s,n,o){return s?t.effects.animateClass.call(this,{add:i},s,n,o):e.apply(this,arguments)}}(t.fn.addClass),removeClass:function(e){return function(i,s,n,o){return arguments.length>1?t.effects.animateClass.call(this,{remove:i},s,n,o):e.apply(this,arguments)}}(t.fn.removeClass),toggleClass:function(i){return function(s,n,o,a,r){return"boolean"==typeof n||n===e?o?t.effects.animateClass.call(this,n?{add:s}:{remove:s},o,a,r):i.apply(this,arguments):t.effects.animateClass.call(this,{toggle:s},n,o,a)}}(t.fn.toggleClass),switchClass:function(e,i,s,n,o){return t.effects.animateClass.call(this,{add:i,remove:e},s,n,o)}})}(),function(){function s(e,i,s,n){return t.isPlainObject(e)&&(i=e,e=e.effect),e={effect:e},null==i&&(i={}),t.isFunction(i)&&(n=i,s=null,i={}),("number"==typeof i||t.fx.speeds[i])&&(n=s,s=i,i={}),t.isFunction(s)&&(n=s,s=null),i&&t.extend(e,i),s=s||i.duration,e.duration=t.fx.off?0:"number"==typeof s?s:s in t.fx.speeds?t.fx.speeds[s]:t.fx.speeds._default,e.complete=n||i.complete,e}function n(e){return!e||"number"==typeof e||t.fx.speeds[e]?!0:"string"!=typeof e||t.effects.effect[e]?t.isFunction(e)?!0:"object"!=typeof e||e.effect?!1:!0:!0}t.extend(t.effects,{version:"1.10.3",save:function(t,e){for(var s=0;e.length>s;s++)null!==e[s]&&t.data(i+e[s],t[0].style[e[s]])},restore:function(t,s){var n,o;for(o=0;s.length>o;o++)null!==s[o]&&(n=t.data(i+s[o]),n===e&&(n=""),t.css(s[o],n))},setMode:function(t,e){return"toggle"===e&&(e=t.is(":hidden")?"show":"hide"),e},getBaseline:function(t,e){var i,s;switch(t[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=t[0]/e.height}switch(t[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=t[1]/e.width}return{x:s,y:i}},createWrapper:function(e){if(e.parent().is(".ui-effects-wrapper"))return e.parent();var i={width:e.outerWidth(!0),height:e.outerHeight(!0),"float":e.css("float")},s=t("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:e.width(),height:e.height()},o=document.activeElement;try{o.id}catch(a){o=document.body}return e.wrap(s),(e[0]===o||t.contains(e[0],o))&&t(o).focus(),s=e.parent(),"static"===e.css("position")?(s.css({position:"relative"}),e.css({position:"relative"})):(t.extend(i,{position:e.css("position"),zIndex:e.css("z-index")}),t.each(["top","left","bottom","right"],function(t,s){i[s]=e.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),e.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),e.css(n),s.css(i).show()},removeWrapper:function(e){var i=document.activeElement;return e.parent().is(".ui-effects-wrapper")&&(e.parent().replaceWith(e),(e[0]===i||t.contains(e[0],i))&&t(i).focus()),e},setTransition:function(e,i,s,n){return n=n||{},t.each(i,function(t,i){var o=e.cssUnit(i);o[0]>0&&(n[i]=o[0]*s+o[1])}),n}}),t.fn.extend({effect:function(){function e(e){function s(){t.isFunction(o)&&o.call(n[0]),t.isFunction(e)&&e()}var n=t(this),o=i.complete,r=i.mode;(n.is(":hidden")?"hide"===r:"show"===r)?(n[r](),s()):a.call(n[0],i,s)}var i=s.apply(this,arguments),n=i.mode,o=i.queue,a=t.effects.effect[i.effect];return t.fx.off||!a?n?this[n](i.duration,i.complete):this.each(function(){i.complete&&i.complete.call(this)}):o===!1?this.each(e):this.queue(o||"fx",e)},show:function(t){return function(e){if(n(e))return t.apply(this,arguments);var i=s.apply(this,arguments);return i.mode="show",this.effect.call(this,i)}}(t.fn.show),hide:function(t){return function(e){if(n(e))return t.apply(this,arguments);var i=s.apply(this,arguments);return i.mode="hide",this.effect.call(this,i)}}(t.fn.hide),toggle:function(t){return function(e){if(n(e)||"boolean"==typeof e)return t.apply(this,arguments);var i=s.apply(this,arguments);return i.mode="toggle",this.effect.call(this,i)}}(t.fn.toggle),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(s=[parseFloat(i),e])}),s}})}(),function(){var e={};t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;((e=Math.pow(2,--i))-1)/11>t;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return.5>t?i(2*t)/2:1-i(-2*t+2)/2}})}()}(jQuery),function(t){var e=0,i={},s={};i.height=i.paddingTop=i.paddingBottom=i.borderTopWidth=i.borderBottomWidth="hide",s.height=s.paddingTop=s.paddingBottom=s.borderTopWidth=s.borderBottomWidth="show",t.widget("ui.accordion",{version:"1.10.3",options:{active:0,animate:{},collapsible:!1,event:"click",header:"> li > :first-child,> :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},_create:function(){var e=this.options;this.prevShow=this.prevHide=t(),this.element.addClass("ui-accordion ui-widget ui-helper-reset").attr("role","tablist"),e.collapsible||e.active!==!1&&null!=e.active||(e.active=0),this._processPanels(),0>e.active&&(e.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():t(),content:this.active.length?this.active.next():t()}},_createIcons:function(){var e=this.options.icons;e&&(t("<span>").addClass("ui-accordion-header-icon ui-icon "+e.header).prependTo(this.headers),this.active.children(".ui-accordion-header-icon").removeClass(e.header).addClass(e.activeHeader),this.headers.addClass("ui-accordion-icons")) },_destroyIcons:function(){this.headers.removeClass("ui-accordion-icons").children(".ui-accordion-header-icon").remove()},_destroy:function(){var t;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.removeClass("ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-selected").removeAttr("aria-controls").removeAttr("tabIndex").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this._destroyIcons(),t=this.headers.next().css("display","").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-labelledby").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),"content"!==this.options.heightStyle&&t.css("height","")},_setOption:function(t,e){return"active"===t?(this._activate(e),undefined):("event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||this.options.active!==!1||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons()),"disabled"===t&&this.headers.add(this.headers.next()).toggleClass("ui-state-disabled",!!e),undefined)},_keydown:function(e){if(!e.altKey&&!e.ctrlKey){var i=t.ui.keyCode,s=this.headers.length,n=this.headers.index(e.target),o=!1;switch(e.keyCode){case i.RIGHT:case i.DOWN:o=this.headers[(n+1)%s];break;case i.LEFT:case i.UP:o=this.headers[(n-1+s)%s];break;case i.SPACE:case i.ENTER:this._eventHandler(e);break;case i.HOME:o=this.headers[0];break;case i.END:o=this.headers[s-1]}o&&(t(e.target).attr("tabIndex",-1),t(o).attr("tabIndex",0),o.focus(),e.preventDefault())}},_panelKeyDown:function(e){e.keyCode===t.ui.keyCode.UP&&e.ctrlKey&&t(e.currentTarget).prev().focus()},refresh:function(){var e=this.options;this._processPanels(),e.active===!1&&e.collapsible===!0||!this.headers.length?(e.active=!1,this.active=t()):e.active===!1?this._activate(0):this.active.length&&!t.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(e.active=!1,this.active=t()):this._activate(Math.max(0,e.active-1)):e.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){this.headers=this.element.find(this.options.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all"),this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").filter(":not(.ui-accordion-content-active)").hide()},_refresh:function(){var i,s=this.options,n=s.heightStyle,o=this.element.parent(),a=this.accordionId="ui-accordion-"+(this.element.attr("id")||++e);this.active=this._findActive(s.active).addClass("ui-accordion-header-active ui-state-active ui-corner-top").removeClass("ui-corner-all"),this.active.next().addClass("ui-accordion-content-active").show(),this.headers.attr("role","tab").each(function(e){var i=t(this),s=i.attr("id"),n=i.next(),o=n.attr("id");s||(s=a+"-header-"+e,i.attr("id",s)),o||(o=a+"-panel-"+e,n.attr("id",o)),i.attr("aria-controls",o),n.attr("aria-labelledby",s)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false",tabIndex:-1}).next().attr({"aria-expanded":"false","aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true",tabIndex:0}).next().attr({"aria-expanded":"true","aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(s.event),"fill"===n?(i=o.height(),this.element.siblings(":visible").each(function(){var e=t(this),s=e.css("position");"absolute"!==s&&"fixed"!==s&&(i-=e.outerHeight(!0))}),this.headers.each(function(){i-=t(this).outerHeight(!0)}),this.headers.next().each(function(){t(this).height(Math.max(0,i-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===n&&(i=0,this.headers.next().each(function(){i=Math.max(i,t(this).css("height","").height())}).height(i))},_activate:function(e){var i=this._findActive(e)[0];i!==this.active[0]&&(i=i||this.active[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return"number"==typeof e?this.headers.eq(e):t()},_setupEvents:function(e){var i={keydown:"_keydown"};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget),o=n[0]===s[0],a=o&&i.collapsible,r=a?t():n.next(),h=s.next(),l={oldHeader:s,oldPanel:h,newHeader:a?t():n,newPanel:r};e.preventDefault(),o&&!i.collapsible||this._trigger("beforeActivate",e,l)===!1||(i.active=a?!1:this.headers.index(n),this.active=o?t():n,this._toggle(l),s.removeClass("ui-accordion-header-active ui-state-active"),i.icons&&s.children(".ui-accordion-header-icon").removeClass(i.icons.activeHeader).addClass(i.icons.header),o||(n.removeClass("ui-corner-all").addClass("ui-accordion-header-active ui-state-active ui-corner-top"),i.icons&&n.children(".ui-accordion-header-icon").removeClass(i.icons.header).addClass(i.icons.activeHeader),n.next().addClass("ui-accordion-content-active")))},_toggle:function(e){var i=e.newPanel,s=this.prevShow.length?this.prevShow:e.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=i,this.prevHide=s,this.options.animate?this._animate(i,s,e):(s.hide(),i.show(),this._toggleComplete(e)),s.attr({"aria-expanded":"false","aria-hidden":"true"}),s.prev().attr("aria-selected","false"),i.length&&s.length?s.prev().attr("tabIndex",-1):i.length&&this.headers.filter(function(){return 0===t(this).attr("tabIndex")}).attr("tabIndex",-1),i.attr({"aria-expanded":"true","aria-hidden":"false"}).prev().attr({"aria-selected":"true",tabIndex:0})},_animate:function(t,e,n){var o,a,r,h=this,l=0,c=t.length&&(!e.length||t.index()<e.index()),u=this.options.animate||{},d=c&&u.down||u,p=function(){h._toggleComplete(n)};return"number"==typeof d&&(r=d),"string"==typeof d&&(a=d),a=a||d.easing||u.easing,r=r||d.duration||u.duration,e.length?t.length?(o=t.show().outerHeight(),e.animate(i,{duration:r,easing:a,step:function(t,e){e.now=Math.round(t)}}),t.hide().animate(s,{duration:r,easing:a,complete:p,step:function(t,i){i.now=Math.round(t),"height"!==i.prop?l+=i.now:"content"!==h.options.heightStyle&&(i.now=Math.round(o-e.outerHeight()-l),l=0)}}),undefined):e.animate(i,r,a,p):t.animate(s,r,a,p)},_toggleComplete:function(t){var e=t.oldPanel;e.removeClass("ui-accordion-content-active").prev().removeClass("ui-corner-top").addClass("ui-corner-all"),e.length&&(e.parent()[0].className=e.parent()[0].className),this._trigger("activate",null,t)}})}(jQuery),function(t){var e=0;t.widget("ui.autocomplete",{version:"1.10.3",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},pending:0,_create:function(){var e,i,s,n=this.element[0].nodeName.toLowerCase(),o="textarea"===n,a="input"===n;this.isMultiLine=o?!0:a?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[o||a?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return e=!0,s=!0,i=!0,undefined;e=!1,s=!1,i=!1;var o=t.ui.keyCode;switch(n.keyCode){case o.PAGE_UP:e=!0,this._move("previousPage",n);break;case o.PAGE_DOWN:e=!0,this._move("nextPage",n);break;case o.UP:e=!0,this._keyEvent("previous",n);break;case o.DOWN:e=!0,this._keyEvent("next",n);break;case o.ENTER:case o.NUMPAD_ENTER:this.menu.active&&(e=!0,n.preventDefault(),this.menu.select(n));break;case o.TAB:this.menu.active&&this.menu.select(n);break;case o.ESCAPE:this.menu.element.is(":visible")&&(this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(e)return e=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),undefined;if(!i){var n=t.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(t){return s?(s=!1,t.preventDefault(),undefined):(this._searchTimeout(t),undefined)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,undefined):(clearTimeout(this.searching),this.close(t),this._change(t),undefined)}}),this._initSource(),this.menu=t("<ul>").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({role:null}).hide().data("ui-menu"),this._on(this.menu.element,{mousedown:function(e){e.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var i=this.menu.element[0];t(e.target).closest(".ui-menu-item").length||this._delay(function(){var e=this;this.document.one("mousedown",function(s){s.target===e.element[0]||s.target===i||t.contains(i,s.target)||e.close()})})},menufocus:function(e,i){if(this.isNewMenu&&(this.isNewMenu=!1,e.originalEvent&&/^mouse/.test(e.originalEvent.type)))return this.menu.blur(),this.document.one("mousemove",function(){t(e.target).trigger(e.originalEvent)}),undefined;var s=i.item.data("ui-autocomplete-item");!1!==this._trigger("focus",e,{item:s})?e.originalEvent&&/^key/.test(e.originalEvent.type)&&this._value(s.value):this.liveRegion.text(s.value)},menuselect:function(t,e){var i=e.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",t,{item:i})&&this._value(i.value),this.term=this._value(),this.close(t),this.selectedItem=i}}),this.liveRegion=t("<span>",{role:"status","aria-live":"polite"}).addClass("ui-helper-hidden-accessible").insertBefore(this.element),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(t,e){this._super(t,e),"source"===t&&this._initSource(),"appendTo"===t&&this.menu.element.appendTo(this._appendTo()),"disabled"===t&&e&&this.xhr&&this.xhr.abort()},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e||(e=this.element.closest(".ui-front")),e.length||(e=this.document[0].body),e},_initSource:function(){var e,i,s=this;t.isArray(this.options.source)?(e=this.options.source,this.source=function(i,s){s(t.ui.autocomplete.filter(e,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(e,n){s.xhr&&s.xhr.abort(),s.xhr=t.ajax({url:i,data:e,dataType:"json",success:function(t){n(t)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(t){clearTimeout(this.searching),this.searching=this._delay(function(){this.term!==this._value()&&(this.selectedItem=null,this.search(null,t))},this.options.delay)},search:function(t,e){return t=null!=t?t:this._value(),this.term=this._value(),t.length<this.options.minLength?this.close(e):this._trigger("search",e)!==!1?this._search(t):undefined},_search:function(t){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:t},this._response())},_response:function(){var t=this,i=++e;return function(s){i===e&&t.__response(s),t.pending--,t.pending||t.element.removeClass("ui-autocomplete-loading")}},__response:function(t){t&&(t=this._normalize(t)),this._trigger("response",null,{content:t}),!this.options.disabled&&t&&t.length&&!this.cancelSearch?(this._suggest(t),this._trigger("open")):this._close()},close:function(t){this.cancelSearch=!0,this._close(t)},_close:function(t){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",t))},_change:function(t){this.previous!==this._value()&&this._trigger("change",t,{item:this.selectedItem})},_normalize:function(e){return e.length&&e[0].label&&e[0].value?e:t.map(e,function(e){return"string"==typeof e?{label:e,value:e}:t.extend({label:e.label||e.value,value:e.value||e.label},e)})},_suggest:function(e){var i=this.menu.element.empty();this._renderMenu(i,e),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(t.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var t=this.menu.element;t.outerWidth(Math.max(t.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(e,i){var s=this;t.each(i,function(t,i){s._renderItemData(e,i)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-autocomplete-item",e)},_renderItem:function(e,i){return t("<li>").append(t("<a>").text(i.label)).appendTo(e)},_move:function(t,e){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(t)||this.menu.isLastItem()&&/^next/.test(t)?(this._value(this.term),this.menu.blur(),undefined):(this.menu[t](e),undefined):(this.search(null,e),undefined)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(t,e){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(t,e),e.preventDefault())}}),t.extend(t.ui.autocomplete,{escapeRegex:function(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(e,i){var s=RegExp(t.ui.autocomplete.escapeRegex(i),"i");return t.grep(e,function(t){return s.test(t.label||t.value||t)})}}),t.widget("ui.autocomplete",t.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(t){return t+(t>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(t){var e;this._superApply(arguments),this.options.disabled||this.cancelSearch||(e=t&&t.length?this.options.messages.results(t.length):this.options.messages.noResults,this.liveRegion.text(e))}})}(jQuery),function(t){var e,i,s,n,o="ui-button ui-widget ui-state-default ui-corner-all",a="ui-state-hover ui-state-active ",r="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",h=function(){var e=t(this);setTimeout(function(){e.find(":ui-button").button("refresh")},1)},l=function(e){var i=e.name,s=e.form,n=t([]);return i&&(i=i.replace(/'/g,"\\'"),n=s?t(s).find("[name='"+i+"']"):t("[name='"+i+"']",e.ownerDocument).filter(function(){return!this.form})),n};t.widget("ui.button",{version:"1.10.3",defaultElement:"<button>",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,h),"boolean"!=typeof this.options.disabled?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var a=this,r=this.options,c="checkbox"===this.type||"radio"===this.type,u=c?"":"ui-state-active",d="ui-state-focus";null===r.label&&(r.label="input"===this.type?this.buttonElement.val():this.buttonElement.html()),this._hoverable(this.buttonElement),this.buttonElement.addClass(o).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){r.disabled||this===e&&t(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){r.disabled||t(this).removeClass(u)}).bind("click"+this.eventNamespace,function(t){r.disabled&&(t.preventDefault(),t.stopImmediatePropagation())}),this.element.bind("focus"+this.eventNamespace,function(){a.buttonElement.addClass(d)}).bind("blur"+this.eventNamespace,function(){a.buttonElement.removeClass(d)}),c&&(this.element.bind("change"+this.eventNamespace,function(){n||a.refresh()}),this.buttonElement.bind("mousedown"+this.eventNamespace,function(t){r.disabled||(n=!1,i=t.pageX,s=t.pageY)}).bind("mouseup"+this.eventNamespace,function(t){r.disabled||(i!==t.pageX||s!==t.pageY)&&(n=!0)})),"checkbox"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){return r.disabled||n?!1:undefined}):"radio"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){if(r.disabled||n)return!1;t(this).addClass("ui-state-active"),a.buttonElement.attr("aria-pressed","true");var e=a.element[0];l(e).not(e).map(function(){return t(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){return r.disabled?!1:(t(this).addClass("ui-state-active"),e=this,a.document.one("mouseup",function(){e=null}),undefined)}).bind("mouseup"+this.eventNamespace,function(){return r.disabled?!1:(t(this).removeClass("ui-state-active"),undefined)}).bind("keydown"+this.eventNamespace,function(e){return r.disabled?!1:((e.keyCode===t.ui.keyCode.SPACE||e.keyCode===t.ui.keyCode.ENTER)&&t(this).addClass("ui-state-active"),undefined)}).bind("keyup"+this.eventNamespace+" blur"+this.eventNamespace,function(){t(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(e){e.keyCode===t.ui.keyCode.SPACE&&t(this).click()})),this._setOption("disabled",r.disabled),this._resetButton()},_determineButtonType:function(){var t,e,i;this.type=this.element.is("[type=checkbox]")?"checkbox":this.element.is("[type=radio]")?"radio":this.element.is("input")?"input":"button","checkbox"===this.type||"radio"===this.type?(t=this.element.parents().last(),e="label[for='"+this.element.attr("id")+"']",this.buttonElement=t.find(e),this.buttonElement.length||(t=t.length?t.siblings():this.element.siblings(),this.buttonElement=t.filter(e),this.buttonElement.length||(this.buttonElement=t.find(e))),this.element.addClass("ui-helper-hidden-accessible"),i=this.element.is(":checked"),i&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",i)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(o+" "+a+" "+r).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(t,e){return this._super(t,e),"disabled"===t?(e?this.element.prop("disabled",!0):this.element.prop("disabled",!1),undefined):(this._resetButton(),undefined)},refresh:function(){var e=this.element.is("input, button")?this.element.is(":disabled"):this.element.hasClass("ui-button-disabled");e!==this.options.disabled&&this._setOption("disabled",e),"radio"===this.type?l(this.element[0]).each(function(){t(this).is(":checked")?t(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):t(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):"checkbox"===this.type&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if("input"===this.type)return this.options.label&&this.element.val(this.options.label),undefined;var e=this.buttonElement.removeClass(r),i=t("<span></span>",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(e.empty()).text(),s=this.options.icons,n=s.primary&&s.secondary,o=[];s.primary||s.secondary?(this.options.text&&o.push("ui-button-text-icon"+(n?"s":s.primary?"-primary":"-secondary")),s.primary&&e.prepend("<span class='ui-button-icon-primary ui-icon "+s.primary+"'></span>"),s.secondary&&e.append("<span class='ui-button-icon-secondary ui-icon "+s.secondary+"'></span>"),this.options.text||(o.push(n?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||e.attr("title",t.trim(i)))):o.push("ui-button-text-only"),e.addClass(o.join(" "))}}),t.widget("ui.buttonset",{version:"1.10.3",options:{items:"button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(t,e){"disabled"===t&&this.buttons.button("option",t,e),this._super(t,e)},refresh:function(){var e="rtl"===this.element.css("direction");this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return t(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(e?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(e?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return t(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}})}(jQuery),function(t,e){function i(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},t.extend(this._defaults,this.regional[""]),this.dpDiv=s(t("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function s(e){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.delegate(i,"mouseout",function(){t(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).removeClass("ui-datepicker-next-hover")}).delegate(i,"mouseover",function(){t.datepicker._isDisabledDatepicker(o.inline?e.parent()[0]:o.input[0])||(t(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),t(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).addClass("ui-datepicker-next-hover"))})}function n(e,i){t.extend(e,i);for(var s in i)null==i[s]&&(e[s]=i[s]);return e}t.extend(t.ui,{datepicker:{version:"1.10.3"}});var o,a="datepicker";t.extend(i.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(t){return n(this._defaults,t||{}),this},_attachDatepicker:function(e,i){var s,n,o;s=e.nodeName.toLowerCase(),n="div"===s||"span"===s,e.id||(this.uuid+=1,e.id="dp"+this.uuid),o=this._newInst(t(e),n),o.settings=t.extend({},i||{}),"input"===s?this._connectDatepicker(e,o):n&&this._inlineDatepicker(e,o)},_newInst:function(e,i){var n=e[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:n,input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?s(t("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(e,i){var s=t(e);i.append=t([]),i.trigger=t([]),s.hasClass(this.markerClassName)||(this._attachments(s,i),s.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp),this._autoSize(i),t.data(e,a,i),i.settings.disabled&&this._disableDatepicker(e))},_attachments:function(e,i){var s,n,o,a=this._get(i,"appendText"),r=this._get(i,"isRTL");i.append&&i.append.remove(),a&&(i.append=t("<span class='"+this._appendClass+"'>"+a+"</span>"),e[r?"before":"after"](i.append)),e.unbind("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),s=this._get(i,"showOn"),("focus"===s||"both"===s)&&e.focus(this._showDatepicker),("button"===s||"both"===s)&&(n=this._get(i,"buttonText"),o=this._get(i,"buttonImage"),i.trigger=t(this._get(i,"buttonImageOnly")?t("<img/>").addClass(this._triggerClass).attr({src:o,alt:n,title:n}):t("<button type='button'></button>").addClass(this._triggerClass).html(o?t("<img/>").attr({src:o,alt:n,title:n}):n)),e[r?"before":"after"](i.trigger),i.trigger.click(function(){return t.datepicker._datepickerShowing&&t.datepicker._lastInput===e[0]?t.datepicker._hideDatepicker():t.datepicker._datepickerShowing&&t.datepicker._lastInput!==e[0]?(t.datepicker._hideDatepicker(),t.datepicker._showDatepicker(e[0])):t.datepicker._showDatepicker(e[0]),!1}))},_autoSize:function(t){if(this._get(t,"autoSize")&&!t.inline){var e,i,s,n,o=new Date(2009,11,20),a=this._get(t,"dateFormat");a.match(/[DM]/)&&(e=function(t){for(i=0,s=0,n=0;t.length>n;n++)t[n].length>i&&(i=t[n].length,s=n);return s},o.setMonth(e(this._get(t,a.match(/MM/)?"monthNames":"monthNamesShort"))),o.setDate(e(this._get(t,a.match(/DD/)?"dayNames":"dayNamesShort"))+20-o.getDay())),t.input.attr("size",this._formatDate(t,o).length)}},_inlineDatepicker:function(e,i){var s=t(e);s.hasClass(this.markerClassName)||(s.addClass(this.markerClassName).append(i.dpDiv),t.data(e,a,i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(e),i.dpDiv.css("display","block"))},_dialogDatepicker:function(e,i,s,o,r){var h,l,c,u,d,p=this._dialogInst;return p||(this.uuid+=1,h="dp"+this.uuid,this._dialogInput=t("<input type='text' id='"+h+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.keydown(this._doKeyDown),t("body").append(this._dialogInput),p=this._dialogInst=this._newInst(this._dialogInput,!1),p.settings={},t.data(this._dialogInput[0],a,p)),n(p.settings,o||{}),i=i&&i.constructor===Date?this._formatDate(p,i):i,this._dialogInput.val(i),this._pos=r?r.length?r:[r.pageX,r.pageY]:null,this._pos||(l=document.documentElement.clientWidth,c=document.documentElement.clientHeight,u=document.documentElement.scrollLeft||document.body.scrollLeft,d=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[l/2-100+u,c/2-150+d]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),p.settings.onSelect=s,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),t.blockUI&&t.blockUI(this.dpDiv),t.data(this._dialogInput[0],a,p),this},_destroyDatepicker:function(e){var i,s=t(e),n=t.data(e,a);s.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),t.removeData(e,a),"input"===i?(n.append.remove(),n.trigger.remove(),s.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):("div"===i||"span"===i)&&s.removeClass(this.markerClassName).empty())},_enableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,a);n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!1,o.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().removeClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}))},_disableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,a);n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!0,o.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().addClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}),this._disabledInputs[this._disabledInputs.length]=e)},_isDisabledDatepicker:function(t){if(!t)return!1;for(var e=0;this._disabledInputs.length>e;e++)if(this._disabledInputs[e]===t)return!0;return!1},_getInst:function(e){try{return t.data(e,a)}catch(i){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(i,s,o){var a,r,h,l,c=this._getInst(i);return 2===arguments.length&&"string"==typeof s?"defaults"===s?t.extend({},t.datepicker._defaults):c?"all"===s?t.extend({},c.settings):this._get(c,s):null:(a=s||{},"string"==typeof s&&(a={},a[s]=o),c&&(this._curInst===c&&this._hideDatepicker(),r=this._getDateDatepicker(i,!0),h=this._getMinMaxDate(c,"min"),l=this._getMinMaxDate(c,"max"),n(c.settings,a),null!==h&&a.dateFormat!==e&&a.minDate===e&&(c.settings.minDate=this._formatDate(c,h)),null!==l&&a.dateFormat!==e&&a.maxDate===e&&(c.settings.maxDate=this._formatDate(c,l)),"disabled"in a&&(a.disabled?this._disableDatepicker(i):this._enableDatepicker(i)),this._attachments(t(i),c),this._autoSize(c),this._setDate(c,r),this._updateAlternate(c),this._updateDatepicker(c)),e)},_changeDatepicker:function(t,e,i){this._optionDatepicker(t,e,i)},_refreshDatepicker:function(t){var e=this._getInst(t);e&&this._updateDatepicker(e)},_setDateDatepicker:function(t,e){var i=this._getInst(t);i&&(this._setDate(i,e),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(t,e){var i=this._getInst(t);return i&&!i.inline&&this._setDateFromField(i,e),i?this._getDate(i):null},_doKeyDown:function(e){var i,s,n,o=t.datepicker._getInst(e.target),a=!0,r=o.dpDiv.is(".ui-datepicker-rtl");if(o._keyEvent=!0,t.datepicker._datepickerShowing)switch(e.keyCode){case 9:t.datepicker._hideDatepicker(),a=!1;break;case 13:return n=t("td."+t.datepicker._dayOverClass+":not(."+t.datepicker._currentClass+")",o.dpDiv),n[0]&&t.datepicker._selectDay(e.target,o.selectedMonth,o.selectedYear,n[0]),i=t.datepicker._get(o,"onSelect"),i?(s=t.datepicker._formatDate(o),i.apply(o.input?o.input[0]:null,[s,o])):t.datepicker._hideDatepicker(),!1; case 27:t.datepicker._hideDatepicker();break;case 33:t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 34:t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 35:(e.ctrlKey||e.metaKey)&&t.datepicker._clearDate(e.target),a=e.ctrlKey||e.metaKey;break;case 36:(e.ctrlKey||e.metaKey)&&t.datepicker._gotoToday(e.target),a=e.ctrlKey||e.metaKey;break;case 37:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?1:-1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 38:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,-7,"D"),a=e.ctrlKey||e.metaKey;break;case 39:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?-1:1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 40:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,7,"D"),a=e.ctrlKey||e.metaKey;break;default:a=!1}else 36===e.keyCode&&e.ctrlKey?t.datepicker._showDatepicker(this):a=!1;a&&(e.preventDefault(),e.stopPropagation())},_doKeyPress:function(i){var s,n,o=t.datepicker._getInst(i.target);return t.datepicker._get(o,"constrainInput")?(s=t.datepicker._possibleChars(t.datepicker._get(o,"dateFormat")),n=String.fromCharCode(null==i.charCode?i.keyCode:i.charCode),i.ctrlKey||i.metaKey||" ">n||!s||s.indexOf(n)>-1):e},_doKeyUp:function(e){var i,s=t.datepicker._getInst(e.target);if(s.input.val()!==s.lastVal)try{i=t.datepicker.parseDate(t.datepicker._get(s,"dateFormat"),s.input?s.input.val():null,t.datepicker._getFormatConfig(s)),i&&(t.datepicker._setDateFromField(s),t.datepicker._updateAlternate(s),t.datepicker._updateDatepicker(s))}catch(n){}return!0},_showDatepicker:function(e){if(e=e.target||e,"input"!==e.nodeName.toLowerCase()&&(e=t("input",e.parentNode)[0]),!t.datepicker._isDisabledDatepicker(e)&&t.datepicker._lastInput!==e){var i,s,o,a,r,h,l;i=t.datepicker._getInst(e),t.datepicker._curInst&&t.datepicker._curInst!==i&&(t.datepicker._curInst.dpDiv.stop(!0,!0),i&&t.datepicker._datepickerShowing&&t.datepicker._hideDatepicker(t.datepicker._curInst.input[0])),s=t.datepicker._get(i,"beforeShow"),o=s?s.apply(e,[e,i]):{},o!==!1&&(n(i.settings,o),i.lastVal=null,t.datepicker._lastInput=e,t.datepicker._setDateFromField(i),t.datepicker._inDialog&&(e.value=""),t.datepicker._pos||(t.datepicker._pos=t.datepicker._findPos(e),t.datepicker._pos[1]+=e.offsetHeight),a=!1,t(e).parents().each(function(){return a|="fixed"===t(this).css("position"),!a}),r={left:t.datepicker._pos[0],top:t.datepicker._pos[1]},t.datepicker._pos=null,i.dpDiv.empty(),i.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),t.datepicker._updateDatepicker(i),r=t.datepicker._checkOffset(i,r,a),i.dpDiv.css({position:t.datepicker._inDialog&&t.blockUI?"static":a?"fixed":"absolute",display:"none",left:r.left+"px",top:r.top+"px"}),i.inline||(h=t.datepicker._get(i,"showAnim"),l=t.datepicker._get(i,"duration"),i.dpDiv.zIndex(t(e).zIndex()+1),t.datepicker._datepickerShowing=!0,t.effects&&t.effects.effect[h]?i.dpDiv.show(h,t.datepicker._get(i,"showOptions"),l):i.dpDiv[h||"show"](h?l:null),t.datepicker._shouldFocusInput(i)&&i.input.focus(),t.datepicker._curInst=i))}},_updateDatepicker:function(e){this.maxRows=4,o=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e),e.dpDiv.find("."+this._dayOverClass+" a").mouseover();var i,s=this._getNumberOfMonths(e),n=s[1],a=17;e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&e.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",a*n+"em"),e.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e===t.datepicker._curInst&&t.datepicker._datepickerShowing&&t.datepicker._shouldFocusInput(e)&&e.input.focus(),e.yearshtml&&(i=e.yearshtml,setTimeout(function(){i===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),i=e.yearshtml=null},0))},_shouldFocusInput:function(t){return t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&!t.input.is(":focus")},_checkOffset:function(e,i,s){var n=e.dpDiv.outerWidth(),o=e.dpDiv.outerHeight(),a=e.input?e.input.outerWidth():0,r=e.input?e.input.outerHeight():0,h=document.documentElement.clientWidth+(s?0:t(document).scrollLeft()),l=document.documentElement.clientHeight+(s?0:t(document).scrollTop());return i.left-=this._get(e,"isRTL")?n-a:0,i.left-=s&&i.left===e.input.offset().left?t(document).scrollLeft():0,i.top-=s&&i.top===e.input.offset().top+r?t(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>h&&h>n?Math.abs(i.left+n-h):0),i.top-=Math.min(i.top,i.top+o>l&&l>o?Math.abs(o+r):0),i},_findPos:function(e){for(var i,s=this._getInst(e),n=this._get(s,"isRTL");e&&("hidden"===e.type||1!==e.nodeType||t.expr.filters.hidden(e));)e=e[n?"previousSibling":"nextSibling"];return i=t(e).offset(),[i.left,i.top]},_hideDatepicker:function(e){var i,s,n,o,r=this._curInst;!r||e&&r!==t.data(e,a)||this._datepickerShowing&&(i=this._get(r,"showAnim"),s=this._get(r,"duration"),n=function(){t.datepicker._tidyDialog(r)},t.effects&&(t.effects.effect[i]||t.effects[i])?r.dpDiv.hide(i,t.datepicker._get(r,"showOptions"),s,n):r.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,o=this._get(r,"onClose"),o&&o.apply(r.input?r.input[0]:null,[r.input?r.input.val():"",r]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),t.blockUI&&(t.unblockUI(),t("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(t){t.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(t.datepicker._curInst){var i=t(e.target),s=t.datepicker._getInst(i[0]);(i[0].id!==t.datepicker._mainDivId&&0===i.parents("#"+t.datepicker._mainDivId).length&&!i.hasClass(t.datepicker.markerClassName)&&!i.closest("."+t.datepicker._triggerClass).length&&t.datepicker._datepickerShowing&&(!t.datepicker._inDialog||!t.blockUI)||i.hasClass(t.datepicker.markerClassName)&&t.datepicker._curInst!==s)&&t.datepicker._hideDatepicker()}},_adjustDate:function(e,i,s){var n=t(e),o=this._getInst(n[0]);this._isDisabledDatepicker(n[0])||(this._adjustInstDate(o,i+("M"===s?this._get(o,"showCurrentAtPos"):0),s),this._updateDatepicker(o))},_gotoToday:function(e){var i,s=t(e),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(i=new Date,n.selectedDay=i.getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(e,i,s){var n=t(e),o=this._getInst(n[0]);o["selected"+("M"===s?"Month":"Year")]=o["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(o),this._adjustDate(n)},_selectDay:function(e,i,s,n){var o,a=t(e);t(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(a[0])||(o=this._getInst(a[0]),o.selectedDay=o.currentDay=t("a",n).html(),o.selectedMonth=o.currentMonth=i,o.selectedYear=o.currentYear=s,this._selectDate(e,this._formatDate(o,o.currentDay,o.currentMonth,o.currentYear)))},_clearDate:function(e){var i=t(e);this._selectDate(i,"")},_selectDate:function(e,i){var s,n=t(e),o=this._getInst(n[0]);i=null!=i?i:this._formatDate(o),o.input&&o.input.val(i),this._updateAlternate(o),s=this._get(o,"onSelect"),s?s.apply(o.input?o.input[0]:null,[i,o]):o.input&&o.input.trigger("change"),o.inline?this._updateDatepicker(o):(this._hideDatepicker(),this._lastInput=o.input[0],"object"!=typeof o.input[0]&&o.input.focus(),this._lastInput=null)},_updateAlternate:function(e){var i,s,n,o=this._get(e,"altField");o&&(i=this._get(e,"altFormat")||this._get(e,"dateFormat"),s=this._getDate(e),n=this.formatDate(i,s,this._getFormatConfig(e)),t(o).each(function(){t(this).val(n)}))},noWeekends:function(t){var e=t.getDay();return[e>0&&6>e,""]},iso8601Week:function(t){var e,i=new Date(t.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),e=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((e-i)/864e5)/7)+1},parseDate:function(i,s,n){if(null==i||null==s)throw"Invalid arguments";if(s="object"==typeof s?""+s:s+"",""===s)return null;var o,a,r,h,l=0,c=(n?n.shortYearCutoff:null)||this._defaults.shortYearCutoff,u="string"!=typeof c?c:(new Date).getFullYear()%100+parseInt(c,10),d=(n?n.dayNamesShort:null)||this._defaults.dayNamesShort,p=(n?n.dayNames:null)||this._defaults.dayNames,f=(n?n.monthNamesShort:null)||this._defaults.monthNamesShort,g=(n?n.monthNames:null)||this._defaults.monthNames,m=-1,v=-1,_=-1,b=-1,y=!1,w=function(t){var e=i.length>o+1&&i.charAt(o+1)===t;return e&&o++,e},k=function(t){var e=w(t),i="@"===t?14:"!"===t?20:"y"===t&&e?4:"o"===t?3:2,n=RegExp("^\\d{1,"+i+"}"),o=s.substring(l).match(n);if(!o)throw"Missing number at position "+l;return l+=o[0].length,parseInt(o[0],10)},x=function(i,n,o){var a=-1,r=t.map(w(i)?o:n,function(t,e){return[[e,t]]}).sort(function(t,e){return-(t[1].length-e[1].length)});if(t.each(r,function(t,i){var n=i[1];return s.substr(l,n.length).toLowerCase()===n.toLowerCase()?(a=i[0],l+=n.length,!1):e}),-1!==a)return a+1;throw"Unknown name at position "+l},D=function(){if(s.charAt(l)!==i.charAt(o))throw"Unexpected literal at position "+l;l++};for(o=0;i.length>o;o++)if(y)"'"!==i.charAt(o)||w("'")?D():y=!1;else switch(i.charAt(o)){case"d":_=k("d");break;case"D":x("D",d,p);break;case"o":b=k("o");break;case"m":v=k("m");break;case"M":v=x("M",f,g);break;case"y":m=k("y");break;case"@":h=new Date(k("@")),m=h.getFullYear(),v=h.getMonth()+1,_=h.getDate();break;case"!":h=new Date((k("!")-this._ticksTo1970)/1e4),m=h.getFullYear(),v=h.getMonth()+1,_=h.getDate();break;case"'":w("'")?D():y=!0;break;default:D()}if(s.length>l&&(r=s.substr(l),!/^\s+/.test(r)))throw"Extra/unparsed characters found in date: "+r;if(-1===m?m=(new Date).getFullYear():100>m&&(m+=(new Date).getFullYear()-(new Date).getFullYear()%100+(u>=m?0:-100)),b>-1)for(v=1,_=b;;){if(a=this._getDaysInMonth(m,v-1),a>=_)break;v++,_-=a}if(h=this._daylightSavingAdjust(new Date(m,v-1,_)),h.getFullYear()!==m||h.getMonth()+1!==v||h.getDate()!==_)throw"Invalid date";return h},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:1e7*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(t,e,i){if(!e)return"";var s,n=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,o=(i?i.dayNames:null)||this._defaults.dayNames,a=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,r=(i?i.monthNames:null)||this._defaults.monthNames,h=function(e){var i=t.length>s+1&&t.charAt(s+1)===e;return i&&s++,i},l=function(t,e,i){var s=""+e;if(h(t))for(;i>s.length;)s="0"+s;return s},c=function(t,e,i,s){return h(t)?s[e]:i[e]},u="",d=!1;if(e)for(s=0;t.length>s;s++)if(d)"'"!==t.charAt(s)||h("'")?u+=t.charAt(s):d=!1;else switch(t.charAt(s)){case"d":u+=l("d",e.getDate(),2);break;case"D":u+=c("D",e.getDay(),n,o);break;case"o":u+=l("o",Math.round((new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-new Date(e.getFullYear(),0,0).getTime())/864e5),3);break;case"m":u+=l("m",e.getMonth()+1,2);break;case"M":u+=c("M",e.getMonth(),a,r);break;case"y":u+=h("y")?e.getFullYear():(10>e.getYear()%100?"0":"")+e.getYear()%100;break;case"@":u+=e.getTime();break;case"!":u+=1e4*e.getTime()+this._ticksTo1970;break;case"'":h("'")?u+="'":d=!0;break;default:u+=t.charAt(s)}return u},_possibleChars:function(t){var e,i="",s=!1,n=function(i){var s=t.length>e+1&&t.charAt(e+1)===i;return s&&e++,s};for(e=0;t.length>e;e++)if(s)"'"!==t.charAt(e)||n("'")?i+=t.charAt(e):s=!1;else switch(t.charAt(e)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":n("'")?i+="'":s=!0;break;default:i+=t.charAt(e)}return i},_get:function(t,i){return t.settings[i]!==e?t.settings[i]:this._defaults[i]},_setDateFromField:function(t,e){if(t.input.val()!==t.lastVal){var i=this._get(t,"dateFormat"),s=t.lastVal=t.input?t.input.val():null,n=this._getDefaultDate(t),o=n,a=this._getFormatConfig(t);try{o=this.parseDate(i,s,a)||n}catch(r){s=e?"":s}t.selectedDay=o.getDate(),t.drawMonth=t.selectedMonth=o.getMonth(),t.drawYear=t.selectedYear=o.getFullYear(),t.currentDay=s?o.getDate():0,t.currentMonth=s?o.getMonth():0,t.currentYear=s?o.getFullYear():0,this._adjustInstDate(t)}},_getDefaultDate:function(t){return this._restrictMinMax(t,this._determineDate(t,this._get(t,"defaultDate"),new Date))},_determineDate:function(e,i,s){var n=function(t){var e=new Date;return e.setDate(e.getDate()+t),e},o=function(i){try{return t.datepicker.parseDate(t.datepicker._get(e,"dateFormat"),i,t.datepicker._getFormatConfig(e))}catch(s){}for(var n=(i.toLowerCase().match(/^c/)?t.datepicker._getDate(e):null)||new Date,o=n.getFullYear(),a=n.getMonth(),r=n.getDate(),h=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,l=h.exec(i);l;){switch(l[2]||"d"){case"d":case"D":r+=parseInt(l[1],10);break;case"w":case"W":r+=7*parseInt(l[1],10);break;case"m":case"M":a+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(o,a));break;case"y":case"Y":o+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(o,a))}l=h.exec(i)}return new Date(o,a,r)},a=null==i||""===i?s:"string"==typeof i?o(i):"number"==typeof i?isNaN(i)?s:n(i):new Date(i.getTime());return a=a&&"Invalid Date"==""+a?s:a,a&&(a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0)),this._daylightSavingAdjust(a)},_daylightSavingAdjust:function(t){return t?(t.setHours(t.getHours()>12?t.getHours()+2:0),t):null},_setDate:function(t,e,i){var s=!e,n=t.selectedMonth,o=t.selectedYear,a=this._restrictMinMax(t,this._determineDate(t,e,new Date));t.selectedDay=t.currentDay=a.getDate(),t.drawMonth=t.selectedMonth=t.currentMonth=a.getMonth(),t.drawYear=t.selectedYear=t.currentYear=a.getFullYear(),n===t.selectedMonth&&o===t.selectedYear||i||this._notifyChange(t),this._adjustInstDate(t),t.input&&t.input.val(s?"":this._formatDate(t))},_getDate:function(t){var e=!t.currentYear||t.input&&""===t.input.val()?null:this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return e},_attachHandlers:function(e){var i=this._get(e,"stepMonths"),s="#"+e.id.replace(/\\\\/g,"\\");e.dpDiv.find("[data-handler]").map(function(){var e={prev:function(){t.datepicker._adjustDate(s,-i,"M")},next:function(){t.datepicker._adjustDate(s,+i,"M")},hide:function(){t.datepicker._hideDatepicker()},today:function(){t.datepicker._gotoToday(s)},selectDay:function(){return t.datepicker._selectDay(s,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return t.datepicker._selectMonthYear(s,this,"M"),!1},selectYear:function(){return t.datepicker._selectMonthYear(s,this,"Y"),!1}};t(this).bind(this.getAttribute("data-event"),e[this.getAttribute("data-handler")])})},_generateHTML:function(t){var e,i,s,n,o,a,r,h,l,c,u,d,p,f,g,m,v,_,b,y,w,k,x,D,C,I,P,T,M,S,z,A,H,E,N,W,O,F,R,L=new Date,j=this._daylightSavingAdjust(new Date(L.getFullYear(),L.getMonth(),L.getDate())),Y=this._get(t,"isRTL"),B=this._get(t,"showButtonPanel"),V=this._get(t,"hideIfNoPrevNext"),K=this._get(t,"navigationAsDateFormat"),U=this._getNumberOfMonths(t),q=this._get(t,"showCurrentAtPos"),Q=this._get(t,"stepMonths"),X=1!==U[0]||1!==U[1],$=this._daylightSavingAdjust(t.currentDay?new Date(t.currentYear,t.currentMonth,t.currentDay):new Date(9999,9,9)),G=this._getMinMaxDate(t,"min"),J=this._getMinMaxDate(t,"max"),Z=t.drawMonth-q,te=t.drawYear;if(0>Z&&(Z+=12,te--),J)for(e=this._daylightSavingAdjust(new Date(J.getFullYear(),J.getMonth()-U[0]*U[1]+1,J.getDate())),e=G&&G>e?G:e;this._daylightSavingAdjust(new Date(te,Z,1))>e;)Z--,0>Z&&(Z=11,te--);for(t.drawMonth=Z,t.drawYear=te,i=this._get(t,"prevText"),i=K?this.formatDate(i,this._daylightSavingAdjust(new Date(te,Z-Q,1)),this._getFormatConfig(t)):i,s=this._canAdjustMonth(t,-1,te,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>":V?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>",n=this._get(t,"nextText"),n=K?this.formatDate(n,this._daylightSavingAdjust(new Date(te,Z+Q,1)),this._getFormatConfig(t)):n,o=this._canAdjustMonth(t,1,te,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>":V?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>",a=this._get(t,"currentText"),r=this._get(t,"gotoCurrent")&&t.currentDay?$:j,a=K?this.formatDate(a,r,this._getFormatConfig(t)):a,h=t.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(t,"closeText")+"</button>",l=B?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(Y?h:"")+(this._isInRange(t,r)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+a+"</button>":"")+(Y?"":h)+"</div>":"",c=parseInt(this._get(t,"firstDay"),10),c=isNaN(c)?0:c,u=this._get(t,"showWeek"),d=this._get(t,"dayNames"),p=this._get(t,"dayNamesMin"),f=this._get(t,"monthNames"),g=this._get(t,"monthNamesShort"),m=this._get(t,"beforeShowDay"),v=this._get(t,"showOtherMonths"),_=this._get(t,"selectOtherMonths"),b=this._getDefaultDate(t),y="",k=0;U[0]>k;k++){for(x="",this.maxRows=4,D=0;U[1]>D;D++){if(C=this._daylightSavingAdjust(new Date(te,Z,t.selectedDay)),I=" ui-corner-all",P="",X){if(P+="<div class='ui-datepicker-group",U[1]>1)switch(D){case 0:P+=" ui-datepicker-group-first",I=" ui-corner-"+(Y?"right":"left");break;case U[1]-1:P+=" ui-datepicker-group-last",I=" ui-corner-"+(Y?"left":"right");break;default:P+=" ui-datepicker-group-middle",I=""}P+="'>"}for(P+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+I+"'>"+(/all|left/.test(I)&&0===k?Y?o:s:"")+(/all|right/.test(I)&&0===k?Y?s:o:"")+this._generateMonthYearHeader(t,Z,te,G,J,k>0||D>0,f,g)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",T=u?"<th class='ui-datepicker-week-col'>"+this._get(t,"weekHeader")+"</th>":"",w=0;7>w;w++)M=(w+c)%7,T+="<th"+((w+c+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+d[M]+"'>"+p[M]+"</span></th>";for(P+=T+"</tr></thead><tbody>",S=this._getDaysInMonth(te,Z),te===t.selectedYear&&Z===t.selectedMonth&&(t.selectedDay=Math.min(t.selectedDay,S)),z=(this._getFirstDayOfMonth(te,Z)-c+7)%7,A=Math.ceil((z+S)/7),H=X?this.maxRows>A?this.maxRows:A:A,this.maxRows=H,E=this._daylightSavingAdjust(new Date(te,Z,1-z)),N=0;H>N;N++){for(P+="<tr>",W=u?"<td class='ui-datepicker-week-col'>"+this._get(t,"calculateWeek")(E)+"</td>":"",w=0;7>w;w++)O=m?m.apply(t.input?t.input[0]:null,[E]):[!0,""],F=E.getMonth()!==Z,R=F&&!_||!O[0]||G&&G>E||J&&E>J,W+="<td class='"+((w+c+6)%7>=5?" ui-datepicker-week-end":"")+(F?" ui-datepicker-other-month":"")+(E.getTime()===C.getTime()&&Z===t.selectedMonth&&t._keyEvent||b.getTime()===E.getTime()&&b.getTime()===C.getTime()?" "+this._dayOverClass:"")+(R?" "+this._unselectableClass+" ui-state-disabled":"")+(F&&!v?"":" "+O[1]+(E.getTime()===$.getTime()?" "+this._currentClass:"")+(E.getTime()===j.getTime()?" ui-datepicker-today":""))+"'"+(F&&!v||!O[2]?"":" title='"+O[2].replace(/'/g,"&#39;")+"'")+(R?"":" data-handler='selectDay' data-event='click' data-month='"+E.getMonth()+"' data-year='"+E.getFullYear()+"'")+">"+(F&&!v?"&#xa0;":R?"<span class='ui-state-default'>"+E.getDate()+"</span>":"<a class='ui-state-default"+(E.getTime()===j.getTime()?" ui-state-highlight":"")+(E.getTime()===$.getTime()?" ui-state-active":"")+(F?" ui-priority-secondary":"")+"' href='#'>"+E.getDate()+"</a>")+"</td>",E.setDate(E.getDate()+1),E=this._daylightSavingAdjust(E);P+=W+"</tr>"}Z++,Z>11&&(Z=0,te++),P+="</tbody></table>"+(X?"</div>"+(U[0]>0&&D===U[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),x+=P}y+=x}return y+=l,t._keyEvent=!1,y},_generateMonthYearHeader:function(t,e,i,s,n,o,a,r){var h,l,c,u,d,p,f,g,m=this._get(t,"changeMonth"),v=this._get(t,"changeYear"),_=this._get(t,"showMonthAfterYear"),b="<div class='ui-datepicker-title'>",y="";if(o||!m)y+="<span class='ui-datepicker-month'>"+a[e]+"</span>";else{for(h=s&&s.getFullYear()===i,l=n&&n.getFullYear()===i,y+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",c=0;12>c;c++)(!h||c>=s.getMonth())&&(!l||n.getMonth()>=c)&&(y+="<option value='"+c+"'"+(c===e?" selected='selected'":"")+">"+r[c]+"</option>");y+="</select>"}if(_||(b+=y+(!o&&m&&v?"":"&#xa0;")),!t.yearshtml)if(t.yearshtml="",o||!v)b+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(u=this._get(t,"yearRange").split(":"),d=(new Date).getFullYear(),p=function(t){var e=t.match(/c[+\-].*/)?i+parseInt(t.substring(1),10):t.match(/[+\-].*/)?d+parseInt(t,10):parseInt(t,10);return isNaN(e)?d:e},f=p(u[0]),g=Math.max(f,p(u[1]||"")),f=s?Math.max(f,s.getFullYear()):f,g=n?Math.min(g,n.getFullYear()):g,t.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";g>=f;f++)t.yearshtml+="<option value='"+f+"'"+(f===i?" selected='selected'":"")+">"+f+"</option>";t.yearshtml+="</select>",b+=t.yearshtml,t.yearshtml=null}return b+=this._get(t,"yearSuffix"),_&&(b+=(!o&&m&&v?"":"&#xa0;")+y),b+="</div>"},_adjustInstDate:function(t,e,i){var s=t.drawYear+("Y"===i?e:0),n=t.drawMonth+("M"===i?e:0),o=Math.min(t.selectedDay,this._getDaysInMonth(s,n))+("D"===i?e:0),a=this._restrictMinMax(t,this._daylightSavingAdjust(new Date(s,n,o)));t.selectedDay=a.getDate(),t.drawMonth=t.selectedMonth=a.getMonth(),t.drawYear=t.selectedYear=a.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(t)},_restrictMinMax:function(t,e){var i=this._getMinMaxDate(t,"min"),s=this._getMinMaxDate(t,"max"),n=i&&i>e?i:e;return s&&n>s?s:n},_notifyChange:function(t){var e=this._get(t,"onChangeMonthYear");e&&e.apply(t.input?t.input[0]:null,[t.selectedYear,t.selectedMonth+1,t])},_getNumberOfMonths:function(t){var e=this._get(t,"numberOfMonths");return null==e?[1,1]:"number"==typeof e?[1,e]:e},_getMinMaxDate:function(t,e){return this._determineDate(t,this._get(t,e+"Date"),null)},_getDaysInMonth:function(t,e){return 32-this._daylightSavingAdjust(new Date(t,e,32)).getDate()},_getFirstDayOfMonth:function(t,e){return new Date(t,e,1).getDay()},_canAdjustMonth:function(t,e,i,s){var n=this._getNumberOfMonths(t),o=this._daylightSavingAdjust(new Date(i,s+(0>e?e:n[0]*n[1]),1));return 0>e&&o.setDate(this._getDaysInMonth(o.getFullYear(),o.getMonth())),this._isInRange(t,o)},_isInRange:function(t,e){var i,s,n=this._getMinMaxDate(t,"min"),o=this._getMinMaxDate(t,"max"),a=null,r=null,h=this._get(t,"yearRange");return h&&(i=h.split(":"),s=(new Date).getFullYear(),a=parseInt(i[0],10),r=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(a+=s),i[1].match(/[+\-].*/)&&(r+=s)),(!n||e.getTime()>=n.getTime())&&(!o||e.getTime()<=o.getTime())&&(!a||e.getFullYear()>=a)&&(!r||r>=e.getFullYear())},_getFormatConfig:function(t){var e=this._get(t,"shortYearCutoff");return e="string"!=typeof e?e:(new Date).getFullYear()%100+parseInt(e,10),{shortYearCutoff:e,dayNamesShort:this._get(t,"dayNamesShort"),dayNames:this._get(t,"dayNames"),monthNamesShort:this._get(t,"monthNamesShort"),monthNames:this._get(t,"monthNames")}},_formatDate:function(t,e,i,s){e||(t.currentDay=t.selectedDay,t.currentMonth=t.selectedMonth,t.currentYear=t.selectedYear);var n=e?"object"==typeof e?e:this._daylightSavingAdjust(new Date(s,i,e)):this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return this.formatDate(this._get(t,"dateFormat"),n,this._getFormatConfig(t))}}),t.fn.datepicker=function(e){if(!this.length)return this;t.datepicker.initialized||(t(document).mousedown(t.datepicker._checkExternalClick),t.datepicker.initialized=!0),0===t("#"+t.datepicker._mainDivId).length&&t("body").append(t.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"!=typeof e||"isDisabled"!==e&&"getDate"!==e&&"widget"!==e?"option"===e&&2===arguments.length&&"string"==typeof arguments[1]?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof e?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this].concat(i)):t.datepicker._attachDatepicker(this,e)}):t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i))},t.datepicker=new i,t.datepicker.initialized=!1,t.datepicker.uuid=(new Date).getTime(),t.datepicker.version="1.10.3"}(jQuery),function(t){var e={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},i={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0};t.widget("ui.dialog",{version:"1.10.3",options:{appendTo:"body",autoOpen:!0,buttons:[],closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(e){var i=t(this).css(e).offset().top;0>i&&t(this).css("top",e.top-i)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),this.options.title=this.options.title||this.originalTitle,this._createWrapper(),this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(this.uiDialog),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&t.fn.draggable&&this._makeDraggable(),this.options.resizable&&t.fn.resizable&&this._makeResizable(),this._isOpen=!1},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var e=this.options.appendTo;return e&&(e.jquery||e.nodeType)?t(e):this.document.find(e||"body").eq(0)},_destroy:function(){var t,e=this.originalPosition;this._destroyOverlay(),this.element.removeUniqueId().removeClass("ui-dialog-content ui-widget-content").css(this.originalCss).detach(),this.uiDialog.stop(!0,!0).remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),t=e.parent.children().eq(e.index),t.length&&t[0]!==this.element[0]?t.before(this.element):e.parent.append(this.element)},widget:function(){return this.uiDialog},disable:t.noop,enable:t.noop,close:function(e){var i=this;this._isOpen&&this._trigger("beforeClose",e)!==!1&&(this._isOpen=!1,this._destroyOverlay(),this.opener.filter(":focusable").focus().length||t(this.document[0].activeElement).blur(),this._hide(this.uiDialog,this.options.hide,function(){i._trigger("close",e)}))},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(t,e){var i=!!this.uiDialog.nextAll(":visible").insertBefore(this.uiDialog).length;return i&&!e&&this._trigger("focus",t),i},open:function(){var e=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),undefined):(this._isOpen=!0,this.opener=t(this.document[0].activeElement),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this._show(this.uiDialog,this.options.show,function(){e._focusTabbable(),e._trigger("focus")}),this._trigger("open"),undefined)},_focusTabbable:function(){var t=this.element.find("[autofocus]");t.length||(t=this.element.find(":tabbable")),t.length||(t=this.uiDialogButtonPane.find(":tabbable")),t.length||(t=this.uiDialogTitlebarClose.filter(":tabbable")),t.length||(t=this.uiDialog),t.eq(0).focus()},_keepFocus:function(e){function i(){var e=this.document[0].activeElement,i=this.uiDialog[0]===e||t.contains(this.uiDialog[0],e);i||this._focusTabbable()}e.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=t("<div>").addClass("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front "+this.options.dialogClass).hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._on(this.uiDialog,{keydown:function(e){if(this.options.closeOnEscape&&!e.isDefaultPrevented()&&e.keyCode&&e.keyCode===t.ui.keyCode.ESCAPE)return e.preventDefault(),this.close(e),undefined;if(e.keyCode===t.ui.keyCode.TAB){var i=this.uiDialog.find(":tabbable"),s=i.filter(":first"),n=i.filter(":last");e.target!==n[0]&&e.target!==this.uiDialog[0]||e.shiftKey?e.target!==s[0]&&e.target!==this.uiDialog[0]||!e.shiftKey||(n.focus(1),e.preventDefault()):(s.focus(1),e.preventDefault())}},mousedown:function(t){this._moveToTop(t)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var e;this.uiDialogTitlebar=t("<div>").addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(this.uiDialog),this._on(this.uiDialogTitlebar,{mousedown:function(e){t(e.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.focus()}}),this.uiDialogTitlebarClose=t("<button></button>").button({label:this.options.closeText,icons:{primary:"ui-icon-closethick"},text:!1}).addClass("ui-dialog-titlebar-close").appendTo(this.uiDialogTitlebar),this._on(this.uiDialogTitlebarClose,{click:function(t){t.preventDefault(),this.close(t)}}),e=t("<span>").uniqueId().addClass("ui-dialog-title").prependTo(this.uiDialogTitlebar),this._title(e),this.uiDialog.attr({"aria-labelledby":e.attr("id")})},_title:function(t){this.options.title||t.html("&#160;"),t.text(this.options.title)},_createButtonPane:function(){this.uiDialogButtonPane=t("<div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),this.uiButtonSet=t("<div>").addClass("ui-dialog-buttonset").appendTo(this.uiDialogButtonPane),this._createButtons()},_createButtons:function(){var e=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),t.isEmptyObject(i)||t.isArray(i)&&!i.length?(this.uiDialog.removeClass("ui-dialog-buttons"),undefined):(t.each(i,function(i,s){var n,o;s=t.isFunction(s)?{click:s,text:i}:s,s=t.extend({type:"button"},s),n=s.click,s.click=function(){n.apply(e.element[0],arguments)},o={icons:s.icons,text:s.showText},delete s.icons,delete s.showText,t("<button></button>",s).button(o).appendTo(e.uiButtonSet)}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),undefined)},_makeDraggable:function(){function e(t){return{position:t.position,offset:t.offset}}var i=this,s=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(s,n){t(this).addClass("ui-dialog-dragging"),i._blockFrames(),i._trigger("dragStart",s,e(n))},drag:function(t,s){i._trigger("drag",t,e(s))},stop:function(n,o){s.position=[o.position.left-i.document.scrollLeft(),o.position.top-i.document.scrollTop()],t(this).removeClass("ui-dialog-dragging"),i._unblockFrames(),i._trigger("dragStop",n,e(o))}})},_makeResizable:function(){function e(t){return{originalPosition:t.originalPosition,originalSize:t.originalSize,position:t.position,size:t.size} }var i=this,s=this.options,n=s.resizable,o=this.uiDialog.css("position"),a="string"==typeof n?n:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:s.maxWidth,maxHeight:s.maxHeight,minWidth:s.minWidth,minHeight:this._minHeight(),handles:a,start:function(s,n){t(this).addClass("ui-dialog-resizing"),i._blockFrames(),i._trigger("resizeStart",s,e(n))},resize:function(t,s){i._trigger("resize",t,e(s))},stop:function(n,o){s.height=t(this).height(),s.width=t(this).width(),t(this).removeClass("ui-dialog-resizing"),i._unblockFrames(),i._trigger("resizeStop",n,e(o))}}).css("position",o)},_minHeight:function(){var t=this.options;return"auto"===t.height?t.minHeight:Math.min(t.minHeight,t.height)},_position:function(){var t=this.uiDialog.is(":visible");t||this.uiDialog.show(),this.uiDialog.position(this.options.position),t||this.uiDialog.hide()},_setOptions:function(s){var n=this,o=!1,a={};t.each(s,function(t,s){n._setOption(t,s),t in e&&(o=!0),t in i&&(a[t]=s)}),o&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",a)},_setOption:function(t,e){var i,s,n=this.uiDialog;"dialogClass"===t&&n.removeClass(this.options.dialogClass).addClass(e),"disabled"!==t&&(this._super(t,e),"appendTo"===t&&this.uiDialog.appendTo(this._appendTo()),"buttons"===t&&this._createButtons(),"closeText"===t&&this.uiDialogTitlebarClose.button({label:""+e}),"draggable"===t&&(i=n.is(":data(ui-draggable)"),i&&!e&&n.draggable("destroy"),!i&&e&&this._makeDraggable()),"position"===t&&this._position(),"resizable"===t&&(s=n.is(":data(ui-resizable)"),s&&!e&&n.resizable("destroy"),s&&"string"==typeof e&&n.resizable("option","handles",e),s||e===!1||this._makeResizable()),"title"===t&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var t,e,i,s=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),s.minWidth>s.width&&(s.width=s.minWidth),t=this.uiDialog.css({height:"auto",width:s.width}).outerHeight(),e=Math.max(0,s.minHeight-t),i="number"==typeof s.maxHeight?Math.max(0,s.maxHeight-t):"none","auto"===s.height?this.element.css({minHeight:e,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,s.height-t)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var e=t(this);return t("<div>").css({position:"absolute",width:e.outerWidth(),height:e.outerHeight()}).appendTo(e.parent()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(e){return t(e.target).closest(".ui-dialog").length?!0:!!t(e.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var e=this,i=this.widgetFullName;t.ui.dialog.overlayInstances||this._delay(function(){t.ui.dialog.overlayInstances&&this.document.bind("focusin.dialog",function(s){e._allowInteraction(s)||(s.preventDefault(),t(".ui-dialog:visible:last .ui-dialog-content").data(i)._focusTabbable())})}),this.overlay=t("<div>").addClass("ui-widget-overlay ui-front").appendTo(this._appendTo()),this._on(this.overlay,{mousedown:"_keepFocus"}),t.ui.dialog.overlayInstances++}},_destroyOverlay:function(){this.options.modal&&this.overlay&&(t.ui.dialog.overlayInstances--,t.ui.dialog.overlayInstances||this.document.unbind("focusin.dialog"),this.overlay.remove(),this.overlay=null)}}),t.ui.dialog.overlayInstances=0,t.uiBackCompat!==!1&&t.widget("ui.dialog",t.ui.dialog,{_position:function(){var e,i=this.options.position,s=[],n=[0,0];i?(("string"==typeof i||"object"==typeof i&&"0"in i)&&(s=i.split?i.split(" "):[i[0],i[1]],1===s.length&&(s[1]=s[0]),t.each(["left","top"],function(t,e){+s[t]===s[t]&&(n[t]=s[t],s[t]=e)}),i={my:s[0]+(0>n[0]?n[0]:"+"+n[0])+" "+s[1]+(0>n[1]?n[1]:"+"+n[1]),at:s.join(" ")}),i=t.extend({},t.ui.dialog.prototype.options.position,i)):i=t.ui.dialog.prototype.options.position,e=this.uiDialog.is(":visible"),e||this.uiDialog.show(),this.uiDialog.position(i),e||this.uiDialog.hide()}})}(jQuery),function(t){var e=/up|down|vertical/,i=/up|left|vertical|horizontal/;t.effects.effect.blind=function(s,n){var o,a,r,h=t(this),l=["position","top","bottom","left","right","height","width"],c=t.effects.setMode(h,s.mode||"hide"),u=s.direction||"up",d=e.test(u),p=d?"height":"width",f=d?"top":"left",g=i.test(u),m={},v="show"===c;h.parent().is(".ui-effects-wrapper")?t.effects.save(h.parent(),l):t.effects.save(h,l),h.show(),o=t.effects.createWrapper(h).css({overflow:"hidden"}),a=o[p](),r=parseFloat(o.css(f))||0,m[p]=v?a:0,g||(h.css(d?"bottom":"right",0).css(d?"top":"left","auto").css({position:"absolute"}),m[f]=v?r:a+r),v&&(o.css(p,0),g||o.css(f,r+a)),o.animate(m,{duration:s.duration,easing:s.easing,queue:!1,complete:function(){"hide"===c&&h.hide(),t.effects.restore(h,l),t.effects.removeWrapper(h),n()}})}}(jQuery),function(t){t.effects.effect.bounce=function(e,i){var s,n,o,a=t(this),r=["position","top","bottom","left","right","height","width"],h=t.effects.setMode(a,e.mode||"effect"),l="hide"===h,c="show"===h,u=e.direction||"up",d=e.distance,p=e.times||5,f=2*p+(c||l?1:0),g=e.duration/f,m=e.easing,v="up"===u||"down"===u?"top":"left",_="up"===u||"left"===u,b=a.queue(),y=b.length;for((c||l)&&r.push("opacity"),t.effects.save(a,r),a.show(),t.effects.createWrapper(a),d||(d=a["top"===v?"outerHeight":"outerWidth"]()/3),c&&(o={opacity:1},o[v]=0,a.css("opacity",0).css(v,_?2*-d:2*d).animate(o,g,m)),l&&(d/=Math.pow(2,p-1)),o={},o[v]=0,s=0;p>s;s++)n={},n[v]=(_?"-=":"+=")+d,a.animate(n,g,m).animate(o,g,m),d=l?2*d:d/2;l&&(n={opacity:0},n[v]=(_?"-=":"+=")+d,a.animate(n,g,m)),a.queue(function(){l&&a.hide(),t.effects.restore(a,r),t.effects.removeWrapper(a),i()}),y>1&&b.splice.apply(b,[1,0].concat(b.splice(y,f+1))),a.dequeue()}}(jQuery),function(t){t.effects.effect.clip=function(e,i){var s,n,o,a=t(this),r=["position","top","bottom","left","right","height","width"],h=t.effects.setMode(a,e.mode||"hide"),l="show"===h,c=e.direction||"vertical",u="vertical"===c,d=u?"height":"width",p=u?"top":"left",f={};t.effects.save(a,r),a.show(),s=t.effects.createWrapper(a).css({overflow:"hidden"}),n="IMG"===a[0].tagName?s:a,o=n[d](),l&&(n.css(d,0),n.css(p,o/2)),f[d]=l?o:0,f[p]=l?0:o/2,n.animate(f,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){l||a.hide(),t.effects.restore(a,r),t.effects.removeWrapper(a),i()}})}}(jQuery),function(t){t.effects.effect.drop=function(e,i){var s,n=t(this),o=["position","top","bottom","left","right","opacity","height","width"],a=t.effects.setMode(n,e.mode||"hide"),r="show"===a,h=e.direction||"left",l="up"===h||"down"===h?"top":"left",c="up"===h||"left"===h?"pos":"neg",u={opacity:r?1:0};t.effects.save(n,o),n.show(),t.effects.createWrapper(n),s=e.distance||n["top"===l?"outerHeight":"outerWidth"](!0)/2,r&&n.css("opacity",0).css(l,"pos"===c?-s:s),u[l]=(r?"pos"===c?"+=":"-=":"pos"===c?"-=":"+=")+s,n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===a&&n.hide(),t.effects.restore(n,o),t.effects.removeWrapper(n),i()}})}}(jQuery),function(t){t.effects.effect.explode=function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),g||p.hide(),i()}var o,a,r,h,l,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=t.effects.setMode(p,e.mode||"hide"),g="show"===f,m=p.show().css("visibility","hidden").offset(),v=Math.ceil(p.outerWidth()/d),_=Math.ceil(p.outerHeight()/u),b=[];for(o=0;u>o;o++)for(h=m.top+o*_,c=o-(u-1)/2,a=0;d>a;a++)r=m.left+a*v,l=a-(d-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-a*v,top:-o*_}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:v,height:_,left:r+(g?l*v:0),top:h+(g?c*_:0),opacity:g?0:1}).animate({left:r+(g?0:l*v),top:h+(g?0:c*_),opacity:g?1:0},e.duration||500,e.easing,s)}}(jQuery),function(t){t.effects.effect.fade=function(e,i){var s=t(this),n=t.effects.setMode(s,e.mode||"toggle");s.animate({opacity:n},{queue:!1,duration:e.duration,easing:e.easing,complete:i})}}(jQuery),function(t){t.effects.effect.fold=function(e,i){var s,n,o=t(this),a=["position","top","bottom","left","right","height","width"],r=t.effects.setMode(o,e.mode||"hide"),h="show"===r,l="hide"===r,c=e.size||15,u=/([0-9]+)%/.exec(c),d=!!e.horizFirst,p=h!==d,f=p?["width","height"]:["height","width"],g=e.duration/2,m={},v={};t.effects.save(o,a),o.show(),s=t.effects.createWrapper(o).css({overflow:"hidden"}),n=p?[s.width(),s.height()]:[s.height(),s.width()],u&&(c=parseInt(u[1],10)/100*n[l?0:1]),h&&s.css(d?{height:0,width:c}:{height:c,width:0}),m[f[0]]=h?n[0]:c,v[f[1]]=h?n[1]:0,s.animate(m,g,e.easing).animate(v,g,e.easing,function(){l&&o.hide(),t.effects.restore(o,a),t.effects.removeWrapper(o),i()})}}(jQuery),function(t){t.effects.effect.highlight=function(e,i){var s=t(this),n=["backgroundImage","backgroundColor","opacity"],o=t.effects.setMode(s,e.mode||"show"),a={backgroundColor:s.css("backgroundColor")};"hide"===o&&(a.opacity=0),t.effects.save(s,n),s.show().css({backgroundImage:"none",backgroundColor:e.color||"#ffff99"}).animate(a,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===o&&s.hide(),t.effects.restore(s,n),i()}})}}(jQuery),function(t){t.effects.effect.pulsate=function(e,i){var s,n=t(this),o=t.effects.setMode(n,e.mode||"show"),a="show"===o,r="hide"===o,h=a||"hide"===o,l=2*(e.times||5)+(h?1:0),c=e.duration/l,u=0,d=n.queue(),p=d.length;for((a||!n.is(":visible"))&&(n.css("opacity",0).show(),u=1),s=1;l>s;s++)n.animate({opacity:u},c,e.easing),u=1-u;n.animate({opacity:u},c,e.easing),n.queue(function(){r&&n.hide(),i()}),p>1&&d.splice.apply(d,[1,0].concat(d.splice(p,l+1))),n.dequeue()}}(jQuery),function(t){t.effects.effect.puff=function(e,i){var s=t(this),n=t.effects.setMode(s,e.mode||"hide"),o="hide"===n,a=parseInt(e.percent,10)||150,r=a/100,h={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()};t.extend(e,{effect:"scale",queue:!1,fade:!0,mode:n,complete:i,percent:o?a:100,from:o?h:{height:h.height*r,width:h.width*r,outerHeight:h.outerHeight*r,outerWidth:h.outerWidth*r}}),s.effect(e)},t.effects.effect.scale=function(e,i){var s=t(this),n=t.extend(!0,{},e),o=t.effects.setMode(s,e.mode||"effect"),a=parseInt(e.percent,10)||(0===parseInt(e.percent,10)?0:"hide"===o?0:100),r=e.direction||"both",h=e.origin,l={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()},c={y:"horizontal"!==r?a/100:1,x:"vertical"!==r?a/100:1};n.effect="size",n.queue=!1,n.complete=i,"effect"!==o&&(n.origin=h||["middle","center"],n.restore=!0),n.from=e.from||("show"===o?{height:0,width:0,outerHeight:0,outerWidth:0}:l),n.to={height:l.height*c.y,width:l.width*c.x,outerHeight:l.outerHeight*c.y,outerWidth:l.outerWidth*c.x},n.fade&&("show"===o&&(n.from.opacity=0,n.to.opacity=1),"hide"===o&&(n.from.opacity=1,n.to.opacity=0)),s.effect(n)},t.effects.effect.size=function(e,i){var s,n,o,a=t(this),r=["position","top","bottom","left","right","width","height","overflow","opacity"],h=["position","top","bottom","left","right","overflow","opacity"],l=["width","height","overflow"],c=["fontSize"],u=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],d=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=t.effects.setMode(a,e.mode||"effect"),f=e.restore||"effect"!==p,g=e.scale||"both",m=e.origin||["middle","center"],v=a.css("position"),_=f?r:h,b={height:0,width:0,outerHeight:0,outerWidth:0};"show"===p&&a.show(),s={height:a.height(),width:a.width(),outerHeight:a.outerHeight(),outerWidth:a.outerWidth()},"toggle"===e.mode&&"show"===p?(a.from=e.to||b,a.to=e.from||s):(a.from=e.from||("show"===p?b:s),a.to=e.to||("hide"===p?b:s)),o={from:{y:a.from.height/s.height,x:a.from.width/s.width},to:{y:a.to.height/s.height,x:a.to.width/s.width}},("box"===g||"both"===g)&&(o.from.y!==o.to.y&&(_=_.concat(u),a.from=t.effects.setTransition(a,u,o.from.y,a.from),a.to=t.effects.setTransition(a,u,o.to.y,a.to)),o.from.x!==o.to.x&&(_=_.concat(d),a.from=t.effects.setTransition(a,d,o.from.x,a.from),a.to=t.effects.setTransition(a,d,o.to.x,a.to))),("content"===g||"both"===g)&&o.from.y!==o.to.y&&(_=_.concat(c).concat(l),a.from=t.effects.setTransition(a,c,o.from.y,a.from),a.to=t.effects.setTransition(a,c,o.to.y,a.to)),t.effects.save(a,_),a.show(),t.effects.createWrapper(a),a.css("overflow","hidden").css(a.from),m&&(n=t.effects.getBaseline(m,s),a.from.top=(s.outerHeight-a.outerHeight())*n.y,a.from.left=(s.outerWidth-a.outerWidth())*n.x,a.to.top=(s.outerHeight-a.to.outerHeight)*n.y,a.to.left=(s.outerWidth-a.to.outerWidth)*n.x),a.css(a.from),("content"===g||"both"===g)&&(u=u.concat(["marginTop","marginBottom"]).concat(c),d=d.concat(["marginLeft","marginRight"]),l=r.concat(u).concat(d),a.find("*[width]").each(function(){var i=t(this),s={height:i.height(),width:i.width(),outerHeight:i.outerHeight(),outerWidth:i.outerWidth()};f&&t.effects.save(i,l),i.from={height:s.height*o.from.y,width:s.width*o.from.x,outerHeight:s.outerHeight*o.from.y,outerWidth:s.outerWidth*o.from.x},i.to={height:s.height*o.to.y,width:s.width*o.to.x,outerHeight:s.height*o.to.y,outerWidth:s.width*o.to.x},o.from.y!==o.to.y&&(i.from=t.effects.setTransition(i,u,o.from.y,i.from),i.to=t.effects.setTransition(i,u,o.to.y,i.to)),o.from.x!==o.to.x&&(i.from=t.effects.setTransition(i,d,o.from.x,i.from),i.to=t.effects.setTransition(i,d,o.to.x,i.to)),i.css(i.from),i.animate(i.to,e.duration,e.easing,function(){f&&t.effects.restore(i,l)})})),a.animate(a.to,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){0===a.to.opacity&&a.css("opacity",a.from.opacity),"hide"===p&&a.hide(),t.effects.restore(a,_),f||("static"===v?a.css({position:"relative",top:a.to.top,left:a.to.left}):t.each(["top","left"],function(t,e){a.css(e,function(e,i){var s=parseInt(i,10),n=t?a.to.left:a.to.top;return"auto"===i?n+"px":s+n+"px"})})),t.effects.removeWrapper(a),i()}})}}(jQuery),function(t){t.effects.effect.shake=function(e,i){var s,n=t(this),o=["position","top","bottom","left","right","height","width"],a=t.effects.setMode(n,e.mode||"effect"),r=e.direction||"left",h=e.distance||20,l=e.times||3,c=2*l+1,u=Math.round(e.duration/c),d="up"===r||"down"===r?"top":"left",p="up"===r||"left"===r,f={},g={},m={},v=n.queue(),_=v.length;for(t.effects.save(n,o),n.show(),t.effects.createWrapper(n),f[d]=(p?"-=":"+=")+h,g[d]=(p?"+=":"-=")+2*h,m[d]=(p?"-=":"+=")+2*h,n.animate(f,u,e.easing),s=1;l>s;s++)n.animate(g,u,e.easing).animate(m,u,e.easing);n.animate(g,u,e.easing).animate(f,u/2,e.easing).queue(function(){"hide"===a&&n.hide(),t.effects.restore(n,o),t.effects.removeWrapper(n),i()}),_>1&&v.splice.apply(v,[1,0].concat(v.splice(_,c+1))),n.dequeue()}}(jQuery),function(t){t.effects.effect.slide=function(e,i){var s,n=t(this),o=["position","top","bottom","left","right","width","height"],a=t.effects.setMode(n,e.mode||"show"),r="show"===a,h=e.direction||"left",l="up"===h||"down"===h?"top":"left",c="up"===h||"left"===h,u={};t.effects.save(n,o),n.show(),s=e.distance||n["top"===l?"outerHeight":"outerWidth"](!0),t.effects.createWrapper(n).css({overflow:"hidden"}),r&&n.css(l,c?isNaN(s)?"-"+s:-s:s),u[l]=(r?c?"+=":"-=":c?"-=":"+=")+s,n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){"hide"===a&&n.hide(),t.effects.restore(n,o),t.effects.removeWrapper(n),i()}})}}(jQuery),function(t){t.effects.effect.transfer=function(e,i){var s=t(this),n=t(e.to),o="fixed"===n.css("position"),a=t("body"),r=o?a.scrollTop():0,h=o?a.scrollLeft():0,l=n.offset(),c={top:l.top-r,left:l.left-h,height:n.innerHeight(),width:n.innerWidth()},u=s.offset(),d=t("<div class='ui-effects-transfer'></div>").appendTo(document.body).addClass(e.className).css({top:u.top-r,left:u.left-h,height:s.innerHeight(),width:s.innerWidth(),position:o?"fixed":"absolute"}).animate(c,e.duration,e.easing,function(){d.remove(),i()})}}(jQuery),function(t){t.widget("ui.menu",{version:"1.10.3",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content ui-corner-all").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}).bind("click"+this.eventNamespace,t.proxy(function(t){this.options.disabled&&t.preventDefault()},this)),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item > a":function(t){t.preventDefault()},"click .ui-state-disabled > a":function(t){t.preventDefault()},"click .ui-menu-item:has(a)":function(e){var i=t(e.target).closest(".ui-menu-item");!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.mouseHandled=!0,this.select(e),i.has(".ui-menu").length?this.expand(e):this.element.is(":focus")||(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(e){var i=t(e.currentTarget);i.siblings().children(".ui-state-active").removeClass("ui-state-active"),this.focus(e,i)},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.children(".ui-menu-item").eq(0);e||this.focus(t,i)},blur:function(e){this._delay(function(){t.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(e){t(e.target).closest(".ui-menu").length||this.collapseAll(e),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").children("a").removeUniqueId().removeClass("ui-corner-all ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var e=t(this);e.data("ui-menu-submenu-carat")&&e.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(e){function i(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}var s,n,o,a,r,h=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:h=!1,n=this.previousFilter||"",o=String.fromCharCode(e.keyCode),a=!1,clearTimeout(this.filterTimer),o===n?a=!0:o=n+o,r=RegExp("^"+i(o),"i"),s=this.activeMenu.children(".ui-menu-item").filter(function(){return r.test(t(this).children("a").text())}),s=a&&-1!==s.index(this.active.next())?this.active.nextAll(".ui-menu-item"):s,s.length||(o=String.fromCharCode(e.keyCode),r=RegExp("^"+i(o),"i"),s=this.activeMenu.children(".ui-menu-item").filter(function(){return r.test(t(this).children("a").text())})),s.length?(this.focus(e,s),s.length>1?(this.previousFilter=o,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter):delete this.previousFilter}h&&e.preventDefault()},_activate:function(t){this.active.is(".ui-state-disabled")||(this.active.children("a[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var e,i=this.options.icons.submenu,s=this.element.find(this.options.menus);s.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-corner-all").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),s=e.prev("a"),n=t("<span>").addClass("ui-menu-icon ui-icon "+i).data("ui-menu-submenu-carat",!0);s.attr("aria-haspopup","true").prepend(n),e.attr("aria-labelledby",s.attr("id"))}),e=s.add(this.element),e.children(":not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","presentation").children("a").uniqueId().addClass("ui-corner-all").attr({tabIndex:-1,role:this._itemRole()}),e.children(":not(.ui-menu-item)").each(function(){var e=t(this);/[^\-\u2014\u2013\s]/.test(e.text())||e.addClass("ui-widget-content ui-menu-divider")}),e.children(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){"icons"===t&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(e.submenu),this._super(t,e)},focus:function(t,e){var i,s;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.children("a").addClass("ui-state-focus"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),this.active.parent().closest(".ui-menu-item").children("a:first").addClass("ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=e.children(".ui-menu"),i.length&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,o,a,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,o=this.activeMenu.scrollTop(),a=this.activeMenu.height(),r=e.height(),0>n?this.activeMenu.scrollTop(o+n):n+r>a&&this.activeMenu.scrollTop(o+n-a+r))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this.active.children("a").removeClass("ui-state-focus"),this.active=null,this._trigger("blur",t,{item:this.active}))},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this.activeMenu=s},this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find("a.ui-state-active").removeClass("ui-state-active")},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this.active.children(".ui-menu ").children(".ui-menu-item").first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[t+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.children(".ui-menu-item")[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=t(this),0>i.offset().top-s-n}),this.focus(e,i)):this.focus(e,this.activeMenu.children(".ui-menu-item")[this.active?"last":"first"]())),undefined):(this.next(e),undefined)},previousPage:function(e){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=t(this),i.offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this.activeMenu.children(".ui-menu-item").first())),undefined):(this.next(e),undefined)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(e){this.active=this.active||t(e.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(e,!0),this._trigger("select",e,i)}})}(jQuery),function(t,e){function i(t,e,i){return[parseFloat(t[0])*(p.test(t[0])?e/100:1),parseFloat(t[1])*(p.test(t[1])?i/100:1)]}function s(e,i){return parseInt(t.css(e,i),10)||0}function n(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}t.ui=t.ui||{};var o,a=Math.max,r=Math.abs,h=Math.round,l=/left|center|right/,c=/top|center|bottom/,u=/[\+\-]\d+(\.[\d]+)?%?/,d=/^\w+/,p=/%$/,f=t.fn.position;t.position={scrollbarWidth:function(){if(o!==e)return o;var i,s,n=t("<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),a=n.children()[0];return t("body").append(n),i=a.offsetWidth,n.css("overflow","scroll"),s=a.offsetWidth,i===s&&(s=n[0].clientWidth),n.remove(),o=i-s},getScrollInfo:function(e){var i=e.isWindow?"":e.element.css("overflow-x"),s=e.isWindow?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth,o="scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight;return{width:o?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=t.isWindow(i[0]);return{element:i,isWindow:s,offset:i.offset()||{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:s?i.width():i.outerWidth(),height:s?i.height():i.outerHeight()}}},t.fn.position=function(e){if(!e||!e.of)return f.apply(this,arguments);e=t.extend({},e);var o,p,g,m,v,_,b=t(e.of),y=t.position.getWithinInfo(e.within),w=t.position.getScrollInfo(y),k=(e.collision||"flip").split(" "),x={};return _=n(b),b[0].preventDefault&&(e.at="left top"),p=_.width,g=_.height,m=_.offset,v=t.extend({},m),t.each(["my","at"],function(){var t,i,s=(e[this]||"").split(" ");1===s.length&&(s=l.test(s[0])?s.concat(["center"]):c.test(s[0])?["center"].concat(s):["center","center"]),s[0]=l.test(s[0])?s[0]:"center",s[1]=c.test(s[1])?s[1]:"center",t=u.exec(s[0]),i=u.exec(s[1]),x[this]=[t?t[0]:0,i?i[0]:0],e[this]=[d.exec(s[0])[0],d.exec(s[1])[0]]}),1===k.length&&(k[1]=k[0]),"right"===e.at[0]?v.left+=p:"center"===e.at[0]&&(v.left+=p/2),"bottom"===e.at[1]?v.top+=g:"center"===e.at[1]&&(v.top+=g/2),o=i(x.at,p,g),v.left+=o[0],v.top+=o[1],this.each(function(){var n,l,c=t(this),u=c.outerWidth(),d=c.outerHeight(),f=s(this,"marginLeft"),_=s(this,"marginTop"),D=u+f+s(this,"marginRight")+w.width,C=d+_+s(this,"marginBottom")+w.height,I=t.extend({},v),P=i(x.my,c.outerWidth(),c.outerHeight());"right"===e.my[0]?I.left-=u:"center"===e.my[0]&&(I.left-=u/2),"bottom"===e.my[1]?I.top-=d:"center"===e.my[1]&&(I.top-=d/2),I.left+=P[0],I.top+=P[1],t.support.offsetFractions||(I.left=h(I.left),I.top=h(I.top)),n={marginLeft:f,marginTop:_},t.each(["left","top"],function(i,s){t.ui.position[k[i]]&&t.ui.position[k[i]][s](I,{targetWidth:p,targetHeight:g,elemWidth:u,elemHeight:d,collisionPosition:n,collisionWidth:D,collisionHeight:C,offset:[o[0]+P[0],o[1]+P[1]],my:e.my,at:e.at,within:y,elem:c})}),e.using&&(l=function(t){var i=m.left-I.left,s=i+p-u,n=m.top-I.top,o=n+g-d,h={target:{element:b,left:m.left,top:m.top,width:p,height:g},element:{element:c,left:I.left,top:I.top,width:u,height:d},horizontal:0>s?"left":i>0?"right":"center",vertical:0>o?"top":n>0?"bottom":"middle"};u>p&&p>r(i+s)&&(h.horizontal="center"),d>g&&g>r(n+o)&&(h.vertical="middle"),h.important=a(r(i),r(s))>a(r(n),r(o))?"horizontal":"vertical",e.using.call(this,t,h)}),c.offset(t.extend(I,{using:l}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,o=s.width,r=t.left-e.collisionPosition.marginLeft,h=n-r,l=r+e.collisionWidth-o-n;e.collisionWidth>o?h>0&&0>=l?(i=t.left+h+e.collisionWidth-o-n,t.left+=h-i):t.left=l>0&&0>=h?n:h>l?n+o-e.collisionWidth:n:h>0?t.left+=h:l>0?t.left-=l:t.left=a(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,o=e.within.height,r=t.top-e.collisionPosition.marginTop,h=n-r,l=r+e.collisionHeight-o-n;e.collisionHeight>o?h>0&&0>=l?(i=t.top+h+e.collisionHeight-o-n,t.top+=h-i):t.top=l>0&&0>=h?n:h>l?n+o-e.collisionHeight:n:h>0?t.top+=h:l>0?t.top-=l:t.top=a(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,o=n.offset.left+n.scrollLeft,a=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=t.left-e.collisionPosition.marginLeft,c=l-h,u=l+e.collisionWidth-a-h,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-a-o,(0>i||r(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-h,(s>0||u>r(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,o=n.offset.top+n.scrollTop,a=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=t.top-e.collisionPosition.marginTop,c=l-h,u=l+e.collisionHeight-a-h,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-a-o,t.top+p+f+g>c&&(0>s||r(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-h,t.top+p+f+g>u&&(i>0||u>r(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}},function(){var e,i,s,n,o,a=document.getElementsByTagName("body")[0],r=document.createElement("div");e=document.createElement(a?"div":"body"),s={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},a&&t.extend(s,{position:"absolute",left:"-1000px",top:"-1000px"});for(o in s)e.style[o]=s[o];e.appendChild(r),i=a||document.documentElement,i.insertBefore(e,i.firstChild),r.style.cssText="position: absolute; left: 10.7432222px;",n=t(r).offset().left,t.support.offsetFractions=n>10&&11>n,e.innerHTML="",i.removeChild(e)}()}(jQuery),function(t,e){t.widget("ui.progressbar",{version:"1.10.3",options:{max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min}),this.valueDiv=t("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element),this._refreshValue()},_destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove() },value:function(t){return t===e?this.options.value:(this.options.value=this._constrainedValue(t),this._refreshValue(),e)},_constrainedValue:function(t){return t===e&&(t=this.options.value),this.indeterminate=t===!1,"number"!=typeof t&&(t=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,t))},_setOptions:function(t){var e=t.value;delete t.value,this._super(t),this.options.value=this._constrainedValue(e),this._refreshValue()},_setOption:function(t,e){"max"===t&&(e=Math.max(this.min,e)),this._super(t,e)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var e=this.options.value,i=this._percentage();this.valueDiv.toggle(this.indeterminate||e>this.min).toggleClass("ui-corner-right",e===this.options.max).width(i.toFixed(0)+"%"),this.element.toggleClass("ui-progressbar-indeterminate",this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=t("<div class='ui-progressbar-overlay'></div>").appendTo(this.valueDiv))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":e}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==e&&(this.oldValue=e,this._trigger("change")),e===this.options.max&&this._trigger("complete")}})}(jQuery),function(t){var e=5;t.widget("ui.slider",t.ui.mouse,{version:"1.10.3",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"),this._refresh(),this._setOption("disabled",this.options.disabled),this._animateOff=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var e,i,s=this.options,n=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),o="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",a=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),e=n.length;i>e;e++)a.push(o);this.handles=n.add(t(a.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.each(function(e){t(this).data("ui-slider-handle-index",e)})},_createRange:function(){var e=this.options,i="";e.range?(e.range===!0&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:t.isArray(e.values)&&(e.values=e.values.slice(0)):e.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?this.range.removeClass("ui-slider-range-min ui-slider-range-max").css({left:"",bottom:""}):(this.range=t("<div></div>").appendTo(this.element),i="ui-slider-range ui-widget-header ui-corner-all"),this.range.addClass(i+("min"===e.range||"max"===e.range?" ui-slider-range-"+e.range:""))):this.range=t([])},_setupEvents:function(){var t=this.handles.add(this.range).filter("a");this._off(t),this._on(t,this._handleEvents),this._hoverable(t),this._focusable(t)},_destroy:function(){this.handles.remove(),this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(e){var i,s,n,o,a,r,h,l,c=this,u=this.options;return u.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:e.pageX,y:e.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var i=Math.abs(s-c.values(e));(n>i||n===i&&(e===c._lastChangedValue||c.values(e)===u.min))&&(n=i,o=t(this),a=e)}),r=this._start(e,a),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=a,o.addClass("ui-state-active").focus(),h=o.offset(),l=!t(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:e.pageX-h.left-o.width()/2,top:e.pageY-h.top-o.height()/2-(parseInt(o.css("borderTopWidth"),10)||0)-(parseInt(o.css("borderBottomWidth"),10)||0)+(parseInt(o.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,a,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,i),!1},_mouseStop:function(t){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,i,s,n,o;return"horizontal"===this.orientation?(e=this.elementSize.width,i=t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,i=t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/e,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),o=this._valueMin()+s*n,this._trimAlignValue(o)},_start:function(t,e){var i={handle:this.handles[e],value:this.value()};return this.options.values&&this.options.values.length&&(i.value=this.values(e),i.values=this.values()),this._trigger("start",t,i)},_slide:function(t,e,i){var s,n,o;this.options.values&&this.options.values.length?(s=this.values(e?0:1),2===this.options.values.length&&this.options.range===!0&&(0===e&&i>s||1===e&&s>i)&&(i=s),i!==this.values(e)&&(n=this.values(),n[e]=i,o=this._trigger("slide",t,{handle:this.handles[e],value:i,values:n}),s=this.values(e?0:1),o!==!1&&this.values(e,i,!0))):i!==this.value()&&(o=this._trigger("slide",t,{handle:this.handles[e],value:i}),o!==!1&&this.value(i))},_stop:function(t,e){var i={handle:this.handles[e],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(e),i.values=this.values()),this._trigger("stop",t,i)},_change:function(t,e){if(!this._keySliding&&!this._mouseSliding){var i={handle:this.handles[e],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(e),i.values=this.values()),this._lastChangedValue=e,this._trigger("change",t,i)}},value:function(t){return arguments.length?(this.options.value=this._trimAlignValue(t),this._refreshValue(),this._change(null,0),undefined):this._value()},values:function(e,i){var s,n,o;if(arguments.length>1)return this.options.values[e]=this._trimAlignValue(i),this._refreshValue(),this._change(null,e),undefined;if(!arguments.length)return this._values();if(!t.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(e):this.value();for(s=this.options.values,n=arguments[0],o=0;s.length>o;o+=1)s[o]=this._trimAlignValue(n[o]),this._change(null,o);this._refreshValue()},_setOption:function(e,i){var s,n=0;switch("range"===e&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.values=null):"max"===i&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),t.isArray(this.options.values)&&(n=this.options.values.length),t.Widget.prototype._setOption.apply(this,arguments),e){case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),s=0;n>s;s+=1)this._change(null,s);this._animateOff=!1;break;case"min":case"max":this._animateOff=!0,this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_value:function(){var t=this.options.value;return t=this._trimAlignValue(t)},_values:function(t){var e,i,s;if(arguments.length)return e=this.options.values[t],e=this._trimAlignValue(e);if(this.options.values&&this.options.values.length){for(i=this.options.values.slice(),s=0;i.length>s;s+=1)i[s]=this._trimAlignValue(i[s]);return i}return[]},_trimAlignValue:function(t){if(this._valueMin()>=t)return this._valueMin();if(t>=this._valueMax())return this._valueMax();var e=this.options.step>0?this.options.step:1,i=(t-this._valueMin())%e,s=t-i;return 2*Math.abs(i)>=e&&(s+=i>0?e:-e),parseFloat(s.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var e,i,s,n,o,a=this.options.range,r=this.options,h=this,l=this._animateOff?!1:r.animate,c={};this.options.values&&this.options.values.length?this.handles.each(function(s){i=100*((h.values(s)-h._valueMin())/(h._valueMax()-h._valueMin())),c["horizontal"===h.orientation?"left":"bottom"]=i+"%",t(this).stop(1,1)[l?"animate":"css"](c,r.animate),h.options.range===!0&&("horizontal"===h.orientation?(0===s&&h.range.stop(1,1)[l?"animate":"css"]({left:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({width:i-e+"%"},{queue:!1,duration:r.animate})):(0===s&&h.range.stop(1,1)[l?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({height:i-e+"%"},{queue:!1,duration:r.animate}))),e=i}):(s=this.value(),n=this._valueMin(),o=this._valueMax(),i=o!==n?100*((s-n)/(o-n)):0,c["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[l?"animate":"css"](c,r.animate),"min"===a&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:i+"%"},r.animate),"max"===a&&"horizontal"===this.orientation&&this.range[l?"animate":"css"]({width:100-i+"%"},{queue:!1,duration:r.animate}),"min"===a&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:i+"%"},r.animate),"max"===a&&"vertical"===this.orientation&&this.range[l?"animate":"css"]({height:100-i+"%"},{queue:!1,duration:r.animate}))},_handleEvents:{keydown:function(i){var s,n,o,a,r=t(i.target).data("ui-slider-handle-index");switch(i.keyCode){case t.ui.keyCode.HOME:case t.ui.keyCode.END:case t.ui.keyCode.PAGE_UP:case t.ui.keyCode.PAGE_DOWN:case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(i.preventDefault(),!this._keySliding&&(this._keySliding=!0,t(i.target).addClass("ui-state-active"),s=this._start(i,r),s===!1))return}switch(a=this.options.step,n=o=this.options.values&&this.options.values.length?this.values(r):this.value(),i.keyCode){case t.ui.keyCode.HOME:o=this._valueMin();break;case t.ui.keyCode.END:o=this._valueMax();break;case t.ui.keyCode.PAGE_UP:o=this._trimAlignValue(n+(this._valueMax()-this._valueMin())/e);break;case t.ui.keyCode.PAGE_DOWN:o=this._trimAlignValue(n-(this._valueMax()-this._valueMin())/e);break;case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:if(n===this._valueMax())return;o=this._trimAlignValue(n+a);break;case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(n===this._valueMin())return;o=this._trimAlignValue(n-a)}this._slide(i,r,o)},click:function(t){t.preventDefault()},keyup:function(e){var i=t(e.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(e,i),this._change(e,i),t(e.target).removeClass("ui-state-active"))}}})}(jQuery),function(t){function e(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t.widget("ui.spinner",{version:"1.10.3",defaultElement:"<input>",widgetEventPrefix:"spin",options:{culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var e={},i=this.element;return t.each(["min","max","step"],function(t,s){var n=i.attr(s);void 0!==n&&n.length&&(e[s]=n)}),e},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t),void 0)},mousewheel:function(t,e){if(e){if(!this.spinning&&!this._start(t))return!1;this._spin((e>0?1:-1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},"mousedown .ui-spinner-button":function(e){function i(){var t=this.element[0]===this.document[0].activeElement;t||(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===this.document[0].activeElement?this.previous:this.element.val(),e.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(e)!==!1&&this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(e){return t(e.currentTarget).hasClass("ui-state-active")?this._start(e)===!1?!1:(this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_draw:function(){var t=this.uiSpinner=this.element.addClass("ui-spinner-input").attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml());this.element.attr("role","spinbutton"),this.buttons=t.find(".ui-spinner-button").attr("tabIndex",-1).button().removeClass("ui-corner-all"),this.buttons.height()>Math.ceil(.5*t.height())&&t.height()>0&&t.height(t.height()),this.options.disabled&&this.disable()},_keydown:function(e){var i=this.options,s=t.ui.keyCode;switch(e.keyCode){case s.UP:return this._repeat(null,1,e),!0;case s.DOWN:return this._repeat(null,-1,e),!0;case s.PAGE_UP:return this._repeat(null,i.page,e),!0;case s.PAGE_DOWN:return this._repeat(null,-i.page,e),!0}return!1},_uiSpinnerHtml:function(){return"<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"},_buttonHtml:function(){return"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'><span class='ui-icon "+this.options.icons.up+"'>&#9650;</span>"+"</a>"+"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>"+"<span class='ui-icon "+this.options.icons.down+"'>&#9660;</span>"+"</a>"},_start:function(t){return this.spinning||this._trigger("start",t)!==!1?(this.counter||(this.counter=1),this.spinning=!0,!0):!1},_repeat:function(t,e,i){t=t||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,e,i)},t),this._spin(e*this.options.step,i)},_spin:function(t,e){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+t*this._increment(this.counter)),this.spinning&&this._trigger("spin",e,{value:i})===!1||(this._value(i),this.counter++)},_increment:function(e){var i=this.options.incremental;return i?t.isFunction(i)?i(e):Math.floor(e*e*e/5e4-e*e/500+17*e/200+1):1},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_adjustValue:function(t){var e,i,s=this.options;return e=null!==s.min?s.min:0,i=t-e,i=Math.round(i/s.step)*s.step,t=e+i,t=parseFloat(t.toFixed(this._precision())),null!==s.max&&t>s.max?s.max:null!==s.min&&s.min>t?s.min:t},_stop:function(t){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",t))},_setOption:function(t,e){if("culture"===t||"numberFormat"===t){var i=this._parse(this.element.val());return this.options[t]=e,this.element.val(this._format(i)),void 0}("max"===t||"min"===t||"step"===t)&&"string"==typeof e&&(e=this._parse(e)),"icons"===t&&(this.buttons.first().find(".ui-icon").removeClass(this.options.icons.up).addClass(e.up),this.buttons.last().find(".ui-icon").removeClass(this.options.icons.down).addClass(e.down)),this._super(t,e),"disabled"===t&&(e?(this.element.prop("disabled",!0),this.buttons.button("disable")):(this.element.prop("disabled",!1),this.buttons.button("enable")))},_setOptions:e(function(t){this._super(t),this._value(this.element.val())}),_parse:function(t){return"string"==typeof t&&""!==t&&(t=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(t,10,this.options.culture):+t),""===t||isNaN(t)?null:t},_format:function(t){return""===t?"":window.Globalize&&this.options.numberFormat?Globalize.format(t,this.options.numberFormat,this.options.culture):t},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},_value:function(t,e){var i;""!==t&&(i=this._parse(t),null!==i&&(e||(i=this._adjustValue(i)),t=this._format(i))),this.element.val(t),this._refresh()},_destroy:function(){this.element.removeClass("ui-spinner-input").prop("disabled",!1).removeAttr("autocomplete").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:e(function(t){this._stepUp(t)}),_stepUp:function(t){this._start()&&(this._spin((t||1)*this.options.step),this._stop())},stepDown:e(function(t){this._stepDown(t)}),_stepDown:function(t){this._start()&&(this._spin((t||1)*-this.options.step),this._stop())},pageUp:e(function(t){this._stepUp((t||1)*this.options.page)}),pageDown:e(function(t){this._stepDown((t||1)*this.options.page)}),value:function(t){return arguments.length?(e(this._value).call(this,t),void 0):this._parse(this.element.val())},widget:function(){return this.uiSpinner}})}(jQuery),function(t,e){function i(){return++n}function s(t){return t.hash.length>1&&decodeURIComponent(t.href.replace(o,""))===decodeURIComponent(location.href.replace(o,""))}var n=0,o=/#.*$/;t.widget("ui.tabs",{version:"1.10.3",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var e=this,i=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",i.collapsible).delegate(".ui-tabs-nav > li","mousedown"+this.eventNamespace,function(e){t(this).is(".ui-state-disabled")&&e.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){t(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this._processTabs(),i.active=this._initialActive(),t.isArray(i.disabled)&&(i.disabled=t.unique(i.disabled.concat(t.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(i.active):t(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var i=this.options.active,s=this.options.collapsible,n=location.hash.substring(1);return null===i&&(n&&this.tabs.each(function(s,o){return t(o).attr("aria-controls")===n?(i=s,!1):e}),null===i&&(i=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===i||-1===i)&&(i=this.tabs.length?0:!1)),i!==!1&&(i=this.tabs.index(this.tabs.eq(i)),-1===i&&(i=s?!1:0)),!s&&i===!1&&this.anchors.length&&(i=0),i},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):t()}},_tabKeydown:function(i){var s=t(this.document[0].activeElement).closest("li"),n=this.tabs.index(s),o=!0;if(!this._handlePageNav(i)){switch(i.keyCode){case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:n++;break;case t.ui.keyCode.UP:case t.ui.keyCode.LEFT:o=!1,n--;break;case t.ui.keyCode.END:n=this.anchors.length-1;break;case t.ui.keyCode.HOME:n=0;break;case t.ui.keyCode.SPACE:return i.preventDefault(),clearTimeout(this.activating),this._activate(n),e;case t.ui.keyCode.ENTER:return i.preventDefault(),clearTimeout(this.activating),this._activate(n===this.options.active?!1:n),e;default:return}i.preventDefault(),clearTimeout(this.activating),n=this._focusNextTab(n,o),i.ctrlKey||(s.attr("aria-selected","false"),this.tabs.eq(n).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",n)},this.delay))}},_panelKeydown:function(e){this._handlePageNav(e)||e.ctrlKey&&e.keyCode===t.ui.keyCode.UP&&(e.preventDefault(),this.active.focus())},_handlePageNav:function(i){return i.altKey&&i.keyCode===t.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):i.altKey&&i.keyCode===t.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):e},_findNextTab:function(e,i){function s(){return e>n&&(e=0),0>e&&(e=n),e}for(var n=this.tabs.length-1;-1!==t.inArray(s(),this.options.disabled);)e=i?e+1:e-1;return e},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).focus(),t},_setOption:function(t,i){return"active"===t?(this._activate(i),e):"disabled"===t?(this._setupDisabled(i),e):(this._super(t,i),"collapsible"===t&&(this.element.toggleClass("ui-tabs-collapsible",i),i||this.options.active!==!1||this._activate(0)),"event"===t&&this._setupEvents(i),"heightStyle"===t&&this._setupHeightStyle(i),e)},_tabId:function(t){return t.attr("aria-controls")||"ui-tabs-"+i()},_sanitizeSelector:function(t){return t?t.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var e=this.options,i=this.tablist.children(":has(a[href])");e.disabled=t.map(i.filter(".ui-state-disabled"),function(t){return i.index(t)}),this._processTabs(),e.active!==!1&&this.anchors.length?this.active.length&&!t.contains(this.tablist[0],this.active[0])?this.tabs.length===e.disabled.length?(e.active=!1,this.active=t()):this._activate(this._findNextTab(Math.max(0,e.active-1),!1)):e.active=this.tabs.index(this.active):(e.active=!1,this.active=t()),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var e=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return t("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=t(),this.anchors.each(function(i,n){var o,a,r,h=t(n).uniqueId().attr("id"),l=t(n).closest("li"),c=l.attr("aria-controls");s(n)?(o=n.hash,a=e.element.find(e._sanitizeSelector(o))):(r=e._tabId(l),o="#"+r,a=e.element.find(o),a.length||(a=e._createPanel(r),a.insertAfter(e.panels[i-1]||e.tablist)),a.attr("aria-live","polite")),a.length&&(e.panels=e.panels.add(a)),c&&l.data("ui-tabs-aria-controls",c),l.attr({"aria-controls":o.substring(1),"aria-labelledby":h}),a.attr("aria-labelledby",h)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.element.find("ol,ul").eq(0)},_createPanel:function(e){return t("<div>").attr("id",e).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(e){t.isArray(e)&&(e.length?e.length===this.anchors.length&&(e=!0):e=!1);for(var i,s=0;i=this.tabs[s];s++)e===!0||-1!==t.inArray(s,e)?t(i).addClass("ui-state-disabled").attr("aria-disabled","true"):t(i).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=e},_setupEvents:function(e){var i={click:function(t){t.preventDefault()}};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(e){var i,s=this.element.parent();"fill"===e?(i=s.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var e=t(this),s=e.css("position");"absolute"!==s&&"fixed"!==s&&(i-=e.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=t(this).outerHeight(!0)}),this.panels.each(function(){t(this).height(Math.max(0,i-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.panels.each(function(){i=Math.max(i,t(this).height("").height())}).height(i))},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget),o=n.closest("li"),a=o[0]===s[0],r=a&&i.collapsible,h=r?t():this._getPanelForTab(o),l=s.length?this._getPanelForTab(s):t(),c={oldTab:s,oldPanel:l,newTab:r?t():o,newPanel:h};e.preventDefault(),o.hasClass("ui-state-disabled")||o.hasClass("ui-tabs-loading")||this.running||a&&!i.collapsible||this._trigger("beforeActivate",e,c)===!1||(i.active=r?!1:this.tabs.index(o),this.active=a?t():o,this.xhr&&this.xhr.abort(),l.length||h.length||t.error("jQuery UI Tabs: Mismatching fragment identifier."),h.length&&this.load(this.tabs.index(o),e),this._toggle(e,c))},_toggle:function(e,i){function s(){o.running=!1,o._trigger("activate",e,i)}function n(){i.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),a.length&&o.options.show?o._show(a,o.options.show,s):(a.show(),s())}var o=this,a=i.newPanel,r=i.oldPanel;this.running=!0,r.length&&this.options.hide?this._hide(r,this.options.hide,function(){i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),n()}):(i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),r.hide(),n()),r.attr({"aria-expanded":"false","aria-hidden":"true"}),i.oldTab.attr("aria-selected","false"),a.length&&r.length?i.oldTab.attr("tabIndex",-1):a.length&&this.tabs.filter(function(){return 0===t(this).attr("tabIndex")}).attr("tabIndex",-1),a.attr({"aria-expanded":"true","aria-hidden":"false"}),i.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(e){var i,s=this._findActive(e);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return e===!1?t():this.tabs.eq(e)},_getIndex:function(t){return"string"==typeof t&&(t=this.anchors.index(this.anchors.filter("[href$='"+t+"']"))),t},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){t.data(this,"ui-tabs-destroy")?t(this).remove():t(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var e=t(this),i=e.data("ui-tabs-aria-controls");i?e.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):e.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(i){var s=this.options.disabled;s!==!1&&(i===e?s=!1:(i=this._getIndex(i),s=t.isArray(s)?t.map(s,function(t){return t!==i?t:null}):t.map(this.tabs,function(t,e){return e!==i?e:null})),this._setupDisabled(s))},disable:function(i){var s=this.options.disabled;if(s!==!0){if(i===e)s=!0;else{if(i=this._getIndex(i),-1!==t.inArray(i,s))return;s=t.isArray(s)?t.merge([i],s).sort():[i]}this._setupDisabled(s)}},load:function(e,i){e=this._getIndex(e);var n=this,o=this.tabs.eq(e),a=o.find(".ui-tabs-anchor"),r=this._getPanelForTab(o),h={tab:o,panel:r};s(a[0])||(this.xhr=t.ajax(this._ajaxSettings(a,i,h)),this.xhr&&"canceled"!==this.xhr.statusText&&(o.addClass("ui-tabs-loading"),r.attr("aria-busy","true"),this.xhr.success(function(t){setTimeout(function(){r.html(t),n._trigger("load",i,h)},1)}).complete(function(t,e){setTimeout(function(){"abort"===e&&n.panels.stop(!1,!0),o.removeClass("ui-tabs-loading"),r.removeAttr("aria-busy"),t===n.xhr&&delete n.xhr},1)})))},_ajaxSettings:function(e,i,s){var n=this;return{url:e.attr("href"),beforeSend:function(e,o){return n._trigger("beforeLoad",i,t.extend({jqXHR:e,ajaxSettings:o},s))}}},_getPanelForTab:function(e){var i=t(e).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+i))}})}(jQuery),function(t){function e(e,i){var s=(e.attr("aria-describedby")||"").split(/\s+/);s.push(i),e.data("ui-tooltip-id",i).attr("aria-describedby",t.trim(s.join(" ")))}function i(e){var i=e.data("ui-tooltip-id"),s=(e.attr("aria-describedby")||"").split(/\s+/),n=t.inArray(i,s);-1!==n&&s.splice(n,1),e.removeData("ui-tooltip-id"),s=t.trim(s.join(" ")),s?e.attr("aria-describedby",s):e.removeAttr("aria-describedby")}var s=0;t.widget("ui.tooltip",{version:"1.10.3",options:{content:function(){var e=t(this).attr("title")||"";return t("<a>").text(e).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,tooltipClass:null,track:!1,close:null,open:null},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.options.disabled&&this._disable()},_setOption:function(e,i){var s=this;return"disabled"===e?(this[i?"_disable":"_enable"](),this.options[e]=i,void 0):(this._super(e,i),"content"===e&&t.each(this.tooltips,function(t,e){s._updateContent(e)}),void 0)},_disable:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur");n.target=n.currentTarget=s[0],e.close(n,!0)}),this.element.find(this.options.items).addBack().each(function(){var e=t(this);e.is("[title]")&&e.data("ui-tooltip-title",e.attr("title")).attr("title","")})},_enable:function(){this.element.find(this.options.items).addBack().each(function(){var e=t(this);e.data("ui-tooltip-title")&&e.attr("title",e.data("ui-tooltip-title"))})},open:function(e){var i=this,s=t(e?e.target:this.element).closest(this.options.items);s.length&&!s.data("ui-tooltip-id")&&(s.attr("title")&&s.data("ui-tooltip-title",s.attr("title")),s.data("ui-tooltip-open",!0),e&&"mouseover"===e.type&&s.parents().each(function(){var e,s=t(this);s.data("ui-tooltip-open")&&(e=t.Event("blur"),e.target=e.currentTarget=this,i.close(e,!0)),s.attr("title")&&(s.uniqueId(),i.parents[this.id]={element:this,title:s.attr("title")},s.attr("title",""))}),this._updateContent(s,e))},_updateContent:function(t,e){var i,s=this.options.content,n=this,o=e?e.type:null;return"string"==typeof s?this._open(e,t,s):(i=s.call(t[0],function(i){t.data("ui-tooltip-open")&&n._delay(function(){e&&(e.type=o),this._open(e,t,i)})}),i&&this._open(e,t,i),void 0)},_open:function(i,s,n){function o(t){l.of=t,a.is(":hidden")||a.position(l)}var a,r,h,l=t.extend({},this.options.position); if(n){if(a=this._find(s),a.length)return a.find(".ui-tooltip-content").html(n),void 0;s.is("[title]")&&(i&&"mouseover"===i.type?s.attr("title",""):s.removeAttr("title")),a=this._tooltip(s),e(s,a.attr("id")),a.find(".ui-tooltip-content").html(n),this.options.track&&i&&/^mouse/.test(i.type)?(this._on(this.document,{mousemove:o}),o(i)):a.position(t.extend({of:s},this.options.position)),a.hide(),this._show(a,this.options.show),this.options.show&&this.options.show.delay&&(h=this.delayedShow=setInterval(function(){a.is(":visible")&&(o(l.of),clearInterval(h))},t.fx.interval)),this._trigger("open",i,{tooltip:a}),r={keyup:function(e){if(e.keyCode===t.ui.keyCode.ESCAPE){var i=t.Event(e);i.currentTarget=s[0],this.close(i,!0)}},remove:function(){this._removeTooltip(a)}},i&&"mouseover"!==i.type||(r.mouseleave="close"),i&&"focusin"!==i.type||(r.focusout="close"),this._on(!0,s,r)}},close:function(e){var s=this,n=t(e?e.currentTarget:this.element),o=this._find(n);this.closing||(clearInterval(this.delayedShow),n.data("ui-tooltip-title")&&n.attr("title",n.data("ui-tooltip-title")),i(n),o.stop(!0),this._hide(o,this.options.hide,function(){s._removeTooltip(t(this))}),n.removeData("ui-tooltip-open"),this._off(n,"mouseleave focusout keyup"),n[0]!==this.element[0]&&this._off(n,"remove"),this._off(this.document,"mousemove"),e&&"mouseleave"===e.type&&t.each(this.parents,function(e,i){t(i.element).attr("title",i.title),delete s.parents[e]}),this.closing=!0,this._trigger("close",e,{tooltip:o}),this.closing=!1)},_tooltip:function(e){var i="ui-tooltip-"+s++,n=t("<div>").attr({id:i,role:"tooltip"}).addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content "+(this.options.tooltipClass||""));return t("<div>").addClass("ui-tooltip-content").appendTo(n),n.appendTo(this.document[0].body),this.tooltips[i]=e,n},_find:function(e){var i=e.data("ui-tooltip-id");return i?t("#"+i):t()},_removeTooltip:function(t){t.remove(),delete this.tooltips[t.attr("id")]},_destroy:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur");n.target=n.currentTarget=s[0],e.close(n,!0),t("#"+i).remove(),s.data("ui-tooltip-title")&&(s.attr("title",s.data("ui-tooltip-title")),s.removeData("ui-tooltip-title"))})}})}(jQuery);
/** * Copyright 2019 Parity Technologies * * 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. */ const React = require("react"); const HomeSplash = require(`${process.cwd()}` + `/core/HomeSplash`); const Container = require("../../../../react-bootstrap/Container"); const Button = require("../../../../react-bootstrap/Button"); const Row = require("../../../../react-bootstrap/Row"); const Col = require("../../../../react-bootstrap/Col"); const Image = require("../../../../react-bootstrap/Image"); const Alert = require("../../../../react-bootstrap/Alert"); const translate = require("../../server/translate").translate; class Index extends React.Component { render() { const { config: siteConfig, language = "" } = this.props; const { baseUrl } = siteConfig; const langPart = language ? `${language}/` : ""; const pageUrl = (page) => `${baseUrl}${langPart}${page}`; const docUrl = (doc = "") => `${baseUrl}docs/${langPart}${doc}`; return ( <section> <div className="announcement"> <div className="announcement-text"> Meet others who speak your language! For devs at all levels - Sub0 Online, October 13-14, 2021. {` `} <a href="https://sub0.substrate.io/?utm_source=substrate.dev&utm_medium=referral&utm_campaign=sub0%202021&utm_content=registrations&utm_term=parity&ref=2bcd2286876e"> <span className="announcement-bottom">Register now</span> </a> </div> </div> <div className="announcement"> <div className="announcement-text"> <strong>A brand new DevHub is here!</strong> As of this Wednesday, Oct. 13th, the current Substrate docs on substrate.dev will be archived and all links will redirect to the new site. Preview it now at{" "} <a href="https://docs.substrate.io"> <span className="announcement-bottom">docs.substrate.io</span> </a> . </div> </div> <HomeSplash id="home-hero" siteConfig={siteConfig} language={language} title={<translate>Substrate Developer Hub</translate>} tagline={<translate>Blockchain Development for Innovators</translate>} description={ <translate> Substrate is a modular framework that enables you to create purpose-built blockchains by composing custom or pre-built components. </translate> } buttonText={<translate>Get Started</translate>} buttonUrl={docUrl()} /> <section className="mainContainer" id="home"> <Container> <section className="intro-statement home-section"> <span className="tagline"> <translate>Why Use Substrate?</translate> </span> <h2 className="large h1"> <translate>Focus on Your Strengths</translate> </h2> <p className="big"> <translate> Substrate's modular design means you can reuse battle-tested libraries while building the custom components that matter most. </translate> </p> </section> <section className="intro-blocks home-section"> <section className="intro-block"> <section className="icon-wrap"> <div className="icon runtime" /> </section> <h4> <translate>Runtime Development</translate> </h4> <p> <translate> Use Substrate's FRAME runtime system to build secure, scalable blockchain logic. </translate> </p> <section className="button-wrap"> <a href={docUrl("knowledgebase/runtime")} className="with-arrow"> <translate>Learn More</translate> </a> </section> </section> <section className="intro-block"> <section className="icon-wrap"> <div className="icon frontend" /> </section> <h4> <translate>Client Libraries</translate> </h4> <p> <translate> Create rich user experiences for any Substrate-based chain with Polkadot-JS. </translate> </p> <section className="button-wrap"> <a href={docUrl("knowledgebase/integrate/polkadot-js")} className="with-arrow"> <translate>Learn More</translate> </a> </section> </section> <section className="intro-block"> <section className="icon-wrap"> <div className="icon smart-contract" /> </section> <h4> <translate>Smart Contracts</translate> </h4> <p> <translate> Substrate supports multiple smart contract platforms, including the EVM. </translate> </p> <section className="button-wrap"> <a href="/tutorials/ink-smart-contracts-tutorial" className="with-arrow"> <translate>Learn More</translate> </a> </section> </section> </section> </Container> <section className="bg-white what-is-substrate"> <div className="container"> <div className="pt-5"> <div className="row justify-content-center text-center py-3"> <div className="col-12 col-md-8"> <span className="tagline"> <translate>What is Substrate?</translate> </span> <h2 className="display-4 h1"> <translate>Everything you need to build a blockchain.</translate> </h2> <p className="big"> <translate> Substrate is powered by best-in-class cryptographic research and comes with peer-to-peer networking, consensus mechanisms, and much more. </translate> </p> </div> </div> </div> <div className="row py-5 features"> <div className="col-12 col-md-4 mb-4"> <div className="d-flex align-items-center mb-2"> <img className="mr-2" src="/img/glyphs/rectangle-1.svg" width="40" /> <h3 className="mb-0"> <translate>Fast and Efficient Database</translate> </h3> </div> </div> <div className="col-12 col-md-4 mb-4"> <div className="d-flex align-items-center mb-2"> <img className="mr-2" src="/img/glyphs/rectangle-2.svg" width="40" /> <h3 className="mb-0"> <translate>Modular P2P Networking Stack</translate> </h3> </div> </div> <div className="col-12 col-md-4"> <div className="d-flex align-items-center mb-2"> <img className="mr-2" src="/img/glyphs/rectangle-3.svg" width="40" /> <h3 className="mb-0"> <translate>Hot-Swappable Consensus Layer</translate> </h3> </div> </div> <div className="col-12 col-md-4 mb-4"> <div className="d-flex align-items-center mb-2"> <img className="mr-2" src="/img/glyphs/rectangle-4.svg" width="40" /> <h3 className="mb-0"> <translate>Configurable Transaction Queue</translate> </h3> </div> </div> <div className="col-12 col-md-4 mb-4"> <div className="d-flex align-items-center mb-2"> <img className="mr-2" src="/img/glyphs/rectangle-5.svg" width="40" /> <h3 className="mb-0"> <translate>Flexible Runtime Library</translate> </h3> </div> </div> <div className="col-12 col-md-4"> <div className="d-flex align-items-center mb-2"> <img className="mr-2" src="/img/glyphs/rectangle-6.svg" width="40" /> <h3 className="mb-0"> <translate>Light Client Optimized</translate> </h3> </div> </div> </div> </div> </section> <section className="bg-light call-outs second"> <div className="container"> <div className="row justify-content-between align-items-center py-5 polkadot-row"> <div className="col-12 col-md-6 pl-md-0 mb-4 mb-md-0 text-center polkadot-graphic-wrap"> <img src="/img/pictures/polkadot-network.svg" className="polkadot-image" /> <div className="polkadot-graphic" style={{ backgroundImage: `url(/img/pictures/polkadot-network.svg)` }} /> </div> <div className="col-12 col-md-5"> <h2 className="h1"> <translate>Production Ready</translate> </h2> <p className="large mb-4"> <translate> Substrate is the backbone that powers Polkadot, a next generation, heterogeneous, multi-chain network. Most of the blockchains in the Polkadot ecosystem are also built on Substrate. The Polkadot Network was launched in May of 2020. </translate> </p> <a className="action-link" href="https://polkadot.network/technology/"> <span> <translate>Learn more about Polkadot</translate> </span> </a> </div> </div> </div> </section> <section className="bg-light call-outs first"> <div className="container"> <div className="row justify-content-between align-items-center py-5"> <div className="col-12 col-md-5 order-2 order-md-1"> <h2 className="h1"> <translate>Smart Contract Ready</translate> </h2> <p className="large mb-4"> <translate> Substrate has a Wasm smart contract platform that you can use out of the box. Because Substrate uses Wasm, you can build your smart contracts using any compatible language. We have built ink!, a Rust-based eDSL, for this purpose. </translate> </p> <a className="action-link" href={docUrl("knowledgebase/smart-contracts/")}> <span> <translate>Learn more about ink!</translate> </span> </a> </div> <div className="col-12 col-md-6 order-1 order-md-2 pl-md-0 mb-4 mb-md-0 text-center"> <img className="w-25" src="/img/pictures/substrate-wasm.svg" /> </div> </div> </div> </section> <section className="bg-white learn"> <div className="container"> <div className="row justify-content-center text-center pt-5"> <div className="col-12 col-md-10"> <span className="tagline"> <translate>Keep Exploring!</translate> </span> <h2 className="display-4 h1"> <translate>There are lots of ways to learn about Substrate.</translate> </h2> </div> </div> </div> </section> <section className="bg-white learn-blocks"> <div className="container"> <div className="row text-center flex-md-nowrap py-md-5"> <div className="col-12 col-md-6"> <div className="row justify-content-center"> <div className="col-12 col-lg-8"> <div className="py-5 py-md-0"> <h2> <translate>Substrate Seminar</translate> </h2> <p className="mb-3"> <translate> An open, collaborative group for learning about Substrate and connecting with other builders. </translate> </p> <a className="btn primary-color" href={pageUrl("seminar")}> <translate>Join the Seminar</translate> </a> </div> <div className="border-bottom d-md-none" /> </div> </div> </div> <div className="border-right d-none d-md-block" /> <div className="col-12 col-md-6"> <div className="row justify-content-center"> <div className="col-12 col-lg-8"> <div className="py-5 py-md-0"> <h2> <translate>Substrate Recipes</translate> </h2> <p className="mb-3"> <translate> A collection of working code examples that solve common problems. </translate> </p> <a className="btn primary-color" href="https://substrate.dev/recipes"> <translate>Browse the Recipes</translate> </a> </div> </div> </div> </div> </div> </div> </section> <section className="bg-light bottom-cta"> <div className="container"> <div className="py-5"> <div className="row justify-content-center text-center py-3"> <div className="col-12 col-md-10"> <h2 className="display-4 h1"> <translate>Ready to build with Substrate?</translate> </h2> </div> <div className="col-12 col-md-8"> <p className="lead mb-4"> <translate> Get started with our helpful documentation or ask questions in our technical chat! </translate> </p> <div className="d-flex justify-content-center"> <div className="px-1"> <a className="btn btn-lg primary-color" href={docUrl()}> <translate>Get Started</translate> </a> </div> <div className="px-1"> <a className="btn btn-lg btn-outline-primary" href="https://app.element.io/#/room/!HzySYSaIhtyWrwiwEV:matrix.org" > <translate>Ask Questions</translate> </a> </div> </div> </div> </div> </div> </div> </section> </section> </section> ); } } Index.title = "Official Substrate Documentation for Blockchain Developers"; Index.description = "Learn to build blockchains using the next generation blockchain framework."; module.exports = Index;
'use strict'; System.register([], function (_export, _context) { "use strict"; var _createClass, HttpService; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } return { setters: [], execute: function () { _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); _export('HttpService', HttpService = function () { function HttpService() { _classCallCheck(this, HttpService); } _createClass(HttpService, [{ key: '_handleErrors', value: function _handleErrors(res) { if (!res.ok) throw new Error(res.statusText); return res; } }, { key: 'get', value: function get(url) { var _this = this; return fetch(url).then(function (res) { return _this._handleErrors(res); }).then(function (res) { return res.json(); }); // return new Promise((resolve, reject) => { // let xhr = new XMLHttpRequest(); // xhr.open('GET', url); // xhr.onreadystatechange = () => { // if (xhr.readyState == 4) { // if (xhr.status == 200) { // resolve(JSON.parse(xhr.responseText)); // } else { // console.log(xhr.responseText); // reject(xhr.responseText); // } // } // } // xhr.send(); // }); } }, { key: 'post', value: function post(url, dado) { var _this2 = this; return fetch(url, { headers: { 'Content-Type': 'application/json' }, method: 'post', body: JSON.stringify(dado) }).then(function (res) { return _this2._handleErrors(res); }); // return new Promise((resolve, reject) => { // let xhr = new XMLHttpRequest(); // xhr.open("POST", url, true); // xhr.setRequestHeader("Content-type", "application/json"); // xhr.onreadystatechange = () => { // if (xhr.readyState == 4) { // if (xhr.status == 200) { // resolve(JSON.parse(xhr.responseText)); // } else { // reject(xhr.responseText); // } // } // }; // xhr.send(JSON.stringify(dado)); // }); } }]); return HttpService; }()); _export('HttpService', HttpService); } }; }); //# sourceMappingURL=HttpService.js.map
import Vue from 'vue' import Vuex from 'vuex' import app from './modules/app' import user from './modules/user' Vue.use(Vuex) export default new Vuex.Store({ state: {}, mutations: {}, actions: {}, modules: { app, user } })
/** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Convert each element in a single-precision floating-point strided array `x` from degrees to radians according to a strided mask array and assign the results to elements in a single-precision floating-point strided array `y`. * * @module @stdlib/math-strided-special-smskdeg2rad * * @example * var Float32Array = require( '@stdlib/array-float32' ); * var Uint8Array = require( '@stdlib/array-uint8' ); * var smskdeg2rad = require( '@stdlib/math-strided-special-smskdeg2rad' ); * * var x = new Float32Array( [ 0.0, 30.0, 45.0, 60.0, 90.0 ] ); * var m = new Uint8Array( [ 0, 0, 1, 0, 1 ] ); * var y = new Float32Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] ); * * smskdeg2rad( x.length, x, 1, m, 1, y, 1 ); * // y => <Float32Array>[ 0.0, ~0.524, 0.0, ~1.047, 0.0 ] * * @example * var Float32Array = require( '@stdlib/array-float32' ); * var Uint8Array = require( '@stdlib/array-uint8' ); * var smskdeg2rad = require( '@stdlib/math-strided-special-smskdeg2rad' ); * * var x = new Float32Array( [ 0.0, 30.0, 45.0, 60.0, 90.0 ] ); * var m = new Uint8Array( [ 0, 0, 1, 0, 1 ] ); * var y = new Float32Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] ); * * smskdeg2rad.ndarray( x.length, x, 1, 0, m, 1, 0, y, 1, 0 ); * // y => <Float32Array>[ 0.0, ~0.524, 0.0, ~1.047, 0.0 ] */ // MODULES // var join = require( 'path' ).join; var tryRequire = require( '@stdlib/utils-try-require' ); var main = require( './main.js' ); // MAIN // var tmp = tryRequire( join( __dirname, './native.js' ) ); if ( !(tmp instanceof Error) ) { main = tmp; } // EXPORTS // module.exports = main;
// JavaScript 中对变量类型的判断 var num = 123; var str = 'abcdef'; var bool = true; var arr = [1, 2, 3, 4]; var json = { name: 'wenzi', age: 25 }; var func = function() { console.log('this is function'); }; var und = undefined; var nul = null; var date = new Date(); var reg = /^[a-zA-Z]{5,20}$/; var error = new Error(); // 1. 使用typeof检测 console.log( typeof num, // number typeof str, // string typeof bool, // boolean typeof arr, // object typeof json, // object typeof func, // function typeof und, // undefined typeof nul, // object typeof date, // object typeof reg, // object typeof error // object ); // 从输出的结果来看,arr, json, nul, date, reg, error 全部被检测为object类型,其他的变量能够被正确检测出来。 // 当需要变量是否是number, string, boolean, function, undefined, json类型时,可以使用typeof进行判断。 // 其他变量是判断不出类型的,包括null。 // 还有,typeof是区分不出array和json类型的。因为使用typeof这个变量时,array和json类型输出的都是object。 // 2. 使用instance检测 // 在 JavaScript 中,判断一个变量的类型尝尝会用 typeof 运算符, // 在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 “object”。 // ECMAScript 引入了另一个 Java 运算符 instanceof 来解决这个问题。 // instanceof 运算符与 typeof 运算符相似,用于识别正在处理的对象的类型。 // 与 typeof 方法不同的是,instanceof 方法要求开发者明确地确认对象为某特定类型。例如: function Person() {} var Tom = new Person(); console.log(Tom instanceof Person); // true function Student() {} Student.prototype = new Person(); var John = new Student(); console.log(John instanceof Student); // true console.log(John instanceof Person); // true // instanceof还能检测出多层继承的关系。 console.log( num instanceof Number, // false str instanceof String, // false bool instanceof Boolean, // false arr instanceof Array, // true json instanceof Object, // true func instanceof Function, // true und instanceof Object, // false nul instanceof Object, // false date instanceof Date, // true reg instanceof RegExp, // true error instanceof Error // true ); // 从上面的运行结果我们可以看到,num, str和bool没有检测出他的类型,但是我们使用下面的方式创建num,是可以检测出类型的: var num1 = new Number(123); var str1 = new String('abcdef'); var bool1 = new Boolean(true); console.log( num1 instanceof Number, // true str1 instanceof String, // true bool1 instanceof Boolean // true ); // 同时,我们也要看到,und和nul是检测的Object类型,才输出的true, // 因为js中没有Undefined和Null的这种全局类型,他们und和nul都属于Object类型,因此输出了true。 // 3. 使用constructor检测 // 在使用instanceof检测变量类型时,我们是检测不到number, 'string', bool的类型的。因此,我们需要换一种方式来解决这个问题。 // constructor本来是原型对象上的属性,指向构造函数。 // 但是根据实例对象寻找属性的顺序,若实例对象上没有实例属性或方法时,就去原型链上寻找,因此,实例对象也是能使用constructor属性的。 console.log( Tom.constructor == Person, // true num.constructor == Number, // true str.constructor == String, // true bool.constructor == Boolean, // true arr.constructor == Array, // true json.constructor == Object, // true func.constructor == Function, // true date.constructor == Date, // true reg.constructor == RegExp, // true error.constructor == Error // true ); // 从输出的结果我们可以看出,除了undefined和null,其他类型的变量均能使用constructor判断出类型。 // 不过使用constructor也不是保险的,因为constructor属性是可以被修改的,会导致检测出的结果不正确,例如: console.log(John.constructor == Student); // false console.log(John.constructor == Person); // true // Student原型中的constructor被修改为指向到Person,导致检测不出实例对象John真实的构造函数。 // 同时,使用instaceof和construcor,被判断的array必须是在当前页面声明的! // 比如,一个页面(父页面)有一个框架,框架中引用了一个页面(子页面),在子页面中声明了一个array,并将其赋值给父页面的一个变量, // 这时判断该变量,Array == object.constructor;会返回false; // 原因: // 1、array属于引用型数据,在传递过程中,仅仅是引用地址的传递。 // 2、每个页面的Array原生对象所引用的地址是不一样的,在子页面声明的array,所对应的构造函数,是子页面的Array对象; // 父页面来进行判断,使用的Array并不等于子页面的Array;切记,不然很难跟踪问题! // 4. 使用Object.prototype.toString.call console.log( Object.prototype.toString.call(num), // [object Number] Object.prototype.toString.call(str), // [object String] Object.prototype.toString.call(bool), // [object Boolean] Object.prototype.toString.call(arr), // [object Array] Object.prototype.toString.call(json), // [object Object] Object.prototype.toString.call(func), // [object Function] Object.prototype.toString.call(und), // [object Undefined] Object.prototype.toString.call(nul), // [object Null] Object.prototype.toString.call(date), // [object Date] Object.prototype.toString.call(reg), // [object RegExp] Object.prototype.toString.call(error) // [object Error] ); // 从输出的结果来看,Object.prototype.toString.call(变量)输出的是一个字符串, // 字符串里有一个数组,第一个参数是Object,第二个参数就是这个变量的类型,而且, // 所有变量的类型都检测出来了,我们只需要取出第二个参数即可。 // 或者可以使用Object.prototype.toString.call(arr)=="object Array"来检测变量arr是不是数组。 // 5. jquery中$.type的实现 // 在jquery中提供了一个$.type的接口,来让我们检测变量的类型: // var $ = require('jquery').$; // console.log( // $.type(num), // $.type(str), // $.type(bool), // $.type(arr), // $.type(json), // $.type(func), // $.type(und), // $.type(nul), // $.type(date), // $.type(reg), // $.type(error) // ); // 看到输出结果,有没有一种熟悉的感觉?对,他就是上面使用Object.prototype.toString.call(变量)输出的结果的第二个参数呀。 // javascript中4种类型识别的方法 // 【1】typeof //   【输出】首字母小写的字符串形式 //   【功能】 //     [a]可以识别标准类型(将Null识别为object) //     [b]不能识别具体的对象类型(Function除外) //   【实例】 (function() { console.log("\n---typeof"); console.log(typeof "jerry"); //"string" console.log(typeof 12); //"number" console.log(typeof true); //"boolean" console.log(typeof undefined); //"undefined" console.log(typeof null); //"object" console.log(typeof { name: "jerry" }); //"object" console.log(typeof function() {}); //"function" console.log(typeof []); //"object" console.log(typeof new Date()); //"object" console.log(typeof /\d/); //"object" function Person() {} console.log(typeof new Person()); //"object" })(); // 【2】Object.prototype.toString //   【输出】[object 数据类型]的字符串形式 //   【功能】 //     [a]可以识别标准类型及内置对象类型 //     [b]不能识别自定义类型 //   【构造方法】 function type(obj) {   return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); } //   【实例1】 (function() { console.log("\n---Object.prototype.toString"); console.log(Object.prototype.toString.call("jerry")); //[object String] console.log(Object.prototype.toString.call(12)); //[object Number] console.log(Object.prototype.toString.call(true)); //[object Boolean] console.log(Object.prototype.toString.call(undefined)); //[object Undefined] console.log(Object.prototype.toString.call(null)); //[object Null] console.log(Object.prototype.toString.call({ name: "jerry" })); //[object Object] console.log(Object.prototype.toString.call(function() {})); //[object Function] console.log(Object.prototype.toString.call([])); //[object Array] console.log(Object.prototype.toString.call(new Date())); //[object Date] console.log(Object.prototype.toString.call(/\d/)); //[object RegExp] function Person() {} console.log(Object.prototype.toString.call(new Person())); //[object Object] })(); //   【实例2】 (function() { console.log("\n---Object.prototype.toString type(obj)"); function type(obj) { return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); } console.log(type("jerry")); //"string" console.log(type(12)); //"number" console.log(type(true)); //"boolean" console.log(type(undefined)); //"undefined" console.log(type(null)); //"null" console.log(type({ name: "jerry" })); //"object" console.log(type(function() {})); //"function" console.log(type([])); //"array" console.log(type(new Date())); //"date" console.log(type(/\d/)); //"regexp" function Person() {} console.log(type(new Person())); //"object" })(); // 【3】constructor //   【输出】function 数据类型(){[native code]}或者function 自定义类型(){} //   【功能】 //     [a]可以识别标准类型、内置对象类型及自定义类型 //     [b]不能识别undefined、null,会报错 //   【构造方法】 function type(obj) { var temp = obj.constructor.toString(); return temp.replace(/^function (\w+)\(\).+$/, '$1'); } //   【实例1】 (function() { console.log("\n---constructor"); console.log(("jerry").constructor); //function String(){[native code]} console.log((12).constructor); //function Number(){[native code]} console.log((true).constructor); //function Boolean(){[native code]} //console.log((undefined).constructor);//报错 //console.log((null).constructor);//报错 console.log(({ name: "jerry" }).constructor); //function Object(){[native code]} console.log((function() {}).constructor); //function Function(){[native code]} console.log(([]).constructor); //function Array(){[native code]} console.log((new Date()).constructor); //function Date(){[native code]} console.log((/\d/).constructor); //function RegExp(){[native code]} function Person() {} console.log((new Person()).constructor); //function Person(){} })(); //   【实例2】 (function() { console.log("\n---constructor type(obj)"); function type(obj) { var temp = obj.constructor.toString().toLowerCase(); return temp.replace(/^function (\w+)\(\).+$/, '$1'); } console.log(type("jerry")); //"string" console.log(type(12)); //"number" console.log(type(true)); //"boolean" //console.log(type(undefined));//错误 //console.log(type(null));//错误 console.log(type({ name: "jerry" })); //"object" console.log(type(function() {})); //"function" console.log(type([])); //"array" console.log(type(new Date())); //"date" console.log(type(/\d/)); //"regexp" function Person() {} console.log(type(new Person())); //"person" })(); // 【4】instanceof //   【输出】true或false //   【功能】 //     [a]可以识别内置对象类型、自定义类型及其父类型 //     [b]不能识别标准类型,会返回false //     [c]不能识别undefined、null,会报错 // //   【实例】 (function() { console.log("\n---instanceof"); console.log("jerry" instanceof String); //false console.log(12 instanceof Number); //false console.log(true instanceof Boolean); //false //console.log(undefined instanceof Undefined);//报错 //console.log(null instanceof Null);//报错 console.log({ name: "jerry" } instanceof Object); //true console.log(function() {} instanceof Function); //true console.log([] instanceof Array); //true console.log(new Date() instanceof Date); //true console.log(/\d/ instanceof RegExp); //true function Person() {} console.log(new Person() instanceof Person); //true console.log(new Person() instanceof Object); //true })();
import React from 'react' import { Text, View, Linking, Image, TouchableOpacity } from 'react-native' import { useNavigation, useRoute } from '@react-navigation/native' import { Feather} from '@expo/vector-icons' import * as MailComposer from 'expo-mail-composer' import logoimg from '../../assets/logo.png' import styles from './styles' export default function Details() { const navigation = useNavigation() const route = useRoute() const incident = route.params.incident const message = `Olá ${incident.name}, estou entrando em contato, pois gostaria de ajudar no caso "${incident.title}", com o valor de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(incident.value)}` function navigateBack() { navigation.goBack() } function sendMail(){ MailComposer.composeAsync({ subject:` Herói do caso: ${incident.title}`, recipients: [incident.email], body: message, }) } function sendWhatsapp(){ Linking.openURL(`whatsapp://send?phone=+55${incident.whatsapp}&text=${message}`) } return ( <View style={styles.container}> <View style={styles.header}> <Image source={logoimg} /> <TouchableOpacity style={styles.detailsButton} onPress={navigateBack} > <Feather name="arrow-left" size={16} color="#e02041"></Feather> </TouchableOpacity> </View> <View style={styles.incident}> <Text style={[styles.incidentProperty, {marginTop:0 }]}>ONG:</Text> <Text style={styles.incidentValue}>{incident.name} de {incident.city}/{incident.uf}</Text> <Text style={styles.incidentProperty}>Caso:</Text> <Text style={styles.incidentValue}>{incident.title}</Text> <Text style={styles.incidentProperty}>Valor:</Text> <Text style={styles.incidentValue}>{Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(incident.value)}</Text> </View> <View style={styles.contactBox}> <Text style={styles.heroTitle}>Salve o dia</Text> <Text style={styles.heroTitle}>Seja o herói desse caso.</Text> <Text style={styles.heroDescription}>Entre em contato:</Text> <View style={styles.actions}> <TouchableOpacity style={styles.action} onPress={sendWhatsapp} > <Text style={styles.actionText}>WhatsApp</Text></TouchableOpacity> <TouchableOpacity style={styles.action} onPress={sendMail} > <Text style={styles.actionText}>Email</Text></TouchableOpacity> </View> </View> </View> ) }
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); /* tslint:disable */ var path = require("path"); var util_1 = require("../util"); var index_1 = require("../Output/index"); var Plugins_1 = require("../Plugin/Plugins"); var CommandManagerBase = /** @class */ (function () { function CommandManagerBase(config) { this.config = config; } CommandManagerBase.prototype.findCommand = function (id) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, null]; }); }); }; CommandManagerBase.prototype.listTopics = function (prefix) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, []]; }); }); }; CommandManagerBase.prototype.findTopic = function (id) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, null]; }); }); }; CommandManagerBase.prototype.require = function (p) { return util_1.undefault(require(p)); }; return CommandManagerBase; }()); exports.CommandManagerBase = CommandManagerBase; var BuiltinCommandManager = /** @class */ (function (_super) { __extends(BuiltinCommandManager, _super); function BuiltinCommandManager() { return _super !== null && _super.apply(this, arguments) || this; } BuiltinCommandManager.prototype.findCommand = function (id) { return __awaiter(this, void 0, void 0, function () { var builtins, p; return __generator(this, function (_a) { builtins = { version: 'version', help: 'help', }; p = builtins[id]; if (p) { p = path.join(__dirname, 'commands', p); return [2 /*return*/, this.require(p)]; } return [2 /*return*/]; }); }); }; BuiltinCommandManager.prototype.listTopics = function (prefix) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, ['version', 'help']]; }); }); }; return BuiltinCommandManager; }(CommandManagerBase)); exports.BuiltinCommandManager = BuiltinCommandManager; var CLICommandManager = /** @class */ (function (_super) { __extends(CLICommandManager, _super); function CLICommandManager() { return _super !== null && _super.apply(this, arguments) || this; } CLICommandManager.prototype.findCommand = function (id) { return __awaiter(this, void 0, void 0, function () { var root, p; return __generator(this, function (_a) { root = this.config.commandsDir; if (!root) return [2 /*return*/]; try { p = require.resolve(path.join.apply(path, [root].concat(id.split(':')))); } catch (err) { if (err.code !== 'MODULE_NOT_FOUND') throw err; } if (p) return [2 /*return*/, this.require(p)]; return [2 /*return*/]; }); }); }; return CLICommandManager; }(CommandManagerBase)); exports.CLICommandManager = CLICommandManager; // TODO look into this later: https://sourcegraph.com/github.com/heroku/cli-engine/-/blob/src/plugins/index.js#L9:33 // not needed right now // var PluginCommandManager = /** @class */ (function (_super) { __extends(PluginCommandManager, _super); function PluginCommandManager() { return _super !== null && _super.apply(this, arguments) || this; } PluginCommandManager.prototype.findCommand = function (id) { return __awaiter(this, void 0, void 0, function () { var out, plugins, foundCommand; return __generator(this, function (_a) { switch (_a.label) { case 0: out = new index_1.Output(this.config); plugins = new Plugins_1.default(out); return [4 /*yield*/, plugins.load()]; case 1: _a.sent(); foundCommand = plugins.findCommand(id || this.config.defaultCommand || 'help'); return [2 /*return*/, foundCommand]; } }); }); }; PluginCommandManager.prototype.findTopic = function (id) { return __awaiter(this, void 0, void 0, function () { var out, plugins; return __generator(this, function (_a) { switch (_a.label) { case 0: out = new index_1.Output(this.config); plugins = new Plugins_1.default(out); return [4 /*yield*/, plugins.load()]; case 1: _a.sent(); return [2 /*return*/, plugins.findTopic(id)]; } }); }); }; return PluginCommandManager; }(CommandManagerBase)); var Dispatcher = /** @class */ (function () { function Dispatcher(config) { this.config = config; this.managers = [ new CLICommandManager(config), new BuiltinCommandManager(config), new PluginCommandManager(config), ]; } Dispatcher.prototype.findCommand = function (id) { return __awaiter(this, void 0, void 0, function () { var _i, _a, manager, Command; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!id) return [2 /*return*/, {}]; _i = 0, _a = this.managers; _b.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/, 4]; manager = _a[_i]; return [4 /*yield*/, manager.findCommand(id)]; case 2: Command = _b.sent(); if (Command) return [2 /*return*/, { Command: Command }]; _b.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: return [2 /*return*/, {}]; } }); }); }; Dispatcher.prototype.findTopic = function (id) { return __awaiter(this, void 0, void 0, function () { var _i, _a, manager, topic; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!id) return [2 /*return*/, {} // TODO: Fix this hack for "cluster". // Find why cache does not invalidate for cluster command ]; // TODO: Fix this hack for "cluster". // Find why cache does not invalidate for cluster command if (id.trim() === 'cluster') return [2 /*return*/, null]; _i = 0, _a = this.managers; _b.label = 1; case 1: if (!(_i < _a.length)) return [3 /*break*/, 4]; manager = _a[_i]; return [4 /*yield*/, manager.findTopic(id)]; case 2: topic = _b.sent(); if (topic) return [2 /*return*/, topic]; _b.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: return [2 /*return*/, null]; } }); }); }; Dispatcher.prototype.listTopics = function (prefix) { return __awaiter(this, void 0, void 0, function () { var arrs; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, Promise.all(this.managers.map(function (m) { return m.listTopics(prefix); }))]; case 1: arrs = _a.sent(); return [2 /*return*/, arrs.reduce(function (next, res) { return res.concat(next); }, [])]; } }); }); }; Object.defineProperty(Dispatcher.prototype, "cmdAskingForHelp", { get: function () { for (var _i = 0, _a = this.config.argv; _i < _a.length; _i++) { var arg = _a[_i]; if (['--help', '-h'].includes(arg)) return true; if (arg === '--') return false; } return false; }, enumerable: true, configurable: true }); return Dispatcher; }()); exports.Dispatcher = Dispatcher; //# sourceMappingURL=Dispatcher.js.map
import '../Css/FormReportListItem.css'; import {useNavigate} from 'react-router-dom'; const FormReportListItem = (props) => { const navigate = useNavigate(); const reportHandler = () => { navigate(props.formCode); } return( <div className="ItemContainer"> <div className="ReportInfoContainer"> <h1 className="FormName">{props.name}</h1> <h1 className="ExpiryDate">Expiring: {props.expiring}</h1> </div> <button className="ReportButton" onClick={reportHandler}>Report</button> </div> ) } export default FormReportListItem;
const webpack = require('webpack') module.exports = { webpack: function (cfg) { cfg.plugins.push(new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify(process.env.NODE_ENV) } })) return cfg } }
export const timer16F = "M10 1H6V0h4zm3.998 4.405a7.018 7.018 0 1 1-2.403-2.403l1.884-1.884 2.403 2.403zM3 9H2v1h1zm5 5H7v1h1zm3-5H8V5H7v5h4z";
/* * * LoginPage reducer * */ import { fromJS } from 'immutable'; import { SET_ERROR } from './constants'; const initialState = fromJS({ error: '', loading: false, }); function loginPageReducer(state = initialState, action) { switch (action.type) { case SET_ERROR: return state.set('error', action.error); default: return state; } } export default loginPageReducer;
!function(e){const i=e.it=e.it||{};i.dictionary=Object.assign(i.dictionary||{},{"%0 of %1":"%0 di %1","Align center":"Allinea al centro","Align left":"Allinea a sinistra","Align right":"Allinea a destra",Aquamarine:"Aquamarina",Big:"Grandi",Black:"Nero","Block quote":"Blocco citazione",Blue:"Blu",Bold:"Grassetto","Break text":"Interrompi testo","Bulleted List":"Elenco puntato","Bulleted list styles toolbar":"Barra degli strumenti con gli stili degli elenchi puntati",Cancel:"Annulla","Cannot upload file:":"Impossibile caricare il file:","Centered image":"Immagine centrata","Change image text alternative":"Cambia testo alternativo dell'immagine","Choose heading":"Seleziona intestazione",Circle:"Cerchio",Column:"Colonna","Could not insert image at the current position.":"Non è stato possibile inserire l'immagine nella posizione corrente.","Could not obtain resized image URL.":"Non è stato possibile ottenere l'URL dell'immagine ridimensionata.",Decimal:"Numero","Decimal with leading zero":"Numero con zero anteposto","Decrease indent":"Riduci rientro",Default:"Predefinito","Delete column":"Elimina colonna","Delete row":"Elimina riga","Dim grey":"Grigio tenue",Disc:"Disco","Document colors":"Colori del docmento",Downloadable:"Scaricabile","Dropdown toolbar":"Barra degli strumenti del menu a discesa","Edit block":"Modifica blocco","Edit link":"Modifica collegamento","Editor toolbar":"Barra degli strumenti dell'editor","Enter image caption":"inserire didascalia dell'immagine","Font Background Color":"Colore di sfondo caratteri","Font Color":"Colore caratteri","Font Family":"Tipo di caratteri","Font Size":"Dimensione caratteri","Full size image":"Immagine a dimensione intera",Green:"Verde",Grey:"Grigio","Header column":"Intestazione colonna","Header row":"Riga d'intestazione",Heading:"Intestazione","Heading 1":"Intestazione 1","Heading 2":"Intestazione 2","Heading 3":"Intestazione 3","Heading 4":"Intestazione 4","Heading 5":"Intestazione 5","Heading 6":"Intestazione 6",Huge:"Grandissimi","Image resize list":"Elenco ridimensionamenti immagine","Image toolbar":"Barra degli strumenti dell'immagine","image widget":"Widget immagine","In line":"In linea","Increase indent":"Aumenta rientro","Insert column left":"Inserisci colonna a sinistra","Insert column right":"Inserisci colonna a destra","Insert image":"Inserisci immagine","Insert image or file":"Inserisci immagine o file","Insert media":"Inserisci media","Insert paragraph after block":"Inserisci paragrafo dopo blocco","Insert paragraph before block":"Inserisci paragrafo prima di blocco","Insert row above":"Inserisci riga sopra","Insert row below":"Inserisci riga sotto","Insert table":"Inserisci tabella","Inserting image failed":"L'inserimento dell'immagine è fallito",Italic:"Corsivo",Justify:"Giustifica","Left aligned image":"Immagine allineata a sinistra","Light blue":"Azzurro","Light green":"Verde chiaro","Light grey":"Grigio chiaro",Link:"Collegamento","Link URL":"URL del collegamento","List properties":"Proprietà elenco","Lower-latin":"Lettera minuscola","Lower–roman":"Numero romano minuscolo","Media URL":"URL media","media widget":"widget media","Merge cell down":"Unisci cella sotto","Merge cell left":"Unisci cella a sinistra","Merge cell right":"Unisci cella a destra","Merge cell up":"Unisci cella sopra","Merge cells":"Unisci celle",Next:"Avanti","Numbered List":"Elenco numerato","Numbered list styles toolbar":"Barra degli strumenti con gli stili degli elenchi numerati","Open in a new tab":"Apri in una nuova scheda","Open link in new tab":"Apri collegamento in nuova scheda",Orange:"Arancio",Original:"Originale",Paragraph:"Paragrafo","Paste the media URL in the input.":"Incolla l'URL del file multimediale nell'input.",Previous:"Indietro",Purple:"Porpora",Red:"Rosso",Redo:"Ripristina","Remove color":"Rimuovi colore","Resize image":"Ridimensiona immagine","Resize image to %0":"Ridimensiona immagine a %0","Resize image to the original size":"Ridimensiona immagine alle dimensioni originali","Reversed order":"Ordine inverso","Rich Text Editor":"Editor di testo formattato","Rich Text Editor, %0":"Editor di testo formattato, %0","Right aligned image":"Immagine allineata a destra",Row:"Riga",Save:"Salva","Select all":"Seleziona tutto","Select column":"Seleziona colonna","Select row":"Seleziona riga","Selecting resized image failed":"La selezione dell'immagine ridimensionata è fallita","Show more items":"Mostra più elementi","Side image":"Immagine laterale",Small:"Piccoli","Split cell horizontally":"Dividi cella orizzontalmente","Split cell vertically":"Dividi cella verticalmente",Square:"Quadrato","Start at":"Inizia da","Start index must be greater than 0.":"L'indice iniziale deve essere maggiore di 0.",Strikethrough:"Barrato","Table toolbar":"Barra degli strumenti della tabella","Text alignment":"Allineamento del testo","Text alignment toolbar":"Barra degli strumenti dell'allineamento","Text alternative":"Testo alternativo","The URL must not be empty.":"L'URL non può essere vuoto.","This link has no URL":"Questo collegamento non ha un URL","This media URL is not supported.":"Questo URL di file multimediali non è supportato.",Tiny:"Piccolissimi","Tip: Paste the URL into the content to embed faster.":"Consiglio: incolla l'URL nel contenuto per un'incorporazione più veloce.","Toggle caption off":"Attiva didascalia","Toggle caption on":"Disattiva didascalia","Toggle the circle list style":"Attiva/disattiva lo stile degli elenchi con cerchi","Toggle the decimal list style":"Attiva/disattiva lo stile degli elenchi con numeri","Toggle the decimal with leading zero list style":"Attiva/disattiva lo stile degli elenchi con numeri con zero anteposto","Toggle the disc list style":"Attiva/disattiva lo stile degli elenchi con dischi","Toggle the lower–latin list style":"Attiva/disattiva lo stile degli elenchi con lettere minuscole","Toggle the lower–roman list style":"Attiva/disattiva lo stile degli elenchi con numeri romani minuscoli","Toggle the square list style":"Attiva/disattiva lo stile degli elenchi con quadrati","Toggle the upper–latin list style":"Attiva/disattiva lo stile degli elenchi con lettere maiuscole","Toggle the upper–roman list style":"Attiva/disattiva lo stile degli elenchi con numeri romani maiuscoli",Turquoise:"Turchese",Underline:"Sottolineato",Undo:"Annulla",Unlink:"Elimina collegamento","Upload failed":"Caricamento fallito","Upload in progress":"Caricamento in corso","Upper-latin":"Lettera maiuscola","Upper-roman":"Numero romano maiuscolo",White:"Bianco","Widget toolbar":"Barra degli strumenti del widget","Wrap text":"Testo a capo",Yellow:"Giallo"}),i.getPluralForm=function(e){return 1!=e}}(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
/*! highlight.js v9.8.0 | BSD3 License | git.io/hljslicense */ !function(e){var n="object"==typeof window&&window||"object"==typeof self&&self;"undefined"!=typeof exports?e(exports):n&&(n.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return n.hljs}))}(function(e){function n(e){return e.replace(/[&<>]/gm,function(e){return I[e]})}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0===t.index}function a(e){return k.test(e)}function i(e){var n,t,r,i,o=e.className+" ";if(o+=e.parentNode?e.parentNode.className:"",t=B.exec(o))return R(t[1])?t[1]:"no-highlight";for(o=o.split(/\s+/),n=0,r=o.length;r>n;n++)if(i=o[n],a(i)||R(i))return i}function o(e,n){var t,r={};for(t in e)r[t]=e[t];if(n)for(t in n)r[t]=n[t];return r}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?a+=i.nodeValue.length:1===i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!==r[0].offset?e[0].offset<r[0].offset?e:r:"start"===r[0].event?e:r:e.length?e:r}function o(e){function r(e){return" "+e.nodeName+'="'+n(e.value)+'"'}l+="<"+t(e)+w.map.call(e.attributes,r).join("")+">"}function u(e){l+="</"+t(e)+">"}function c(e){("start"===e.event?o:u)(e.node)}for(var s=0,l="",f=[];e.length||r.length;){var g=i();if(l+=n(a.substr(s,g[0].offset-s)),s=g[0].offset,g===e){f.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g===e&&g.length&&g[0].offset===s);f.reverse().forEach(o)}else"start"===g[0].event?f.push(g[0].node):f.pop(),c(g.splice(0,1)[0])}return l+n(a.substr(s))}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var u={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");u[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):E(a.k).forEach(function(e){c(e,a.k[e])}),a.k=u}a.lR=t(a.l||/\w+/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),null==a.r&&(a.r=1),a.c||(a.c=[]);var s=[];a.c.forEach(function(e){e.v?e.v.forEach(function(n){s.push(o(e,n))}):s.push("self"===e?a:e)}),a.c=s,a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var l=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=l.length?t(l.join("|"),!0):{exec:function(){return null}}}}r(e)}function l(e,t,a,i){function o(e,n){var t,a;for(t=0,a=n.c.length;a>t;t++)if(r(n.c[t].bR,e))return n.c[t]}function u(e,n){if(r(e.eR,n)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?u(e.parent,n):void 0}function c(e,n){return!a&&r(n.iR,e)}function g(e,n){var t=N.cI?n[0].toLowerCase():n[0];return e.k.hasOwnProperty(t)&&e.k[t]}function h(e,n,t,r){var a=r?"":y.classPrefix,i='<span class="'+a,o=t?"":C;return i+=e+'">',i+n+o}function p(){var e,t,r,a;if(!E.k)return n(B);for(a="",t=0,E.lR.lastIndex=0,r=E.lR.exec(B);r;)a+=n(B.substr(t,r.index-t)),e=g(E,r),e?(M+=e[1],a+=h(e[0],n(r[0]))):a+=n(r[0]),t=E.lR.lastIndex,r=E.lR.exec(B);return a+n(B.substr(t))}function d(){var e="string"==typeof E.sL;if(e&&!x[E.sL])return n(B);var t=e?l(E.sL,B,!0,L[E.sL]):f(B,E.sL.length?E.sL:void 0);return E.r>0&&(M+=t.r),e&&(L[E.sL]=t.top),h(t.language,t.value,!1,!0)}function b(){k+=null!=E.sL?d():p(),B=""}function v(e){k+=e.cN?h(e.cN,"",!0):"",E=Object.create(e,{parent:{value:E}})}function m(e,n){if(B+=e,null==n)return b(),0;var t=o(n,E);if(t)return t.skip?B+=n:(t.eB&&(B+=n),b(),t.rB||t.eB||(B=n)),v(t,n),t.rB?0:n.length;var r=u(E,n);if(r){var a=E;a.skip?B+=n:(a.rE||a.eE||(B+=n),b(),a.eE&&(B=n));do E.cN&&(k+=C),E.skip||(M+=E.r),E=E.parent;while(E!==r.parent);return r.starts&&v(r.starts,""),a.rE?0:n.length}if(c(n,E))throw new Error('Illegal lexeme "'+n+'" for mode "'+(E.cN||"<unnamed>")+'"');return B+=n,n.length||1}var N=R(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var w,E=i||N,L={},k="";for(w=E;w!==N;w=w.parent)w.cN&&(k=h(w.cN,"",!0)+k);var B="",M=0;try{for(var I,j,O=0;;){if(E.t.lastIndex=O,I=E.t.exec(t),!I)break;j=m(t.substr(O,I.index-O),I[0]),O=I.index+j}for(m(t.substr(O)),w=E;w.parent;w=w.parent)w.cN&&(k+=C);return{r:M,value:k,language:e,top:E}}catch(T){if(T.message&&-1!==T.message.indexOf("Illegal"))return{r:0,value:n(t)};throw T}}function f(e,t){t=t||y.languages||E(x);var r={r:0,value:n(e)},a=r;return t.filter(R).forEach(function(n){var t=l(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}),a.language&&(r.second_best=a),r}function g(e){return y.tabReplace||y.useBR?e.replace(M,function(e,n){return y.useBR&&"\n"===e?"<br>":y.tabReplace?n.replace(/\t/g,y.tabReplace):void 0}):e}function h(e,n,t){var r=n?L[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function p(e){var n,t,r,o,s,p=i(e);a(p)||(y.useBR?(n=document.createElementNS("http://www.w3.org/1999/xhtml","div"),n.innerHTML=e.innerHTML.replace(/\n/g,"").replace(/<br[ \/]*>/g,"\n")):n=e,s=n.textContent,r=p?l(p,s,!0):f(s),t=u(n),t.length&&(o=document.createElementNS("http://www.w3.org/1999/xhtml","div"),o.innerHTML=r.value,r.value=c(t,u(o),s)),r.value=g(r.value),e.innerHTML=r.value,e.className=h(e.className,p,r.language),e.result={language:r.language,re:r.r},r.second_best&&(e.second_best={language:r.second_best.language,re:r.second_best.r}))}function d(e){y=o(y,e)}function b(){if(!b.called){b.called=!0;var e=document.querySelectorAll("pre code");w.forEach.call(e,p)}}function v(){addEventListener("DOMContentLoaded",b,!1),addEventListener("load",b,!1)}function m(n,t){var r=x[n]=t(e);r.aliases&&r.aliases.forEach(function(e){L[e]=n})}function N(){return E(x)}function R(e){return e=(e||"").toLowerCase(),x[e]||x[L[e]]}var w=[],E=Object.keys,x={},L={},k=/^(no-?highlight|plain|text)$/i,B=/\blang(?:uage)?-([\w-]+)\b/i,M=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,C="</span>",y={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},I={"&":"&amp;","<":"&lt;",">":"&gt;"};return e.highlight=l,e.highlightAuto=f,e.fixMarkup=g,e.highlightBlock=p,e.configure=d,e.initHighlighting=b,e.initHighlightingOnLoad=v,e.registerLanguage=m,e.listLanguages=N,e.getLanguage=R,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|like)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e});hljs.registerLanguage("lisp",function(b){var e="[a-zA-Z_\\-\\+\\*\\/\\<\\=\\>\\&\\#][a-zA-Z0-9_\\-\\+\\*\\/\\<\\=\\>\\&\\#!]*",c="\\|[^]*?\\|",r="(\\-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|\\-)?\\d+)?",a={cN:"meta",b:"^#!",e:"$"},l={cN:"literal",b:"\\b(t{1}|nil)\\b"},n={cN:"number",v:[{b:r,r:0},{b:"#(b|B)[0-1]+(/[0-1]+)?"},{b:"#(o|O)[0-7]+(/[0-7]+)?"},{b:"#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?"},{b:"#(c|C)\\("+r+" +"+r,e:"\\)"}]},i=b.inherit(b.QSM,{i:null}),t=b.C(";","$",{r:0}),s={b:"\\*",e:"\\*"},u={cN:"symbol",b:"[:&]"+e},d={b:e,r:0},f={b:c},m={b:"\\(",e:"\\)",c:["self",l,i,n,d]},o={c:[n,i,s,u,m,d],v:[{b:"['`]\\(",e:"\\)"},{b:"\\(quote ",e:"\\)",k:{name:"quote"}},{b:"'"+c}]},v={v:[{b:"'"+e},{b:"#'"+e+"(::"+e+")*"}]},N={b:"\\(\\s*",e:"\\)"},A={eW:!0,r:0};return N.c=[{cN:"name",v:[{b:e},{b:c}]},A],A.c=[o,v,N,l,n,i,t,s,u,f,d],{i:/\S/,c:[n,a,l,i,t,o,v,N,d]}});hljs.registerLanguage("sml",function(e){return{aliases:["ml"],k:{keyword:"abstype and andalso as case datatype do else end eqtype exception fn fun functor handle if in include infix infixr let local nonfix of op open orelse raise rec sharing sig signature struct structure then type val with withtype where while",built_in:"array bool char exn int list option order real ref string substring vector unit word",literal:"true false NONE SOME LESS EQUAL GREATER nil"},i:/\/\/|>>/,l:"[a-z_]\\w*!?",c:[{cN:"literal",b:/\[(\|\|)?\]|\(\)/,r:0},e.C("\\(\\*","\\*\\)",{c:["self"]}),{cN:"symbol",b:"'[A-Za-z_](?!')[\\w']*"},{cN:"type",b:"`[A-Z][\\w']*"},{cN:"type",b:"\\b[A-Z][\\w']*",r:0},{b:"[a-z_]\\w*'[\\w']*"},e.inherit(e.ASM,{cN:"string",r:0}),e.inherit(e.QSM,{i:null}),{cN:"number",b:"\\b(0[xX][a-fA-F0-9_]+[Lln]?|0[oO][0-7_]+[Lln]?|0[bB][01_]+[Lln]?|[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)",r:0},{b:/[-=]>/}]}});hljs.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"meta",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"comment",v:[{b:/Index: /,e:/$/},{b:/={3,}/,e:/$/},{b:/^\-{3}/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+{3}/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"addition",b:"^\\!",e:"$"}]}});hljs.registerLanguage("javascript",function(e){var r="[A-Za-z$_][0-9A-Za-z$_]*",t={keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},a={cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},n={cN:"subst",b:"\\$\\{",e:"\\}",k:t,c:[]},c={cN:"string",b:"`",e:"`",c:[e.BE,n]};n.c=[e.ASM,e.QSM,c,a,e.RM];var s=n.c.concat([e.CBCM,e.CLCM]);return{aliases:["js","jsx"],k:t,c:[{cN:"meta",r:10,b:/^\s*['"]use (strict|asm)['"]/},{cN:"meta",b:/^#!/,e:/$/},e.ASM,e.QSM,c,e.CLCM,e.CBCM,a,{b:/[{,]\s*/,r:0,c:[{b:r+"\\s*:",rB:!0,r:0,c:[{cN:"attr",b:r,r:0}]}]},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{cN:"function",b:"(\\(.*?\\)|"+r+")\\s*=>",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:r},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:t,c:s}]}]},{b:/</,e:/(\/\w+|\w+\/)>/,sL:"xml",c:[{b:/<\w+\s*\/>/,skip:!0},{b:/<\w+/,e:/(\/\w+|\w+\/)>/,skip:!0,c:[{b:/<\w+\s*\/>/,skip:!0},"self"]}]}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:r}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:s}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor",e:/\{/,eE:!0}],i:/#(?!!)/}});hljs.registerLanguage("css",function(e){var c="[a-zA-Z-][a-zA-Z0-9_-]*",t={b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{eW:!0,eE:!0,c:[{b:/[\w-]+\(/,rB:!0,c:[{cN:"built_in",b:/[\w-]+/},{b:/\(/,e:/\)/,c:[e.ASM,e.QSM]}]},e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"number",b:"#[0-9A-Fa-f]+"},{cN:"meta",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,{cN:"selector-id",b:/#[A-Za-z0-9_-]+/},{cN:"selector-class",b:/\.[A-Za-z0-9_-]+/},{cN:"selector-attr",b:/\[/,e:/\]/,i:"$"},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/},{b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{b:"@",e:"[{;]",i:/:/,c:[{cN:"keyword",b:/\w+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[e.ASM,e.QSM,e.CSSNM]}]},{cN:"selector-tag",b:c,r:0},{b:"{",e:"}",i:/\S/,c:[e.CBCM,t]}]}});hljs.registerLanguage("ini",function(e){var b={cN:"string",c:[e.BE],v:[{b:"'''",e:"'''",r:10},{b:'"""',e:'"""',r:10},{b:'"',e:'"'},{b:"'",e:"'"}]};return{aliases:["toml"],cI:!0,i:/\S/,c:[e.C(";","$"),e.HCM,{cN:"section",b:/^\s*\[+/,e:/\]+/},{b:/^[a-z0-9\[\]_-]+\s*=\s*/,e:"$",rB:!0,c:[{cN:"attr",b:/[a-z0-9\[\]_-]+/},{b:/=/,eW:!0,r:0,c:[{cN:"literal",b:/\bon|off|true|false|yes|no\b/},{cN:"variable",v:[{b:/\$[\w\d"][\w\d_]*/},{b:/\$\{(.*?)}/}]},b,{cN:"number",b:/([\+\-]+)?[\d]+_[\d_]+/},e.NM]}]}]}});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/-?[a-z\._]+/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,s,a,t]}});hljs.registerLanguage("scheme",function(e){var t="[^\\(\\)\\[\\]\\{\\}\",'`;#|\\\\\\s]+",r="(\\-|\\+)?\\d+([./]\\d+)?",a=r+"[+\\-]"+r+"i",i={"builtin-name":"case-lambda call/cc class define-class exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules ' * + , ,@ - ... / ; < <= = => > >= ` abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?"},n={cN:"meta",b:"^#!",e:"$"},c={cN:"literal",b:"(#t|#f|#\\\\"+t+"|#\\\\.)"},l={cN:"number",v:[{b:r,r:0},{b:a,r:0},{b:"#b[0-1]+(/[0-1]+)?"},{b:"#o[0-7]+(/[0-7]+)?"},{b:"#x[0-9a-f]+(/[0-9a-f]+)?"}]},s=e.QSM,o=[e.C(";","$",{r:0}),e.C("#\\|","\\|#")],u={b:t,r:0},p={cN:"symbol",b:"'"+t},d={eW:!0,r:0},m={b:/'/,c:[{b:"\\(",e:"\\)",c:["self",c,s,l,u,p]}]},g={cN:"name",b:t,l:t,k:i},h={b:/lambda/,eW:!0,rB:!0,c:[g,{b:/\(/,e:/\)/,endsParent:!0,c:[u]}]},b={v:[{b:"\\(",e:"\\)"},{b:"\\[",e:"\\]"}],c:[h,g,d]};return d.c=[c,l,s,u,p,m,b].concat(o),{i:/\S/,c:[n,l,s,p,m,b].concat(o)}});hljs.registerLanguage("dockerfile",function(e){return{aliases:["docker"],cI:!0,k:"from maintainer expose env user onbuild",c:[e.HCM,e.ASM,e.QSM,e.NM,{bK:"run cmd entrypoint volume add copy workdir label healthcheck",starts:{e:/[^\\]\n/,sL:"bash"}}],i:"</"}});hljs.registerLanguage("python",function(e){var r={cN:"meta",b:/^(>>>|\.\.\.) /},b={cN:"string",c:[e.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[r],r:10},{b:/(u|b)?r?"""/,e:/"""/,c:[r],r:10},{b:/(u|r|ur)'/,e:/'/,r:10},{b:/(u|r|ur)"/,e:/"/,r:10},{b:/(b|br)'/,e:/'/},{b:/(b|br)"/,e:/"/},e.ASM,e.QSM]},a={cN:"number",r:0,v:[{b:e.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:e.CNR+"[lLjJ]?"}]},l={cN:"params",b:/\(/,e:/\)/,c:["self",r,a,b]};return{aliases:["py","gyp"],k:{keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10 None True False",built_in:"Ellipsis NotImplemented"},i:/(<\/|->|\?)|=>/,c:[r,a,b,e.HCM,{v:[{cN:"function",bK:"def"},{cN:"class",bK:"class"}],e:/:/,i:/[${=;\n,]/,c:[e.UTM,l,{b:/->/,eW:!0,k:"None"}]},{cN:"meta",b:/^[\t ]*@/,e:/$/},{b:/\b(print|exec)\(/}]}});hljs.registerLanguage("php",function(e){var c={b:"\\$+[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]*"},i={cN:"meta",b:/<\?(php)?|\?>/},t={cN:"string",c:[e.BE,i],v:[{b:'b"',e:'"'},{b:"b'",e:"'"},e.inherit(e.ASM,{i:null}),e.inherit(e.QSM,{i:null})]},a={v:[e.BNM,e.CNM]};return{aliases:["php3","php4","php5","php6"],cI:!0,k:"and include_once list abstract global private echo interface as static endswitch array null if endwhile or const for endforeach self var while isset public protected exit foreach throw elseif include __FILE__ empty require_once do xor return parent clone use __CLASS__ __LINE__ else break print eval new catch __METHOD__ case exception default die require __FUNCTION__ enddeclare final try switch continue endfor endif declare unset true false trait goto instanceof insteadof __DIR__ __NAMESPACE__ yield finally",c:[e.HCM,e.C("//","$",{c:[i]}),e.C("/\\*","\\*/",{c:[{cN:"doctag",b:"@[A-Za-z]+"}]}),e.C("__halt_compiler.+?;",!1,{eW:!0,k:"__halt_compiler",l:e.UIR}),{cN:"string",b:/<<<['"]?\w+['"]?$/,e:/^\w+;?$/,c:[e.BE,{cN:"subst",v:[{b:/\$\w+/},{b:/\{\$/,e:/\}/}]}]},i,{cN:"keyword",b:/\$this\b/},c,{b:/(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/},{cN:"function",bK:"function",e:/[;{]/,eE:!0,i:"\\$|\\[|%",c:[e.UTM,{cN:"params",b:"\\(",e:"\\)",c:["self",c,e.CBCM,t,a]}]},{cN:"class",bK:"class interface",e:"{",eE:!0,i:/[:\(\$"]/,c:[{bK:"extends implements"},e.UTM]},{bK:"namespace",e:";",i:/[\.']/,c:[e.UTM]},{bK:"use",e:";",c:[e.UTM]},{b:"=>"},t,a]}});hljs.registerLanguage("xml",function(s){var e="[A-Za-z0-9\\._:-]+",t={eW:!0,i:/</,r:0,c:[{cN:"attr",b:e,r:0},{b:/=\s*/,r:0,c:[{cN:"string",endsParent:!0,v:[{b:/"/,e:/"/},{b:/'/,e:/'/},{b:/[^\s"'=<>`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist"],cI:!0,c:[{cN:"meta",b:"<!DOCTYPE",e:">",r:10,c:[{b:"\\[",e:"\\]"}]},s.C("<!--","-->",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0}]},{cN:"tag",b:"<style(?=\\s|>|$)",e:">",k:{name:"style"},c:[t],starts:{e:"</style>",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"<script(?=\\s|>|$)",e:">",k:{name:"script"},c:[t],starts:{e:"</script>",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"meta",v:[{b:/<\?xml/,e:/\?>/,r:10},{b:/<\?\w+/,e:/\?>/}]},{cN:"tag",b:"</?",e:"/?>",c:[{cN:"name",b:/[^\/><\s]+/,r:0},t]}]}});hljs.registerLanguage("coffeescript",function(e){var c={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",built_in:"npm require console print module global window document"},n="[A-Za-z$_][0-9A-Za-z$_]*",r={cN:"subst",b:/#\{/,e:/}/,k:c},s=[e.BNM,e.inherit(e.CNM,{starts:{e:"(\\s*/)?",r:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,r]},{b:/"/,e:/"/,c:[e.BE,r]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[r,e.HCM]},{b:"//[gim]*",r:0},{b:/\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/}]},{b:"@"+n},{b:"`",e:"`",eB:!0,eE:!0,sL:"javascript"}];r.c=s;var i=e.inherit(e.TM,{b:n}),t="(\\(.*\\))?\\s*\\B[-=]>",o={cN:"params",b:"\\([^\\(]",rB:!0,c:[{b:/\(/,e:/\)/,k:c,c:["self"].concat(s)}]};return{aliases:["coffee","cson","iced"],k:c,i:/\/\*/,c:s.concat([e.C("###","###"),e.HCM,{cN:"function",b:"^\\s*"+n+"\\s*=\\s*"+t,e:"[-=]>",rB:!0,c:[i,o]},{b:/[:\(,=]\s*/,r:0,c:[{cN:"function",b:t,e:"[-=]>",rB:!0,c:[o]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[i]},i]},{b:n+":",e:":",rB:!0,rE:!0,r:0}])}});hljs.registerLanguage("cs",function(e){var i={keyword:"abstract as base bool break byte case catch char checked const continue decimal default delegate do double else enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual void volatile while nameof add alias ascending async await by descending dynamic equals from get global group into join let on orderby partial remove select set value var where yield",literal:"null false true"},r={cN:"string",b:'@"',e:'"',c:[{b:'""'}]},t=e.inherit(r,{i:/\n/}),a={cN:"subst",b:"{",e:"}",k:i},n=e.inherit(a,{i:/\n/}),c={cN:"string",b:/\$"/,e:'"',i:/\n/,c:[{b:"{{"},{b:"}}"},e.BE,n]},s={cN:"string",b:/\$@"/,e:'"',c:[{b:"{{"},{b:"}}"},{b:'""'},a]},o=e.inherit(s,{i:/\n/,c:[{b:"{{"},{b:"}}"},{b:'""'},n]});a.c=[s,c,r,e.ASM,e.QSM,e.CNM,e.CBCM],n.c=[o,c,t,e.ASM,e.QSM,e.CNM,e.inherit(e.CBCM,{i:/\n/})];var l={v:[s,c,r,e.ASM,e.QSM]},b=e.IR+"(<"+e.IR+"(\\s*,\\s*"+e.IR+")*>)?(\\[\\])?";return{aliases:["csharp"],k:i,i:/::/,c:[e.C("///","$",{rB:!0,c:[{cN:"doctag",v:[{b:"///",r:0},{b:"<!--|-->"},{b:"</?",e:">"}]}]}),e.CLCM,e.CBCM,{cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elif endif define undef warning error line region endregion pragma checksum"}},l,e.CNM,{bK:"class interface",e:/[{;=]/,i:/[^\s:]/,c:[e.TM,e.CLCM,e.CBCM]},{bK:"namespace",e:/[{;=]/,i:/[^\s:]/,c:[e.inherit(e.TM,{b:"[a-zA-Z](\\.?\\w)*"}),e.CLCM,e.CBCM]},{bK:"new return throw await",r:0},{cN:"function",b:"("+b+"\\s+)+"+e.IR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:i,c:[{b:e.IR+"\\s*\\(",rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:i,r:0,c:[l,e.CNM,e.CBCM]},e.CLCM,e.CBCM]}]}});hljs.registerLanguage("http",function(e){var t="HTTP/[0-9\\.]+";return{aliases:["https"],i:"\\S",c:[{b:"^"+t,e:"$",c:[{cN:"number",b:"\\b\\d{3}\\b"}]},{b:"^[A-Z]+ (.*?) "+t+"$",rB:!0,e:"$",c:[{cN:"string",b:" ",e:" ",eB:!0,eE:!0},{b:t},{cN:"keyword",b:"[A-Z]+"}]},{cN:"attribute",b:"^\\w",e:": ",eE:!0,i:"\\n|\\s|=",starts:{e:"$",r:0}},{b:"\\n\\n",starts:{sL:[],eW:!0}}]}});hljs.registerLanguage("markdown",function(e){return{aliases:["md","mkdown","mkd"],c:[{cN:"section",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",r:0},{cN:"bullet",b:"^([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"quote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"^```w*s*$",e:"^```s*$"},{b:"`.+?`"},{b:"^( {4}| )",e:"$",r:0}]},{b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"string",b:"\\[",e:"\\]",eB:!0,rE:!0,r:0},{cN:"link",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"symbol",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],r:10},{b:/^\[[^\n]+\]:/,rB:!0,c:[{cN:"symbol",b:/\[/,e:/\]/,eB:!0,eE:!0},{cN:"link",b:/:\s*/,e:/$/,eB:!0}]}]}});hljs.registerLanguage("rust",function(e){var t="([uif](8|16|32|64|size))?",r="alignof as be box break const continue crate do else enum extern false fn for if impl in let loop match mod mut offsetof once priv proc pub pure ref return self Self sizeof static struct super trait true type typeof unsafe unsized use virtual while where yield move default int i8 i16 i32 i64 isize uint u8 u32 u64 usize float f32 f64 str char bool",n="Copy Send Sized Sync Drop Fn FnMut FnOnce drop Box ToOwned Clone PartialEq PartialOrd Eq Ord AsRef AsMut Into From Default Iterator Extend IntoIterator DoubleEndedIterator ExactSizeIterator Option Result SliceConcatExt String ToString Vec assert! assert_eq! bitflags! bytes! cfg! col! concat! concat_idents! debug_assert! debug_assert_eq! env! panic! file! format! format_args! include_bin! include_str! line! local_data_key! module_path! option_env! print! println! select! stringify! try! unimplemented! unreachable! vec! write! writeln! macro_rules!";return{aliases:["rs"],k:{keyword:r,literal:"true false Some None Ok Err",built_in:n},l:e.IR+"!?",i:"</",c:[e.CLCM,e.C("/\\*","\\*/",{c:["self"]}),e.inherit(e.QSM,{b:/b?"/,i:null}),{cN:"string",v:[{b:/r(#*)".*?"\1(?!#)/},{b:/b?'\\?(x\w{2}|u\w{4}|U\w{8}|.)'/}]},{cN:"symbol",b:/'[a-zA-Z_][a-zA-Z0-9_]*/},{cN:"number",v:[{b:"\\b0b([01_]+)"+t},{b:"\\b0o([0-7_]+)"+t},{b:"\\b0x([A-Fa-f0-9_]+)"+t},{b:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+t}],r:0},{cN:"function",bK:"fn",e:"(\\(|<)",eE:!0,c:[e.UTM]},{cN:"meta",b:"#\\!?\\[",e:"\\]",c:[{cN:"meta-string",b:/"/,e:/"/}]},{cN:"class",bK:"type",e:";",c:[e.inherit(e.UTM,{endsParent:!0})],i:"\\S"},{cN:"class",bK:"trait enum struct",e:"{",c:[e.inherit(e.UTM,{endsParent:!0})],i:"[\\w\\d]"},{b:e.IR+"::",k:{built_in:n}},{b:"->"}]}});hljs.registerLanguage("haskell",function(e){var i={v:[e.C("--","$"),e.C("{-","-}",{c:["self"]})]},a={cN:"meta",b:"{-#",e:"#-}"},l={cN:"meta",b:"^#",e:"$"},c={cN:"type",b:"\\b[A-Z][\\w']*",r:0},n={b:"\\(",e:"\\)",i:'"',c:[a,l,{cN:"type",b:"\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"},e.inherit(e.TM,{b:"[_a-z][\\w']*"}),i]},s={b:"{",e:"}",c:n.c};return{aliases:["hs"],k:"let in if then else case of where do module import hiding qualified type data newtype deriving class instance as default infix infixl infixr foreign export ccall stdcall cplusplus jvm dotnet safe unsafe family forall mdo proc rec",c:[{bK:"module",e:"where",k:"module where",c:[n,i],i:"\\W\\.|;"},{b:"\\bimport\\b",e:"$",k:"import qualified as hiding",c:[n,i],i:"\\W\\.|;"},{cN:"class",b:"^(\\s*)?(class|instance)\\b",e:"where",k:"class family instance where",c:[c,n,i]},{cN:"class",b:"\\b(data|(new)?type)\\b",e:"$",k:"data family type newtype deriving",c:[a,c,n,s,i]},{bK:"default",e:"$",c:[c,n,i]},{bK:"infix infixl infixr",e:"$",c:[e.CNM,i]},{b:"\\bforeign\\b",e:"$",k:"foreign import export ccall stdcall cplusplus jvm dotnet safe unsafe",c:[c,e.QSM,i]},{cN:"meta",b:"#!\\/usr\\/bin\\/env runhaskell",e:"$"},a,l,e.QSM,e.CNM,c,e.inherit(e.TM,{b:"^[_a-z][\\w']*"}),i,{b:"->|<-"}]}});hljs.registerLanguage("ocaml",function(e){return{aliases:["ml"],k:{keyword:"and as assert asr begin class constraint do done downto else end exception external for fun function functor if in include inherit! inherit initializer land lazy let lor lsl lsr lxor match method!|10 method mod module mutable new object of open! open or private rec sig struct then to try type val! val virtual when while with parser value",built_in:"array bool bytes char exn|5 float int int32 int64 list lazy_t|5 nativeint|5 string unit in_channel out_channel ref",literal:"true false"},i:/\/\/|>>/,l:"[a-z_]\\w*!?",c:[{cN:"literal",b:"\\[(\\|\\|)?\\]|\\(\\)",r:0},e.C("\\(\\*","\\*\\)",{c:["self"]}),{cN:"symbol",b:"'[A-Za-z_](?!')[\\w']*"},{cN:"type",b:"`[A-Z][\\w']*"},{cN:"type",b:"\\b[A-Z][\\w']*",r:0},{b:"[a-z_]\\w*'[\\w']*",r:0},e.inherit(e.ASM,{cN:"string",r:0}),e.inherit(e.QSM,{i:null}),{cN:"number",b:"\\b(0[xX][a-fA-F0-9_]+[Lln]?|0[oO][0-7_]+[Lln]?|0[bB][01_]+[Lln]?|[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)",r:0},{b:/[-=]>/}]}});hljs.registerLanguage("perl",function(e){var t="getpwent getservent quotemeta msgrcv scalar kill dbmclose undef lc ma syswrite tr send umask sysopen shmwrite vec qx utime local oct semctl localtime readpipe do return format read sprintf dbmopen pop getpgrp not getpwnam rewinddir qqfileno qw endprotoent wait sethostent bless s|0 opendir continue each sleep endgrent shutdown dump chomp connect getsockname die socketpair close flock exists index shmgetsub for endpwent redo lstat msgctl setpgrp abs exit select print ref gethostbyaddr unshift fcntl syscall goto getnetbyaddr join gmtime symlink semget splice x|0 getpeername recv log setsockopt cos last reverse gethostbyname getgrnam study formline endhostent times chop length gethostent getnetent pack getprotoent getservbyname rand mkdir pos chmod y|0 substr endnetent printf next open msgsnd readdir use unlink getsockopt getpriority rindex wantarray hex system getservbyport endservent int chr untie rmdir prototype tell listen fork shmread ucfirst setprotoent else sysseek link getgrgid shmctl waitpid unpack getnetbyname reset chdir grep split require caller lcfirst until warn while values shift telldir getpwuid my getprotobynumber delete and sort uc defined srand accept package seekdir getprotobyname semop our rename seek if q|0 chroot sysread setpwent no crypt getc chown sqrt write setnetent setpriority foreach tie sin msgget map stat getlogin unless elsif truncate exec keys glob tied closedirioctl socket readlink eval xor readline binmode setservent eof ord bind alarm pipe atan2 getgrent exp time push setgrent gt lt or ne m|0 break given say state when",r={cN:"subst",b:"[$@]\\{",e:"\\}",k:t},s={b:"->{",e:"}"},n={v:[{b:/\$\d/},{b:/[\$%@](\^\w\b|#\w+(::\w+)*|{\w+}|\w+(::\w*)*)/},{b:/[\$%@][^\s\w{]/,r:0}]},i=[e.BE,r,n],o=[n,e.HCM,e.C("^\\=\\w","\\=cut",{eW:!0}),s,{cN:"string",c:i,v:[{b:"q[qwxr]?\\s*\\(",e:"\\)",r:5},{b:"q[qwxr]?\\s*\\[",e:"\\]",r:5},{b:"q[qwxr]?\\s*\\{",e:"\\}",r:5},{b:"q[qwxr]?\\s*\\|",e:"\\|",r:5},{b:"q[qwxr]?\\s*\\<",e:"\\>",r:5},{b:"qw\\s+q",e:"q",r:5},{b:"'",e:"'",c:[e.BE]},{b:'"',e:'"'},{b:"`",e:"`",c:[e.BE]},{b:"{\\w+}",c:[],r:0},{b:"-?\\w+\\s*\\=\\>",c:[],r:0}]},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\/\\/|"+e.RSR+"|\\b(split|return|print|reverse|grep)\\b)\\s*",k:"split return print reverse grep",r:0,c:[e.HCM,{cN:"regexp",b:"(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*",r:10},{cN:"regexp",b:"(m|qr)?/",e:"/[a-z]*",c:[e.BE],r:0}]},{cN:"function",bK:"sub",e:"(\\s*\\(.*?\\))?[;{]",eE:!0,r:5,c:[e.TM]},{b:"-\\w\\b",r:0},{b:"^__DATA__$",e:"^__END__$",sL:"mojolicious",c:[{b:"^@@.*",e:"$",cN:"comment"}]}];return r.c=o,s.c=o,{aliases:["pl","pm"],l:/[\w\.]+/,k:t,c:o}});hljs.registerLanguage("json",function(e){var i={literal:"true false null"},n=[e.QSM,e.CNM],r={e:",",eW:!0,eE:!0,c:n,k:i},t={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(r,{b:/:/})],i:"\\S"},c={b:"\\[",e:"\\]",c:[e.inherit(r)],i:"\\S"};return n.splice(n.length,0,t,c),{c:n,k:i,i:"\\S"}});hljs.registerLanguage("elm",function(e){var i={v:[e.C("--","$"),e.C("{-","-}",{c:["self"]})]},t={cN:"type",b:"\\b[A-Z][\\w']*",r:0},c={b:"\\(",e:"\\)",i:'"',c:[{cN:"type",b:"\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?"},i]},n={b:"{",e:"}",c:c.c};return{k:"let in if then else case of where module import exposing type alias as infix infixl infixr port effect command subscription",c:[{bK:"port effect module",e:"exposing",k:"port effect module where command subscription exposing",c:[c,i],i:"\\W\\.|;"},{b:"import",e:"$",k:"import as exposing",c:[c,i],i:"\\W\\.|;"},{b:"type",e:"$",k:"type alias",c:[t,c,n,i]},{bK:"infix infixl infixr",e:"$",c:[e.CNM,i]},{b:"port",e:"$",k:"port",c:[i]},e.QSM,e.CNM,t,e.inherit(e.TM,{b:"^[_a-z][\\w']*"}),i,{b:"->|<-"}]}});hljs.registerLanguage("nginx",function(e){var r={cN:"variable",v:[{b:/\$\d+/},{b:/\$\{/,e:/}/},{b:"[\\$\\@]"+e.UIR}]},b={eW:!0,l:"[a-z/_]+",k:{literal:"on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll"},r:0,i:"=>",c:[e.HCM,{cN:"string",c:[e.BE,r],v:[{b:/"/,e:/"/},{b:/'/,e:/'/}]},{b:"([a-z]+):/",e:"\\s",eW:!0,eE:!0,c:[r]},{cN:"regexp",c:[e.BE,r],v:[{b:"\\s\\^",e:"\\s|{|;",rE:!0},{b:"~\\*?\\s+",e:"\\s|{|;",rE:!0},{b:"\\*(\\.[a-z\\-]+)+"},{b:"([a-z\\-]+\\.)+\\*"}]},{cN:"number",b:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{cN:"number",b:"\\b\\d+[kKmMgGdshdwy]*\\b",r:0},r]};return{aliases:["nginxconf"],c:[e.HCM,{b:e.UIR+"\\s+{",rB:!0,e:"{",c:[{cN:"section",b:e.UIR}],r:0},{b:e.UIR+"\\s",e:";|{",rB:!0,c:[{cN:"attribute",b:e.UIR,starts:b}],r:0}],i:"[^\\s\\}]"}});hljs.registerLanguage("makefile",function(e){var a={cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]};return{aliases:["mk","mak"],c:[e.HCM,{b:/^\w+\s*\W*=/,rB:!0,r:0,starts:{e:/\s*\W*=/,eE:!0,starts:{e:/$/,r:0,c:[a]}}},{cN:"section",b:/^[\w]+:\s*$/},{cN:"meta",b:/^\.PHONY:/,e:/$/,k:{"meta-keyword":".PHONY"},l:/[\.\w]+/},{b:/^\t+/,e:/$/,r:0,c:[e.QSM,a]}]}});hljs.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*#]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null",built_in:"array bigint binary bit blob boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t]},e.CBCM,t]}});hljs.registerLanguage("cpp",function(t){var e={cN:"keyword",b:"\\b[a-z\\d_]*_t\\b"},r={cN:"string",v:[{b:'(u8?|U)?L?"',e:'"',i:"\\n",c:[t.BE]},{b:'(u8?|U)?R"',e:'"',c:[t.BE]},{b:"'\\\\?.",e:"'",i:"."}]},s={cN:"number",v:[{b:"\\b(0b[01']+)"},{b:"\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{b:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],r:0},i={cN:"meta",b:/#\s*[a-z]+\b/,e:/$/,k:{"meta-keyword":"if else elif endif define undef warning error line pragma ifdef ifndef include"},c:[{b:/\\\n/,r:0},t.inherit(r,{cN:"meta-string"}),{cN:"meta-string",b:"<",e:">",i:"\\n"},t.CLCM,t.CBCM]},a=t.IR+"\\s*\\(",c={keyword:"int float while private char catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const struct for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using class asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignof constexpr decltype noexcept static_assert thread_local restrict _Bool complex _Complex _Imaginary atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return",built_in:"std string cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr",literal:"true false nullptr NULL"},n=[e,t.CLCM,t.CBCM,s,r];return{aliases:["c","cc","h","c++","h++","hpp"],k:c,i:"</",c:n.concat([i,{b:"\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<",e:">",k:c,c:["self",e]},{b:t.IR+"::",k:c},{v:[{b:/=/,e:/;/},{b:/\(/,e:/\)/},{bK:"new throw return else",e:/;/}],k:c,c:n.concat([{b:/\(/,e:/\)/,k:c,c:n.concat(["self"]),r:0}]),r:0},{cN:"function",b:"("+t.IR+"[\\*&\\s]+)+"+a,rB:!0,e:/[{;=]/,eE:!0,k:c,i:/[^\w\s\*&]/,c:[{b:a,rB:!0,c:[t.TM],r:0},{cN:"params",b:/\(/,e:/\)/,k:c,r:0,c:[t.CLCM,t.CBCM,r,s,e]},t.CLCM,t.CBCM,i]}]),exports:{preprocessor:i,strings:r,k:c}}});hljs.registerLanguage("ruby",function(e){var b="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",r={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},c={cN:"doctag",b:"@[A-Za-z]+"},a={b:"#<",e:">"},s=[e.C("#","$",{c:[c]}),e.C("^\\=begin","^\\=end",{c:[c],r:10}),e.C("^__END__","\\n$")],n={cN:"subst",b:"#\\{",e:"}",k:r},t={cN:"string",c:[e.BE,n],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{b:/<<(-?)\w+$/,e:/^\s*\w+$/}]},i={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:r},d=[t,a,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(s)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:b}),i].concat(s)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"symbol",b:":(?!\\s)",c:[t,{b:b}],r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:r},{b:"("+e.RSR+")\\s*",c:[a,{cN:"regexp",c:[e.BE,n],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(s),r:0}].concat(s);n.c=d,i.c=d;var l="[>?]>",o="[\\w#]+\\(\\w+\\):\\d+:\\d+>",w="(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>",u=[{b:/^\s*=>/,starts:{e:"$",c:d}},{cN:"meta",b:"^("+l+"|"+o+"|"+w+")",starts:{e:"$",c:d}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:r,i:/\/\*/,c:s.concat(u).concat(d)}});hljs.registerLanguage("java",function(e){var a="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",t=a+"(<"+a+"(\\s*,\\s*"+a+")*>)?",r="false synchronized int abstract float private char boolean static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do",s="\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",c={cN:"number",b:s,r:0};return{aliases:["jsp"],k:r,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"new throw return else",r:0},{cN:"function",b:"("+t+"\\s+)+"+e.UIR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:r,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,k:r,r:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},c,{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("coq",function(e){return{k:{keyword:"_ as at cofix else end exists exists2 fix for forall fun if IF in let match mod Prop return Set then Type using where with Abort About Add Admit Admitted All Arguments Assumptions Axiom Back BackTo Backtrack Bind Blacklist Canonical Cd Check Class Classes Close Coercion Coercions CoFixpoint CoInductive Collection Combined Compute Conjecture Conjectures Constant constr Constraint Constructors Context Corollary CreateHintDb Cut Declare Defined Definition Delimit Dependencies DependentDerive Drop eauto End Equality Eval Example Existential Existentials Existing Export exporting Extern Extract Extraction Fact Field Fields File Fixpoint Focus for From Function Functional Generalizable Global Goal Grab Grammar Graph Guarded Heap Hint HintDb Hints Hypotheses Hypothesis ident Identity If Immediate Implicit Import Include Inductive Infix Info Initial Inline Inspect Instance Instances Intro Intros Inversion Inversion_clear Language Left Lemma Let Libraries Library Load LoadPath Local Locate Ltac ML Mode Module Modules Monomorphic Morphism Next NoInline Notation Obligation Obligations Opaque Open Optimize Options Parameter Parameters Parametric Path Paths pattern Polymorphic Preterm Print Printing Program Projections Proof Proposition Pwd Qed Quit Rec Record Recursive Redirect Relation Remark Remove Require Reserved Reset Resolve Restart Rewrite Right Ring Rings Save Scheme Scope Scopes Script Search SearchAbout SearchHead SearchPattern SearchRewrite Section Separate Set Setoid Show Solve Sorted Step Strategies Strategy Structure SubClass Table Tables Tactic Term Test Theorem Time Timeout Transparent Type Typeclasses Types Undelimit Undo Unfocus Unfocused Unfold Universe Universes Unset Unshelve using Variable Variables Variant Verbose Visibility where with",built_in:"abstract absurd admit after apply as assert assumption at auto autorewrite autounfold before bottom btauto by case case_eq cbn cbv change classical_left classical_right clear clearbody cofix compare compute congruence constr_eq constructor contradict contradiction cut cutrewrite cycle decide decompose dependent destruct destruction dintuition discriminate discrR do double dtauto eapply eassumption eauto ecase econstructor edestruct ediscriminate eelim eexact eexists einduction einjection eleft elim elimtype enough equality erewrite eright esimplify_eq esplit evar exact exactly_once exfalso exists f_equal fail field field_simplify field_simplify_eq first firstorder fix fold fourier functional generalize generalizing gfail give_up has_evar hnf idtac in induction injection instantiate intro intro_pattern intros intuition inversion inversion_clear is_evar is_var lapply lazy left lia lra move native_compute nia nsatz omega once pattern pose progress proof psatz quote record red refine reflexivity remember rename repeat replace revert revgoals rewrite rewrite_strat right ring ring_simplify rtauto set setoid_reflexivity setoid_replace setoid_rewrite setoid_symmetry setoid_transitivity shelve shelve_unifiable simpl simple simplify_eq solve specialize split split_Rabs split_Rmult stepl stepr subst sum swap symmetry tactic tauto time timeout top transitivity trivial try tryif unfold unify until using vm_compute with"},c:[e.QSM,e.C("\\(\\*","\\*\\)"),e.CNM,{cN:"type",eB:!0,b:"\\|\\s*",e:"\\w+"},{b:/[-=]>/}]}});
/** * Get the object replicationInfo to replicate data and metadata, or only * metadata if the operation only changes metadata or the object is 0 bytes * @param {string} objKey - The key of the object * @param {object} bucketMD - The bucket metadata * @param {boolean} isMD - Whether the operation is only updating metadata * @param {boolean} objSize - The size, in bytes, of the object being PUT * @return {undefined} */ function getReplicationInfo(objKey, bucketMD, isMD, objSize) { const content = isMD || objSize === 0 ? ['METADATA'] : ['DATA', 'METADATA']; const config = bucketMD.getReplicationConfiguration(); // If bucket does not have a replication configuration, do not replicate. if (config) { const rule = config.rules.find(rule => objKey.startsWith(rule.prefix)); if (rule) { return { status: 'PENDING', content, destination: config.destination, storageClass: rule.storageClass || '', role: config.role, }; } } return undefined; } module.exports = getReplicationInfo;
'use strict' const { Model } = require('../../class') const { query } = require('../mysql') class AdminLogModel extends Model { constructor() { super('admin_log') } create({ userId = 0, url = '', params = '' }) { const post = [userId, url, params] const sql = ` insert into \`${this.tableName}\` (user_id, url, params) values (?, ?, ?) ` return query(sql, post) } getList({ startId = 0, pageSize = 10 }) { const post = [startId, pageSize] const sql = ` select id, user_id, url, params, create_at from ${this.tableName} where id >= ? and is_valid = 1 order by id desc limit ? offset 0 ` return query(sql, post) } } module.exports = new AdminLogModel()
(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.MembersThemeBindings = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ "use strict"; var root = require('./_root'); var Symbol = root.Symbol; module.exports = Symbol; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_Symbol.js },{"./_root":24}],2:[function(require,module,exports){ "use strict"; function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_arrayEach.js },{}],3:[function(require,module,exports){ "use strict"; var baseTimes = require('./_baseTimes'), isArguments = require('./isArguments'), isArray = require('./isArray'), isBuffer = require('./isBuffer'), isIndex = require('./_isIndex'), isTypedArray = require('./isTypedArray'); var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == 'length' || (isBuff && (key == 'offset' || key == 'parent')) || (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || isIndex(key, length)))) { result.push(key); } } return result; } module.exports = arrayLikeKeys; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_arrayLikeKeys.js },{"./_baseTimes":11,"./_isIndex":18,"./isArguments":28,"./isArray":29,"./isBuffer":31,"./isTypedArray":36}],4:[function(require,module,exports){ "use strict"; var baseForOwn = require('./_baseForOwn'), createBaseEach = require('./_createBaseEach'); var baseEach = createBaseEach(baseForOwn); module.exports = baseEach; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_baseEach.js },{"./_baseForOwn":6,"./_createBaseEach":14}],5:[function(require,module,exports){ "use strict"; var createBaseFor = require('./_createBaseFor'); var baseFor = createBaseFor(); module.exports = baseFor; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_baseFor.js },{"./_createBaseFor":15}],6:[function(require,module,exports){ "use strict"; var baseFor = require('./_baseFor'), keys = require('./keys'); function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } module.exports = baseForOwn; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_baseForOwn.js },{"./_baseFor":5,"./keys":37}],7:[function(require,module,exports){ "use strict"; var Symbol = require('./_Symbol'), getRawTag = require('./_getRawTag'), objectToString = require('./_objectToString'); var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; var symToStringTag = Symbol ? Symbol.toStringTag : undefined; function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_baseGetTag.js },{"./_Symbol":1,"./_getRawTag":17,"./_objectToString":22}],8:[function(require,module,exports){ "use strict"; var baseGetTag = require('./_baseGetTag'), isObjectLike = require('./isObjectLike'); var argsTag = '[object Arguments]'; function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } module.exports = baseIsArguments; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_baseIsArguments.js },{"./_baseGetTag":7,"./isObjectLike":35}],9:[function(require,module,exports){ "use strict"; var baseGetTag = require('./_baseGetTag'), isLength = require('./isLength'), isObjectLike = require('./isObjectLike'); var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } module.exports = baseIsTypedArray; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_baseIsTypedArray.js },{"./_baseGetTag":7,"./isLength":33,"./isObjectLike":35}],10:[function(require,module,exports){ "use strict"; var isPrototype = require('./_isPrototype'), nativeKeys = require('./_nativeKeys'); var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } module.exports = baseKeys; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_baseKeys.js },{"./_isPrototype":19,"./_nativeKeys":20}],11:[function(require,module,exports){ "use strict"; function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } module.exports = baseTimes; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_baseTimes.js },{}],12:[function(require,module,exports){ "use strict"; function baseUnary(func) { return function(value) { return func(value); }; } module.exports = baseUnary; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_baseUnary.js },{}],13:[function(require,module,exports){ "use strict"; var identity = require('./identity'); function castFunction(value) { return typeof value == 'function' ? value : identity; } module.exports = castFunction; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_castFunction.js },{"./identity":27}],14:[function(require,module,exports){ "use strict"; var isArrayLike = require('./isArrayLike'); function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } module.exports = createBaseEach; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_createBaseEach.js },{"./isArrayLike":30}],15:[function(require,module,exports){ "use strict"; function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_createBaseFor.js },{}],16:[function(require,module,exports){ (function (global){ "use strict"; var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_freeGlobal.js }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],17:[function(require,module,exports){ "use strict"; var Symbol = require('./_Symbol'); var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; var nativeObjectToString = objectProto.toString; var symToStringTag = Symbol ? Symbol.toStringTag : undefined; function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_getRawTag.js },{"./_Symbol":1}],18:[function(require,module,exports){ "use strict"; var MAX_SAFE_INTEGER = 9007199254740991; var reIsUint = /^(?:0|[1-9]\d*)$/; function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } module.exports = isIndex; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_isIndex.js },{}],19:[function(require,module,exports){ "use strict"; var objectProto = Object.prototype; function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } module.exports = isPrototype; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_isPrototype.js },{}],20:[function(require,module,exports){ "use strict"; var overArg = require('./_overArg'); var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_nativeKeys.js },{"./_overArg":23}],21:[function(require,module,exports){ "use strict"; var freeGlobal = require('./_freeGlobal'); var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; var moduleExports = freeModule && freeModule.exports === freeExports; var freeProcess = moduleExports && freeGlobal.process; var nodeUtil = (function() { try { var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_nodeUtil.js },{"./_freeGlobal":16}],22:[function(require,module,exports){ "use strict"; var objectProto = Object.prototype; var nativeObjectToString = objectProto.toString; function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_objectToString.js },{}],23:[function(require,module,exports){ "use strict"; function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_overArg.js },{}],24:[function(require,module,exports){ "use strict"; var freeGlobal = require('./_freeGlobal'); var freeSelf = typeof self == 'object' && self && self.Object === Object && self; var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/_root.js },{"./_freeGlobal":16}],25:[function(require,module,exports){ "use strict"; module.exports = require('./forEach'); //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/each.js },{"./forEach":26}],26:[function(require,module,exports){ "use strict"; var arrayEach = require('./_arrayEach'), baseEach = require('./_baseEach'), castFunction = require('./_castFunction'), isArray = require('./isArray'); function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, castFunction(iteratee)); } module.exports = forEach; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/forEach.js },{"./_arrayEach":2,"./_baseEach":4,"./_castFunction":13,"./isArray":29}],27:[function(require,module,exports){ "use strict"; function identity(value) { return value; } module.exports = identity; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/identity.js },{}],28:[function(require,module,exports){ "use strict"; var baseIsArguments = require('./_baseIsArguments'), isObjectLike = require('./isObjectLike'); var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; var propertyIsEnumerable = objectProto.propertyIsEnumerable; var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; module.exports = isArguments; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/isArguments.js },{"./_baseIsArguments":8,"./isObjectLike":35}],29:[function(require,module,exports){ "use strict"; var isArray = Array.isArray; module.exports = isArray; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/isArray.js },{}],30:[function(require,module,exports){ "use strict"; var isFunction = require('./isFunction'), isLength = require('./isLength'); function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } module.exports = isArrayLike; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/isArrayLike.js },{"./isFunction":32,"./isLength":33}],31:[function(require,module,exports){ "use strict"; var root = require('./_root'), stubFalse = require('./stubFalse'); var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; var moduleExports = freeModule && freeModule.exports === freeExports; var Buffer = moduleExports ? root.Buffer : undefined; var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; var isBuffer = nativeIsBuffer || stubFalse; module.exports = isBuffer; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/isBuffer.js },{"./_root":24,"./stubFalse":38}],32:[function(require,module,exports){ "use strict"; var baseGetTag = require('./_baseGetTag'), isObject = require('./isObject'); var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; function isFunction(value) { if (!isObject(value)) { return false; } var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } module.exports = isFunction; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/isFunction.js },{"./_baseGetTag":7,"./isObject":34}],33:[function(require,module,exports){ "use strict"; var MAX_SAFE_INTEGER = 9007199254740991; function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/isLength.js },{}],34:[function(require,module,exports){ "use strict"; function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } module.exports = isObject; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/isObject.js },{}],35:[function(require,module,exports){ "use strict"; function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/isObjectLike.js },{}],36:[function(require,module,exports){ "use strict"; var baseIsTypedArray = require('./_baseIsTypedArray'), baseUnary = require('./_baseUnary'), nodeUtil = require('./_nodeUtil'); var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; module.exports = isTypedArray; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/isTypedArray.js },{"./_baseIsTypedArray":9,"./_baseUnary":12,"./_nodeUtil":21}],37:[function(require,module,exports){ "use strict"; var arrayLikeKeys = require('./_arrayLikeKeys'), baseKeys = require('./_baseKeys'), isArrayLike = require('./isArrayLike'); function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } module.exports = keys; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/keys.js },{"./_arrayLikeKeys":3,"./_baseKeys":10,"./isArrayLike":30}],38:[function(require,module,exports){ "use strict"; function stubFalse() { return false; } module.exports = stubFalse; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/lodash/stubFalse.js },{}],39:[function(require,module,exports){ "use strict"; module.exports = function(n) { var t = {}, e = []; n = n || this, n.on = function(e, r, l) { return (t[e] = t[e] || []).push([r, l]), n; }, n.off = function(r, l) { r || (t = {}); for (var o = t[r] || e, u = o.length = l ? o.length : 0; u--; ) l == o[u][0] && o.splice(u, 1); return n; }, n.emit = function(r) { for (var l, o = t[r] || e, u = o.length > 0 ? o.slice(0, o.length) : o, i = 0; l = u[i++]; ) l[0].apply(l[1], e.slice.call(arguments, 1)); return n; }; }; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/minivents/dist/minivents.commonjs.min.js },{}],40:[function(require,module,exports){ "use strict"; var gatewayApi = require('@tryghost/members-gateway-api'); module.exports = function layer2(options) { var authUrl = (options.membersUrl + "/auth"); var gatewayUrl = (options.membersUrl + "/gateway"); var container = options.container; var members = gatewayApi({ gatewayUrl: gatewayUrl, container: container }); var loadAuth = loadFrame(authUrl, container).then(function(frame) { frame.style.position = 'fixed'; frame.style.width = '100%'; frame.style.height = '100%'; frame.style.background = 'transparent'; frame.style.top = '0'; frame.style['z-index'] = '9999'; return frame; }); function openAuth(hash) { var query = arguments[1] !== (void 0) ? arguments[1] : ''; return loadAuth.then(function(frame) { return new Promise(function(resolve) { frame.src = (authUrl + "#" + hash + "?" + query); frame.style.display = 'block'; window.addEventListener('message', function messageListener(event) { if (event.source !== frame.contentWindow) { return; } if (!event.data || event.data.msg !== 'pls-close-auth-popup') { return; } window.removeEventListener('message', messageListener); frame.style.display = 'none'; resolve(!!event.data.success); }); }); }); } function resetPassword($__0) { var token = $__0.token; var query = ("token=" + token); return openAuth('reset-password', query); } function signin() { return openAuth('signin'); } function upgrade() { return openAuth('upgrade'); } function signup() { var coupon = (arguments[0] !== (void 0) ? arguments[0] : {}).coupon; var query = ("coupon=" + coupon); return openAuth('signup', query); } function getToken($__0) { var $__1 = $__0, audience = $__1.audience, fresh = $__1.fresh; return members.getToken({ audience: audience, fresh: fresh }); } function getSSRToken() { var fresh = (arguments[0] !== (void 0) ? arguments[0] : {}).fresh; return members.getConfig().then(function($__1) { var issuer = $__1.issuer; return members.getToken({ audience: issuer, fresh: fresh }); }); } function signout() { return members.signout(); } return Object.assign(members.bus, { getToken: getToken, getSSRToken: getSSRToken, signout: signout, signin: signin, signup: signup, upgrade: upgrade, resetPassword: resetPassword }); }; function loadFrame(src) { var container = arguments[1] !== (void 0) ? arguments[1] : document.body; return new Promise(function(resolve) { var frame = document.createElement('iframe'); frame.style.display = 'none'; frame.src = src; frame.onload = function() { resolve(frame); }; container.appendChild(frame); }); } //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/@tryghost/members-browser-auth/index.js },{"@tryghost/members-gateway-api":41}],41:[function(require,module,exports){ "use strict"; var gatewayProtocol = require('@tryghost/members-gateway-protocol'); var events = require('minivents'); module.exports = function layer1(options) { var members = { getToken: getToken, getConfig: getConfig, signout: signout, signin: signin, signup: signup, requestPasswordReset: requestPasswordReset, resetPassword: resetPassword, bus: new events() }; var loadGateway = loadFrame(options.gatewayUrl, options.container).then(function(frame) { var gateway = gatewayProtocol(frame); var init = gatewayFn('init'); gateway.listen(function(data) { members.bus.emit(data.event, data.payload); }); return init(gateway).then(function() { return gateway; }); }); function getToken($__0) { var $__1 = $__0, audience = $__1.audience, fresh = $__1.fresh; return loadGateway.then(gatewayFn('getToken', { audience: audience, fresh: fresh })); } function getConfig() { return loadGateway.then(gatewayFn('getConfig')); } function signout() { return loadGateway.then(gatewayFn('signout')); } function signin($__0) { var $__1 = $__0, email = $__1.email, password = $__1.password; return loadGateway.then(gatewayFn('signin', { email: email, password: password })); } function signup($__0) { var $__1 = $__0, name = $__1.name, email = $__1.email, password = $__1.password; return loadGateway.then(gatewayFn('signin', { name: name, email: email, password: password })); } function requestPasswordReset($__0) { var email = $__0.email; return loadGateway.then(gatewayFn('request-password-reset', {email: email})); } function resetPassword($__0) { var $__1 = $__0, token = $__1.token, password = $__1.password; return loadGateway.then(gatewayFn('reset-password', { token: token, password: password })); } return members; }; function gatewayFn(method) { var opts = arguments[1] !== (void 0) ? arguments[1] : {}; return function(gateway) { return new Promise(function(resolve, reject) { gateway.call(method, opts, function(err, res) { if (err) { reject(err); } resolve(res); }); }); }; } function loadFrame(src) { var container = arguments[1] !== (void 0) ? arguments[1] : document.body; return new Promise(function(resolve) { var frame = document.createElement('iframe'); frame.style.display = 'none'; frame.src = src; frame.onload = function() { resolve(frame); }; container.appendChild(frame); }); } //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/@tryghost/members-gateway-api/index.js },{"@tryghost/members-gateway-protocol":42,"minivents":39}],42:[function(require,module,exports){ "use strict"; module.exports = function layer0(frame) { var getuid = (function(i) { return function() { return i += 1; }; })(1); var origin = new URL(frame.getAttribute('src')).origin; var handlers = {}; var listener = null; window.addEventListener('message', function(event) { if (event.origin !== origin) { return; } if (!event.data || !event.data.uid) { if (event.data.event) { return listener && listener(event.data); } return; } var handler = handlers[event.data.uid]; if (!handler) { return; } delete handlers[event.data.uid]; handler(event.data.error, event.data.data); }); function call(method, options, cb) { var uid = getuid(); var data = { uid: uid, method: method, options: options }; handlers[uid] = cb; frame.contentWindow.postMessage(data, origin); } function listen(fn) { if (listener) { return false; } listener = fn; return true; } return { call: call, listen: listen }; }; //# sourceURL=/home/donny/usr/src/ghost.org/Members/node_modules/@tryghost/members-gateway-protocol/index.js },{}],43:[function(require,module,exports){ "use strict"; var each = require('lodash/each'); var browserAuth = require('@tryghost/members-browser-auth'); module.exports.init = init; function init($__0) { var siteUrl = $__0.siteUrl; var auth = browserAuth({membersUrl: siteUrl + '/members'}); var $__2 = window.location.hash.match(/^#([^?]+)\??(.*)$/) || [], hashMatch = $__2[0], hash = $__2[1], query = $__2[2]; if (hashMatch && hash === 'reset-password') { var $__3 = query.match(/token=([a-zA-Z0-9-_]+.[a-zA-Z0-9-_]+.[a-zA-Z0-9-_]+)/) || [], tokenMatch = $__3[0], token = $__3[1]; if (tokenMatch) { return auth.resetPassword({token: token}).then((function(success) { window.location.hash = ''; return success; })).then(reload); } } auth.on('signedin', function() { auth.getSSRToken({fresh: true}).then(function(token) { createSession(token); }); }); auth.on('signedout', function() { destroySession(); }); function signout() { auth.signout().then((function() { return destroySession(); })).then(reload); } function signin() { auth.signin().then((function() { return auth.getSSRToken({fresh: true}).then(function(token) { return createSession(token); }); })).then(reload); } function signup($__4) { var $__6; var $__5 = $__4, coupon = ($__6 = $__5.coupon) === void 0 ? '' : $__6; auth.signup({coupon: coupon}).then((function() { return auth.getSSRToken({fresh: true}).then(function(token) { return createSession(token); }); })).then(reload); } function upgrade() { auth.upgrade().then((function() { return auth.getSSRToken({fresh: true}).then(function(token) { return createSession(token); }); })).then(reload); } var signinEls = document.querySelectorAll('[data-members-signin]'); var signupEls = document.querySelectorAll('[data-members-signup]'); var upgradeEls = document.querySelectorAll('[data-members-upgrade]'); var signoutEls = document.querySelectorAll('[data-members-signout]'); each(signinEls, (function(el) { el.addEventListener('click', (function(event) { event.preventDefault(); signin(); })); })); each(signupEls, (function(el) { el.addEventListener('click', (function(event) { event.preventDefault(); var coupon = el.dataset.membersCoupon; signup({coupon: coupon}); })); })); each(upgradeEls, (function(el) { el.addEventListener('click', (function(event) { event.preventDefault(); upgrade(); })); })); each(signoutEls, (function(el) { el.addEventListener('click', (function(event) { event.preventDefault(); signout(); })); })); } function reload(success) { if (success) { window.location.reload(); } } function createSession(token) { return fetch('/members/ssr', { method: 'post', credentials: 'include', body: token }).then(function(res) { return !!res.ok; }); } function destroySession() { return fetch('/members/ssr', {method: 'delete'}).then(function(res) { return !!res.ok; }); } //# sourceURL=/home/donny/usr/src/ghost.org/Members/packages/members-theme-bindings/index.js },{"@tryghost/members-browser-auth":40,"lodash/each":25}]},{},[43])(43) });
!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e("object"==typeof exports?require("jquery"):jQuery)}(function(e){"use strict";function t(e){for(var t,n=e.split(/\s+/),a=[],o=0;t=n[o];o++)t=t.charAt(0).toUpperCase(),a.push(t);return a}function n(t){return t.id&&e('label[for="'+t.id+'"]').val()||t.name}function a(t,o,s){return s||(s=0),o.each(function(){var o,i,c=e(this),l=this,r=this.nodeName.toLowerCase();switch("label"===r&&c.find("input, textarea, select").length&&(o=c.text(),r=(l=(c=c.children().first()).get(0)).nodeName.toLowerCase()),r){case"menu":i={name:c.attr("label"),items:{}},s=a(i.items,c.children(),s);break;case"a":case"button":i={name:c.text(),disabled:!!c.attr("disabled"),callback:function(){c.get(0).click()}};break;case"menuitem":case"command":switch(c.attr("type")){case void 0:case"command":case"menuitem":i={name:c.attr("label"),disabled:!!c.attr("disabled"),icon:c.attr("icon"),callback:function(){c.get(0).click()}};break;case"checkbox":i={type:"checkbox",disabled:!!c.attr("disabled"),name:c.attr("label"),selected:!!c.attr("checked")};break;case"radio":i={type:"radio",disabled:!!c.attr("disabled"),name:c.attr("label"),radio:c.attr("radiogroup"),value:c.attr("id"),selected:!!c.attr("checked")};break;default:i=void 0}break;case"hr":i="-------";break;case"input":switch(c.attr("type")){case"text":i={type:"text",name:o||n(l),disabled:!!c.attr("disabled"),value:c.val()};break;case"checkbox":i={type:"checkbox",name:o||n(l),disabled:!!c.attr("disabled"),selected:!!c.attr("checked")};break;case"radio":i={type:"radio",name:o||n(l),disabled:!!c.attr("disabled"),radio:!!c.attr("name"),value:c.val(),selected:!!c.attr("checked")};break;default:i=void 0}break;case"select":i={type:"select",name:o||n(l),disabled:!!c.attr("disabled"),selected:c.val(),options:{}},c.children().each(function(){i.options[this.value]=e(this).text()});break;case"textarea":i={type:"textarea",name:o||n(l),disabled:!!c.attr("disabled"),value:c.val()};break;case"label":break;default:i={type:"html",html:c.clone(!0)}}i&&(t["key"+ ++s]=i)}),s}e.support.htmlMenuitem="HTMLMenuItemElement"in window,e.support.htmlCommand="HTMLCommandElement"in window,e.support.eventSelectstart="onselectstart"in document.documentElement,e.ui&&e.widget||(e.cleanData=function(t){return function(n){var a,o,s;for(s=0;null!=n[s];s++){o=n[s];try{(a=e._data(o,"events"))&&a.remove&&e(o).triggerHandler("remove")}catch(e){}}t(n)}}(e.cleanData));var o=null,s=!1,i=e(window),c=0,l={},r={},u={},d={selector:null,appendTo:null,trigger:"right",autoHide:!1,delay:200,reposition:!0,selectableSubMenu:!1,classNames:{hover:"context-menu-hover",disabled:"context-menu-disabled",visible:"context-menu-visible",notSelectable:"context-menu-not-selectable",icon:"context-menu-icon",iconEdit:"context-menu-icon-edit",iconCut:"context-menu-icon-cut",iconCopy:"context-menu-icon-copy",iconPaste:"context-menu-icon-paste",iconDelete:"context-menu-icon-delete",iconAdd:"context-menu-icon-add",iconQuit:"context-menu-icon-quit",iconLoadingClass:"context-menu-icon-loading"},determinePosition:function(t){if(e.ui&&e.ui.position)t.css("display","block").position({my:"center top",at:"center bottom",of:this,offset:"0 5",collision:"fit"}).css("display","none");else{var n=this.offset();n.top+=this.outerHeight(),n.left+=this.outerWidth()/2-t.outerWidth()/2,t.css(n)}},position:function(e,t,n){var a;if(t||n){if("maintain"===t&&"maintain"===n)a=e.$menu.position();else{var o=e.$menu.offsetParent().offset();a={top:n-o.top,left:t-o.left}}var s=i.scrollTop()+i.height(),c=i.scrollLeft()+i.width(),l=e.$menu.outerHeight(),r=e.$menu.outerWidth();a.top+l>s&&(a.top-=l),a.top<0&&(a.top=0),a.left+r>c&&(a.left-=r),a.left<0&&(a.left=0),e.$menu.css(a)}else e.determinePosition.call(this,e.$menu)},positionSubmenu:function(t){if(void 0!==t)if(e.ui&&e.ui.position)t.css("display","block").position({my:"left top-5",at:"right top",of:this,collision:"flipfit fit"}).css("display","");else{var n={top:-9,left:this.outerWidth()-5};t.css(n)}},zIndex:1,animation:{duration:50,show:"slideDown",hide:"slideUp"},events:{show:e.noop,hide:e.noop},callback:null,items:{}},m={timer:null,pageX:null,pageY:null},p=function(e){for(var t=0,n=e;;)if(t=Math.max(t,parseInt(n.css("z-index"),10)||0),!(n=n.parent())||!n.length||"html body".indexOf(n.prop("nodeName").toLowerCase())>-1)break;return t},f={abortevent:function(e){e.preventDefault(),e.stopImmediatePropagation()},contextmenu:function(t){var n=e(this);if("right"===t.data.trigger&&(t.preventDefault(),t.stopImmediatePropagation()),!("right"!==t.data.trigger&&"demand"!==t.data.trigger&&t.originalEvent||!(void 0===t.mouseButton||!t.data||"left"===t.data.trigger&&0===t.mouseButton||"right"===t.data.trigger&&2===t.mouseButton)||n.hasClass("context-menu-active")||n.hasClass("context-menu-disabled"))){if(o=n,t.data.build){var a=t.data.build(o,t);if(!1===a)return;if(t.data=e.extend(!0,{},d,t.data,a||{}),!t.data.items||e.isEmptyObject(t.data.items))throw window.console&&(console.error||console.log).call(console,"No items specified to show in contextMenu"),new Error("No Items specified");t.data.$trigger=o,h.create(t.data)}var s=!1;for(var i in t.data.items)if(t.data.items.hasOwnProperty(i)){(e.isFunction(t.data.items[i].visible)?t.data.items[i].visible.call(e(t.currentTarget),i,t.data):void 0===t.data.items[i]||!t.data.items[i].visible||!0===t.data.items[i].visible)&&(s=!0)}s&&h.show.call(n,t.data,t.pageX,t.pageY)}},click:function(t){t.preventDefault(),t.stopImmediatePropagation(),e(this).trigger(e.Event("contextmenu",{data:t.data,pageX:t.pageX,pageY:t.pageY}))},mousedown:function(t){var n=e(this);o&&o.length&&!o.is(n)&&o.data("contextMenu").$menu.trigger("contextmenu:hide"),2===t.button&&(o=n.data("contextMenuActive",!0))},mouseup:function(t){var n=e(this);n.data("contextMenuActive")&&o&&o.length&&o.is(n)&&!n.hasClass("context-menu-disabled")&&(t.preventDefault(),t.stopImmediatePropagation(),o=n,n.trigger(e.Event("contextmenu",{data:t.data,pageX:t.pageX,pageY:t.pageY}))),n.removeData("contextMenuActive")},mouseenter:function(t){var n=e(this),a=e(t.relatedTarget),s=e(document);a.is(".context-menu-list")||a.closest(".context-menu-list").length||o&&o.length||(m.pageX=t.pageX,m.pageY=t.pageY,m.data=t.data,s.on("mousemove.contextMenuShow",f.mousemove),m.timer=setTimeout(function(){m.timer=null,s.off("mousemove.contextMenuShow"),o=n,n.trigger(e.Event("contextmenu",{data:m.data,pageX:m.pageX,pageY:m.pageY}))},t.data.delay))},mousemove:function(e){m.pageX=e.pageX,m.pageY=e.pageY},mouseleave:function(t){var n=e(t.relatedTarget);if(!n.is(".context-menu-list")&&!n.closest(".context-menu-list").length){try{clearTimeout(m.timer)}catch(t){}m.timer=null}},layerClick:function(t){var n,a,o=e(this).data("contextMenuRoot"),s=t.button,c=t.pageX,l=t.pageY;t.preventDefault(),setTimeout(function(){var r,u="left"===o.trigger&&0===s||"right"===o.trigger&&2===s;if(document.elementFromPoint&&o.$layer){if(o.$layer.hide(),(n=document.elementFromPoint(c-i.scrollLeft(),l-i.scrollTop())).isContentEditable){var d=document.createRange(),m=window.getSelection();d.selectNode(n),d.collapse(!0),m.removeAllRanges(),m.addRange(d)}e(n).trigger(t),o.$layer.show()}if(o.reposition&&u)if(document.elementFromPoint){if(o.$trigger.is(n))return void o.position.call(o.$trigger,o,c,l)}else if(a=o.$trigger.offset(),r=e(window),a.top+=r.scrollTop(),a.top<=t.pageY&&(a.left+=r.scrollLeft(),a.left<=t.pageX&&(a.bottom=a.top+o.$trigger.outerHeight(),a.bottom>=t.pageY&&(a.right=a.left+o.$trigger.outerWidth(),a.right>=t.pageX))))return void o.position.call(o.$trigger,o,c,l);n&&u&&o.$trigger.one("contextmenu:hidden",function(){e(n).contextMenu({x:c,y:l,button:s})}),null!==o&&void 0!==o&&null!==o.$menu&&void 0!==o.$menu&&o.$menu.trigger("contextmenu:hide")},50)},keyStop:function(e,t){t.isInput||e.preventDefault(),e.stopPropagation()},key:function(e){var t={};o&&(t=o.data("contextMenu")||{}),void 0===t.zIndex&&(t.zIndex=0);var n=0,a=function(e){""!==e.style.zIndex?n=e.style.zIndex:null!==e.offsetParent&&void 0!==e.offsetParent?a(e.offsetParent):null!==e.parentElement&&void 0!==e.parentElement&&a(e.parentElement)};if(a(e.target),!(t.$menu&&parseInt(n,10)>parseInt(t.$menu.css("zIndex"),10))){switch(e.keyCode){case 9:case 38:if(f.keyStop(e,t),t.isInput){if(9===e.keyCode&&e.shiftKey)return e.preventDefault(),t.$selected&&t.$selected.find("input, textarea, select").blur(),void(null!==t.$menu&&void 0!==t.$menu&&t.$menu.trigger("prevcommand"));if(38===e.keyCode&&"checkbox"===t.$selected.find("input, textarea, select").prop("type"))return void e.preventDefault()}else if(9!==e.keyCode||e.shiftKey)return void(null!==t.$menu&&void 0!==t.$menu&&t.$menu.trigger("prevcommand"));break;case 40:if(f.keyStop(e,t),!t.isInput)return void(null!==t.$menu&&void 0!==t.$menu&&t.$menu.trigger("nextcommand"));if(9===e.keyCode)return e.preventDefault(),t.$selected&&t.$selected.find("input, textarea, select").blur(),void(null!==t.$menu&&void 0!==t.$menu&&t.$menu.trigger("nextcommand"));if(40===e.keyCode&&"checkbox"===t.$selected.find("input, textarea, select").prop("type"))return void e.preventDefault();break;case 37:if(f.keyStop(e,t),t.isInput||!t.$selected||!t.$selected.length)break;if(!t.$selected.parent().hasClass("context-menu-root")){var s=t.$selected.parent().parent();return t.$selected.trigger("contextmenu:blur"),void(t.$selected=s)}break;case 39:if(f.keyStop(e,t),t.isInput||!t.$selected||!t.$selected.length)break;var i=t.$selected.data("contextMenu")||{};if(i.$menu&&t.$selected.hasClass("context-menu-submenu"))return t.$selected=null,i.$selected=null,void i.$menu.trigger("nextcommand");break;case 35:case 36:return t.$selected&&t.$selected.find("input, textarea, select").length?void 0:((t.$selected&&t.$selected.parent()||t.$menu).children(":not(."+t.classNames.disabled+", ."+t.classNames.notSelectable+")")[36===e.keyCode?"first":"last"]().trigger("contextmenu:focus"),void e.preventDefault());case 13:if(f.keyStop(e,t),t.isInput){if(t.$selected&&!t.$selected.is("textarea, select"))return void e.preventDefault();break}return void(void 0!==t.$selected&&null!==t.$selected&&t.$selected.trigger("mouseup"));case 32:case 33:case 34:return void f.keyStop(e,t);case 27:return f.keyStop(e,t),void(null!==t.$menu&&void 0!==t.$menu&&t.$menu.trigger("contextmenu:hide"));default:var c=String.fromCharCode(e.keyCode).toUpperCase();if(t.accesskeys&&t.accesskeys[c])return void t.accesskeys[c].$node.trigger(t.accesskeys[c].$menu?"contextmenu:focus":"mouseup")}e.stopPropagation(),void 0!==t.$selected&&null!==t.$selected&&t.$selected.trigger(e)}},prevItem:function(t){t.stopPropagation();var n=e(this).data("contextMenu")||{},a=e(this).data("contextMenuRoot")||{};if(n.$selected){var o=n.$selected;(n=n.$selected.parent().data("contextMenu")||{}).$selected=o}for(var s=n.$menu.children(),i=n.$selected&&n.$selected.prev().length?n.$selected.prev():s.last(),c=i;i.hasClass(a.classNames.disabled)||i.hasClass(a.classNames.notSelectable)||i.is(":hidden");)if((i=i.prev().length?i.prev():s.last()).is(c))return;n.$selected&&f.itemMouseleave.call(n.$selected.get(0),t),f.itemMouseenter.call(i.get(0),t);var l=i.find("input, textarea, select");l.length&&l.focus()},nextItem:function(t){t.stopPropagation();var n=e(this).data("contextMenu")||{},a=e(this).data("contextMenuRoot")||{};if(n.$selected){var o=n.$selected;(n=n.$selected.parent().data("contextMenu")||{}).$selected=o}for(var s=n.$menu.children(),i=n.$selected&&n.$selected.next().length?n.$selected.next():s.first(),c=i;i.hasClass(a.classNames.disabled)||i.hasClass(a.classNames.notSelectable)||i.is(":hidden");)if((i=i.next().length?i.next():s.first()).is(c))return;n.$selected&&f.itemMouseleave.call(n.$selected.get(0),t),f.itemMouseenter.call(i.get(0),t);var l=i.find("input, textarea, select");l.length&&l.focus()},focusInput:function(){var t=e(this).closest(".context-menu-item"),n=t.data(),a=n.contextMenu,o=n.contextMenuRoot;o.$selected=a.$selected=t,o.isInput=a.isInput=!0},blurInput:function(){var t=e(this).closest(".context-menu-item").data(),n=t.contextMenu;t.contextMenuRoot.isInput=n.isInput=!1},menuMouseenter:function(){e(this).data().contextMenuRoot.hovering=!0},menuMouseleave:function(t){var n=e(this).data().contextMenuRoot;n.$layer&&n.$layer.is(t.relatedTarget)&&(n.hovering=!1)},itemMouseenter:function(t){var n=e(this),a=n.data(),o=a.contextMenu,s=a.contextMenuRoot;s.hovering=!0,t&&s.$layer&&s.$layer.is(t.relatedTarget)&&(t.preventDefault(),t.stopImmediatePropagation()),(o.$menu?o:s).$menu.children("."+s.classNames.hover).trigger("contextmenu:blur").children(".hover").trigger("contextmenu:blur"),n.hasClass(s.classNames.disabled)||n.hasClass(s.classNames.notSelectable)?o.$selected=null:n.trigger("contextmenu:focus")},itemMouseleave:function(t){var n=e(this),a=n.data(),o=a.contextMenu,s=a.contextMenuRoot;if(s!==o&&s.$layer&&s.$layer.is(t.relatedTarget))return void 0!==s.$selected&&null!==s.$selected&&s.$selected.trigger("contextmenu:blur"),t.preventDefault(),t.stopImmediatePropagation(),void(s.$selected=o.$selected=o.$node);o&&o.$menu&&o.$menu.hasClass("context-menu-visible")||n.trigger("contextmenu:blur")},itemClick:function(t){var n,a=e(this),o=a.data(),s=o.contextMenu,i=o.contextMenuRoot,c=o.contextMenuKey;if(!(!s.items[c]||a.is("."+i.classNames.disabled+", .context-menu-separator, ."+i.classNames.notSelectable)||a.is(".context-menu-submenu")&&!1===i.selectableSubMenu)){if(t.preventDefault(),t.stopImmediatePropagation(),e.isFunction(s.callbacks[c])&&Object.prototype.hasOwnProperty.call(s.callbacks,c))n=s.callbacks[c];else{if(!e.isFunction(i.callback))return;n=i.callback}!1!==n.call(i.$trigger,c,i,t)?i.$menu.trigger("contextmenu:hide"):i.$menu.parent().length&&h.update.call(i.$trigger,i)}},inputClick:function(e){e.stopImmediatePropagation()},hideMenu:function(t,n){var a=e(this).data("contextMenuRoot");h.hide.call(a.$trigger,a,n&&n.force)},focusItem:function(t){t.stopPropagation();var n=e(this),a=n.data(),o=a.contextMenu,s=a.contextMenuRoot;n.hasClass(s.classNames.disabled)||n.hasClass(s.classNames.notSelectable)||(n.addClass([s.classNames.hover,s.classNames.visible].join(" ")).parent().find(".context-menu-item").not(n).removeClass(s.classNames.visible).filter("."+s.classNames.hover).trigger("contextmenu:blur"),o.$selected=s.$selected=n,o&&o.$node&&o.$node.hasClass("context-menu-submenu")&&o.$node.addClass(s.classNames.hover),o.$node&&s.positionSubmenu.call(o.$node,o.$menu))},blurItem:function(t){t.stopPropagation();var n=e(this),a=n.data(),o=a.contextMenu,s=a.contextMenuRoot;o.autoHide&&n.removeClass(s.classNames.visible),n.removeClass(s.classNames.hover),o.$selected=null}},h={show:function(t,n,a){var s=e(this),i={};if(e("#context-menu-layer").trigger("mousedown"),t.$trigger=s,!1!==t.events.show.call(s,t)){if(h.update.call(s,t),t.position.call(s,t,n,a),t.zIndex){var c=t.zIndex;"function"==typeof t.zIndex&&(c=t.zIndex.call(s,t)),i.zIndex=p(s)+c}h.layer.call(t.$menu,t,i.zIndex),t.$menu.find("ul").css("zIndex",i.zIndex+1),t.$menu.css(i)[t.animation.show](t.animation.duration,function(){s.trigger("contextmenu:visible")}),s.data("contextMenu",t).addClass("context-menu-active"),e(document).off("keydown.contextMenu").on("keydown.contextMenu",f.key),t.autoHide&&e(document).on("mousemove.contextMenuAutoHide",function(e){var n=s.offset();n.right=n.left+s.outerWidth(),n.bottom=n.top+s.outerHeight(),!t.$layer||t.hovering||e.pageX>=n.left&&e.pageX<=n.right&&e.pageY>=n.top&&e.pageY<=n.bottom||setTimeout(function(){t.hovering||null===t.$menu||void 0===t.$menu||t.$menu.trigger("contextmenu:hide")},50)})}else o=null},hide:function(t,n){var a=e(this);if(t||(t=a.data("contextMenu")||{}),n||!t.events||!1!==t.events.hide.call(a,t)){if(a.removeData("contextMenu").removeClass("context-menu-active"),t.$layer){setTimeout(function(e){return function(){e.remove()}}(t.$layer),10);try{delete t.$layer}catch(e){t.$layer=null}}o=null,t.$menu.find("."+t.classNames.hover).trigger("contextmenu:blur"),t.$selected=null,t.$menu.find("."+t.classNames.visible).removeClass(t.classNames.visible),e(document).off(".contextMenuAutoHide").off("keydown.contextMenu"),t.$menu&&t.$menu[t.animation.hide](t.animation.duration,function(){t.build&&(t.$menu.remove(),e.each(t,function(e){switch(e){case"ns":case"selector":case"build":case"trigger":return!0;default:t[e]=void 0;try{delete t[e]}catch(e){}return!0}})),setTimeout(function(){a.trigger("contextmenu:hidden")},10)})}},create:function(n,a){function o(t){var n=e("<span></span>");if(t._accesskey)t._beforeAccesskey&&n.append(document.createTextNode(t._beforeAccesskey)),e("<span></span>").addClass("context-menu-accesskey").text(t._accesskey).appendTo(n),t._afterAccesskey&&n.append(document.createTextNode(t._afterAccesskey));else if(t.isHtmlName){if(void 0!==t.accesskey)throw new Error("accesskeys are not compatible with HTML names and cannot be used together in the same item");n.html(t.name)}else n.text(t.name);return n}void 0===a&&(a=n),n.$menu=e('<ul class="context-menu-list"></ul>').addClass(n.className||"").data({contextMenu:n,contextMenuRoot:a}),e.each(["callbacks","commands","inputs"],function(e,t){n[t]={},a[t]||(a[t]={})}),a.accesskeys||(a.accesskeys={}),e.each(n.items,function(s,i){var c=e('<li class="context-menu-item"></li>').addClass(i.className||""),l=null,r=null;if(c.on("click",e.noop),"string"!=typeof i&&"cm_separator"!==i.type||(i={type:"cm_seperator"}),i.$node=c.data({contextMenu:n,contextMenuRoot:a,contextMenuKey:s}),void 0!==i.accesskey)for(var d,m=t(i.accesskey),p=0;d=m[p];p++)if(!a.accesskeys[d]){a.accesskeys[d]=i;var x=i.name.match(new RegExp("^(.*?)("+d+")(.*)$","i"));x&&(i._beforeAccesskey=x[1],i._accesskey=x[2],i._afterAccesskey=x[3]);break}if(i.type&&u[i.type])u[i.type].call(c,i,n,a),e.each([n,a],function(t,a){a.commands[s]=i,!e.isFunction(i.callback)||void 0!==a.callbacks[s]&&void 0!==n.type||(a.callbacks[s]=i.callback)});else{switch("cm_seperator"===i.type?c.addClass("context-menu-separator "+a.classNames.notSelectable):"html"===i.type?c.addClass("context-menu-html "+a.classNames.notSelectable):"sub"===i.type||(i.type?(l=e("<label></label>").appendTo(c),o(i).appendTo(l),c.addClass("context-menu-input"),n.hasTypes=!0,e.each([n,a],function(e,t){t.commands[s]=i,t.inputs[s]=i})):i.items&&(i.type="sub")),i.type){case"cm_seperator":break;case"text":r=e('<input type="text" value="1" name="" />').attr("name","context-menu-input-"+s).val(i.value||"").appendTo(l);break;case"textarea":r=e('<textarea name=""></textarea>').attr("name","context-menu-input-"+s).val(i.value||"").appendTo(l),i.height&&r.height(i.height);break;case"checkbox":r=e('<input type="checkbox" value="1" name="" />').attr("name","context-menu-input-"+s).val(i.value||"").prop("checked",!!i.selected).prependTo(l);break;case"radio":r=e('<input type="radio" value="1" name="" />').attr("name","context-menu-input-"+i.radio).val(i.value||"").prop("checked",!!i.selected).prependTo(l);break;case"select":r=e('<select name=""></select>').attr("name","context-menu-input-"+s).appendTo(l),i.options&&(e.each(i.options,function(t,n){e("<option></option>").val(t).text(n).appendTo(r)}),r.val(i.selected));break;case"sub":o(i).appendTo(c),i.appendTo=i.$node,c.data("contextMenu",i).addClass("context-menu-submenu"),i.callback=null,"function"==typeof i.items.then?h.processPromises(i,a,i.items):h.create(i,a);break;case"html":e(i.html).appendTo(c);break;default:e.each([n,a],function(t,a){a.commands[s]=i,!e.isFunction(i.callback)||void 0!==a.callbacks[s]&&void 0!==n.type||(a.callbacks[s]=i.callback)}),o(i).appendTo(c)}i.type&&"sub"!==i.type&&"html"!==i.type&&"cm_seperator"!==i.type&&(r.on("focus",f.focusInput).on("blur",f.blurInput),i.events&&r.on(i.events,n)),i.icon&&(e.isFunction(i.icon)?i._icon=i.icon.call(this,this,c,s,i):"string"==typeof i.icon&&"fa-"===i.icon.substring(0,3)?i._icon=a.classNames.icon+" "+a.classNames.icon+"--fa fa "+i.icon:i._icon=a.classNames.icon+" "+a.classNames.icon+"-"+i.icon,c.addClass(i._icon))}i.$input=r,i.$label=l,c.appendTo(n.$menu),!n.hasTypes&&e.support.eventSelectstart&&c.on("selectstart.disableTextSelect",f.abortevent)}),n.$node||n.$menu.css("display","none").addClass("context-menu-root"),n.$menu.appendTo(n.appendTo||document.body)},resize:function(t,n){var a;t.css({position:"absolute",display:"block"}),t.data("width",(a=t.get(0)).getBoundingClientRect?Math.ceil(a.getBoundingClientRect().width):t.outerWidth()+1),t.css({position:"static",minWidth:"0px",maxWidth:"100000px"}),t.find("> li > ul").each(function(){h.resize(e(this),!0)}),n||t.find("ul").addBack().css({position:"",display:"",minWidth:"",maxWidth:""}).outerWidth(function(){return e(this).data("width")})},update:function(t,n){var a=this;void 0===n&&(n=t,h.resize(t.$menu)),t.$menu.children().each(function(){var o,s=e(this),i=s.data("contextMenuKey"),c=t.items[i],l=e.isFunction(c.disabled)&&c.disabled.call(a,i,n)||!0===c.disabled;if(o=e.isFunction(c.visible)?c.visible.call(a,i,n):void 0===c.visible||!0===c.visible,s[o?"show":"hide"](),s[l?"addClass":"removeClass"](n.classNames.disabled),e.isFunction(c.icon)&&(s.removeClass(c._icon),c._icon=c.icon.call(this,a,s,i,c),s.addClass(c._icon)),c.type)switch(s.find("input, select, textarea").prop("disabled",l),c.type){case"text":case"textarea":c.$input.val(c.value||"");break;case"checkbox":case"radio":c.$input.val(c.value||"").prop("checked",!!c.selected);break;case"select":c.$input.val((0===c.selected?"0":c.selected)||"")}c.$menu&&h.update.call(a,c,n)})},layer:function(t,n){var a=t.$layer=e('<div id="context-menu-layer"></div>').css({height:i.height(),width:i.width(),display:"block",position:"fixed","z-index":n,top:0,left:0,opacity:0,filter:"alpha(opacity=0)","background-color":"#000"}).data("contextMenuRoot",t).insertBefore(this).on("contextmenu",f.abortevent).on("mousedown",f.layerClick);return void 0===document.body.style.maxWidth&&a.css({position:"absolute",height:e(document).height()}),a},processPromises:function(e,t,n){function a(e,t,n){void 0===n?(n={error:{name:"No items and no error item",icon:"context-menu-icon context-menu-icon-quit"}},window.console&&(console.error||console.log).call(console,'When you reject a promise, provide an "items" object, equal to normal sub-menu items')):"string"==typeof n&&(n={error:{name:n}}),o(e,t,n)}function o(e,t,n){void 0!==t.$menu&&t.$menu.is(":visible")&&(e.$node.removeClass(t.classNames.iconLoadingClass),e.items=n,h.create(e,t,!0),h.update(e,t),t.positionSubmenu.call(e.$node,e.$menu))}e.$node.addClass(t.classNames.iconLoadingClass),n.then(function(e,t,n){void 0===n&&a(void 0),o(e,t,n)}.bind(this,e,t),a.bind(this,e,t))}};e.fn.contextMenu=function(t){var n=this,a=t;if(this.length>0)if(void 0===t)this.first().trigger("contextmenu");else if(void 0!==t.x&&void 0!==t.y)this.first().trigger(e.Event("contextmenu",{pageX:t.x,pageY:t.y,mouseButton:t.button}));else if("hide"===t){var o=this.first().data("contextMenu")?this.first().data("contextMenu").$menu:null;o&&o.trigger("contextmenu:hide")}else"destroy"===t?e.contextMenu("destroy",{context:this}):e.isPlainObject(t)?(t.context=this,e.contextMenu("create",t)):t?this.removeClass("context-menu-disabled"):t||this.addClass("context-menu-disabled");else e.each(r,function(){this.selector===n.selector&&(a.data=this,e.extend(a.data,{trigger:"demand"}))}),f.contextmenu.call(a.target,a);return this},e.contextMenu=function(t,n){"string"!=typeof t&&(n=t,t="create"),"string"==typeof n?n={selector:n}:void 0===n&&(n={});var a=e.extend(!0,{},d,n||{}),o=e(document),i=o,u=!1;switch(a.context&&a.context.length?(i=e(a.context).first(),a.context=i.get(0),u=!e(a.context).is(document)):a.context=document,t){case"create":if(!a.selector)throw new Error("No selector specified");if(a.selector.match(/.context-menu-(list|item|input)($|\s)/))throw new Error('Cannot bind to selector "'+a.selector+'" as it contains a reserved className');if(!a.build&&(!a.items||e.isEmptyObject(a.items)))throw new Error("No Items specified");if(c++,a.ns=".contextMenu"+c,u||(l[a.selector]=a.ns),r[a.ns]=a,a.trigger||(a.trigger="right"),!s){var m="click"===a.itemClickEvent?"click.contextMenu":"mouseup.contextMenu",p={"contextmenu:focus.contextMenu":f.focusItem,"contextmenu:blur.contextMenu":f.blurItem,"contextmenu.contextMenu":f.abortevent,"mouseenter.contextMenu":f.itemMouseenter,"mouseleave.contextMenu":f.itemMouseleave};p[m]=f.itemClick,o.on({"contextmenu:hide.contextMenu":f.hideMenu,"prevcommand.contextMenu":f.prevItem,"nextcommand.contextMenu":f.nextItem,"contextmenu.contextMenu":f.abortevent,"mouseenter.contextMenu":f.menuMouseenter,"mouseleave.contextMenu":f.menuMouseleave},".context-menu-list").on("mouseup.contextMenu",".context-menu-input",f.inputClick).on(p,".context-menu-item"),s=!0}switch(i.on("contextmenu"+a.ns,a.selector,a,f.contextmenu),u&&i.on("remove"+a.ns,function(){e(this).contextMenu("destroy")}),a.trigger){case"hover":i.on("mouseenter"+a.ns,a.selector,a,f.mouseenter).on("mouseleave"+a.ns,a.selector,a,f.mouseleave);break;case"left":i.on("click"+a.ns,a.selector,a,f.click);break;case"touchstart":i.on("touchstart"+a.ns,a.selector,a,f.click)}a.build||h.create(a);break;case"destroy":var x;if(u){var v=a.context;e.each(r,function(t,n){if(!n)return!0;if(!e(v).is(n.selector))return!0;(x=e(".context-menu-list").filter(":visible")).length&&x.data().contextMenuRoot.$trigger.is(e(n.context).find(n.selector))&&x.trigger("contextmenu:hide",{force:!0});try{r[n.ns].$menu&&r[n.ns].$menu.remove(),delete r[n.ns]}catch(e){r[n.ns]=null}return e(n.context).off(n.ns),!0})}else if(a.selector){if(l[a.selector]){(x=e(".context-menu-list").filter(":visible")).length&&x.data().contextMenuRoot.$trigger.is(a.selector)&&x.trigger("contextmenu:hide",{force:!0});try{r[l[a.selector]].$menu&&r[l[a.selector]].$menu.remove(),delete r[l[a.selector]]}catch(e){r[l[a.selector]]=null}o.off(l[a.selector])}}else o.off(".contextMenu .contextMenuAutoHide"),e.each(r,function(t,n){e(n.context).off(n.ns)}),l={},r={},c=0,s=!1,e("#context-menu-layer, .context-menu-list").remove();break;case"html5":(!e.support.htmlCommand&&!e.support.htmlMenuitem||"boolean"==typeof n&&n)&&e('menu[type="context"]').each(function(){this.id&&e.contextMenu({selector:"[contextmenu="+this.id+"]",items:e.contextMenu.fromMenu(this)})}).css("display","none");break;default:throw new Error('Unknown operation "'+t+'"')}return this},e.contextMenu.setInputValues=function(t,n){void 0===n&&(n={}),e.each(t.inputs,function(e,t){switch(t.type){case"text":case"textarea":t.value=n[e]||"";break;case"checkbox":t.selected=!!n[e];break;case"radio":t.selected=(n[t.radio]||"")===t.value;break;case"select":t.selected=n[e]||""}})},e.contextMenu.getInputValues=function(t,n){return void 0===n&&(n={}),e.each(t.inputs,function(e,t){switch(t.type){case"text":case"textarea":case"select":n[e]=t.$input.val();break;case"checkbox":n[e]=t.$input.prop("checked");break;case"radio":t.$input.prop("checked")&&(n[t.radio]=t.value)}}),n},e.contextMenu.fromMenu=function(t){var n={};return a(n,e(t).children()),n},e.contextMenu.defaults=d,e.contextMenu.types=u,e.contextMenu.handle=f,e.contextMenu.op=h,e.contextMenu.menus=r}); //# sourceMappingURL=jquery.contextMenu.min.js.map
self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "e0e33bf88c87951140c68b365d393ae0", "url": "/index.html" }, { "revision": "aa9b81dec490d3c728c3", "url": "/static/css/main.084116ef.chunk.css" }, { "revision": "d32517dbc56c85792bd6", "url": "/static/js/2.7618e04a.chunk.js" }, { "revision": "aef280276b8d6f56e9d8dc46988119d9", "url": "/static/js/2.7618e04a.chunk.js.LICENSE.txt" }, { "revision": "aa9b81dec490d3c728c3", "url": "/static/js/main.409bc656.chunk.js" }, { "revision": "e666292ccc221b8a2b4d", "url": "/static/js/runtime-main.8bf54f37.js" } ]);
const fs = require('fs'); const filename = require('minimist')(process.argv.slice(2)).file; const readline = require('readline'); const reader = readline.createInterface(process.stdin, process.stdout); const app = { //Создаем массив с картами getCardsArr : ()=>{ return new Map([ [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8], [9, 9], [10,10], ['Королева', 10], ['Король', 10], ['Валет', 10], ['Туз', 11] ]); }, //Создаем массив с мастями suits : new Map([ ['diamonds', '♦'], ['hearts', '♥'], ['spades', '♠'], ['clubs', '♣'] ]), //Генерация полной колоды generateDeck : function (){ let fullDeck = new Map(); for(let suit of this.suits.keys()) { fullDeck.set(suit, this.getCardsArr()); } return fullDeck; }, getRandomCard : function(){ //Отдаем рандомную карту и удаляем из колоды let deck = this.deck; let suits = Array.from(deck); let suit = suits[Math.floor(Math.random() * suits.length)]; let cards = Array.from(suit[1]); let suitKey = suit[0]; let cardRandom = cards[Math.floor(Math.random() * cards.length)]; let cardRandomKey = cardRandom[0]; deck.get(suitKey).delete(cardRandomKey); return cardRandom; }, player : { points: 0, wins: 0 }, ai : { points: 0, wins: 0 }, plays: 0, deck: null, play: function(){ const that = this; reader.question('\nХотите начать игру? (да/нет) ', function(text) { if (text === "нет") { console.log('Игра не начата'); reader.close(); }else if(text === "да"){ that.deck = that.generateDeck(); const dealerFirstCard = that.generateStartScore(); console.log('Игра начата, первая карта дилера: ', dealerFirstCard); that.listener(); }else{ console.log('Введен не верный ответ'); that.reset(); that.play(); } }); }, generateStartScore: function(){ const p = this.player; const ai = this.ai; p.points = this.getRandomCard()[1] + this.getRandomCard()[1]; const aiFirstCard = this.getRandomCard(); ai.points = aiFirstCard[1] + this.getRandomCard()[1]; if(p.points>21 || ai.points>21){ this.generateStartScore(); } return aiFirstCard; }, move: function(){ let card = this.getRandomCard(); let p = this.player; p.points += card[1]; console.log('Вы взяли карту ', card); this.listener(); }, aiMove: function(){ const card = this.getRandomCard(); const ai = this.ai; let random = (min, max) => { return Math.floor(Math.random() * (max - min + 1)) + min; } let decide = () => { return (Math.floor(Math.random() * 2) === 0); } if(ai.points <= 2 || ai.points <= 15){ ai.points += card[1]; this.aiMove(); }else if(ai.points <=16 + random(1,4)){ //Рандомизируем проверку в рискованных случаях if(decide()){ //Рандомизируем решение в рискованных случаях ai.points += card[1]; this.aiMove(); }else{ this.checkPoints(); } }else if(ai.points == 21){ this.checkPoints(); }else if(ai.points > 21){ this.checkPoints(); } }, endGame: function(result){ if(result === 'ai'){ console.log('\nВы проиграли! Ваш счет: ', this.player.points); console.log('Счет дилера: ', this.ai.points); this.ai.wins += 1; }else if(result === 'player'){ console.log('\nВы выиграли! Ваш счет: ', this.player.points); console.log('Счет дилера: ', this.ai.points); this.player.wins += 1; }else if(result === 'middle'){ console.log('\nНичья! Ваш счет: ', this.player.points); console.log('Счет дилера: ', this.ai.points); } console.log('****Счёт:****\n Игрок: ', this.player.wins, 'побед'); console.log('*************\n Компьтер: ', this.ai.wins, 'побед'); this.writeLog(result); this.reset(); this.play(); }, checkPoints: function(){ const playerScore = this.player.points; const aiScore = this.ai.points; if(playerScore > 21){ this.endGame('ai'); }else if(playerScore == 21 && aiScore == 21){ this.endGame('middle'); }else if(playerScore > 21 && aiScore > 21){ this.endGame('middle'); }else if(playerScore == aiScore){ this.endGame('middle'); }else if(playerScore == 21){ this.endGame('player'); }else if(playerScore < 21 && aiScore > 21){ this.endGame('player'); }else if(playerScore < 21 && playerScore > aiScore){ this.endGame('player'); }else if((playerScore < 21 && playerScore < aiScore) && aiScore < 21){ this.endGame('ai'); }else if(playerScore < 21 && aiScore == 21){ this.endGame('ai'); } this.plays++; }, listener: function(){ const that = this; reader.question('Ваш счёт ' + that.player.points + '.\nХотите взять карту? (да/нет) ', (line) => { if (line == "нет") { that.aiMove(); }else if(line == "да"){ that.move(); }else{ console.log('Введите да или нет'); that.listener(); } }); }, reset: function(){ this.player.points = 0; this.ai.points = 0; }, writeLog: function(winner){ const filenameFull = filename + '.json'; if(typeof filename === 'undefined'){ return; }else{ let gameLog = { gameNum: this.plays, winner: winner, player: { wins: this.player.wins, points: this.player.points }, ai: { wins: this.ai.wins, points: this.ai.points } }; let gamelogStr = JSON.stringify(gameLog); if(!fs.exists(filenameFull)){ fs.writeFile(filenameFull, gamelogStr); console.log(fs.exists(filenameFull)); }else{ fs.appendFile(filenameFull, gamelogStr); } } } } app.play();
hackApp.service( 'AuthService', [ '$q', 'ApiService', '$injector', function ( $q, ApiService, $injector ) { var me = this; me.token = undefined; var isLogged = function ( ) { return angular.isDefined( me.token ); }; var getToken = function ( ) { return me.token; }; var setToken = function ( uToken ) { return me.token = uToken; }; var logout = function ( ) { token = undefined; }; var login = function ( userApiToken ) { var loginDeferred = $q.defer(); ApiService.login( { token : userApiToken } ).$promise .then( function ( response ) { me.token = userApiToken; var cookies = $injector.get( '$cookies' ); cookies.put( 'u-token', userApiToken ); loginDeferred.resolve( true ); } ) .catch( function ( error ) { me.token = undefined; loginDeferred.reject( 'Token invalid.' ); } ); return loginDeferred.promise; }; return { isLogged : isLogged, getToken : getToken, setToken : setToken, logout : logout, login : login } } ] );
//v.3.6 build 130417 /* Copyright DHTMLX LTD. http://www.dhtmlx.com You allowed to use this component or parts of it under GPL terms To use it on other terms or get Professional edition of the component please contact us at sales@dhtmlx.com */ /** * @desc: constructor, creates a single window under dhtmlxWindows system * @pseudonym: win * @type: public */ function dhtmlXWindowsSngl(){ } /** * @desc: constructor, creates a button for a window under dhtmlxWindows system * @pseudonym: btn * @type: public */ function dhtmlXWindowsBtn(){ } /** * @desc: constructor, creates a new dhtmlxWindows object * @type: public */ function dhtmlXWindows() { if (!window.dhtmlXContainer) { alert(this.i18n.dhx); return; } // engine this.engine = "dhx"; // this.engine = "clear"; var engineFunc = "_"+this.engine+"_Engine"; if (!this[engineFunc]) { alert(this.i18n.noenginealert); return; } else { this[engineFunc](); } this._isIPad = (navigator.userAgent.search(/iPad/gi)>=0); var that = this; // image manipulation this.pathPrefix = "dhxwins_"; this.imagePath = dhtmlx.image_path||"codebase/imgs/"; /** * @desc: sets path to the directory where used images are located * @param: path - url to the directory where images are located * @type: public */ this.setImagePath = function(path) { this.imagePath = path; } // skins this.skin = (typeof(dhtmlx) != "undefined" && typeof(dhtmlx.skin) == "string" ? dhtmlx.skin : "dhx_skyblue"); this.skinParams = { // dhx "dhx_black" : { "header_height": 21, "border_left_width": 2, "border_right_width": 2, "border_bottom_height": 2 }, "dhx_blue" : { "header_height": 21, "border_left_width": 2, "border_right_width": 2, "border_bottom_height": 2 }, "dhx_skyblue" : { "header_height": 21, "border_left_width": 2, "border_right_width": 2, "border_bottom_height": 2 } }; /** * @desc: changes window's skin * @param: skin - skin's name * @type: public */ this.setSkin = function(skin) { this.skin = skin; this._engineRedrawSkin(); //this.skin = skin; //this._redrawSkin(); } /* this._redrawSkin = function() { for (var a in this.wins) { var win = this.wins[a]; var skinParams = (win._skinParams!=null?win._skinParams:this.skinParams[this.skin]); // win.childNodes[0].className = "dhtmlx_wins_"+this.skin; // icon win.childNodes[1].className = "dhtmlx_wins_icon_"+this.skin; this._restoreWindowIcons(win); // title win.childNodes[2].className = "dhtmlx_wins_title_"+this.skin; // butons win.childNodes[3].className = "dhtmlx_wins_buttons_"+this.skin; // this._redrawWindow(win); // this._engineRedrawWindowSize(win); alert("stop PGhNyVSe"); } // this._restoreWindowIcons(this.getTopmostWindow()); } */ // return true if window with specified id is exists /** * @desc: returns true if the window with specified id exists * @param: id * @type: public */ this.isWindow = function(id) { var t = (this.wins[id] != null); return t; } //#wind_uber:09062008{ // return array of handlers finded by text /** * @desc: returns array of window handlers found by header text * @param: id * @type: public */ this.findByText = function(text) { var wins = new Array(); for (var a in this.wins) { if (this.wins[a].getText().search(text, "gi") >= 0) { wins[wins.length] = this.wins[a]; } } return wins; } //#} // return handler by id /** * @desc: returns the window handler (dhtmlXWindowSngl object) found by id * @param: id * @type: public */ this.window = function(id) { var win = null; if (this.wins[id] != null) { win = this.wins[id]; } return win; } //#wind_uber:09062008{ // iterator /** * @desc: iterator - goes through all windows and calls a user handler * @param: hander (user function) * @type: public */ this.forEachWindow = function(handler) { for (var a in this.wins) { handler(this.wins[a]); } } // return bottommost focused window handler /** * @desc: returns the bottommost window * @type: public */ this.getBottommostWindow = function() { var bottommost = this.getTopmostWindow(); for (var a in this.wins) { if (this.wins[a].zi < bottommost.zi) { bottommost = this.wins[a]; } } return (bottommost.zi != 0 ? bottommost : null); } //#} // return topmost focused window handler /** * @desc: returns the topmost window * @type: public */ this.getTopmostWindow = function(visibleOnly) { var topmost = {"zi": 0}; for (var a in this.wins) { if (this.wins[a].zi > topmost.zi) { if (visibleOnly == true && !this._isWindowHidden(this.wins[a])) { topmost = this.wins[a]; } if (visibleOnly != true) { topmost = this.wins[a]; } } } return (topmost.zi != 0 ? topmost : null); } // windows storage this.wins = {}; for (var a in this.wins) delete this.wins[a]; // viewport this.autoViewport = true; this._createViewport = function() { this.vp = document.body; this._clearVPCss(); this.vp._css = (String(this.vp.className).length > 0 ? this.vp.className : ""); this.vp.className += " dhtmlx_skin_"+this.skin+(this._r?" dhx_wins_rtl":""); // modal cover this.modalCoverI = document.createElement("IFRAME"); this.modalCoverI.frameBorder = "0"; this.modalCoverI.className = "dhx_modal_cover_ifr"; this.modalCoverI.setAttribute("src","javascript:false;"); this.modalCoverI.style.display = "none"; this.modalCoverI.style.zIndex = 0; this.vp.appendChild(this.modalCoverI); this.modalCoverD = document.createElement("DIV"); this.modalCoverD.className = "dhx_modal_cover_dv"; this.modalCoverD.style.display = "none"; this.modalCoverD.style.zIndex = 0; this.vp.appendChild(this.modalCoverD); // vp move/resize cover this._vpcover = document.createElement("DIV"); this._vpcover.className = "dhx_content_vp_cover"; this._vpcover.style.display = "none"; this.vp.appendChild(this._vpcover); // resize/move carcass this._carcass = document.createElement("DIV"); this._carcass.className = "dhx_carcass_resmove"; this._carcass.style.display = "none"; if (_isIE) { this._carcass.innerHTML = "<iframe border=0 frameborder=0 style='filter: alpha(opacity=0); width: 100%; height:100%; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; z-index:1;'></iframe>"+ "<div style='position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;z-index:2;background:white;filter:alpha(opacity=0);opacity:0;'></div>"; if (navigator.userAgent.indexOf("MSIE 10") >= 0) { } else { this._carcass.childNodes[0].setAttribute("src","javascript:false;"); } } this._carcass.onselectstart = function(e) { e = e||event; e.returnValue = false; } this.vp.appendChild(this._carcass); } this._clearVPCss = function(css) { this.vp.className = String(this.vp.className).replace(/[a-z_]{1,}/gi,function(t){return({"dhtmlx_skin_dhx_skyblue":1,"dhtmlx_skin_dhx_blue":1,"dhtmlx_skin_dhx_black":1,"dhtmlx_skin_dhx_web":1,"dhtmlx_skin_dhx_terrace":1}[t]==1?"":t);}); } this._autoResizeViewport = function() { for (var a in this.wins) { if (this.wins[a]._isFullScreened) { /* this.wins[a]._content.style.width = document.body.offsetWidth-(_isIE?4:0)+"px"; // doctype fix if (document.body.offsetHeight == 0) { if (window.innerHeight) { this.wins[a]._content.style.height = window.innerHeight+"px"; } else { this.wins[a]._content.style.height = document.body.scrollHeight+"px"; } } else { this.wins[a]._content.style.height = document.body.offsetHeight-(_isIE?4:0)+"px"; } // this.wins[a]._content.style.height = document.body.offsetHeight-(_isIE?4:0)+"px"; if (this.wins[a].layout != null && _isOpera) { this.wins[a].layout._fixCellsContentOpera950(); } this.wins[a].updateNestedObjects(); */ this.wins[a].adjustContent(document.body, 0, 0, false, 0); this.wins[a].updateNestedObjects(); } if (this.wins[a]._isMaximized && this.wins[a].style.display != "none") { this._restoreWindow(a); this._maximizeWindow(a); } } if (this.vp == document.body) return; if (this.autoViewport == false) return; this.vp.style.width = (_isIE ? document.body.offsetWidth - 4 : window.innerWidth) + "px"; this.vp.style.height = (_isIE ? document.body.offsetHeight - 4 : window.innerHeight) + "px"; // // check windows out of viewports edge for (var a in this.wins) { var win = this.wins[a]; var overX = false; var overY = false; if (win.x > this.vp.offsetWidth - 10) { win.x = this.vp.offsetWidth - 10; overX = true; } var skinParams = (win._skinParams!=null?win._skinParams:this.skinParams[this.skin]); if (win.y + skinParams["header_height"] > this.vp.offsetHeight) { win.y = this.vp.offsetHeight - skinParams["header_height"]; overY = true; } if (overX || overY) { // this._redrawWindow(win); this._engineRedrawWindowPos(win); } } } /** * @desc: if true - allows an object to adjust the viewport automatically to document.body * @param: state - true|false * @type: public */ this.enableAutoViewport = function(state) { if (this.vp != document.body) return; this.autoViewport = state; if (state == false) { // clear old vp if (this.vp == document.body) document.body.className = this.vp._css; this.vp.removeChild(this.modalCoverI); this.vp.removeChild(this.modalCoverD); this.vp.removeChild(this._vpcover); this.vp.removeChild(this._carcass); this.vp = null; // create a new one this.vp = document.createElement("DIV"); this.vp.autocreated = true; this.vp.className = "dhtmlx_winviewport dhtmlx_skin_"+this.skin+(this._r?" dhx_wins_rtl":""); this.vp.style.left = "0px"; this.vp.style.top = "0px"; document.body.appendChild(this.vp); this.vp.ax = 0; this.vp.ay = 0; this._autoResizeViewport(); this.vp.appendChild(this.modalCoverI); this.vp.appendChild(this.modalCoverD); this.vp.appendChild(this._vpcover); this.vp.appendChild(this._carcass); } } /** * @desc: attaches a vp to an existing object on page (renders an object as a viewport) * @param: objId - object id * @type: public */ this.attachViewportTo = function(objId) { if (this.autoViewport == false) { // clear old vp this.vp.removeChild(this.modalCoverI); this.vp.removeChild(this.modalCoverD); this.vp.removeChild(this._vpcover); this.vp.removeChild(this._carcass); if (this.vp != document.body) this.vp.parentNode.removeChild(this.vp); this.vp = null; // create a new one this.vp = (typeof(objId)=="string"?document.getElementById(objId):objId); this.vp.autocreated = false; this._clearVPCss(); this.vp.className += " dhtmlx_skin_"+this.skin+(this._r?" dhx_wins_rtl":""); this.vp.style.position = "relative"; this.vp.style.overflow = "hidden"; this.vp.ax = 0; this.vp.ay = 0; // attach data this.vp.appendChild(this.modalCoverI); this.vp.appendChild(this.modalCoverD); this.vp.appendChild(this._vpcover); this.vp.appendChild(this._carcass); } } /** * @desc: sets user-defined viewport if enableAutoViewport(false) * @param: x - top-left viewport corner's X-coordinate * @param: y - top-left viewport corner's Y-coordinate * @param: width - viewport's width * @param: height - viewport's height * @type: public */ this.setViewport = function(x, y, width, height, parentObj) { if (this.autoViewport == false) { this.vp.style.left = x + "px"; this.vp.style.top = y + "px"; this.vp.style.width = width + "px"; this.vp.style.height = height + "px"; // attach to parent if (parentObj != null) { parentObj.appendChild(this.vp); } this.vp.ax = getAbsoluteLeft(this.vp); this.vp.ay = getAbsoluteTop(this.vp); } } // effects this._effects = {"move" : false, "resize" : false}; /** * @desc: sets a visual effect * @param: efName - effect's name * @param: efValue - true/false to enable/disable * @type: public */ this.setEffect = function(efName, efValue) { if ((this._effects[efName] != null) && (typeof(efValue) == "boolean")) { this._effects[efName] = efValue; } } /** * @desc: returns true if the effect is enabled * @param: efName - effect's name * @type: public */ this.getEffect = function(efName) { return this._effects[efName]; } // windows /** * @desc: creates a new window and returns its handler * @param: id - window's id * @param: x - top-left window corner's X-coordinate * @param: y - top-left window corner's Y-coordinate * @param: width - window's width * @param: height - window's height * @type: public */ this.createWindow = function(id, x, y, width, height) { var win = document.createElement("DIV"); // win.className = "dhtmlx_window_inactive"; win.className = "dhtmlx_window_inactive"; win.dir = "ltr"; // move all available windows up for (var a in this.wins) { this.wins[a].zi += this.zIndexStep; this.wins[a].style.zIndex = this.wins[a].zi; if (this.iframeMode && this.wins[a].ifr) { this.wins[a].ifr.style.zIndex = this.wins[a].style.zIndex-1; } } // bottom, bring on top will at the end of createWindow function win.zi = this.zIndexStep;// this._getTopZIndex(true) + this.zIndexStep; win.style.zIndex = win.zi; // win.active = false; // win._isWindow = true; win.isWindow = true; // // win.that = this; // win.w = Number(width); win.h = Number(height); win.x = x; win.y = y; // this._fixWindowPositionInViewport(win); this._engineFixWindowPosInViewport(win); // // win.style.width = win.w + "px"; // win.style.height = win.h + "px"; // win.style.left = win.x + "px"; // win.style.top = win.y + "px"; win._isModal = false; // resize params win._allowResize = true; win.maxW = "auto"; // occupy all viewport on click or win.maxH = "auto"; win.minW = 200; win.minH = 140; win.iconsPresent = true; win.icons = new Array(this.imagePath+this.pathPrefix+this.skin+"/active/icon_normal.gif", this.imagePath+this.pathPrefix+this.skin+"/inactive/icon_normal.gif"); // win._allowMove = true; win._allowMoveGlobal = true; win._allowResizeGlobal = true; // win._keepInViewport = false; // var skin = this.skinParams[this.skin]; win.idd = id; //win._midd = "dhxWMNObj_"+this._genStr(12); //win._tidd = "dhxWTBObj_"+this._genStr(12); //win._sidd = "dhxSTBObj_"+this._genStr(12); // this.vp.appendChild(win); this._engineSetWindowBody(win); this._engineRedrawWindowPos(win); this._engineRedrawWindowSize(win); this._engineUpdateWindowIcon(win, win.icons[0]); this._engineDiableOnSelectInWindow(win, true); // this.wins[id] = win; // dhtmlxEventable(win); // // this._makeActive(win, true); // moving this._engineGetWindowHeader(win)[this._isIPad?"ontouchstart":"onmousedown"] = function(e) { e = e||event; var w = that.wins[this.idd]; if (!w.isOnTop()) w.bringToTop(); if (that._engineGetWindowHeaderState(w)) return; if (!that._engineCheckHeaderMouseDown(w, e)) return; if (!w._allowMove || !w._allowMoveGlobal) return; that._wasMoved = false; // w.moveOffsetX = w.x - (that._isIPad?e.touches[0].clientX:e.clientX); w.moveOffsetY = w.y - (that._isIPad?e.touches[0].clientY:e.clientY); that.movingWin = w; // carcass if (that._effects["move"] == false) { that._carcass.x = that.movingWin.x; that._carcass.y = that.movingWin.y; that._carcass.w = parseInt(that.movingWin.style.width)+(_isIE?0:-2); that._carcass.h = parseInt(that.movingWin.style.height)+(_isIE?0:-2); that._carcass.style.left = that._carcass.x+"px"; that._carcass.style.top = that._carcass.y+"px"; that._carcass.style.width = that._carcass.w+"px"; that._carcass.style.height = that._carcass.h+"px"; // that._carcass.style.zIndex = that.movingWin.style.zIndex+that._getTopZIndex()+10; that._carcass.style.zIndex = that._getTopZIndex(true)+1; // that._carcass.style.cursor = "move"; that._carcass._keepInViewport = win._keepInViewport; } that._blockSwitcher(true); // cursor // that._engineGetWindowHeader(that.movingWin).style.cursor = "move"; // vpcover that._vpcover.style.zIndex = that.movingWin.style.zIndex-1; that._vpcover.style.display = ""; // // w = null; e.returnValue = false; e.cancelBubble = true; return false; } /* win.ongesturestart = function(e) { e.preventDefault(); that._carcass.x = this.x; that._carcass.y = this.y; that._carcass.w = this.w; that._carcass.h = this.h; that._carcass.style.left = that._carcass.x+"px"; that._carcass.style.top = that._carcass.y+"px"; that._carcass.style.width = that._carcass.w+"px"; that._carcass.style.height = that._carcass.h+"px"; that._carcass.style.display = ""; that._carcass.style.zIndex = this.style.zIndex+1; } win.ongesturechange = function(e) { e.preventDefault(); var scale = e.scale; var cx = that._carcass.x+that._carcass.w/2; var cy = that._carcass.y+that._carcass.h/2; var nw = that._carcass.w*scale; var nh = that._carcass.h*scale; var ncx = cx-nw/2; var ncy = cy-nh/2; that._carcass.style.left = Math.round(ncx)+"px"; that._carcass.style.top = Math.round(ncy)+"px"; that._carcass.style.width = Math.round(nw)+"px"; that._carcass.style.height = Math.round(nh)+"px"; //console.log(e.scale+","+e.rotation) } win.ongestureend = function(e) { e.preventDefault(); that._carcass.style.display = "none"; this.setPosition(parseInt(that._carcass.style.left), parseInt(that._carcass.style.top)); this.setDimension(parseInt(that._carcass.style.width), parseInt(that._carcass.style.height)); } */ this._engineGetWindowHeader(win).ondblclick = function(e) { var w = that.wins[this.idd]; // maximize/minimize if (!that._engineCheckHeaderMouseDown(w, e||event)) { return; } if (w._allowResizeGlobal && !w._isParked) { if (w._isMaximized == true) { that._restoreWindow(w.idd); } else { that._maximizeWindow(w.idd); } } // parkup/parkup /* if (w._isParkedAllowed && w.button("park").isEnabled()) { that._parkWindow(w); } */ w = null; } // set text /** * @desc: sets window's header text * @param: text * @type: public */ win.setText = function(text) { that._engineGetWindowLabel(this).innerHTML = text; } // get text /** * @desc: returns window's header text * @type: public */ win.getText = function() { return that._engineGetWindowLabel(this).innerHTML; } // het id by handler /** * @desc: returns window's id * @type: public */ win.getId = function() { return this.idd; } // show /** * @desc: shows a window * @type: public */ win.show = function() { that._showWindow(this); } // hide /** * @desc: hides a window * @type: public */ win.hide = function() { that._hideWindow(this); } // minimize /** * @desc: minimizes a window * @type: public */ win.minimize = function() { that._restoreWindow(this.idd); } // maximize /** * @desc: maximizes a window * @type: public */ win.maximize = function() { that._maximizeWindow(this.idd); } // close /** * @desc: closes a window * @type: public */ win.close = function() { that._closeWindow(this.idd); } // park /** * @desc: parks a window (next action is based on window's current state) * @type: public */ win.park = function() { if (this._isParkedAllowed) { that._parkWindow(this.idd); } } // stick/unstick /** * @desc: sticks a window * @type: public */ win.stick = function() { that._stickWindow(this.idd); } /** * @desc: unsticks a window * @type: public */ win.unstick = function() { that._unstickWindow(this.idd); } /** * @desc: returns true if the window is sticked * @type: public */ win.isSticked = function() { return this._isSticked; } // set icon /** * @desc: sets window's header icon * @param: iconEnabled - url to the icon for the enabled state * @param: iconDisabled - url to the icon for the disabled state * @type: public */ win.setIcon = function(iconEnabled, iconDisabled) { that._setWindowIcon(win, iconEnabled, iconDisabled); } // return array(iconEnabled, iconDisabled) icons for window /** * @desc: returns current window's header icon * @param: text * @type: public */ win.getIcon = function() { return that._getWindowIcon(this); } // clear icon /** * @desc: clears window's header icon * @type: public */ win.clearIcon = function() { that._clearWindowIcons(this); } // restore default window icon according the loaded skin /** * @desc: restores default window's header icon (based on skin) * @type: public */ win.restoreIcon = function() { that._restoreWindowIcons(this); } // /** * @desc: keeps a window within the viewport * @param: state - if true - window is not allowed to be placed outside the viewport if false - window is not allowed to be placed outside the viewport leaving only a small part of its header within the viewport * @type: public */ win.keepInViewport = function(state) { this._keepInViewport = state; } // ask window be/not be modal /** * @desc: makes a window modal/modeless * @param: state - true|false * @type: public */ win.setModal = function(state) { if (state == true) { if (that.modalWin != null || that.modalWin == this) return; that._setWindowModal(this, true); } else { if (that.modalWin != this) return; that._setWindowModal(this, false); } } // return true if window is modal /** * @desc: returns true if the window is modal * @type: public */ win.isModal = function() { return this._isModal; } // return true if window is hidden /** * @desc: returns true if the window is hidden * @type: public */ win.isHidden = function() { return that._isWindowHidden(this); } // return true if window is maximized /** * @desc: returns true if the window is maximized * @type: public */ win.isMaximized = function() { return this._isMaximized; } // return true if window is parkded /** * @desc: returns true if the window is parked * @type: public */ win.isParked = function() { return this._isParked; } // allow/deny park /** * @desc: allows a window to be parked * @type: public */ win.allowPark = function() { that._allowParking(this); } /** * @desc: denies a window from parking * @type: public */ win.denyPark = function() { that._denyParking(this); } /** * @desc: returns true if the window is parkable * @type: public */ win.isParkable = function() { return this._isParkedAllowed; } // allow/deny for allow window to be resized /** * @desc: allows a window to be resized * @type: public */ win.allowResize = function() { that._allowReszieGlob(this); } /** * @desc: denies a window from resizing * @type: public */ win.denyResize = function() { that._denyResize(this); } // return true if window resizeable /** * @desc: returns true if the window is resizable * @type: public */ win.isResizable = function() { return this._allowResizeGlobal; } // move /** * @desc: allows a window to be moved * @type: public */ win.allowMove = function() { if (!this._isMaximized) { this._allowMove = true; } this._allowMoveGlobal = true; } /** * @desc: denies a window from moving * @type: public */ win.denyMove = function() { this._allowMoveGlobal = false; } /** * @desc: returns true if the window is movable * @type: public */ win.isMovable = function() { return this._allowMoveGlobal; } // bring window to top and set focus /** * @desc: brings/sends a window on top (z-positioning) * @type: public */ win.bringToTop = function() { that._bringOnTop(this); that._makeActive(this); } // bring window to bottom and set focus /** * @desc: brings/sends a window to bottom (z-positioning) * @type: public */ win.bringToBottom = function() { that._bringOnBottom(this); } // return true if window is on top /** * @desc: returns true if the window is on top * @type: public */ win.isOnTop = function() { return that._isWindowOnTop(this); } // return true if window if on bottom /** * @desc: returns true if the window is on bottom * @type: public */ win.isOnBottom = function() { return that._isWindowOnBottom(this); } // set new position for window, if it will outlay the viewport it was moved into it visible area /** * @desc: sets window's position (moves a window to the point set by user) * @param: x - x coordinate * @param: y - y coordinate * @type: public */ win.setPosition = function(x, y) { this.x = x; this.y = y; // that._fixWindowPositionInViewport(this); // fixing mozilla artefakts /* if (_isFF) { this.h++; that._redrawWindow(this); this.h--; } */ that._engineFixWindowPosInViewport(this); that._engineRedrawWindowPos(this); // that._redrawWindow(this); } // return array(x, y) with position of window /** * @desc: returns current window's position * @type: public */ win.getPosition = function() { return new Array(this.x, this.y); } // set new dimension for window, if it will outlay the viewport it was moved into it visible area /** * @desc: sets window's dimension * @param: width * @param: height * @type: public */ win.setDimension = function(width, height) { // alert(2) if (width != null) { if (this.maxW != "auto") if (width > this.maxW) width = this.maxW; if (width < this.minW) width = this.minW; this.w = width; } if (height != null) { if (this.maxH != "auto") if (height > this.maxH) height = this.maxH; if (height < this.minH) height = this.minH; this.h = height; } that._fixWindowDimensionInViewport(this); // that._fixWindowPositionInViewport(this); that._engineFixWindowPosInViewport(this); // // that._redrawWindow(this); that._engineRedrawWindowSize(this); // this.updateNestedObjects(); } // return array(width, height) with current dimension of window /** * @desc: returns current window's dimension * @type: public */ win.getDimension = function() { return new Array(this.w, this.h); } // set max dimension for window /** * @desc: sets max window's dimension * @param: maxWidth * @param: maxHeight * @type: public */ win.setMaxDimension = function(maxWidth, maxHeight) { this.maxW = (isNaN(maxWidth)?"auto":maxWidth); this.maxH = (isNaN(maxHeight)?"auto":maxHeight); //that._redrawWindow(this); that._engineRedrawWindowSize(this); } // return array(maxWidth, maxheight) with max dimension for window /** * @desc: returns current max window's dimension * @type: public */ win.getMaxDimension = function() { return new Array(this.maxW, this.maxH); } // set min dimensuion for window /** * @desc: sets min window's dimension * @param: minWidth * @param: minHeight * @type: public */ win.setMinDimension = function(minWidth, minHeight) { if (minWidth != null) { this.minW = minWidth; } if (minHeight != null) { this.minH = minHeight; } that._fixWindowDimensionInViewport(this); // that._redrawWindow(this); that._engineRedrawWindowPos(this); } // return array(minWidth, minHeight) with min dimension for window /** * @desc: returns current min window's dimension * @type: public */ win.getMinDimension = function() { return new Array(this.minW, this.minH); } win._adjustToContent = function(cw, ch) { that._engineAdjustWindowToContent(this, cw, ch); } win._doOnAttachMenu = function() { that._engineRedrawWindowSize(this); this.updateNestedObjects(); } win._doOnAttachToolbar = function() { that._engineRedrawWindowSize(this); this.updateNestedObjects(); } win._doOnAttachStatusBar = function() { that._engineRedrawWindowSize(this); this.updateNestedObjects(); } win._doOnFrameMouseDown = function() { this.bringToTop(); } win._doOnFrameContentLoaded = function() { that.callEvent("onContentLoaded",[this]); } /* win._doOnAttachURL = function(addIFrameEvents) { if (!addIFrameEvents) { // just call onContentLoaded that.callEvent("onContentLoaded", [this]); return; } // attach events into iframe if (_isIE) { // ie var w = this; var f = this._frame; f.onreadystatechange = function(a) { if (f.readyState == "complete") { try{f.contentWindow.document.body.onmousedown = function(){try{w.bringToTop();}catch(e){};};}catch(e){}; try{that.callEvent("onContentLoaded",[w]);}catch(e){} } } } else { // ff, opera, safari var w = this; var f = this._frame; f.onload = function() { try {f.contentWindow.onmousedown = function(){try{w.bringToTop();}catch(e){};};}catch(e){}; that.callEvent("onContentLoaded",[w]); } } } */ //#wind_buttons:09062008{ // add user button /** * @desc: adds a user button * @param: id - button's id * @param: pos - button's position * @param: title - button's tooltip * @param: label - button's name (according to css) * @type: public */ win.addUserButton = function(id, pos, title, label) { var userBtn = that._addUserButton(this, id, pos, title, label); return userBtn; } // remove user button /** * @desc: removes a user button * @param: id - button's id * @type: public */ win.removeUserButton = function(id) { id = String(id).toLowerCase(); if (!((id == "minmax1") || (id == "minmax2") || (id == "park") || (id == "close") || (id == "stick") || (id == "unstick") || (id == "help"))) { if (btn != null) { that._removeUserButton(this, id); } } } //#} /** * @desc: shows a progress indicator * @type: public */ win.progressOn = function() { that._engineSwitchWindowProgress(this, true); } /** * @desc: hides a progress indicator * @type: public */ win.progressOff = function() { that._engineSwitchWindowProgress(this, false); } /** * @desc: sets a window to the fullscreen mode * @param: state - true|false * @type: public */ win.setToFullScreen = function(state) { that._setWindowToFullScreen(this, state); } /** * @desc: shows window's header * @type: public */ win.showHeader = function() { that._engineSwitchWindowHeader(this, true); // that._showWindowHeader(this); } /** * @desc: hides window's header * @type: public */ win.hideHeader = function() { that._engineSwitchWindowHeader(this, false); // that._hideWindowHeader(this); } // win.progressOff(); // resize cursor modifications and handlers win.canStartResize = false; win.onmousemove = function(e) { if (_isIE && this._isMaximized) return true; e = e || event; var targetObj = e.target || e.srcElement; if (String(targetObj.className).search("dhtmlx_wins_resizer") < 0) targetObj = null; // resize not allowed if (!this._allowResize || this._allowResizeGlobal == false || !targetObj) { if (targetObj) { if (targetObj.style.cursor != "default") targetObj.style.cursor = "default"; } if (this.style.cursor != "default") this.style.cursor = "default"; this.canStartResize = false; return true; // required to allow selection in IE } // resize can't be realized if (that.resizingWin != null) return; if (that.movingWin != null) return; if (this._isParked) return; // coords if (that._isIPad) { var px = e.touches[0].clientX; var py = e.touches[0].clientY; } else { var px = (_isIE||_isOpera?e.offsetX:e.layerX); var py = (_isIE||_isOpera?e.offsetY:e.layerY); } // direction var resDir = that._engineAllowWindowResize(win, targetObj, px, py); if (resDir == null) { this.canStartResize = false; if (targetObj.style.cursor != "default") targetObj.style.cursor = "default"; if (this.style.cursor != "default") this.style.cursor = "default"; return; } // prepare that.resizingDirs = resDir; var xy = {x:e.clientX,y:e.clientY}; switch (that.resizingDirs) { case "border_left": targetObj.style.cursor = "w-resize"; this.resizeOffsetX = this.x - xy.x; break; case "border_right": targetObj.style.cursor = "e-resize"; this.resizeOffsetXW = this.x + this.w - xy.x; break; case "border_top": targetObj.style.cursor = "n-resize"; this.resizeOffsetY = this.y - xy.y; break; case "border_bottom": targetObj.style.cursor = "n-resize"; this.resizeOffsetYH = this.y + this.h - xy.y; break; case "corner_left": targetObj.style.cursor = "sw-resize"; this.resizeOffsetX = this.x - e.clientX; this.resizeOffsetYH = this.y + this.h - xy.y; break; case "corner_up_left": targetObj.style.cursor = "nw-resize"; this.resizeOffsetY = this.y - xy.y; this.resizeOffsetX = this.x - xy.x; break; case "corner_right": targetObj.style.cursor = "nw-resize"; this.resizeOffsetXW = this.x + this.w - xy.x; this.resizeOffsetYH = this.y + this.h - xy.y; break; case "corner_up_right": targetObj.style.cursor = "sw-resize"; this.resizeOffsetY = this.y - xy.y; this.resizeOffsetXW = this.x + this.w - xy.x; break; } this.canStartResize = true; this.style.cursor = targetObj.style.cursor; e.cancelBubble = true; e.returnValue = false; return false; } win.onmousedown = function(e) { if (that._getActive() != this) that._makeActive(this); that._bringOnTop(this); if (this.canStartResize) { that._blockSwitcher(true); that.resizingWin = this; if (!that._effects["resize"]) { that._carcass.x = that.resizingWin.x; that._carcass.y = that.resizingWin.y; that._carcass.w = Number(that.resizingWin.w)+(_isIE?0:-2); that._carcass.h = Number(that.resizingWin.h)+(_isIE?0:-2); that._carcass.style.left = that._carcass.x+"px"; that._carcass.style.top = that._carcass.y+"px"; that._carcass.style.width = that._carcass.w+"px"; that._carcass.style.height = that._carcass.h+"px"; that._carcass.style.zIndex = that._getTopZIndex(true)+1; that._carcass.style.cursor = this.style.cursor; that._carcass._keepInViewport = this._keepInViewport; that._carcass.style.display = ""; } // vpcover that._vpcover.style.zIndex = that.resizingWin.style.zIndex-1; that._vpcover.style.display = ""; // updated for 2.6-views if (this.vs[this.av].layout) { this.callEvent("_onBeforeTryResize", [this]); } e = e||event; //e.returnValue = false; //e.cancelBubble = true; //return false; } } // add buttons this._addDefaultButtons(win.idd); // //#wind_buttons:09062008{ // return button handler win.button = function(id) { id = String(id).toLowerCase(); var b = null; if (this.btns[id] != null) { b = this.btns[id]; } return b; } //#} // /** * @desc: centers a window in the viewport * @type: public */ win.center = function() { that._centerWindow(this, false); } /** * @desc: centers a window on the screen * @type: public */ win.centerOnScreen = function() { that._centerWindow(this, true); } // win._attachContent("empty", null); win._redraw = function() { that._engineRedrawWindowSize(this); } win.bringToTop(); this._engineRedrawWindowSize(win); //win.setDimension(win.w, win.h); //window.setTitemout(function(){win.setDimension(win.w+100, win.h+100);},100); // return this.wins[id]; } this.zIndexStep = 2000; this._getTopZIndex = function(ignoreSticked) { var topZIndex = 0; for (var a in this.wins) { if (ignoreSticked == true) { if (this.wins[a].zi > topZIndex) { topZIndex = this.wins[a].zi; } } else { if (this.wins[a].zi > topZIndex && !this.wins[a]._isSticked) { topZIndex = this.wins[a].zi; } } } return topZIndex; } this.movingWin = null; //#wind_move:09062008{ this._moveWindow = function(e) { if (this.movingWin != null) { // if (!this.movingWin._allowMove || !this.movingWin._allowMoveGlobal) { return; } if (this._effects["move"] == true) { // // cursor if (this._engineGetWindowHeader(this.movingWin).style.cursor != "move") { this._engineGetWindowHeader(this.movingWin).style.cursor = "move"; } // this._wasMoved = true; // this.movingWin.x = (this._isIPad?e.touches[0].clientX:e.clientX) + this.movingWin.moveOffsetX; this.movingWin.y = (this._isIPad?e.touches[0].clientY:e.clientY) + this.movingWin.moveOffsetY; // // check out of viewport // this._fixWindowPositionInViewport(this.movingWin); this._engineFixWindowPosInViewport(this.movingWin); // // this._redrawWindow(this.movingWin); this._engineRedrawWindowPos(this.movingWin); } else { if (this._carcass.style.display != "") { this._carcass.style.display = ""; } // cursor if (this._carcass.style.cursor != "move") { this._carcass.style.cursor = "move"; } if (this._engineGetWindowHeader(this.movingWin).style.cursor != "move") { this._engineGetWindowHeader(this.movingWin).style.cursor = "move"; } // this._carcass.x = (this._isIPad?e.touches[0].clientX:e.clientX) + this.movingWin.moveOffsetX; this._carcass.y = (this._isIPad?e.touches[0].clientY:e.clientY) + this.movingWin.moveOffsetY; this._wasMoved = true; // this._fixWindowPositionInViewport(this._carcass); this._engineFixWindowPosInViewport(this._carcass); this._carcass.style.left = this._carcass.x+"px"; this._carcass.style.top = this._carcass.y+"px"; } } if (this.resizingWin != null) { // if (!this.resizingWin._allowResize) { return; } // // resize through left border var xy = {x:e.clientX,y:e.clientY}; if (this.resizingDirs == "border_left" || this.resizingDirs == "corner_left" || this.resizingDirs == "corner_up_left") { if (this._effects["resize"]) { var ofs = xy.x + this.resizingWin.resizeOffsetX; var sign = (ofs > this.resizingWin.x ? -1 : 1); newW = this.resizingWin.w + Math.abs(ofs - this.resizingWin.x)*sign; if ((newW < this.resizingWin.minW) && (sign < 0)) { this.resizingWin.x = this.resizingWin.x + this.resizingWin.w - this.resizingWin.minW; this.resizingWin.w = this.resizingWin.minW; } else { this.resizingWin.w = newW; this.resizingWin.x = ofs; } this._engineRedrawWindowPos(this.resizingWin); this._engineRedrawWindowSize(this.resizingWin); } else { var ofs = xy.x + this.resizingWin.resizeOffsetX; var sign = (ofs > this._carcass.x ? -1 : 1); newW = this._carcass.w + Math.abs(ofs - this._carcass.x)*sign; if (newW > this.resizingWin.maxW) { newW = this.resizingWin.maxW; ofs = this._carcass.x + this._carcass.w - this.resizingWin.maxW; } if ((newW < this.resizingWin.minW) && (sign < 0)) { this._carcass.x = this._carcass.x + this._carcass.w - this.resizingWin.minW; this._carcass.w = this.resizingWin.minW; } else { this._carcass.w = newW; this._carcass.x = ofs; } this._carcass.style.left = this._carcass.x+"px"; this._carcass.style.width = this._carcass.w+"px"; } } // resize through right border if (this.resizingDirs == "border_right" || this.resizingDirs == "corner_right" || this.resizingDirs == "corner_up_right") { if (this._effects["resize"]) { var ofs = xy.x - (this.resizingWin.x + this.resizingWin.w) + this.resizingWin.resizeOffsetXW; newW = this.resizingWin.w + ofs; if (newW < this.resizingWin.minW) { newW = this.resizingWin.minW; } this.resizingWin.w = newW; this._engineRedrawWindowPos(this.resizingWin); this._engineRedrawWindowSize(this.resizingWin); } else { var ofs = xy.x - (this._carcass.x + this._carcass.w) + this.resizingWin.resizeOffsetXW; newW = this._carcass.w + ofs; if (newW < this.resizingWin.minW) newW = this.resizingWin.minW; if (this.resizingWin.maxW != "auto") if (newW > this.resizingWin.maxW) newW = this.resizingWin.maxW; this._carcass.w = newW; this._carcass.style.width = this._carcass.w+"px"; } } // resize through bottom border if (this.resizingDirs == "border_bottom" || this.resizingDirs == "corner_left" || this.resizingDirs == "corner_right") { if (this._effects["resize"]) { var ofs = xy.y - (this.resizingWin.y + this.resizingWin.h) + this.resizingWin.resizeOffsetYH; newH = this.resizingWin.h + ofs; if (newH < this.resizingWin.minH) newH = this.resizingWin.minH; this.resizingWin.h = newH; this._engineRedrawWindowPos(this.resizingWin); this._engineRedrawWindowSize(this.resizingWin); } else { var ofs = xy.y - (this._carcass.y + this._carcass.h) + this.resizingWin.resizeOffsetYH; newH = this._carcass.h + ofs; if (newH < this.resizingWin.minH) newH = this.resizingWin.minH; if (newH > this.resizingWin.maxH) newH = this.resizingWin.maxH; this._carcass.h = newH; this._carcass.style.height = this._carcass.h+"px"; } } if (this.resizingDirs == "border_top" || this.resizingDirs == "corner_up_right" || this.resizingDirs == "corner_up_left") { if (this._effects["resize"]) { } else { var ofs = xy.y + this.resizingWin.resizeOffsetY; var sign = (ofs > this.resizingWin.y ? -1 : 1); newH = this.resizingWin.h + Math.abs(ofs - this.resizingWin.y)*sign; if (newH > this.resizingWin.maxH) { newH = this.resizingWin.maxH; ofs = this.resizingWin.y + this.resizingWin.h - this.resizingWin.maxH; } if ((newH < this.resizingWin.minH) && (sign < 0)) { this._carcass.y = this._carcass.y + this._carcass.h - this.resizingWin.minH; this._carcass.h = this.resizingWin.minH; } else { this._carcass.h = newH+(_isIE?0:-2); this._carcass.y = ofs; } this._carcass.style.top = this._carcass.y+"px"; this._carcass.style.height = this._carcass.h+"px"; } } } } this._stopMove = function() { if (this.movingWin != null) { if (this._effects["move"]) { var win = this.movingWin; this.movingWin = null; this._blockSwitcher(false); // cursor // win.childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[1].style.cursor = ""; // win.childNodes[2].style.cursor = ""; this._engineGetWindowHeader(win).style.cursor = ""; // fixing mozilla artefakts if (_isFF) { win.h++; // this._redrawWindow(win); that._engineRedrawWindowPos(win); win.h--; // this._redrawWindow(win); that._engineRedrawWindowPos(win); } } else { this._carcass.style.cursor = ""; this._carcass.style.display = "none"; var win = this.movingWin; this._engineGetWindowHeader(win).style.cursor = ""; this.movingWin = null; this._blockSwitcher(false); win.setPosition(parseInt(this._carcass.style.left), parseInt(this._carcass.style.top)); } // vpcover this._vpcover.style.display = "none"; // events if (this._wasMoved) { // if (win.checkEvent("onMoveFinish")) { win.callEvent("onMoveFinish",[win]); } else { this.callEvent("onMoveFinish",[win]); } } this._wasMoved = false; } if (this.resizingWin != null) { var win = this.resizingWin; this.resizingWin = null; this._blockSwitcher(false); if (!this._effects["resize"]) { this._carcass.style.display = "none"; win.setDimension(this._carcass.w+(_isIE?0:2), this._carcass.h+(_isIE?0:2)); win.setPosition(this._carcass.x, this._carcass.y); } else { // sizes in attached components win.updateNestedObjects(); } // event in layout if (win.vs[win.av].layout) { win.vs[win.av].layout.callEvent("onResize", []); } // opera fix /* if (_isOpera) { win._content.childNodes[2].style.border="#FFFFFF 0px solid"; var w = win._content.childNodes[2]; window.setTimeout(function(){ w.style.border="none"; }, 1); } */ // vpcover this._vpcover.style.display = "none"; // events if (win.checkEvent("onResizeFinish")) { win.callEvent("onResizeFinish",[win]); } else { this.callEvent("onResizeFinish",[win]); } } } //#} // check viewport overflow /* this._fixWindowPositionInViewport = function(win) { return; var skin = (win._skinParams!=null?win._skinParams:this.skinParams[this.skin]); if (win._keepInViewport) { // keep strongly in viewport if (win.x < 0) { win.x = 0; } if (win.x + win.w > this.vp.offsetWidth) { win.x = this.vp.offsetWidth - win.w; } // if (win.y < 0) { win.y = 0; } if (win.y + win.h > this.vp.offsetHeight) { win.y = this.vp.offsetHeight - win.h; } if (win.y < 0) { win.y = 0; } } else { // if (win.y < 0) { win.y = 0; } if (win.y + skin["header_height"] > this.vp.offsetHeight) { win.y = this.vp.offsetHeight - skin["header_height"]; } if (win.y < 0) { win.y = 0; } if (win.x + win.w - 10 < 0) { win.x = 10 - win.w; } if (win.x > this.vp.offsetWidth - 10) { win.x = this.vp.offsetWidth - 10; } } } */ // check and correct window dimensions this._fixWindowDimensionInViewport = function(win) { if (win.w < win.minW) { win.w = win.minW; } if (win._isParked) return; if (win.h < win.minH) { win.h = win.minH; } } this._bringOnTop = function(win) { var cZIndex = win.zi; var topZIndex = this._getTopZIndex(win._isSticked); for (var a in this.wins) { if (this.wins[a] != win) { if (win._isSticked || (!win._isSticked && !this.wins[a]._isSticked)) { if (this.wins[a].zi > cZIndex) { this.wins[a].zi = this.wins[a].zi - this.zIndexStep; this.wins[a].style.zIndex = this.wins[a].zi; if (this.iframeMode && this.wins[a].ifr) { this.wins[a].ifr.style.zIndex = this.wins[a].style.zIndex-1; } } } } } win.zi = topZIndex; win.style.zIndex = win.zi; if (this.iframeMode && win.ifr) { win.ifr.style.zIndex = topZIndex-1; } } this._makeActive = function(win, ignoreFocusEvent) { for (var a in this.wins) { if (this.wins[a] == win) { var needEvent = false; if (this.wins[a].className != "dhtmlx_window_active" && !ignoreFocusEvent) { needEvent = true; } this.wins[a].className = "dhtmlx_window_active"; this._engineUpdateWindowIcon(this.wins[a], this.wins[a].icons[0]); if (needEvent == true) { if (win.checkEvent("onFocus")) { win.callEvent("onFocus",[win]); } else { this.callEvent("onFocus",[win]); } } } else { this.wins[a].className = "dhtmlx_window_inactive"; this._engineUpdateWindowIcon(this.wins[a], this.wins[a].icons[1]); } } } this._getActive = function() { var win = null; for (var a in this.wins) { if (this.wins[a].className == "dhtmlx_window_active") { win = this.wins[a]; } } return win; } this._centerWindow = function(win, onScreen) { if (win._isMaximized == true) return; // if (win._isParked == true) return; if (onScreen == true) { var vpw = (_isIE?document.body.offsetWidth:window.innerWidth); var vph = (_isIE?document.body.offsetHeight:window.innerHeight); } else { var vpw = (this.vp==document.body?document.body.offsetWidth:(Number(parseInt(this.vp.style.width))&&String(this.vp.style.width).search("%")==-1?parseInt(this.vp.style.width):this.vp.offsetWidth)); var vph = (this.vp==document.body?document.body.offsetHeight:(Number(parseInt(this.vp.style.height))&&String(this.vp.style.height).search("%")==-1?parseInt(this.vp.style.height):this.vp.offsetHeight)); } var newX = Math.round((vpw/2) - (win.w/2)); var newY = Math.round((vph/2) - (win.h/2)); win.x = newX; win.y = newY; // this._fixWindowPositionInViewport(win); this._engineFixWindowPosInViewport(win); // this._redrawWindow(win); this._engineRedrawWindowPos(win); } this._addDefaultButtons = function(winId) { //#wind_buttons:09062008{ var win = this.wins[winId]; // stick var btnStick = this._engineGetWindowButton(win, "stick"); btnStick.title = this.i18n.stick; btnStick.isVisible = false; btnStick.style.display = "none"; btnStick._isEnabled = true; btnStick.isPressed = false; btnStick.label = "stick"; btnStick._doOnClick = function() { this.isPressed = true; that._stickWindow(this.winId); } // sticked var btnSticked = this._engineGetWindowButton(win, "sticked"); btnSticked.title = this.i18n.unstick; btnSticked.isVisible = false; btnSticked.style.display = "none"; btnSticked._isEnabled = true; btnSticked.isPressed = false; btnSticked.label = "sticked"; btnSticked._doOnClick = function() { this.isPressed = false; that._unstickWindow(this.winId); } // help var btnHelp = this._engineGetWindowButton(win, "help"); btnHelp.title = this.i18n.help; btnHelp.isVisible = false; btnHelp.style.display = "none"; btnHelp._isEnabled = true; btnHelp.isPressed = false; btnHelp.label = "help"; btnHelp._doOnClick = function() { that._needHelp(this.winId); } // park var btnPark = this._engineGetWindowButton(win, "park"); btnPark.titleIfParked = this.i18n.parkdown; btnPark.titleIfNotParked = this.i18n.parkup; btnPark.title = btnPark.titleIfNotParked; btnPark.isVisible = true; btnPark._isEnabled = true; btnPark.isPressed = false; btnPark.label = "park"; btnPark._doOnClick = function() { that._parkWindow(this.winId); } // minmax maximize var btnMinMax1 = this._engineGetWindowButton(win, "minmax1"); btnMinMax1.title = this.i18n.maximize; btnMinMax1.isVisible = true; btnMinMax1._isEnabled = true; btnMinMax1.isPressed = false; btnMinMax1.label = "minmax1"; btnMinMax1._doOnClick = function() { that._maximizeWindow(this.winId); } // minmax restore var btnMinMax2 = this._engineGetWindowButton(win, "minmax2"); btnMinMax2.title = this.i18n.restore; btnMinMax2.isVisible = false; btnMinMax2.style.display = "none"; btnMinMax2._isEnabled = true; btnMinMax2.isPressed = false; btnMinMax2.label = "minmax2"; btnMinMax2._doOnClick = function() { that._restoreWindow(this.winId); } // close var btnClose = this._engineGetWindowButton(win, "close"); btnClose.title = this.i18n.close; btnClose.isVisible = true; btnClose._isEnabled = true; btnClose.isPressed = false; btnClose.label = "close"; btnClose._doOnClick = function() { that._closeWindow(this.winId); } // dock var btnDock = this._engineGetWindowButton(win, "dock"); btnDock.title = this.i18n.dock; btnDock.style.display = "none"; btnDock.isVisible = false; btnDock._isEnabled = true; btnDock.isPressed = false; btnDock.label = "dock"; btnDock._doOnClick = function() { // that._closeWindow(win); } // win._isSticked = false; win._isParked = false; win._isParkedAllowed = true; win._isMaximized = false; win._isDocked = false; // win.btns = {}; win.btns["stick"] = btnStick; win.btns["sticked"] = btnSticked; win.btns["help"] = btnHelp; win.btns["park"] = btnPark; win.btns["minmax1"] = btnMinMax1; win.btns["minmax2"] = btnMinMax2; win.btns["close"] = btnClose; win.btns["dock"] = btnDock; // events for (var a in win.btns) { win.btns[a].winId = win.idd; this._attachEventsOnButton(win.idd, a); } win = btnStick = btnSticked = btnHelp = btnPark = btnMinMax1 = btnMinMax2 = btnClose = btnDock = null; //*/ //#} } //#wind_buttons:09062008{ this._attachEventsOnButton = function(winId, btnId) { var btn = this.wins[winId].btns[btnId]; // add events if (!this._isIPad) { btn.onmouseover = function() { if (this._isEnabled) { this.className = "dhtmlx_wins_btns_button dhtmlx_button_"+this.label+"_over_"+(this.isPressed?"pressed":"default"); } else { this.className = "dhtmlx_wins_btns_button dhtmlx_button_"+this.label+"_disabled"; } } btn.onmouseout = function() { if (this._isEnabled) { this.isPressed = false; this.className = "dhtmlx_wins_btns_button dhtmlx_button_"+this.label+"_default"; } else { this.className = "dhtmlx_wins_btns_button dhtmlx_button_"+this.label+"_disabled"; } } btn.onmousedown = function() { if (this._isEnabled) { this.isPressed = true; this.className = "dhtmlx_wins_btns_button dhtmlx_button_"+this.label+"_over_pressed"; } else { this.className = "dhtmlx_wins_btns_button dhtmlx_button_"+this.label+"_disabled"; } } btn.onmouseup = function() { if (this._isEnabled) { var wasPressed = this.isPressed; this.isPressed = false; this.className = "dhtmlx_wins_btns_button dhtmlx_button_"+this.label+"_over_default"; if (wasPressed) { // events if (this.checkEvent("onClick")) { this.callEvent("onClick", [that.wins[this.winId], this]); } else { this._doOnClick(); } } } else { this.className = "dhtmlx_wins_btns_button dhtmlx_button_"+this.label+"_disabled"; } } } else { btn.ontouchstart = function(e) { e.cancelBubble = true; e.returnValue = false; return false; } btn.ontouchend = function(e) { e.cancelBubble = true; e.returnValue = false; if (!this._isEnabled) return false; // events if (this.checkEvent("onClick")) { this.callEvent("onClick", [that.wins[this.winId], this]); } else { this._doOnClick(); } return false; } } /** * @desc: shows a button * @type: public */ btn.show = function() { that._showButton(that.wins[this.winId], this.label, true); } /** * @desc: hides a button * @type: public */ btn.hide = function() { that._hideButton(that.wins[this.winId], this.label, true); } /** * @desc: enables a button * @type: public */ btn.enable = function() { that._enableButton(that.wins[this.winId], this.label); } /** * @desc: disables a button * @type: public */ btn.disable = function() { that._disableButton(that.wins[this.winId], this.label); } /** * @desc: checks if a button is enabled * @returns: true if enabled, otherwise - false * @type: public */ btn.isEnabled = function() { return this._isEnabled; } /** * @desc: checks if a button is hidden * @returns: true if hidden, otherwise - false * @type: public */ btn.isHidden = function() { return (!this.isVisible); } dhtmlxEventable(btn); btn = null; } //#} //#wind_park:09062008{ this._parkWindow = function(winId, parkBeforeMinMax) { var win = this.wins[winId]; if (!win._isParkedAllowed && !parkBeforeMinMax) return; if (this.enableParkEffect && win.parkBusy) return; if (win._isParked) { // park down if (this.enableParkEffect && !parkBeforeMinMax) { // effect win.parkBusy = true; this._doParkDown(win); } else { // no effect win.h = win.lastParkH; this._engineRedrawWindowSize(win); this._engineDoOnWindowParkDown(win); win.updateNestedObjects(); win.btns["park"].title = win.btns["park"].titleIfNotParked; if (win._allowResizeGlobal == true) { this._enableButton(win, "minmax1"); this._enableButton(win, "minmax2"); } win._isParked = false; // onParkDown event if (!parkBeforeMinMax) if (win.checkEvent("onParkDown")) win.callEvent("onParkDown", [win]); else this.callEvent("onParkDown", [win]); } } else { // park up if (this.enableParkEffect && !parkBeforeMinMax) { win.lastParkH = (String(win.h).search(/\%$/)==-1?win.h:win.offsetHeight); if (win._allowResizeGlobal == true) { this._disableButton(win, "minmax1"); this._disableButton(win, "minmax2"); } if (this.enableParkEffect) { win.parkBusy = true; this._doParkUp(win); } else { var skinParams = (win._skinParams!=null?win._skinParams:this.skinParams[this.skin]); win.h = skinParams["header_height"] + skinParams["border_bottom_height"]; win.btns["park"].title = win.btns["park"].titleIfParked; } } else { win.lastParkH = (String(win.h).search(/\%$/)==-1?win.h:win.offsetHeight); win.h = this._engineGetWindowParkedHeight(win); this._engineRedrawWindowSize(win); this._engineDoOnWindowParkUp(win); win.btns["park"].title = win.btns["park"].titleIfParked; win._isParked = true; // onParkUp event if (!parkBeforeMinMax) if (win.checkEvent("onParkUp")) win.callEvent("onParkUp", [win]); else this.callEvent("onParkUp", [win]); } } win = null; } this._allowParking = function(win) { win._isParkedAllowed = true; this._enableButton(win, "park"); } this._denyParking = function(win) { win._isParkedAllowed = false; this._disableButton(win, "park"); } // park with effects this.enableParkEffect = false; this.parkStartSpeed = 80; this.parkSpeed = this.parkStartSpeed; this.parkTM = null; this.parkTMTime = 5; this._doParkUp = function(win) { if (String(win.h).search(/\%$/) != -1) { win.h = win.offsetHeight; } win.h -= this.parkSpeed; var hh = this._engineGetWindowParkedHeight(win); if (win.h <= hh) { // end purkUp win.h = hh; this._engineGetWindowButton(win, "park").title = this._engineGetWindowButton(win, "park").titleIfParked; win._isParked = true; win.parkBusy = false; this._engineRedrawWindowSize(win); this._engineDoOnWindowParkUp(win); if (win.checkEvent("onParkUp")) win.callEvent("onParkUp", [win]); else this.callEvent("onParkUp", [win]); } else { // continue purkUp this._engineRedrawWindowSize(win); this.parkTM = window.setTimeout(function(){that._doParkUp(win);}, this.parkTMTime); } } this._doParkDown = function(win) { win.h += this.parkSpeed; if (win.h >= win.lastParkH) { win.h = win.lastParkH; this._engineGetWindowButton(win, "park").title = this._engineGetWindowButton(win, "park").titleIfNotParked; if (win._allowResizeGlobal == true) { this._enableButton(win, "minmax1"); this._enableButton(win, "minmax2"); } win._isParked = false; win.parkBusy = false; this._engineRedrawWindowSize(win); win.updateNestedObjects(); this._engineDoOnWindowParkDown(win); if (win.checkEvent("onParkDown")) win.callEvent("onParkDown", [win]); else this.callEvent("onParkDown", [win]); } else { // continue purkDown this._engineRedrawWindowSize(win); this.parkTM = window.setTimeout(function(){that._doParkDown(win);}, this.parkTMTime); } } //#} //#wind_buttons:09062008{ this._enableButton = function(win, btn) { var button = this._engineGetWindowButton(win, btn); if (!button) return; button._isEnabled = true; button.className = "dhtmlx_wins_btns_button dhtmlx_button_"+button.label+"_default"; button = null; } this._disableButton = function(win, btn) { var button = this._engineGetWindowButton(win, btn); if (!button) return; button._isEnabled = false; button.className = "dhtmlx_wins_btns_button dhtmlx_button_"+win.btns[btn].label+"_disabled"; button = null; } //#} // resize this._allowReszieGlob = function(win) { win._allowResizeGlobal = true; this._enableButton(win, "minmax1"); this._enableButton(win, "minmax2"); } this._denyResize = function(win) { win._allowResizeGlobal = false; this._disableButton(win, "minmax1"); this._disableButton(win, "minmax2"); } this._maximizeWindow = function(winId) { var win = this.wins[winId]; if (win._allowResizeGlobal == false) return; var isParkedBeforeMinMax = win._isParked; if (isParkedBeforeMinMax) this._parkWindow(win.idd, true); win.lastMaximizeX = win.x; win.lastMaximizeY = win.y; win.lastMaximizeW = win.w; win.lastMaximizeH = win.h; // put window into top/left corner if complete maximize or center new maximized window if maxDimension set if (win.maxW != "auto" && win.maxW != "auto") { win.x = Math.round(win.x+(win.w-win.maxW)/2); win.y = Math.round(win.y+(win.h-win.maxH)/2); win._allowMove = true; } else { win.x = 0; win.y = 0; win._allowMove = false; } win._isMaximized = true; win._allowResize = false; // win.w = (win.maxW == "auto" ? (this.vp == document.body ? document.body.offsetWidth:parseInt(this.vp.style.width)) : win.maxW); // win.h = (win.maxH == "auto" ? (this.vp == document.body ? document.body.offsetHeight:parseInt(this.vp.style.height)) : win.maxH); // win.w = (win.maxW == "auto" ? (this.vp == document.body ? "100%" : (this.vp.style.width != "" && String(this.vp.style.width).search("%") == -1 ? parseInt(this.vp.style.width) : this.vp.offsetWidth)) : win.maxW); win.h = (win.maxH == "auto" ? (this.vp == document.body ? "100%" : (this.vp.style.height != "" && String(this.vp.style.width).search("%") == -1 ? parseInt(this.vp.style.height) : this.vp.offsetHeight)) : win.maxH); // this._hideButton(win, "minmax1"); this._showButton(win, "minmax2"); this._engineRedrawWindowPos(win); if (isParkedBeforeMinMax) { this._parkWindow(win.idd, true); } else { this._engineRedrawWindowSize(win); win.updateNestedObjects(); } // event if (win.checkEvent("onMaximize")) win.callEvent("onMaximize", [win]); else this.callEvent("onMaximize", [win]); win = null; } this._restoreWindow = function(winId) { var win = this.wins[winId]; if (win._allowResizeGlobal == false) return; if (win.layout) win.layout._defineWindowMinDimension(win); var isParkedBeforeMinMax = win._isParked; if (isParkedBeforeMinMax) this._parkWindow(win.idd, true); // put window to prev place if auto max dimension or center if (win.maxW != "auto" && win.maxW != "auto") { win.x = Math.round(win.x+(win.w-win.lastMaximizeW)/2); win.y = Math.round(win.y+(win.h-win.lastMaximizeH)/2); } else { win.x = win.lastMaximizeX; win.y = win.lastMaximizeY; } win.w = win.lastMaximizeW; win.h = win.lastMaximizeH; win._isMaximized = false; win._allowMove = win._allowMoveGlobal; win._allowResize = true; this._fixWindowDimensionInViewport(win); this._hideButton(win, "minmax2"); this._showButton(win, "minmax1"); this._engineRedrawWindowPos(win); if (isParkedBeforeMinMax) { this._parkWindow(win.idd, true); } else { this._engineRedrawWindowSize(win); win.updateNestedObjects(); } // events if (win.checkEvent("onMinimize")) win.callEvent("onMinimize", [win]); else this.callEvent("onMinimize", [win]); win = null; } //#wind_buttons:09062008{ this._showButton = function(win, btn, userShow) { var button = this._engineGetWindowButton(win, btn); if (!button) return; if ((!userShow && button._userHide) || button.isVisible === true) return; button.isVisible = true; button.style.display = ""; button.style.visibility = "visible"; button._userHide = !(userShow==true); this._engineRedrawWindowTitle(win); button = null; } this._hideButton = function(win, btn, userHide) { var button = this._engineGetWindowButton(win, btn); if (!button || (!userHide && button.isVisible === false)) return; button.isVisible = false; button.style.display = "none"; button.style.visibility = "hidden"; button._userHide = (userHide==true); this._engineRedrawWindowTitle(win); button = null; } //#} this._showWindow = function(win) { win.style.display = ""; // event if (win.checkEvent("onShow")) { win.callEvent("onShow", [win]); } else { this.callEvent("onShow", [win]); } // fixed 24.03.2008 var w = this._getActive(); if (w == null) { this._bringOnTop(win); this._makeActive(win); } else if (this._isWindowHidden(w)) { this._bringOnTop(win); this._makeActive(win); } if (this.iframeMode && win.ifr) win.ifr.style.display = ""; } this._hideWindow = function(win) { win.style.display = "none"; // event if (win.checkEvent("onHide")) { win.callEvent("onHide", [win]); } else { this.callEvent("onHide", [win]); } // fixed 24.03.2008 var w = this.getTopmostWindow(true); if (w != null) { this._bringOnTop(w); this._makeActive(w); } if (this.iframeMode && win.ifr) win.ifr.style.display = "none"; } this._isWindowHidden = function(win) { var isHidden = (win.style.display == "none"); return isHidden; } this._closeWindow = function(winId) { var win = this.wins[winId]; // ie focus fix if (this._focusFixIE) { this._focusFixIE.style.top = (this.vp==document.body?0:getAbsoluteTop(this.vp))+Number(win.y)+"px"; this._focusFixIE.focus(); } // event if (win.checkEvent("onClose")) { if (!win.callEvent("onClose", [win])) return; } else { if(!this.callEvent("onClose", [win])) return; } // closing // for (var a in win.btns) { this._removeButtonGlobal(win, a, win.btns[a]); } win = null; this._removeWindowGlobal(winId); /* this.vp.removeChild(win); delete this.wins[win.idd]; // make active latest window */ var latest = { "zi": 0 }; for (var a in this.wins) { if (this.wins[a].zi > latest.zi) { latest = this.wins[a]; } } if (latest != null) { this._makeActive(latest); } /* // toolbar clicks events, temporary removed if (_isFF && this.vp != document.body) { this.vp.style.display = "none"; var vp = this.vp; window.setTimeout(function(){vp.style.display="";},1); } */ } this._needHelp = function(winId) { // event only var win = this.wins[winId]; if (win.checkEvent("onHelp")) { win.callEvent("onHelp", [win]); } else { this.callEvent("onHelp", [win]); } win = null; } this._setWindowIcon = function(win, iconEnabled, iconDisabled) { win.iconsPresent = true; win.icons[0] = this.imagePath + iconEnabled; win.icons[1] = this.imagePath + iconDisabled; this._engineUpdateWindowIcon(win, win.icons[win.isOnTop()?0:1]); } this._getWindowIcon = function(win) { if (win.iconsPresent) { return new Array(win.icons[0], win.icons[1]); } else { return new Array(null, null); } } this._clearWindowIcons = function(win) { win.iconsPresent = false; win.icons[0] = this.imagePath + this.pathPrefix + this.skin + "/active/icon_blank.gif"; win.icons[1] = this.imagePath + this.pathPrefix + this.skin + "/inactive/icon_blank.gif"; this._engineUpdateWindowIcon(win, win.icons[win.isOnTop()?0:1]); } this._restoreWindowIcons = function(win) { win.iconsPresent = true; win.icons[0] = this.imagePath + this.pathPrefix + this.skin + "/active/icon_normal.gif"; win.icons[1] = this.imagePath + this.pathPrefix + this.skin + "/inactive/icon_normal.gif"; this._engineUpdateWindowIcon(win, win.icons[win.className=="dhtmlx_window_active"?0:1]); } this._attachWindowContentTo = function(win, obj, w, h) { var data = this._engineGetWindowContent(win).parentNode; data.parentNode.removeChild(data); win.hide(); data.style.left = "0px"; data.style.top = "0px"; data.style.width = (w!=null?w:obj.offsetWidth)+"px"; data.style.height = (h!=null?h:obj.offsetHeight)+"px"; data.style.position = "relative"; // obj.appendChild(data); this._engineGetWindowContent(win).style.width = data.style.width; this._engineGetWindowContent(win).style.height = data.style.height; /* var data = win._content; data.parentNode.removeChild(data); win.hide(); // data.style.left = "0px"; data.style.top = "0px"; data.style.width = (w!=null?w:obj.offsetWidth)+"px"; data.style.height = (h!=null?h:obj.offsetHeight)+"px"; data.style.position = "relative"; // obj.appendChild(data); */ } this._setWindowToFullScreen = function(win, state) { if (state == true && !win._isFullScreened) { // win._p1 = win.vs[win.av].dhxcont.nextSibling; win._p1.parentNode.removeChild(win.vs[win.av].dhxcont); win.hide(); win._isFullScreened = true; win._FSoffsetHeight = win._offsetHeight; win._FSoffsetHeightSaved = win._offsetHeightSaved; win._FSoffsetLeft = win._offsetLeft; win._FSoffsetWidth = win._offsetWidth; win._offsetHeight = 0; win._offsetHeightSaved = 0; win._offsetLeft = 0; win._offsetWidth = 0; win.vs[win.av].dhxcont.style.position = "absolute"; document.body.appendChild(win.vs[win.av].dhxcont); win.adjustContent(document.body, 0, 0, false, 0); win.updateNestedObjects(); } if (state == false && win._isFullScreened) { win._p1.parentNode.insertBefore(win.vs[win.av].dhxcont, win._p1); win._p1 = null; win._isFullScreened = false; win._offsetHeight = win._FSoffsetHeight; win._offsetHeightSaved = win._FSoffsetHeightSaved; win._offsetLeft = win._FSoffsetLeft; win._offsetWidth = win._FSoffsetWidth; win._FSoffsetHeight = win._FSoffsetHeightSaved = win._FSoffsetLeft = win._FSoffsetWidth = null; win.show(); win.setDimension(win.w, win.h); win.bringToTop(); } } this._isWindowOnTop = function(win) { var state = (this.getTopmostWindow() == win); return state; } this._bringOnBottom = function(win) { for (var a in this.wins) { if (this.wins[a].zi < win.zi) { this.wins[a].zi += this.zIndexStep; this.wins[a].style.zIndex = this.wins[a].zi; } } win.zi = 50; win.style.zIndex = win.zi; // this._makeActive(this.getTopmostWindow()); } this._isWindowOnBottom = function(win) { var state = true; for (var a in this.wins) { if (this.wins[a] != win) { state = state && (this.wins[a].zi > win.zi); } } return state; } this._stickWindow = function(winId) { var win = this.wins[winId]; win._isSticked = true; this._hideButton(win, "stick"); this._showButton(win, "sticked"); this._bringOnTop(win); win = null; } this._unstickWindow = function(winId) { var win = this.wins[winId]; win._isSticked = false; this._hideButton(win, "sticked"); this._showButton(win, "stick"); this._bringOnTopAnyStickedWindows(); win = null; } //#wind_buttons:09062008{ // add user button this._addUserButton = function(win, id, pos, title) { id = String(id).toLowerCase(); var userButton = this._engineAddUserButton(win, id, pos); userButton.title = title; userButton.isVisible = true; userButton._isEnabled = true; userButton.isPressed = false; userButton.label = id; win.btns[id] = userButton; win.btns[id].winId = win.idd win.btns[id]._doOnClick = function(){}; // attach events this._attachEventsOnButton(win.idd, id); userButton = null; } // remove user button this._removeUserButton = function(win, buttonId) { this._removeButtonGlobal(win, buttonId); } //#} // add iframe blockers before drag and resize this._blockSwitcher = function(state) { for (var a in this.wins) { if (state == true) { this.wins[a].showCoverBlocker(); } else { this.wins[a].hideCoverBlocker(); } } } this.resizingWin = null; this.modalWin = null; this.resizingDirs = "none"; // init functions // focus fix ie case if (_isIE) { this._focusFixIE = document.createElement("INPUT"); this._focusFixIE.className = "dhx_windows_ieonclosefocusfix"; this._focusFixIE.style.position = "absolute"; this._focusFixIE.style.width = "1px"; this._focusFixIE.style.height = "1px"; this._focusFixIE.style.border = "none"; this._focusFixIE.style.background = "none"; this._focusFixIE.style.left = "-10px"; this._focusFixIE.style.fontSize = "1px"; document.body.appendChild(this._focusFixIE); } this._createViewport(); //#wind_move:09062008{ this._doOnMouseUp = function() { if (that != null) that._stopMove(); } this._doOnMoseMove = function(e) { e = e||event; if (that != null) that._moveWindow(e); } //#} this._resizeTM = null; this._resizeTMTime = 200; this._lw = null; this._doOnResize = function() { if (that._lw != document.documentElement.clientHeight) { window.clearTimeout(that._resizeTM); that._resizeTM = window.setTimeout(function(){that._autoResizeViewport();}, that._resizeTMTime); } that._lw = document.documentElement.clientHeight; } this._doOnUnload = function() { that.unload(); } this._doOnSelectStart = function(e) { e = e||event; if (that.movingWin != null || that.resizingWin != null) e.returnValue = false; } if (_isIE) { document.body.attachEvent("onselectstart", this._doOnSelectStart); } dhtmlxEvent(window, "resize", this._doOnResize); dhtmlxEvent(document.body, "unload", this._doOnUnload); if (this._isIPad) { document.addEventListener("touchmove", this._doOnMoseMove, false); document.addEventListener("touchend", this._doOnMouseUp, false); } else { //#wind_move:09062008{ dhtmlxEvent(document.body, "mouseup", this._doOnMouseUp); dhtmlxEvent(this.vp, "mousemove", this._doOnMoseMove); dhtmlxEvent(this.vp, "mouseup", this._doOnMouseUp); //#} } this._setWindowModal = function(win, state) { if (state == true) { this._makeActive(win); this._bringOnTop(win); this.modalWin = win; win._isModal = true; // this.modalCoverI.style.zIndex = win.zi - 2; this.modalCoverI.style.display = ""; // this.modalCoverD.style.zIndex = win.zi - 2; this.modalCoverD.style.display = ""; } else { this.modalWin = null; win._isModal = false; // this.modalCoverI.style.zIndex = 0; this.modalCoverI.style.display = "none"; // this.modalCoverD.style.zIndex = 0; this.modalCoverD.style.display = "none"; } } this._bringOnTopAnyStickedWindows = function() { var wins = new Array(); for (var a in this.wins) { if (this.wins[a]._isSticked) { wins[wins.length] = this.wins[a]; } } for (var q=0; q<wins.length; q++) { this._bringOnTop(wins[q]); } // if no more sticked search any non-top active and move them on top if (wins.length == 0) { for (var a in this.wins) { if (this.wins[a].className == "dhtmlx_window_active") { this._bringOnTop(this.wins[a]); } } } } /** * @desc: unloads an object and clears memory * @param: id - button's id * @type: public */ this.unload = function() { this._clearAll(); } this._removeButtonGlobal = function(winId, buttonId) { //#wind_buttons:09062008{ // if (!this.wins[winId]) return; if (!this.wins[winId].btns[buttonId]) return; var btn = this.wins[winId].btns[buttonId]; btn.title = null; btn.isVisible = null; btn._isEnabled = null; btn.isPressed = null; btn.label = null; btn._doOnClick = null; btn.detachAllEvents(); btn.attachEvent = null; btn.callEvent = null; btn.checkEvent = null; btn.detachEvent = null; btn.detachAllEvents = null; btn.disable = null; btn.enable = null; btn.eventCatcher = null; btn.hide = null; btn.isEnabled = null; btn.isHidden = null; btn.show = null; btn.onmousedown = null; btn.onmouseout = null; btn.onmouseover = null; btn.onmouseup = null; btn.ontouchstart = null; btn.ontouchend = null; if (btn.parentNode) btn.parentNode.removeChild(btn); btn = null; this.wins[winId].btns[buttonId] = null; delete this.wins[winId].btns[buttonId]; //#} } this._removeWindowGlobal = function(winId) { var win = this.wins[winId]; // modal check if (this.modalWin == win) this._setWindowModal(win, false); if (this.iframeMode && win.ifr) { win.ifr.parentNode.removeChild(win.ifr); win.ifr = null; } // clear attached frame events /* if (win._frame) { if (_isIE) { try { win._frame.onreadystatechange = null; win._frame.contentWindow.document.body.onmousedown = null; win._frame.onload = null; } catch(e) {} } else { try { win._frame.contentWindow.onmousedown = null; win._frame.onload = null; } catch(e) {} } } */ // clear cover events var t = win.coverBlocker(); t.onselectstart = null; t = null; // remove onselect event this._engineDiableOnSelectInWindow(win, false); // remove dhxcont win._dhxContDestruct(); // remove header events this._engineGetWindowHeader(win).onmousedown = null; this._engineGetWindowHeader(win).ondblclick = null; // clear links this.movingWin = null; this.resizingWin = null; // clearing buttons for (var a in win.btns) this._removeButtonGlobal(win, a); win.btns = null; win.detachAllEvents(); // clear win other events win._adjustToContent = null; win._doOnAttachMenu = null; win._doOnAttachStatusBar = null; win._doOnAttachToolbar = null; win._doOnFrameMouseDown = null; win._doOnFrameContentLoaded = null; // win._redraw = null; win.addUserButton = null; win.allowMove = null; win.allowPark = null; win.allowResize = null; win.attachEvent = null; win.bringToBottom = null; win.bringToTop = null; win.callEvent = null; win.center = null; win.centerOnScreen = null; win.checkEvent = null; win.clearIcon = null; win.close = null; win.denyMove = null; win.denyPark = null; win.denyResize = null; win.detachEvent = null; win.detachAllEvents = null; win.eventCatcher = null; win.getDimension = null; win.getIcon = null; win.getId = null; win.getMaxDimension = null; win.getMinDimension = null; win.getPosition = null; win.getText = null; win.hide = null; win.hideHeader = null; win.isHidden = null; win.isMaximized = null; win.isModal = null; win.isMovable = null; win.isOnBottom = null; win.isOnTop = null; win.isParkable = null; win.isParked = null; win.isResizable = null; win.isSticked = null; win.keepInViewport = null; win.maximize = null; win.minimize = null; win.park = null; win.progressOff = null; win.progressOn = null; win.removeUserButton = null; win.restoreIcon = null; win.setDimension = null; win.setIcon = null; win.setMaxDimension = null; win.setMinDimension = null; win.setModal = null; win.setPosition = null; win.setText = null; win.setToFullScreen = null; win.show = null; win.showHeader = null; win.stick = null; win.unstick = null; win.onmousemove = null; win.onmousedown = null; win.icons = null; win.button = null; win._dhxContDestruct = null; win.dhxContGlobal.obj = null; win.dhxContGlobal.setContent = null; win.dhxContGlobal.dhxcont = null; win.dhxContGlobal = null; // frame if (win._frame) { while (win._frame.childNodes.length > 0) win._frame.removeChild(win._frame.childNodes[0]); win._frame = null; } // clear functions this._parseNestedForEvents(win); // remove from page win._content = null; win.innerHTML = ""; win.parentNode.removeChild(win); win = null; this.wins[winId] = null; delete this.wins[winId]; } this._removeEvents = function(obj) { obj.onmouseover = null; obj.onmouseout = null; obj.onmousemove = null; obj.onclick = null; obj.ondblclick = null; obj.onmouseenter = null; obj.onmouseleave = null; obj.onmouseup = null; obj.onmousewheel = null; obj.onmousedown = null; obj.onselectstart = null; obj.onfocus = null; obj.style.display = ""; obj = null; } this._parseNestedForEvents = function(obj) { this._removeEvents(obj); for (var q=0; q<obj.childNodes.length; q++) { if (obj.childNodes[q].tagName != null) { this._parseNestedForEvents(obj.childNodes[q]); } } obj = null; } this._clearAll = function() { // remove events attached to document.body/window/viewport this._clearDocumentEvents(); // remove windows for (var a in this.wins) this._removeWindowGlobal(a); this.wins = null; // remove carcass this._parseNestedForEvents(this._carcass); while (this._carcass.childNodes.length > 0) this._carcass.removeChild(this._carcass.childNodes[0]); this._carcass.onselectstart = null; this._carcass.parentNode.removeChild(this._carcass); this._carcass = null; // remove viewport cover this._parseNestedForEvents(this._vpcover); this._vpcover.parentNode.removeChild(this._vpcover); this._vpcover = null; // remove modal covers this._parseNestedForEvents(this.modalCoverD); this.modalCoverD.parentNode.removeChild(this.modalCoverD); this.modalCoverD = null; this._parseNestedForEvents(this.modalCoverI); this.modalCoverI.parentNode.removeChild(this.modalCoverI); this.modalCoverI = null; // remove viewport // this.vp.className = String(this.vp.className).replace(/[a-z_]{1,}/gi,function(t){return({"dhtmlx_skin_dhx_skyblue":1,"dhtmlx_skin_dhx_blue":1,"dhtmlx_skin_dhx_black":1,"dhtmlx_skin_dhx_web":1}[t]==1?"":t);}); if (this.vp.autocreated == true) this.vp.parentNode.removeChild(this.vp); this.vp = null; // skin params for (var a in this.skinParams) { delete this.skinParams[a]; } this.skinParams = null; this._effects = null; this._engineSkinParams = null; this._addDefaultButtons = null; this._addUserButton = null; this._allowParking = null; this._allowReszieGlob = null; this._attachEventsOnButton = null; this._attachWindowContentTo = null; this._autoResizeViewport = null; this._blockSwitcher = null; this._bringOnBottom = null; this._bringOnTop = null; this._bringOnTopAnyStickedWindows = null; this._centerWindow = null; this._clearAll = null; this._clearDocumentEvents = null; this._clearWindowIcons = null; this._closeWindow = null; this._createViewport = null; this._denyParking = null; this._denyResize = null; this._dhx_Engine = null; this._disableButton = null; this._doOnMoseMove = null; this._doOnMouseUp = null; this._doOnResize = null; this._doOnSelectStart = null; this._doOnUnload = null; this._doParkDown = null; this._doParkUp = null; this._enableButton = null; this._engineAddUserButton = null; this._engineAdjustWindowToContent = null; this._engineAllowWindowResize = null; this._engineCheckHeaderMouseDown = null; this._engineDiableOnSelectInWindow = null; this._engineDoOnWindowParkDown = null; this._engineDoOnWindowParkUp = null; this._engineFixWindowPosInViewport = null; this._engineGetWindowButton = null; this._engineGetWindowContent = null; this._engineGetWindowHeader = null; this._engineGetWindowHeaderState = null; this._engineGetWindowLabel = null; this._engineGetWindowParkedHeight = null; this._engineRedrawSkin = null; this._engineRedrawWindowPos = null; this._engineRedrawWindowSize = null; this._engineRedrawWindowTitle = null; this._engineSetWindowBody = null; this._engineSwitchWindowHeader = null; this._engineSwitchWindowProgress = null; this._engineUpdateWindowIcon = null; this._fixWindowDimensionInViewport = null; this._genStr = null; this._getActive = null; this._getTopZIndex = null; this._getWindowIcon = null; this._hideButton = null; this._hideWindow = null; this._isWindowHidden = null; this._isWindowOnBottom = null; this._isWindowOnTop = null; this._makeActive = null; this._maximizeWindow = null; this._moveWindow = null; this._needHelp = null; this._parkWindow = null; this._parseNestedForEvents = null; this._removeButtonGlobal = null; this._removeEvents = null; this._removeUserButton = null; this._removeWindowGlobal = null; this._restoreWindow = null; this._restoreWindowIcons = null; this._setWindowIcon = null; this._setWindowModal = null; this._setWindowToFullScreen = null; this._showButton = null; this._showWindow = null; this._stickWindow = null; this._stopMove = null; this._unstickWindow = null; this.attachEvent = null; this.attachViewportTo = null; this.callEvent = null; this.checkEvent = null; this.createWindow = null; this.detachEvent = null; this.enableAutoViewport = null; this.eventCatcher = null; this.findByText = null; this.forEachWindow = null; this.getBottommostWindow = null; this.getEffect = null; this.getTopmostWindow = null; this.isWindow = null; this.setEffect = null; this.setImagePath = null; this.setSkin = null; this.setViewport = null; this.unload = null; this.window = null; that = null; } this._clearDocumentEvents = function() { if (_isIE) { window.detachEvent("onresize", this._doOnResize); document.body.detachEvent("onselectstart", this._doOnSelectStart); document.body.detachEvent("onmouseup", this._doOnMouseUp); document.body.detachEvent("onunload", this._doOnUnload); this.vp.detachEvent("onmousemove", this._doOnMoseMove); this.vp.detachEvent("onmouseup", this._doOnMouseUp); } else { window.removeEventListener("resize", this._doOnResize, false); document.body.removeEventListener("mouseup", this._doOnMouseUp, false); document.body.removeEventListener("unload", this._doOnUnload, false); this.vp.removeEventListener("mousemove", this._doOnMoseMove, false); this.vp.removeEventListener("mouseup", this._doOnMouseUp, false); } } /* additional features */ /* if (this._enableStatusBar != null) { this._enableStatusBar(); } if (this._enableWebMenu != null) { this._enableWebMenu(); } if (this._enableWebToolbar != null) { this._enableWebToolbar(); } */ this._genStr = function(w) { var s = ""; var z = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; for (var q=0; q<w; q++) s += z.charAt(Math.round(Math.random() * (z.length-1))); return s; } dhtmlxEventable(this); return this; }; dhtmlXWindows.prototype._dhx_Engine = function() { // engine init params this._engineEnabled = true; this._engineName = "dhx"; // skin params // mh = menu height // th = toolbar height // sh = statusbar height this._engineSkinParams = {dhx_blue: {"hh": 21, "lbw": 2, "rbw": 2, "lch": 2, "lcw": 14, "rch": 14, "rcw": 14, "bbh": 2, "mnh": 23, "tbh": 25, "sbh": 20, "noh_t": null, "noh_h": null}, dhx_black: {"hh": 21, "lbw": 2, "rbw": 2, "lch": 2, "lcw": 14, "rch": 14, "rcw": 14, "bbh": 2, "mnh": 23, "tbh": 25, "sbh": 20, "noh_t": null, "noh_h": null}, dhx_skyblue: {"hh": 29, "lbw": 2, "rbw": 2, "lch": 2, "lcw": 14, "rch": 14, "rcw": 14, "bbh": 2, "mnh": 23, "tbh": 25, "sbh": 20, "noh_t": 5, "noh_h": -10}, dhx_web: {"hh": 27, "lbw": 5, "rbw": 5, "lch": 5, "lcw": 14, "rch": 14, "rcw": 14, "bbh": 5, "mnh": 23, "tbh": 25, "sbh": 20, "noh_t": 5, "noh_h": -10}, dhx_terrace: {"hh": 37, "lbw": 5, "rbw": 5, "lch": 5, "lcw": 14, "rch": 14, "rcw": 14, "bbh": 5, "mnh": 23, "tbh": 25, "sbh": 20, "noh_t": 0, "noh_h": -10} }; this._isIE6 = false; if (_isIE) this._isIE6 = (window.XMLHttpRequest==null?true:false); // forms window html this._engineSetWindowBody = function(win) { win.innerHTML = "<div iswin='1' class='dhtmlx_wins_body_outer' style='position: relative;'>"+ (this._isIE6?"<iframe src='javascript:false;' frameborder='0' class='dhtmlx_wins_ie6_cover_fix' onload='this.contentWindow.document.body.style.overflow=\"hidden\";'></iframe>":"")+ "<div class='dhtmlx_wins_icon'></div>"+ "<div class='dhtmlx_wins_progress'></div>"+ "<div class='dhtmlx_wins_title'>dhtmlxWindow</div>"+ "<div class='dhtmlx_wins_btns'>"+ "<div class='dhtmlx_wins_btns_button dhtmlx_button_sticked_default'></div>"+ "<div class='dhtmlx_wins_btns_button dhtmlx_button_stick_default'></div>"+ "<div class='dhtmlx_wins_btns_button dhtmlx_button_help_default'></div>"+ "<div class='dhtmlx_wins_btns_button dhtmlx_button_park_default'></div>"+ "<div class='dhtmlx_wins_btns_button dhtmlx_button_minmax2_default'></div>"+ "<div class='dhtmlx_wins_btns_button dhtmlx_button_minmax1_default'></div>"+ "<div class='dhtmlx_wins_btns_button dhtmlx_button_close_default'></div>"+ "<div class='dhtmlx_wins_btns_button dhtmlx_button_dock_default'></div>"+ "</div>"+ "<div class='dhtmlx_wins_body_inner'></div>"+ "<div winResT='yes' class='dhtmlx_wins_resizer_t' style='display:none;'></div>"+ "<div winResL='yes' class='dhtmlx_wins_resizer_l'></div>"+ "<div winResR='yes' class='dhtmlx_wins_resizer_r'></div>"+ "<div winResB='yes' class='dhtmlx_wins_resizer_b'></div>"+ "<div class='white_line'></div>"+ "<div class='white_line2'></div>"+ "</div>"; // dhxCont(win); win.dhxContGlobal = new dhtmlXContainer(win); if (this.skin == "dhx_skyblue") { win.dhxContGlobal.obj._offsetWidth = -10; win.dhxContGlobal.obj._offsetHeight = -5; win.dhxContGlobal.obj._offsetLeft = 5; win.dhxContGlobal.obj._offsetHeightSaved = win.dhxContGlobal.obj._offsetHeight; } if (this.skin == "dhx_web") { win.dhxContGlobal.obj._offsetWidth = -10; win.dhxContGlobal.obj._offsetHeight = -5; win.dhxContGlobal.obj._offsetLeft = 5; win.dhxContGlobal.obj._offsetHeightSaved = win.dhxContGlobal.obj._offsetHeight; } win.skin = this.skin; win.dhxContGlobal.setContent(win.childNodes[0].childNodes[(this._isIE6?5:4)]); var t = win.coverBlocker(); t.onselectstart = function(e) { e = e||event; e.returnValue = false; e.cancelBubble = true; } t = null; if (this.iframeMode) { win.ifr = document.createElement("IFRAME"); win.ifr.style.position = "absolute"; win.ifr.style.left = win.style.left; win.ifr.style.top = win.style.top; win.ifr.style.width = win.style.width; win.ifr.style.height = win.style.height; win.ifr.style.zIndex = win.style.zIndex-1; win.ifr.style.backgroundColor = "white"; win.ifr.frameBorder = 0; win.ifr.setAttribute("src","javascript:false;"); win.parentNode.appendChild(win.ifr); } } // block selection this._engineDiableOnSelectInWindow = function(win, state) { var data = new Array(); data[0] = win.childNodes[0].childNodes[(this._isIE6?1:0)]; data[1] = win.childNodes[0].childNodes[(this._isIE6?2:1)]; data[2] = win.childNodes[0].childNodes[(this._isIE6?3:2)]; data[3] = win.childNodes[0].childNodes[(this._isIE6?4:3)]; // resizers data[4] = win.childNodes[0].childNodes[(this._isIE6?6:5)]; data[5] = win.childNodes[0].childNodes[(this._isIE6?7:6)]; data[6] = win.childNodes[0].childNodes[(this._isIE6?8:7)]; data[7] = win.childNodes[0].childNodes[(this._isIE6?9:8)]; for (var q=0; q<data.length; q++) { //console.log(data[q]) data[q].onselectstart = (state?function(e){e=e||event;e.returnValue=false;return false;}:null); data[q] = null; } data = null; } // return window header this._engineGetWindowHeader = function(win) { win.childNodes[0].idd = win.idd; return win.childNodes[0]; } // setting correct size for window this._engineRedrawWindowSize = function(win) { win.style.width = (String(win.w).search("%")==-1?win.w+"px":win.w); win.style.height = (String(win.h).search("%")==-1?win.h+"px":win.h); var body = win.childNodes[0]; body.style.width = win.clientWidth+"px"; body.style.height = win.clientHeight+"px"; if (body.offsetWidth > win.clientWidth) { body.style.width = win.clientWidth*2-body.offsetWidth+"px"; } if (body.offsetHeight > win.clientHeight) { // park check var px = win.clientHeight*2-body.offsetHeight; if (px < 0) px = 0; // body.style.height = px+"px"; } var hh = (win._noHeader==true?win._hdrSize:this._engineSkinParams[this.skin]["hh"]); if (this.iframeMode && win.ifr) { win.ifr.style.width = win.style.width; win.ifr.style.height = win.style.height; } // header this._engineRedrawWindowTitle(win); win.adjustContent(body, hh); // this.updateNestedObjects(); } // redraw window position this._engineRedrawWindowPos = function(win) { if (win._isFullScreened) return; win.style.left = win.x + "px"; win.style.top = win.y + "px"; if (this.iframeMode && win.ifr) { win.ifr.style.top = win.style.top; win.ifr.style.left = win.style.left; } } // fixing window position in viewport this._engineFixWindowPosInViewport = function(win) { // var hh = this._engineSkinParams[this.skin]["hh"]; var hh = (win._noHeader==true?win._hdrSize:this._engineSkinParams[this.skin]["hh"]); if (win._keepInViewport) { // keep strongly in viewport if (win.x < 0) { win.x = 0; } if (win.x + win.w > this.vp.offsetWidth) { win.x = this.vp.offsetWidth - win.w; } // if (win.y < 0) { win.y = 0; } if (win.y + win.h > this.vp.offsetHeight) { win.y = this.vp.offsetHeight - win.h; } if (win.y < 0) { win.y = 0; } } else { // if (win.y < 0) { win.y = 0; } if (win.y + hh > this.vp.offsetHeight) { win.y = this.vp.offsetHeight - hh; } if (win.y < 0) { win.y = 0; } if (win.x + win.w - 10 < 0) { win.x = 10 - win.w; } if (win.x > this.vp.offsetWidth - 10) { win.x = this.vp.offsetWidth - 10; } } } // check is header in onmousedown this._engineCheckHeaderMouseDown = function(win, ev) { if (this._isIPad) { var x = ev.touches[0].clientX; var y = ev.touches[0].clientY; var obj = ev.target||ev.srcElement; if (obj == win.childNodes[0] || obj == win.childNodes[0].childNodes[0] || obj == win.childNodes[0].childNodes[2] || obj == win.childNodes[0].childNodes[3]) return true; return false; } else { var x = (_isIE||_isOpera?ev.offsetX:ev.layerX); var y = (_isIE||_isOpera?ev.offsetY:ev.layerY); var obj = ev.target||ev.srcElement; } var hh = (win._noHeader==true?win._hdrSize:this._engineSkinParams[this.skin]["hh"]); if (y <= hh && (obj == win.childNodes[0] || obj == win.childNodes[0].childNodes[(this._isIE6?1:0)] || obj == win.childNodes[0].childNodes[(this._isIE6?3:2)] || obj == win.childNodes[0].childNodes[(this._isIE6?4:3)])) return true; return false; } // return window content this._engineGetWindowContent = function(win) { alert("_engineGetWindowContent"); /* var contObj = null; var contPoly = win.childNodes[0].childNodes[(this._isIE6?5:4)]; for (var q=0; q<contPoly.childNodes.length; q++) { if (contPoly.childNodes[q].getAttribute("iscont") != null) { if (contPoly.childNodes[q].getAttribute("iscont") === "1") { contObj = contPoly.childNodes[q]; } } } if (contObj != null) { win._contObj = contObj; } else { if (win._contObj != null) { contObj = win._contObj; } } return contObj; //.childNodes[0]; */ } // return window button this._engineGetWindowButton = function(win, buttonName) { buttonName = String(buttonName).toLowerCase(); var buttonObj = null; var buttonStyle = "dhtmlx_button_"+buttonName+"_"; for (var q=0; q<win.childNodes[0].childNodes[(this._isIE6?4:3)].childNodes.length; q++) { var buttonTemp = win.childNodes[0].childNodes[(this._isIE6?4:3)].childNodes[q]; if (String(buttonTemp.className).search(buttonStyle) != -1) { buttonObj = buttonTemp; } buttonTemp = null; } return buttonObj; } // adding user button this._engineAddUserButton = function(win, buttonName, buttonPos) { if (isNaN(buttonPos)) buttonPos = 0; var button = document.createElement("DIV"); button.className = "dhtmlx_wins_btns_button dhtmlx_button_"+buttonName+"_default"; var buttonPoly = win.childNodes[0].childNodes[(this._isIE6?4:3)]; buttonPos = buttonPoly.childNodes.length - buttonPos; if (buttonPos < 0) buttonPos = 0; if (buttonPos >= buttonPoly.childNodes.length) { buttonPoly.appendChild(button); } else { buttonPoly.insertBefore(button, buttonPoly.childNodes[buttonPos]); } this._engineRedrawWindowTitle(win); return button; } // return min park height this._engineGetWindowParkedHeight = function(win) { return this._engineSkinParams[this.skin]["hh"]+1; } // do on window park down this._engineDoOnWindowParkDown = function(win) { // console.log(1) win.childNodes[0].childNodes[(this._isIE6?6:5)].style.display = (win._noHeader==true?"":"none"); win.childNodes[0].childNodes[(this._isIE6?7:6)].style.display = ""; win.childNodes[0].childNodes[(this._isIE6?8:7)].style.display = ""; win.childNodes[0].childNodes[(this._isIE6?9:8)].style.display = ""; } // do on window park up this._engineDoOnWindowParkUp = function(win) { win.childNodes[0].childNodes[(this._isIE6?6:5)].style.display = "none"; win.childNodes[0].childNodes[(this._isIE6?7:6)].style.display = "none"; win.childNodes[0].childNodes[(this._isIE6?8:7)].style.display = "none"; win.childNodes[0].childNodes[(this._isIE6?9:8)].style.display = "none"; } // update window's icon this._engineUpdateWindowIcon = function(win, icon) { win.childNodes[0].childNodes[(this._isIE6?1:0)].style.backgroundImage = "url('"+icon+"')"; } // check is targetObj a windows node and is resize allowed this._engineAllowWindowResize = function(win, targetObj, mouseX, mouseY) { // IE fix for disabled input if (!targetObj.getAttribute) return; // var sk = this._engineSkinParams[this.skin]; var hh = (win._noHeader==true?win._hdrSize:this._engineSkinParams[this.skin]["hh"]); if (targetObj.getAttribute("winResL") != null) { if (targetObj.getAttribute("winResL") == "yes") { if (mouseY >= hh) { if (mouseY >= win.h - sk["lch"]) return "corner_left"; if (mouseY <= sk["lch"] && win._noHeader == true) return "corner_up_left"; return "border_left"; } } } if (targetObj.getAttribute("winResR") != null) { if (targetObj.getAttribute("winResR") == "yes") { if (mouseY >= hh) { if (mouseY >= win.h - sk["rch"]) return "corner_right"; if (mouseY <= sk["rch"] && win._noHeader == true) return "corner_up_right"; return "border_right"; } } } if (targetObj.getAttribute("winResT") != null) { if (targetObj.getAttribute("winResT") == "yes" && win._noHeader == true) { if (mouseX <= sk["lcw"]) return "corner_up_left"; if (mouseX >= win.w - sk["rcw"]) return "corner_up_right"; return "border_top"; } } if (targetObj.getAttribute("winResB") != null) { if (targetObj.getAttribute("winResB") == "yes") { if (mouseX <= sk["lcw"]) return "corner_left"; if (mouseX >= win.w - sk["rcw"]) return "corner_right"; return "border_bottom"; } } return null; } // adjusting window to content size this._engineAdjustWindowToContent = function(win, w, h) { var newW = w+win.w-win.vs[win.av].dhxcont.clientWidth; var newH = h+win.h-win.vs[win.av].dhxcont.clientHeight; win.setDimension(newW, newH); } // redraw windows skin this._engineRedrawSkin = function() { this.vp.className = (this.vp==document.body&&this.vp._css?this.vp._css+" ":"")+"dhtmlx_winviewport dhtmlx_skin_"+this.skin+(this._r?" dhx_wins_rtl":""); var sk = this._engineSkinParams[this.skin]; for (var a in this.wins) { if (this.skin == "dhx_skyblue") { this.wins[a].dhxContGlobal.obj._offsetTop = (this.wins[a]._noHeader?sk["noh_t"]:null); this.wins[a].dhxContGlobal.obj._offsetWidth = -10; this.wins[a].dhxContGlobal.obj._offsetHeight = (this.wins[a]._noHeader?sk["noh_h"]:-5); this.wins[a].dhxContGlobal.obj._offsetLeft = 5; this.wins[a].dhxContGlobal.obj._offsetHeightSaved = -5; } else { this.wins[a].dhxContGlobal.obj._offsetWidth = null; this.wins[a].dhxContGlobal.obj._offsetHeight = null; this.wins[a].dhxContGlobal.obj._offsetLeft = null; this.wins[a].dhxContGlobal.obj._offsetTop = null; this.wins[a].dhxContGlobal.obj._offsetHeightSaved = null; } this.wins[a].skin = this.skin; this._restoreWindowIcons(this.wins[a]); this._engineRedrawWindowSize(this.wins[a]); } } // enable/disable window loader this._engineSwitchWindowProgress = function(win, state) { if (state == true) { win.childNodes[0].childNodes[(this._isIE6?1:0)].style.display = "none"; win.childNodes[0].childNodes[(this._isIE6?2:1)].style.display = ""; } else { win.childNodes[0].childNodes[(this._isIE6?2:1)].style.display = "none"; win.childNodes[0].childNodes[(this._isIE6?1:0)].style.display = ""; } } // show/hide window header this._engineSwitchWindowHeader = function(win, state) { if (!win._noHeader) win._noHeader = false; if (state != win._noHeader) return; // win._noHeader = (state==true?false:true); win._hdrSize = 0; win.childNodes[0].childNodes[(this._isIE6?5:4)].className = "dhtmlx_wins_body_inner"+(win._noHeader?" dhtmlx_wins_no_header":""); win.childNodes[0].childNodes[(this._isIE6?6:5)].style.display = (win._noHeader?"":"none"); win.childNodes[0].childNodes[(this._isIE6?1:0)].style.display = (win._noHeader?"none":""); // title win.childNodes[0].childNodes[(this._isIE6?3:2)].style.display = (win._noHeader?"none":""); // buttons win.childNodes[0].childNodes[(this._isIE6?4:3)].style.display = (win._noHeader?"none":""); // var sk = this._engineSkinParams[this.skin]; if (win._noHeader) { win.dhxContGlobal.obj._offsetHeightSaved = win.dhxContGlobal.obj._offsetHeight; win.dhxContGlobal.obj._offsetHeight = sk["noh_h"]; win.dhxContGlobal.obj._offsetTop = sk["noh_t"]; } else { win.dhxContGlobal.obj._offsetHeight = win.dhxContGlobal.obj._offsetHeightSaved; win.dhxContGlobal.obj._offsetTop = null; } this._engineRedrawWindowSize(win); } // return true if header is visible this._engineGetWindowHeaderState = function(win) { return (win._noHeader?true:false); } // return window label this._engineGetWindowLabel = function(win) { return win.childNodes[0].childNodes[(this._isIE6?3:2)]; } // redraw window's header text this._engineRedrawWindowTitle = function(win) { if (win._noHeader!==true) { var p2 = win.childNodes[0].childNodes[(this._isIE6?1:0)].offsetWidth; // icon var p3 = win.childNodes[0].childNodes[(this._isIE6?4:3)].offsetWidth; // buttons var newW = win.offsetWidth-p2-p3-24; if (newW < 0) newW = "100%"; else newW += "px"; win.childNodes[0].childNodes[(this._isIE6?3:2)].style.width = newW; /* var p1 = win.childNodes[0].childNodes[(this._isIE6?3:2)].offsetLeft; var p2 = win.childNodes[0].childNodes[(this._isIE6?4:3)].offsetWidth; var newW = win.offsetWidth-p1-p2-16; if (newW < 0) { newW = "100%"; } else { newW += "px"; } win.childNodes[0].childNodes[(this._isIE6?3:2)].style.width = newW; */ } } }; dhtmlXWindows.prototype.i18n = { dhxcontaler: "dhtmlxcontainer.js is missed on the page", noenginealert: "No dhtmlxWindows engine was found.", stick: "Stick", unstick: "Unstick", help: "Help", parkdown: "Park Down", parkup: "Park Up", maximize: "Maximize", restore: "Restore", close: "Close", dock: "Dock" }; (function(){ dhtmlx.extend_api("dhtmlXWindows",{ _init:function(obj){ return []; }, _patch:function(obj){ obj.old_createWindow=obj.createWindow; obj.createWindow=function(obj){ if (arguments.length>1) return this.old_createWindow.apply(this,arguments); var res = this.old_createWindow(obj.id,(obj.x||obj.left),(obj.y||obj.top),obj.width,obj.height); res.allowMoveA=function(mode){ if (mode) this.allowMove(); else this.denyMove(); } res.allowParkA=function(mode){ if (mode) this.allowPark(); else this.denyPark(); } res.allowResizeA=function(mode){ if (mode) this.allowResize(); else this.denyResize(); } //local settings for (var a in obj){ if (map[a]) res[map[a]](obj[a]); else if (a.indexOf("on")==0){ res.attachEvent(a,obj[a]); } } return res; } }, animation:"setEffect", image_path:"setImagePath", skin:"setSkin", viewport:"_viewport", wins:"_wins" },{ _viewport:function(data){ if (data.object) { this.enableAutoViewport(false); this.attachViewportTo(data.object); } else { this.enableAutoViewport(false); this.setViewport(data.left, data.top, data.width, data.height, data.parent); } }, _wins:function(arr){ for (var q=0; q<arr.length; q++) { var win = arr[q]; this.createWindow(win.id, win.left, win.top, win.width, win.height); if (win.text) this.window(win.id).setText(win.text); if (win.keep_in_viewport) this.window(win.id).keepInViewport(true); if (win.deny_resize) this.window(win.id).denyResize(); if (win.deny_park) this.window(win.id).denyPark(); if (win.deny_move) this.window(win.id).denyMove(); } } }); var map={ move:"allowMoveA", park:"allowParkA", resize:"allowResizeA", center:"center", modal:"setModal", caption:"setText", header:"showHeader" }; })();
var ColorPicker = function($parent, callback, colorC){ var Fce = function(tag){return document.createElement(tag);} var FValidateColor = function(color){if(!color){return false;} if(color.match(new RegExp("^#(([0-9a-f]{3})|([0-9a-f]{6}))$","i"))) return true; else return false}; var color = FValidateColor(colorC) ? colorC : '#ffffff'; var colors = new Array( new Array('ffffff','ffcccc','ffcc99','ffff99','ffffcc','99ff99','99ffff','ccffff','ccccff','ffccff'), new Array('cccccc','ff6666','ff9966','ffff66','ffff33','66ff99','33ffff','66ffff','9999ff','ff99ff'), new Array('c0c0c0','ff0000','ff9900','ffcc66','ffff00','33ff33','66cccc','33ccff','6666cc','cc66cc'), new Array('999999','cc0000','ff6600','ffcc33','ffcc00','33cc00','00cccc','3366ff','6633ff','cc33cc'), new Array('666666','990000','cc6600','cc9933','999900','009900','339999','3333ff','6600cc','993399'), new Array('333333','660000','993300','996633','666600','006600','336666','000099','333399','663366'), new Array('222222','550000','883300','883300','555500','004400','225555','000077','222288','441144'), new Array('000000','330000','663300','663333','333300','003300','003333','000066','330099','330033') ); var $colorTable = $(Fce('tbody')); var $colorTableWB = $(Fce('table')).attr('cellspacing','3').addClass('colorPicker').append($colorTable); var $coloredTd = $('<td colspan="5"></td>').css({backgroundColor:color}); var $colorInput = $(Fce('input')).attr('type', 'text').attr('class', 'colorCode').attr('value', color).bind('keyup', function(){ if( FValidateColor($colorInput.attr('value')) ){ color = $colorInput.attr('value'); $coloredTd.css({backgroundColor:$colorInput.attr('value')}); } } ); var $colorInputSubmit = $(Fce('input')).attr('type', 'button').attr('value', 'Ok').attr('class', 'ow_ic_ok').bind('click', function(){callback(color);}); var $colorInputSubmitWrapper = $('<span class="ow_ic_ok"></span>').append($colorInputSubmit); $colorInputSubmitWrapper = $('<span class="ow_button"></span>').append($colorInputSubmitWrapper); var $colorInputCont = $('<td colspan="5"></td>').append($colorInput).append($colorInputSubmitWrapper); var $inputTr = $(Fce('tr')).append($coloredTd).append($colorInputCont); $colorTable.append($inputTr); for(i=0;i<colors.length;i++){ var $colorTr = $(Fce('tr')); for(j=0;j<colors[i].length;j++){ var $colorTd = $(Fce('td')).css({backgroundColor:'#'+colors[i][j],cursor:'pointer'}).bind('click',{color:'#'+colors[i][j]}, function(e){ color = e.data.color; $coloredTd.css({backgroundColor:color}); callback(color); } ); $colorTr.append($colorTd); } $colorTable.append($colorTr); } $midDiv = $(Fce('div')).attr('class', 'special_block_mid').append($colorTableWB); $parent.append($(Fce('div')).attr('class', 'special_block_top')).append($midDiv).append($(Fce('div')).attr('class', 'special_block_bot')); this.setColor = function(colorP){ if(!FValidateColor(color)){alert('Invalid color code!!!');return;} color = colorP; $coloredTd.css({backgroundColor:colorP}); $colorInput.attr('value', colorP); } this.getColor = function(){return color;} }
// Copyright (C) 2015 André Bargull. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es6id: B.2.1.2 description: > unescape.length is 1. info: > unescape (string) 17 ECMAScript Standard Built-in Objects: Every built-in Function object, including constructors, has a length property whose value is an integer. Unless otherwise specified, this value is equal to the largest number of named arguments shown in the subclause headings for the function description, including optional parameters. However, rest parameters shown using the form “...name” are not included in the default argument count. Unless otherwise specified, the length property of a built-in Function object has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }. includes: [propertyHelper.js] ---*/ assert.sameValue(unescape.length, 1); verifyNotEnumerable(unescape, "length"); verifyNotWritable(unescape, "length"); verifyConfigurable(unescape, "length");