code stringlengths 2 1.05M |
|---|
var CompositeDisposable = require('atom').CompositeDisposable;
module.exports = {
subscriptions: null,
activate: function(state) {
var _this = this;
this.subscriptions = new CompositeDisposable;
return this.subscriptions.add(atom.commands.add('atom-workspace', {
'atom-bemmet:convert': function() {
return _this.convert();
}
}));
},
deactivate: function() {
return this.subscriptions.dispose();
},
convert: function() {
var editor = atom.workspace.getActiveTextEditor();
if (!editor) return;
var bemmet = require('bemmet'),
selection = editor.getSelectedText(),
caretPos = editor.getCursorBufferPosition(),
rangeBeforeCaret = [[0, 0], caretPos],
textBeforeCaret = editor.getTextInBufferRange(rangeBeforeCaret);
if (selection && !(new RegExp(selection + '$')).test(textBeforeCaret)) {
rangeBeforeCaret = [[0, 0], [caretPos.row, caretPos.column + selection.length]];
textBeforeCaret += selection;
}
if (!selection) {
var textBeforeCaretNoSpaces = textBeforeCaret.replace(/\{(.*)\}/g, function(str) {
return str.replace(/\ /g, 'S');
});
var lastSpaceSymbol = /\s/.exec(textBeforeCaretNoSpaces.split('').reverse().join('')),
spaceNearCaretIdx = lastSpaceSymbol && textBeforeCaretNoSpaces.lastIndexOf(lastSpaceSymbol[0]);
selection = ((typeof spaceNearCaretIdx !== null && spaceNearCaretIdx > -1) ? textBeforeCaret.substr(spaceNearCaretIdx) : textBeforeCaret).trim();
}
var parentBlock = /block['"\s]*:(?:\s)?['"]{1}(.*?)['"]{1}/.exec(textBeforeCaret.substr(textBeforeCaret.lastIndexOf('block')));
parentBlock && parentBlock[1] && (parentBlock = parentBlock[1]);
var bemjson = '';
try {
bemjson = bemmet.stringify(selection, parentBlock);
} catch(err) {
console.error(err);
}
var indexOfSelection = textBeforeCaret.lastIndexOf(selection),
replacedContent = '';
if (bemjson && indexOfSelection >= 0) {
replacedContent = textBeforeCaret.substring(0, indexOfSelection) + bemjson + textBeforeCaret.substring(indexOfSelection + selection.length);
}
replacedContent && editor.setTextInBufferRange(rangeBeforeCaret, replacedContent);
// reindent inserted content
caretPos = editor.getCursorBufferPosition();
editor.selectUp(bemjson.split('\n').length);
atom.commands.dispatch(atom.views.getView(editor), 'editor:auto-indent');
editor.setSelectedBufferRange([caretPos, caretPos]);
}
};
|
import React from 'react'
import { patchData } from '../../helpers'
class ChangeTranscript extends React.Component {
constructor(){
super()
this.confirm = this.confirm.bind(this)
this.blacklistTranscript = this.blacklistTranscript.bind(this)
this.state = {
confirmChange:false,
}
}
confirm(){
if(this.state.confirmChange) {
this.setState({confirmChange:false})
} else {
this.setState({confirmChange:true})
}
}
blacklistTranscript(){
let pk = this.props.pk,
user = this.props.user,
url = `/api/profile/${user}/skip_transcript/`,
data = {'transcript':pk}
patchData(url, data).then((resp)=>{
this.props.reload()
})
}
render(){
let ui
if(this.state.confirmChange) {
ui = <div className='confirm'>
<button className='dismiss' onClick={() => this.confirm()}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500">
<title>Dismiss</title>
<path d="M340.2 160l-84.4 84.2-84-83.8-11.8 11.8 84 83.8-84 83.8 11.8 11.8 84-83.8 84.4 84.2 11.8-11.8-84.4-84.2 84.4-84.2"/>
</svg>
</button>
<p>Want to try a different transcript?</p>
<button onClick={() => this.blacklistTranscript()}>Yes</button>
<button onClick={() => this.confirm()}>No</button>
</div>
}
else {
ui = <button className='change-transcript-button' onClick={() => this.confirm()}>Try another transcript</button>
}
return(
<div className='change-transcript'>
{ui}
</div>
)
}
}
export default ChangeTranscript; |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mysql = require("mysql");
const config_1 = require("./config");
let pool = mysql.createPool(Object.assign({}, config_1.db));
exports.default = pool;
//# sourceMappingURL=db.js.map |
'use strict';
var Hoopla = require('hoopla');
var Request = require('./messages/Request');
var Response = require('./messages/Response');
var HttpRequestEvent = require('./events/HttpRequestEvent');
var HttpResponseEvent = require('./events/HttpResponseEvent');
var encodeAttributes = require('./utilities/encodeAttributes');
var isPlainObject = require('./utilities/isPlainObject');
var isEmptyObject = require('./utilities/isEmptyObject');
/**
* The Http client. Creates and sends requests.
*
* @class Http
* @param {Object} driver Must implement `send(request, callback)`
* @param {Hoopla} [dispatcher] Overrides the default event dispatcher
*/
function Http(driver, dispatcher) {
if (!dispatcher) {
dispatcher = new Hoopla();
}
this._driver = driver || Http.getDefaultDriver();
this._dispatcher = dispatcher;
}
var proto = Http.prototype;
/**
* Create a request object
*
* @method request
* @memberof Http.prototype
* @param {string} method The HTTP method (GET, POST, etc.)
* @param {string} url The request url
* @param {*} [contents] The request body
* @param {Headers|Object} [headers] Request headers
* @return {Request} The new Request object
*/
proto.request = function(method, url, contents, headers) {
var request = new Request(method, url, contents, headers);
request.setHttp(this);
return request;
};
/**
* Creates a GET request, optionally with encoded attributes
*
* @method get
* @memberof Http.prototype
* @see {@link Http#request}
* @param {string} url The request url
* @param {Object} [attributes] Attributes to be converted to GET parameters
* @param {Headers|Object} [headers] Request headers
* @return {request} The new GET Request object
*/
proto.get = function(url, attributes, headers) {
if (isPlainObject(attributes) && !isEmptyObject(attributes)) {
url = url + '?' + encodeAttributes(attributes);
}
return this.request('GET', url, undefined, headers);
};
/**
* Creates a POST request, a shortcut for `request('POST', ...)`
*
* @method post
* @memberof Http.prototype
* @see {@link Http#request}
* @param {string} url The request url
* @param {*} contents The request body
* @param {Headers|Object} headers Request headers
* @return {Request} The new POST Request object
*/
proto.post = function(url, contents, headers) {
return this.request('POST', url, contents, headers);
};
/**
* Sends a Request
*
* Sends a request instance to the driver. Returns a promise
* that is resolved with a Response object. If the request
* is unsuccessful, the promise is rejected with a Response object.
*
* Triggers `http.request` immediately, request handlers may modify
* the `Request` object before it is sent.
*
* Triggers `http.response` when the driver returns the response.
* Response handlers may modify the response before the promise is
* resolved.
*
* @method send
* @memberof Http.prototype
* @param {Request} request The request to send
* @param {function(response)} onResolve A callback to be run on success
* @param {function(response)} onReject A callback to be run on failure
* @return {Promise<Response, Response>} A Promise resolved or rejected with a Response object
*/
proto.send = function(request, onResolve, onReject) {
var self = this;
request = dispatchRequest(self, request);
var promise = new Http.Promise(function(resolve, reject) {
self._driver.send(request, function(response) {
if (!(response instanceof Response)) {
throw new Error('send callback must be called with a Response instance');
}
response = dispatchResponse(self, response);
if (response.isSuccessful()) {
resolve(response);
} else {
reject(response);
}
});
});
promise.then(onResolve, onReject);
return promise;
};
/**
* Gets the internal event dispatcher
*
* @method getDispatcher
* @memberof Http.prototype
* @alias module:http#getDispatcher
* @return {Hoopla} The Hoopla event dispatcher
*/
proto.getDispatcher = function() {
return this._dispatcher;
};
/**
* Add an extension
*
* @method addExtension
* @memberof Http.prototype
* @alias module:http#addExtension
* @param {Object} extension An extension implementing the `register(http)` function
* @return [Http] `this`
*/
proto.addExtension = function(extension) {
extension.register(this);
return this;
};
/**
* Gets a new instance of the default drivers
*
* This is NodeDriver in a node environment, and XmlHttpRequestDriver
* in a browser environment. This can be overridden to return
* the driver of your choice.
*
* @return {driver} A new default driver instance
*/
Http.getDefaultDriver = function() {};
function dispatchRequest(self, request) {
var event = new HttpRequestEvent(request);
self._dispatcher.dispatch(event);
return event.getRequest();
}
function dispatchResponse(self, response) {
var event = new HttpResponseEvent(response);
self._dispatcher.dispatch(event);
return event.getResponse();
}
module.exports = Http;
|
import { getRenderedVm, createVue, destroyVM } from '../utils'
import CellBox from 'components/cell-box'
describe('component cell-box testing', () => {
let vm
afterEach(() => {
destroyVM(vm)
})
it('should render correct classes', () => {
vm = getRenderedVm(CellBox, {})
expect(vm.$el.className).toEqual('yui-cells-box')
})
it('should render props:title', () => {
vm = getRenderedVm(CellBox, {
title: 'title'
})
expect(vm.title).toEqual('title')
expect(vm.$el.querySelector('.yui-cells-title').textContent).toEqual('title')
})
it('child render', () => {
vm = createVue({
template: `
<cell-box title="ๅ่กจ">
<cell title="haha" desc="asasa" value="asas"></cell>
<cell title="haha" desc="asasa" value="asas"></cell>
</cell-box>
`
})
expect(vm.$el.querySelectorAll('.yui-cell').length).toEqual(2)
})
}) |
"use strict";
module.exports = {
AdonError: require('./errors/AdonError'),
command: {
CommandError: require('./errors/command/CommandError'),
CommandInvalidError: require('./errors/command/CommandInvalidError'),
CommandNotFoundError: require('./errors/command/CommandNotFoundError')
},
database: {
DatabaseError: require('./errors/database/DatabaseError'),
connection: {
DatabaseConnectionError: require('./errors/database/connection/DatabaseConnectionError'),
DatabaseConnectionRejectedError: require('./errors/database/connection/DatabaseConnectionRejectedError'),
},
result: {
DatabaseResultCreateError: require('./errors/database/result/DatabaseResultCreateError'),
DatabaseResultDisabledError: require('./errors/database/result/DatabaseResultDisabledError'),
DatabaseResultError: require('./errors/database/result/DatabaseResultError'),
DatabaseResultNotFoundError: require('./errors/database/result/DatabaseResultNotFoundError'),
DatabaseResultUniqueCollisionError: require('./errors/database/result/DatabaseResultUniqueCollisionError'),
}
},
input: {
InputError: require('./errors/input/InputError'),
InputRequiredError: require('./errors/input/InputRequiredError'),
InputValidationError: require('./errors/input/InputValidationError'),
},
security: {
SecurityError: require('./errors/security/SecurityError'),
authentication: {
AuthenticationError: require('./errors/security/authentication/AuthenticationError'),
},
authorization: {
AuthorizationError: require('./errors/security/authorization/AuthorizationError'),
AuthorizationAccessError: require('./errors/security/authorization/AuthorizationAccessError'),
}
},
server: {
ServerError: require('./errors/server/ServerError'),
},
session: {
SessionError: require('./errors/session/SessionError'),
SessionNotFoundError: require('./errors/session/SessionNotFoundError')
}
}; |
/*
* @name jQuery.bootcomplete
* @projectDescription Lightweight AJAX autocomplete for Bootstrap 3
* @author Rick Somers | http://getwebhelp.com/bootcomplete
* @modified Danyel Cabello to use client side filtering
* @version 1.0
* @license MIT License
*
*/
(function ( $ ) {
$.fn.bootcomplete = function(options) {
var defaults = {
method : 'get',
wrapperClass : "bc-wrapper",
menuClass : "bc-menu",
idField : true,
idFieldName : $(this).attr('name')+"_id",
minLength : 3,
dataParams : {},
formParams : {},
filter: function(){ return new Promise(function(resolve){resolve()} )},
select: function(){},
hide: function(){},
}
var settings = $.extend( {}, defaults, options );
$(this).attr('autocomplete','off')
$(this).wrap('<div class="'+settings.wrapperClass+'"></div>')
if (settings.idField) {
if ($(this).parent().parent().find('input[name="' + settings.idFieldName + '"]').length !== 0) {
//use existing id field
} else {
//there is no existing id field so create one
$('<input type="hidden" name="' + settings.idFieldName + '" value="">').insertBefore($(this))
}
}
$('<div class="'+settings.menuClass+' list-group"></div>').insertAfter($(this))
$(this).on("keyup", searchQuery);
$(this).on("focusout", hideThat)
var xhr;
var that = $(this)
function hideThat() {
if ($('.list-group-item' + ':hover').length) {
return;
}
$(that).next('.' + settings.menuClass).hide();
settings.hide();
}
function searchQuery(){
var arr = [];
$.each(settings.formParams,function(k,v){
arr[k]=$(v).val()
})
var dyFormParams = $.extend({}, arr );
var Data = $.extend({query: $(this).val()}, settings.dataParams, dyFormParams);
if(!Data.query){
$(this).next('.'+settings.menuClass).html('')
$(this).next('.'+settings.menuClass).hide()
}
if(Data.query.length >= settings.minLength){
/*
if(xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
type: settings.method,
url: settings.url,
data: Data,
dataType: "json",
success: function( json ) {
var results = ''
$.each( json, function(i, j) {
results += '<a href="#" class="list-group-item" data-id="'+j.id+'" data-label="'+j.label+'">'+j.label+'</a>'
});
$(that).next('.'+settings.menuClass).html(results)
$(that).next('.'+settings.menuClass).children().on("click", selectResult)
$(that).next('.'+settings.menuClass).show()
}
})
*/
settings.filter(Data.query)
.then(function(json){
var results = ''
$.each( json, function(i, j) {
var content=j.label;
var label = j.label;
if(Array.isArray(content)){
content = content.reduce(function(last,now,index){
return last + "<div>"+now+"</div>"
},"");
label = label.join(",");
}
results += '<a href="#" class="list-group-item" data-id="'+j.id+'" data-type="'+j.type+'" data-label="'+label+'">'+
content
+'</a>'
});
$(that).next('.'+settings.menuClass).html(results)
$(that).next('.'+settings.menuClass).children().on("click", selectResult)
$(that).next('.'+settings.menuClass).show()
})
}
}
function selectResult(){
$(that).val($(this).data('label'))
settings.select($(this).data("id"),$(this).data("type"));
$(that).next('.' + settings.menuClass).hide();
return false;
}
return this;
};
}( jQuery )); |
const fonts = [
'Arial',
'Arial Black',
'Comic Sans MS',
'Courier New',
'Helvetica Neue',
'Helvetica',
'Impact',
'Lucida Grande',
'Tahoma',
'Times New Roman',
'Verdana'
];
export default {
install(Leylim) {
let isOpen = false;
let isProcessed = false;
let _selection = null;
const modal = Leylim.$getModal({
title: 'SELECT FONT',
button: {
cancel() {},
save() {}
}
});
let options = '';
for (var ii = 0; ii < fonts.length; ii++) {
options += `<option value="${fonts[ii]}">${fonts[ii]}</option>`;
}
modal.setContent(`
<select name="select-font" class="leylim-modal-input" id="leylim-select-font">
${options}
</select>
`);
const fontInput = document.querySelector('#leylim-select-font');
fontInput.onchange = e => {
Leylim.restoreSelection();
if (isOpen) {
isProcessed = true;
document.execCommand(
'insertHTML',
true,
`<span style="font-family: ${e.target.value}">${_selection}</span>`
);
}
Leylim.restoreSelection();
};
modal.onSave = () => {
modal.close();
Leylim.forceUpdate();
}
modal.onClose = () => {
_selection = null;
isOpen = false;
Leylim.restoreSelection();
if (isProcessed) {
isProcessed = false;
document.execCommand('undo');
}
modal.close();
};
Leylim.editorButtons.unshift({
command: '',
icon: 'fa fa-font',
handler(selection) {
Leylim.saveSelection();
isOpen = true;
_selection = selection;
modal.open();
}
});
}
};
|
describe('select callback', function() {
var options;
beforeEach(function() {
affix('#cal');
options = {
defaultDate: '2014-05-25',
selectable: true
};
});
afterEach(function() {
$('#cal').njCalendar('destroy');
});
[ false, true ].forEach(function(isRTL) {
describe('when isRTL is ' + isRTL, function() {
beforeEach(function() {
options.isRTL = isRTL;
});
describe('when in month view', function() {
beforeEach(function() {
options.defaultView = 'month';
});
it('gets fired correctly when the user selects cells', function(done) {
options.select = function(start, end, jsEvent, view) {
expect(moment.isMoment(start)).toEqual(true);
expect(moment.isMoment(end)).toEqual(true);
expect(typeof jsEvent).toEqual('object'); // TODO: more descrimination
expect(typeof view).toEqual('object'); // "
expect(start.hasTime()).toEqual(false);
expect(end.hasTime()).toEqual(false);
expect(start).toEqualMoment('2014-04-28');
expect(end).toEqualMoment('2014-05-07');
};
spyOn(options, 'select').and.callThrough();
$('#cal').njCalendar(options);
$('.fc-day[data-date="2014-04-28"]').simulate('drag-n-drop', {
dropTarget: '.fc-day[data-date="2014-05-06"]',
callback: function() {
expect(options.select).toHaveBeenCalled();
done();
}
});
});
it('gets fired correctly when the user selects just one cell', function(done) {
options.select = function(start, end, jsEvent, view) {
expect(moment.isMoment(start)).toEqual(true);
expect(moment.isMoment(end)).toEqual(true);
expect(typeof jsEvent).toEqual('object'); // TODO: more descrimination
expect(typeof view).toEqual('object'); // "
expect(start.hasTime()).toEqual(false);
expect(end.hasTime()).toEqual(false);
expect(start).toEqualMoment('2014-04-28');
expect(end).toEqualMoment('2014-04-29');
};
spyOn(options, 'select').and.callThrough();
$('#cal').njCalendar(options);
$('.fc-day[data-date="2014-04-28"]').simulate('drag-n-drop', {
dropTarget: '.fc-day[data-date="2014-04-28"]',
callback: function() {
expect(options.select).toHaveBeenCalled();
done();
}
});
});
});
describe('when in agendaWeek view', function() {
beforeEach(function() {
options.defaultView = 'agendaWeek';
});
describe('when selecting all-day slots', function() {
it('gets fired correctly when the user selects cells', function(done) {
options.select = function(start, end, jsEvent, view) {
expect(moment.isMoment(start)).toEqual(true);
expect(moment.isMoment(end)).toEqual(true);
expect(typeof jsEvent).toEqual('object'); // TODO: more descrimination
expect(typeof view).toEqual('object'); // "
expect(start.hasTime()).toEqual(false);
expect(end.hasTime()).toEqual(false);
expect(start).toEqualMoment('2014-05-28');
expect(end).toEqualMoment('2014-05-30');
};
spyOn(options, 'select').and.callThrough();
$('#cal').njCalendar(options);
$('.fc-agenda-view .fc-day-grid .fc-day:eq(3)').simulate('drag-n-drop', { // will be 2014-05-28 for LTR and RTL
dx: $('.fc-sun').outerWidth() * (isRTL ? -1 : 1), // the width of one column
callback: function() {
expect(options.select).toHaveBeenCalled();
done();
}
});
});
it('gets fired correctly when the user selects a single cell', function(done) {
options.select = function(start, end, jsEvent, view) {
expect(moment.isMoment(start)).toEqual(true);
expect(moment.isMoment(end)).toEqual(true);
expect(typeof jsEvent).toEqual('object'); // TODO: more descrimination
expect(typeof view).toEqual('object'); // "
expect(start.hasTime()).toEqual(false);
expect(end.hasTime()).toEqual(false);
expect(start).toEqualMoment('2014-05-28');
expect(end).toEqualMoment('2014-05-29');
};
spyOn(options, 'select').and.callThrough();
$('#cal').njCalendar(options);
$('.fc-agenda-view .fc-day-grid .fc-day:eq(3)').simulate('drag-n-drop', { // will be 2014-05-28 for LTR and RTL
callback: function() {
expect(options.select).toHaveBeenCalled();
done();
}
});
});
});
describe('when selecting timed slots', function(done) {
it('gets fired correctly when the user selects slots', function(done) {
options.select = function(start, end, jsEvent, view) {
expect(moment.isMoment(start)).toEqual(true);
expect(moment.isMoment(end)).toEqual(true);
expect(typeof jsEvent).toEqual('object'); // TODO: more descrimination
expect(typeof view).toEqual('object'); // "
expect(start.hasTime()).toEqual(true);
expect(end.hasTime()).toEqual(true);
expect(start).toEqualMoment('2014-05-28T09:00:00');
expect(end).toEqualMoment('2014-05-28T10:30:00');
};
spyOn(options, 'select').and.callThrough();
$('#cal').njCalendar(options);
$('.fc-slats tr:eq(18) td:not(.fc-time)').simulate('drag-n-drop', { // middle will be 2014-05-28T09:00:00
dy: $('.fc-slats tr:eq(18)').outerHeight() * 2, // move down two slots
callback: function() {
expect(options.select).toHaveBeenCalled();
done();
}
});
});
it('gets fired correctly when the user selects slots in a different day', function(done) {
options.select = function(start, end, jsEvent, view) {
expect(moment.isMoment(start)).toEqual(true);
expect(moment.isMoment(end)).toEqual(true);
expect(typeof jsEvent).toEqual('object'); // TODO: more descrimination
expect(typeof view).toEqual('object'); // "
expect(start.hasTime()).toEqual(true);
expect(end.hasTime()).toEqual(true);
expect(start).toEqualMoment('2014-05-28T09:00:00');
expect(end).toEqualMoment('2014-05-29T10:30:00');
};
spyOn(options, 'select').and.callThrough();
$('#cal').njCalendar(options);
$('.fc-slats tr:eq(18) td:not(.fc-time)').simulate('drag-n-drop', { // middle will be 2014-05-28T09:00:00
dx: $('.fc-day-header:first').outerWidth() * .9 * (isRTL ? -1 : 1), // one day ahead
dy: $('.fc-slats tr:eq(18)').outerHeight() * 2, // move down two slots
callback: function() {
expect(options.select).toHaveBeenCalled();
done();
}
});
});
it('gets fired correctly when the user selects a single slot', function(done) {
options.select = function(start, end, jsEvent, view) {
expect(moment.isMoment(start)).toEqual(true);
expect(moment.isMoment(end)).toEqual(true);
expect(typeof jsEvent).toEqual('object'); // TODO: more descrimination
expect(typeof view).toEqual('object'); // "
expect(start.hasTime()).toEqual(true);
expect(end.hasTime()).toEqual(true);
expect(start).toEqualMoment('2014-05-28T09:00:00');
expect(end).toEqualMoment('2014-05-28T09:30:00');
};
spyOn(options, 'select').and.callThrough();
$('#cal').njCalendar(options);
$('.fc-slats tr:eq(18) td:not(.fc-time)').simulate('drag-n-drop', { // middle will be 2014-05-28T09:00:00
callback: function() {
expect(options.select).toHaveBeenCalled();
done();
}
});
});
});
});
});
});
}); |
(function() {
var modalTemplate,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
modalTemplate = "<div class=\"modal\" tabindex=\"-1\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n </div>\n </div>\n</div>";
window.RemoteModalView = (function() {
function RemoteModalView(srcEl) {
this.close = __bind(this.close, this);
this.routeResponse = __bind(this.routeResponse, this);
this.config = RemoteHelpers.extractAttributes(srcEl);
RemoteHelpers.requireAttributes(this.config, ['modal-url']);
this.$el = $(modalTemplate);
$('body').append(this.$el);
this.$el.modal({
keyboard: true,
show: true
});
}
RemoteModalView.prototype.submitForm = function(form) {
var remoteAction;
remoteAction = form.attr('action');
return $.post(remoteAction, form.serialize()).then((function(_this) {
return function(responseBody, status, response) {
RemoteResponseValidator.validateSuccessfulResponse(responseBody, remoteAction);
return _this.routeResponse(responseBody);
};
})(this)).fail((function(_this) {
return function(response, status, errorMsg) {
RemoteResponseValidator.validateErrorResponse(response, status, errorMsg, remoteAction);
return _this.routeResponse(response.responseJSON);
};
})(this));
};
RemoteModalView.prototype.routeResponse = function(response) {
switch (response.status) {
case 'Success':
this.close();
return RemoteHelpers.triggerChange(this.config['mutates-models']);
case 'UnprocessableEntity':
return this.replaceModalContent(response.template);
default:
throw new Error("Unknown response status " + response.status);
}
};
RemoteModalView.prototype.replaceModalContent = function(html) {
this.setHtml(html);
this.bindToForm();
return $(document).trigger('partial:load', [this.$el.find('.modal-content').children()]);
};
RemoteModalView.prototype.setHtml = function(html) {
return this.$el.find('.modal-content').html(html);
};
RemoteModalView.prototype.bindToForm = function() {
var cancelButton, form;
form = this.$el.find('form');
form.on('submit', (function(_this) {
return function(e) {
e.preventDefault();
return _this.submitForm(form);
};
})(this));
cancelButton = this.$el.find('[data-action="cancel"]');
return cancelButton.on('click', (function(_this) {
return function(e) {
e.preventDefault();
return _this.close();
};
})(this));
};
RemoteModalView.prototype.render = function() {
var deferred;
deferred = $.Deferred();
$.get(this.config['modal-url']).done((function(_this) {
return function(body) {
_this.replaceModalContent(body);
return deferred.resolve();
};
})(this)).fail((function(_this) {
return function(response) {
console.log("Error fetching modal content:");
console.log(response);
_this.setHtml("Unable to load content, please reload the page");
return deferred.reject(new Error("Unable to load remote view from '" + _this.config['modal-url'] + "'"));
};
})(this));
return deferred.promise();
};
RemoteModalView.prototype.close = function() {
this.$el.modal('hide');
return this.$el.remove();
};
return RemoteModalView;
})();
RemoteHelpers.onDataAction('remote_modal', 'click', function(event) {
var view;
event.preventDefault();
view = new RemoteModalView(event.currentTarget);
return view.render();
});
}).call(this);
|
const path = require('path');
const webpack = require('webpack');
const config = require('../src/config');
const rootPath = path.resolve(__dirname, '../');
const srcPath = path.join(rootPath, '/src/');
const distPath = path.join(rootPath, '/build/');
const webpackConfig = {
devtool: false,
entry: {
main: ['babel-polyfill', srcPath + 'electron']
},
output: {
path: distPath,
filename: 'main.js'
},
module: {
loaders: [
{ test: /\.(jsx|js)$/, include: srcPath, loaders: ['babel']}
],
},
plugins: [
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
unused: true,
dead_code: true,
drop_debugger: true,
drop_console: true
}
})
],
resolve: {
extensions: ['', '.js', '.jsx'],
},
node: {
__dirname: false,
__filename: false
},
externals: [
(function () {
var IGNORES = [
'electron'
];
return function (context, request, callback) {
if (IGNORES.indexOf(request) >= 0) {
return callback(null, "require('" + request + "')");
}
return callback();
};
})()
]
}
module.exports = webpackConfig;
|
'use strict'
var op = require('pitch-op')
// pitch to pitch classes
function pitchClasses (gamut) { return gamut.map(op.pitchClass) }
// simplify interval
function simplify (gamut) { return gamut.map(op.simplify) }
// return pitch heights: distance from C0 or interval semitones
function heights (gamut) { return gamut.map(op.semitones) }
function transpose (interval, gamut) {
if (!interval) return []
return gamut.map(function (p) {
return p ? op.add(interval, p) : null
})
}
// get distances from tonic to the rest of the notes
function distances (tonic, gamut) {
if (!tonic) {
if (!gamut[0]) return []
tonic = gamut[0]
}
tonic = op.setDefaultOctave(0, tonic)
return gamut.map(function (p) {
return p ? op.subtract(tonic, op.setDefaultOctave(0, p)) : null
})
}
// remove duplicated notes AND nulls
function uniq (gamut) {
var semitones = heights(gamut)
return gamut.reduce(function (uniq, current, currentIndex) {
if (current) {
var index = semitones.indexOf(semitones[currentIndex])
if (index === currentIndex) uniq.push(current)
}
return uniq
}, [])
}
function sort (gamut) {
return gamut.sort(op.comparator())
}
// get an interval set
function intervalSet (gamut) {
return sort(uniq(simplify(distances(null, gamut))))
}
// get a pitch set
function pitchSet (gamut) {
return transpose(op.pitchClass(gamut[0]), intervalSet(gamut))
}
function binarySet (gamut) {
var number = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
var semitones = heights(intervalSet(gamut))
semitones.forEach(function (s) {
number[s] = 1
})
return number.join('')
}
// pitch-array of 'C Db D Eb E F F# G Ab A Bb B'
var NOTES = [
[ 0, 0, null ], [ 1, -1, null ], [ 1, 0, null ], [ 2, -1, null ],
[ 2, 0, null ], [ 3, 0, null ], [ 3, 1, null ], [ 4, 0, null ],
[ 5, -1, null ], [ 5, 0, null ], [ 6, -1, null ], [ 6, 0, null ] ]
function fromBinarySet (number) {
if (/^1[01]{11}$/.test(number)) number = parseInt(number, 2)
else if (typeof number !== 'number') return []
var binary = ((number % 2048) + 2048).toString(2)
var set = []
for (var i = 0; i < 12; i++) {
if (binary.charAt(i) === '1') set.push(NOTES[i])
}
return set
}
module.exports = {
pitchClasses: pitchClasses,
simplify: simplify,
heights: heights,
transpose: transpose,
distances: distances,
uniq: uniq,
sort: sort,
intervalSet: intervalSet,
pitchSet: pitchSet,
binarySet: binarySet,
fromBinarySet: fromBinarySet
}
|
var convict = require('convict');
var fs = require('fs');
var path = require('path');
const config = convict({
cron: {
doc: 'Cron schedule for capturing images',
format: String,
default: '0,10,20,30,40,50 * * * *',
env: 'CRON',
arg: 'cron'
},
dropbox: {
token: {
doc: 'Dropbox API Access Token',
format: String,
default: null,
env: 'DROPBOX_TOKEN',
arg: 'dropbox-token'
}
},
log: {
doc: 'Logfile location',
format: String,
default: path.join(__dirname, 'spacebucket.log'),
env: 'LOG',
arg: 'log'
},
photocell: {
pin: {
doc: 'Pin number to read photocell data from',
format: Number,
default: 37,
env: 'PHOTOCELL_PIN',
arg: 'photocell-pin'
}
},
port: {
doc: 'Express port to listen to',
format: 'port',
default: 3000,
env: 'PORT',
arg: 'port'
}
});
let env = process.env.NODE_ENV || 'production';
let configPath = path.join(__dirname, `config.${env}.json`);
if (fs.existsSync(configPath)) {
config.loadFile(configPath);
}
config.validate();
module.exports = config;
|
{
if (props.x === 297) {
return React.createElement(
"div",
{
className: "_1o_8 _44ra _5cyn"
},
React.createElement(AdsPECampaignGroupEditorContainer133, {
x: 296
})
);
}
}
|
/**
* autoNumeric.js
* @author: Bob Knothe
* @author: Sokolov Yura
* @version: 1.9.39 - 2015-07-17 GMT 5:00 PM / 19:00
*
* Created by Robert J. Knothe on 2010-10-25. Please report any bugs to https://github.com/BobKnothe/autoNumeric
* Contributor by Sokolov Yura on 2010-11-07
*
* Copyright (c) 2011 Robert J. Knothe http://www.decorplanit.com/plugin/
*
* The MIT License (http://www.opensource.org/licenses/mit-license.php)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
(function ($) {
"use strict";
/*jslint browser: true*/
/*global jQuery: false*/
/*Cross browser routine for getting selected range/cursor position
*/
/**
* Cross browser routine for getting selected range/cursor position
*/
function getElementSelection(that) {
var position = {};
if (that.selectionStart === undefined) {
that.focus();
var select = document.selection.createRange();
position.length = select.text.length;
select.moveStart('character', -that.value.length);
position.end = select.text.length;
position.start = position.end - position.length;
} else {
position.start = that.selectionStart;
position.end = that.selectionEnd;
position.length = position.end - position.start;
}
return position;
}
/**
* Cross browser routine for setting selected range/cursor position
*/
function setElementSelection(that, start, end) {
if (that.selectionStart === undefined) {
that.focus();
var r = that.createTextRange();
r.collapse(true);
r.moveEnd('character', end);
r.moveStart('character', start);
r.select();
} else {
that.selectionStart = start;
that.selectionEnd = end;
}
}
/**
* run callbacks in parameters if any
* any parameter could be a callback:
* - a function, which invoked with jQuery element, parameters and this parameter name and returns parameter value
* - a name of function, attached to $(selector).autoNumeric.functionName(){} - which was called previously
*/
function runCallbacks($this, settings) {
/**
* loops through the settings object (option array) to find the following
* k = option name example k=aNum
* val = option value example val=0123456789
*/
$.each(settings, function (k, val) {
if (typeof val === 'function') {
settings[k] = val($this, settings, k);
} else if (typeof $this.autoNumeric[val] === 'function') {
/**
* calls the attached function from the html5 data example: data-a-sign="functionName"
*/
settings[k] = $this.autoNumeric[val]($this, settings, k);
}
});
}
/**
* Converts the vMin, vMax & mDec string to numeric value
*/
function convertKeyToNumber(settings, key) {
if (typeof (settings[key]) === 'string') {
settings[key] *= 1;
}
}
/**
* Preparing user defined options for further usage
* merge them with defaults appropriately
*/
function autoCode($this, settings) {
runCallbacks($this, settings);
settings.tagList = ['b', 'caption', 'cite', 'code', 'dd', 'del', 'div', 'dfn', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ins', 'kdb', 'label', 'li', 'output', 'p', 'q', 's', 'sample', 'span', 'strong', 'td', 'th', 'u', 'var'];
var vmax = settings.vMax.toString().split('.'),
vmin = (!settings.vMin && settings.vMin !== 0) ? [] : settings.vMin.toString().split('.');
convertKeyToNumber(settings, 'vMax');
convertKeyToNumber(settings, 'vMin');
convertKeyToNumber(settings, 'mDec'); /** set mDec if not defined by user */
settings.mDec = (settings.mRound === 'CHF') ? '2' : settings.mDec;
settings.allowLeading = true;
settings.aNeg = settings.vMin < 0 ? '-' : '';
vmax[0] = vmax[0].replace('-', '');
vmin[0] = vmin[0].replace('-', '');
settings.mInt = Math.max(vmax[0].length, vmin[0].length, 1);
if (settings.mDec === null) {
var vmaxLength = 0,
vminLength = 0;
if (vmax[1]) {
vmaxLength = vmax[1].length;
}
if (vmin[1]) {
vminLength = vmin[1].length;
}
settings.mDec = Math.max(vmaxLength, vminLength);
} /** set alternative decimal separator key */
if (settings.altDec === null && settings.mDec > 0) {
if (settings.aDec === '.' && settings.aSep !== ',') {
settings.altDec = ',';
} else if (settings.aDec === ',' && settings.aSep !== '.') {
settings.altDec = '.';
}
}
/** cache regexps for autoStrip */
var aNegReg = settings.aNeg ? '([-\\' + settings.aNeg + ']?)' : '(-?)';
settings.aNegRegAutoStrip = aNegReg;
settings.skipFirstAutoStrip = new RegExp(aNegReg + '[^-' + (settings.aNeg ? '\\' + settings.aNeg : '') + '\\' + settings.aDec + '\\d]' + '.*?(\\d|\\' + settings.aDec + '\\d)');
settings.skipLastAutoStrip = new RegExp('(\\d\\' + settings.aDec + '?)[^\\' + settings.aDec + '\\d]\\D*$');
var allowed = '-' + settings.aNum + '\\' + settings.aDec;
settings.allowedAutoStrip = new RegExp('[^' + allowed + ']', 'gi');
settings.numRegAutoStrip = new RegExp(aNegReg + '(?:\\' + settings.aDec + '?(\\d+\\' + settings.aDec + '\\d+)|(\\d*(?:\\' + settings.aDec + '\\d*)?))');
return settings;
}
/**
* strips all unwanted characters and leave only a number alert
*/
function autoStrip(s, settings, strip_zero) {
if (settings.aSign) { /** remove currency sign */
while (s.indexOf(settings.aSign) > -1) {
s = s.replace(settings.aSign, '');
}
}
s = s.replace(settings.skipFirstAutoStrip, '$1$2'); /** first replace anything before digits */
s = s.replace(settings.skipLastAutoStrip, '$1'); /** then replace anything after digits */
s = s.replace(settings.allowedAutoStrip, ''); /** then remove any uninterested characters */
if (settings.altDec) {
s = s.replace(settings.altDec, settings.aDec);
} /** get only number string */
var m = s.match(settings.numRegAutoStrip);
s = m ? [m[1], m[2], m[3]].join('') : '';
if ((settings.lZero === 'allow' || settings.lZero === 'keep') && strip_zero !== 'strip') {
var parts = [],
nSign = '';
parts = s.split(settings.aDec);
if (parts[0].indexOf('-') !== -1) {
nSign = '-';
parts[0] = parts[0].replace('-', '');
}
if (parts[0].length > settings.mInt && parts[0].charAt(0) === '0') { /** strip leading zero if need */
parts[0] = parts[0].slice(1);
}
s = nSign + parts.join(settings.aDec);
}
if ((strip_zero && settings.lZero === 'deny') || (strip_zero && settings.lZero === 'allow' && settings.allowLeading === false)) {
var strip_reg = '^' + settings.aNegRegAutoStrip + '0*(\\d' + (strip_zero === 'leading' ? ')' : '|$)');
strip_reg = new RegExp(strip_reg);
s = s.replace(strip_reg, '$1$2');
}
return s;
}
/**
* places or removes brackets on negative values
* works only when with pSign: 'p'
*/
function negativeBracket(s, settings) {
if (settings.pSign === 'p') {
var brackets = settings.nBracket.split(',');
if (!settings.hasFocus && !settings.removeBrackets) {
s = s.replace(settings.aNeg, '');
s = brackets[0] + s + brackets[1];
} else if ((settings.hasFocus && s.charAt(0) === brackets[0]) || (settings.removeBrackets && s.charAt(0) === brackets[0])) {
s = s.replace(brackets[0], settings.aNeg);
s = s.replace(brackets[1], '');
}
}
return s;
}
/**
* function to handle numbers less than 0 that are stored in Exponential notation ex: .0000001 stored as 1e-7
*/
function checkValue(value, settings) {
if (value) {
var checkSmall = +value;
if (checkSmall < 0.000001 && checkSmall > -1) {
value = +value;
if (value < 0.000001 && value > 0) {
value = (value + 10).toString();
value = value.substring(1);
}
if (value < 0 && value > -1) {
value = (value - 10).toString();
value = '-' + value.substring(2);
}
value = value.toString();
} else {
var parts = value.split('.');
if (parts[1] !== undefined) {
if (+parts[1] === 0) {
value = parts[0];
} else {
parts[1] = parts[1].replace(/0*$/, '');
value = parts.join('.');
}
}
}
}
return (settings.lZero === 'keep') ? value : value.replace(/^0*(\d)/, '$1');
}
/**
* prepare number string to be converted to real number
*/
function fixNumber(s, aDec, aNeg) {
if (aDec && aDec !== '.') {
s = s.replace(aDec, '.');
}
if (aNeg && aNeg !== '-') {
s = s.replace(aNeg, '-');
}
if (!s.match(/\d/)) {
s += '0';
}
return s;
}
/**
* prepare real number to be converted to our format
*/
function presentNumber(s, aDec, aNeg) {
if (aNeg && aNeg !== '-') {
s = s.replace('-', aNeg);
}
if (aDec && aDec !== '.') {
s = s.replace('.', aDec);
}
return s;
}
/**
* private function to check for empty value
*/
function checkEmpty(iv, settings, signOnEmpty) {
if (iv === '' || iv === settings.aNeg) {
if (settings.wEmpty === 'zero') {
return iv + '0';
}
if (settings.wEmpty === 'sign' || signOnEmpty) {
return iv + settings.aSign;
}
return iv;
}
return null;
}
/**
* private function that formats our number
*/
function autoGroup(iv, settings) {
iv = autoStrip(iv, settings);
var testNeg = iv.replace(',', '.'),
empty = checkEmpty(iv, settings, true);
if (empty !== null) {
return empty;
}
var digitalGroup = '';
if (settings.dGroup === 2) {
digitalGroup = /(\d)((\d)(\d{2}?)+)$/;
} else if (settings.dGroup === 4) {
digitalGroup = /(\d)((\d{4}?)+)$/;
} else {
digitalGroup = /(\d)((\d{3}?)+)$/;
} /** splits the string at the decimal string */
var ivSplit = iv.split(settings.aDec);
if (settings.altDec && ivSplit.length === 1) {
ivSplit = iv.split(settings.altDec);
} /** assigns the whole number to the a variable (s) */
var s = ivSplit[0];
if (settings.aSep) {
while (digitalGroup.test(s)) { /** re-inserts the thousand separator via a regular expression */
s = s.replace(digitalGroup, '$1' + settings.aSep + '$2');
}
}
if (settings.mDec !== 0 && ivSplit.length > 1) {
if (ivSplit[1].length > settings.mDec) {
ivSplit[1] = ivSplit[1].substring(0, settings.mDec);
} /** joins the whole number with the decimal value */
iv = s + settings.aDec + ivSplit[1];
} else { /** if whole numbers only */
iv = s;
}
if (settings.aSign) {
var has_aNeg = iv.indexOf(settings.aNeg) !== -1;
iv = iv.replace(settings.aNeg, '');
iv = settings.pSign === 'p' ? settings.aSign + iv : iv + settings.aSign;
if (has_aNeg) {
iv = settings.aNeg + iv;
}
}
if (testNeg < 0 && settings.nBracket !== null) { /** removes the negative sign and places brackets */
iv = negativeBracket(iv, settings);
}
return iv;
}
/**
* round number after setting by pasting or $().autoNumericSet()
* private function for round the number
* please note this handled as text - JavaScript math function can return inaccurate values
* also this offers multiple rounding methods that are not easily accomplished in JavaScript
*/
function autoRound(iv, settings) { /** value to string */
iv = (iv === '') ? '0' : iv.toString();
convertKeyToNumber(settings, 'mDec'); /** set mDec to number needed when mDec set by 'update method */
if (settings.mRound === 'CHF') {
iv = (Math.round(iv * 20) / 20).toString();
}
var ivRounded = '',
i = 0,
nSign = '',
rDec = (typeof (settings.aPad) === 'boolean' || settings.aPad === null) ? (settings.aPad ? settings.mDec : 0) : +settings.aPad;
var truncateZeros = function (ivRounded) { /** truncate not needed zeros */
var regex = (rDec === 0) ? (/(\.(?:\d*[1-9])?)0*$/) : rDec === 1 ? (/(\.\d(?:\d*[1-9])?)0*$/) : new RegExp('(\\.\\d{' + rDec + '}(?:\\d*[1-9])?)0*$');
ivRounded = ivRounded.replace(regex, '$1'); /** If there are no decimal places, we don't need a decimal point at the end */
if (rDec === 0) {
ivRounded = ivRounded.replace(/\.$/, '');
}
return ivRounded;
};
if (iv.charAt(0) === '-') { /** Checks if the iv (input Value)is a negative value */
nSign = '-';
iv = iv.replace('-', ''); /** removes the negative sign will be added back later if required */
}
if (!iv.match(/^\d/)) { /** append a zero if first character is not a digit (then it is likely to be a dot)*/
iv = '0' + iv;
}
if (nSign === '-' && +iv === 0) { /** determines if the value is zero - if zero no negative sign */
nSign = '';
}
if ((+iv > 0 && settings.lZero !== 'keep') || (iv.length > 0 && settings.lZero === 'allow')) { /** trims leading zero's if needed */
iv = iv.replace(/^0*(\d)/, '$1');
}
var dPos = iv.lastIndexOf('.'),
/** virtual decimal position */
vdPos = (dPos === -1) ? iv.length - 1 : dPos,
/** checks decimal places to determine if rounding is required */
cDec = (iv.length - 1) - vdPos; /** check if no rounding is required */
if (cDec <= settings.mDec) {
ivRounded = iv; /** check if we need to pad with zeros */
if (cDec < rDec) {
if (dPos === -1) {
ivRounded += '.';
}
var zeros = '000000';
while (cDec < rDec) {
zeros = zeros.substring(0, rDec - cDec);
ivRounded += zeros;
cDec += zeros.length;
}
} else if (cDec > rDec) {
ivRounded = truncateZeros(ivRounded);
} else if (cDec === 0 && rDec === 0) {
ivRounded = ivRounded.replace(/\.$/, '');
}
if (settings.mRound !== 'CHF') {
return (+ivRounded === 0) ? ivRounded : nSign + ivRounded;
}
if (settings.mRound === 'CHF') {
dPos = ivRounded.lastIndexOf('.');
iv = ivRounded;
}
} /** rounded length of the string after rounding */
var rLength = dPos + settings.mDec,
tRound = +iv.charAt(rLength + 1),
ivArray = iv.substring(0, rLength + 1).split(''),
odd = (iv.charAt(rLength) === '.') ? (iv.charAt(rLength - 1) % 2) : (iv.charAt(rLength) % 2),
onePass = true;
if (odd !== 1) {
odd = (odd === 0 && (iv.substring(rLength + 2, iv.length) > 0)) ? 1 : 0;
}
/*jslint white: true*/
if ((tRound > 4 && settings.mRound === 'S') || /** Round half up symmetric */
(tRound > 4 && settings.mRound === 'A' && nSign === '') || /** Round half up asymmetric positive values */
(tRound > 5 && settings.mRound === 'A' && nSign === '-') || /** Round half up asymmetric negative values */
(tRound > 5 && settings.mRound === 's') || /** Round half down symmetric */
(tRound > 5 && settings.mRound === 'a' && nSign === '') || /** Round half down asymmetric positive values */
(tRound > 4 && settings.mRound === 'a' && nSign === '-') || /** Round half down asymmetric negative values */
(tRound > 5 && settings.mRound === 'B') || /** Round half even "Banker's Rounding" */
(tRound === 5 && settings.mRound === 'B' && odd === 1) || /** Round half even "Banker's Rounding" */
(tRound > 0 && settings.mRound === 'C' && nSign === '') || /** Round to ceiling toward positive infinite */
(tRound > 0 && settings.mRound === 'F' && nSign === '-') || /** Round to floor toward negative infinite */
(tRound > 0 && settings.mRound === 'U') || /** round up away from zero */
(settings.mRound === 'CHF')) { /** Round Swiss FRanc */
/*jslint white: false*/
for (i = (ivArray.length - 1); i >= 0; i -= 1) { /** Round up the last digit if required, and continue until no more 9's are found */
if (ivArray[i] !== '.') {
if (settings.mRound === 'CHF' && ivArray[i] <= 2 && onePass) {
ivArray[i] = 0;
onePass = false;
break;
}
if (settings.mRound === 'CHF' && ivArray[i] <= 7 && onePass) {
ivArray[i] = 5;
onePass = false;
break;
}
if (settings.mRound === 'CHF' && onePass) {
ivArray[i] = 10;
onePass = false;
} else {
ivArray[i] = +ivArray[i] + 1;
}
if (ivArray[i] < 10) {
break;
}
if (i > 0) {
ivArray[i] = '0';
}
}
}
}
ivArray = ivArray.slice(0, rLength + 1); /** Reconstruct the string, converting any 10's to 0's */
ivRounded = truncateZeros(ivArray.join('')); /** return rounded value */
return (+ivRounded === 0) ? ivRounded : nSign + ivRounded;
}
/**
* truncate decimal part of a number
*/
function truncateDecimal(s, settings, paste) {
var aDec = settings.aDec,
mDec = settings.mDec;
s = (paste === 'paste') ? autoRound(s, settings) : s;
if (aDec && mDec) {
var parts = s.split(aDec);
/** truncate decimal part to satisfying length
* cause we would round it anyway */
if (parts[1] && parts[1].length > mDec) {
if (mDec > 0) {
parts[1] = parts[1].substring(0, mDec);
s = parts.join(aDec);
} else {
s = parts[0];
}
}
}
return s;
}
/**
* checking that number satisfy format conditions
* and lays between settings.vMin and settings.vMax
* and the string length does not exceed the digits in settings.vMin and settings.vMax
*/
function autoCheck(s, settings) {
s = autoStrip(s, settings);
s = truncateDecimal(s, settings);
s = fixNumber(s, settings.aDec, settings.aNeg);
var value = +s;
return value >= settings.vMin && value <= settings.vMax;
}
/**
* Holder object for field properties
*/
function AutoNumericHolder(that, settings) {
this.settings = settings;
this.that = that;
this.$that = $(that);
this.formatted = false;
this.settingsClone = autoCode(this.$that, this.settings);
this.value = that.value;
}
AutoNumericHolder.prototype = {
init: function (e) {
this.value = this.that.value;
this.settingsClone = autoCode(this.$that, this.settings);
this.ctrlKey = e.ctrlKey;
this.cmdKey = e.metaKey;
this.shiftKey = e.shiftKey;
this.selection = getElementSelection(this.that); /** keypress event overwrites meaningful value of e.keyCode */
if (e.type === 'keydown' || e.type === 'keyup') {
this.kdCode = e.keyCode;
}
this.which = e.which;
this.processed = false;
this.formatted = false;
},
setSelection: function (start, end, setReal) {
start = Math.max(start, 0);
end = Math.min(end, this.that.value.length);
this.selection = {
start: start,
end: end,
length: end - start
};
if (setReal === undefined || setReal) {
setElementSelection(this.that, start, end);
}
},
setPosition: function (pos, setReal) {
this.setSelection(pos, pos, setReal);
},
getBeforeAfter: function () {
var value = this.value,
left = value.substring(0, this.selection.start),
right = value.substring(this.selection.end, value.length);
return [left, right];
},
getBeforeAfterStriped: function () {
var parts = this.getBeforeAfter();
parts[0] = autoStrip(parts[0], this.settingsClone);
parts[1] = autoStrip(parts[1], this.settingsClone);
return parts;
},
/**
* strip parts from excess characters and leading zeroes
*/
normalizeParts: function (left, right) {
var settingsClone = this.settingsClone;
right = autoStrip(right, settingsClone); /** if right is not empty and first character is not aDec, */
/** we could strip all zeros, otherwise only leading */
var strip = right.match(/^\d/) ? true : 'leading';
left = autoStrip(left, settingsClone, strip); /** prevents multiple leading zeros from being entered */
if ((left === '' || left === settingsClone.aNeg) && settingsClone.lZero === 'deny') {
if (right > '') {
right = right.replace(/^0*(\d)/, '$1');
}
}
var new_value = left + right; /** insert zero if has leading dot */
if (settingsClone.aDec) {
var m = new_value.match(new RegExp('^' + settingsClone.aNegRegAutoStrip + '\\' + settingsClone.aDec));
if (m) {
left = left.replace(m[1], m[1] + '0');
new_value = left + right;
}
} /** insert zero if number is empty and io.wEmpty == 'zero' */
if (settingsClone.wEmpty === 'zero' && (new_value === settingsClone.aNeg || new_value === '')) {
left += '0';
}
return [left, right];
},
/**
* set part of number to value keeping position of cursor
*/
setValueParts: function (left, right, paste) {
var settingsClone = this.settingsClone,
parts = this.normalizeParts(left, right),
new_value = parts.join(''),
position = parts[0].length;
if (autoCheck(new_value, settingsClone)) {
new_value = truncateDecimal(new_value, settingsClone, paste);
if (position > new_value.length) {
position = new_value.length;
}
this.value = new_value;
this.setPosition(position, false);
return true;
}
return false;
},
/**
* helper function for expandSelectionOnSign
* returns sign position of a formatted value
*/
signPosition: function () {
var settingsClone = this.settingsClone,
aSign = settingsClone.aSign,
that = this.that;
if (aSign) {
var aSignLen = aSign.length;
if (settingsClone.pSign === 'p') {
var hasNeg = settingsClone.aNeg && that.value && that.value.charAt(0) === settingsClone.aNeg;
return hasNeg ? [1, aSignLen + 1] : [0, aSignLen];
}
var valueLen = that.value.length;
return [valueLen - aSignLen, valueLen];
}
return [1000, -1];
},
/**
* expands selection to cover whole sign
* prevents partial deletion/copying/overwriting of a sign
*/
expandSelectionOnSign: function (setReal) {
var sign_position = this.signPosition(),
selection = this.selection;
if (selection.start < sign_position[1] && selection.end > sign_position[0]) { /** if selection catches something except sign and catches only space from sign */
if ((selection.start < sign_position[0] || selection.end > sign_position[1]) && this.value.substring(Math.max(selection.start, sign_position[0]), Math.min(selection.end, sign_position[1])).match(/^\s*$/)) { /** then select without empty space */
if (selection.start < sign_position[0]) {
this.setSelection(selection.start, sign_position[0], setReal);
} else {
this.setSelection(sign_position[1], selection.end, setReal);
}
} else { /** else select with whole sign */
this.setSelection(Math.min(selection.start, sign_position[0]), Math.max(selection.end, sign_position[1]), setReal);
}
}
},
/**
* try to strip pasted value to digits
*/
checkPaste: function () {
if (this.valuePartsBeforePaste !== undefined) {
var parts = this.getBeforeAfter(),
oldParts = this.valuePartsBeforePaste;
delete this.valuePartsBeforePaste; /** try to strip pasted value first */
parts[0] = parts[0].substr(0, oldParts[0].length) + autoStrip(parts[0].substr(oldParts[0].length), this.settingsClone);
if (!this.setValueParts(parts[0], parts[1], 'paste')) {
this.value = oldParts.join('');
this.setPosition(oldParts[0].length, false);
}
}
},
/**
* process pasting, cursor moving and skipping of not interesting keys
* if returns true, further processing is not performed
*/
skipAllways: function (e) {
var kdCode = this.kdCode,
which = this.which,
ctrlKey = this.ctrlKey,
cmdKey = this.cmdKey,
shiftKey = this.shiftKey; /** catch the ctrl up on ctrl-v */
if (((ctrlKey || cmdKey) && e.type === 'keyup' && this.valuePartsBeforePaste !== undefined) || (shiftKey && kdCode === 45)) {
this.checkPaste();
return false;
}
/** codes are taken from http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx
* skip Fx keys, windows keys, other special keys
* Thanks Ney Estrabelli for the FF for Mac meta key support "keycode 224"
*/
if ((kdCode >= 112 && kdCode <= 123) || (kdCode >= 91 && kdCode <= 93) || (kdCode >= 9 && kdCode <= 31) || (kdCode < 8 && (which === 0 || which === kdCode)) || kdCode === 144 || kdCode === 145 || kdCode === 45 || kdCode === 224) {
return true;
}
if ((ctrlKey || cmdKey) && kdCode === 65) { /** if select all (a=65)*/
return true;
}
if ((ctrlKey || cmdKey) && (kdCode === 67 || kdCode === 86 || kdCode === 88)) { /** if copy (c=67) paste (v=86) or cut (x=88) */
if (e.type === 'keydown') {
this.expandSelectionOnSign();
}
if (kdCode === 86 || kdCode === 45) { /** try to prevent wrong paste */
if (e.type === 'keydown' || e.type === 'keypress') {
if (this.valuePartsBeforePaste === undefined) {
this.valuePartsBeforePaste = this.getBeforeAfter();
}
} else {
this.checkPaste();
}
}
return e.type === 'keydown' || e.type === 'keypress' || kdCode === 67;
}
if (ctrlKey || cmdKey) {
return true;
}
if (kdCode === 37 || kdCode === 39) { /** jump over thousand separator */
var aSep = this.settingsClone.aSep,
start = this.selection.start,
value = this.that.value;
if (e.type === 'keydown' && aSep && !this.shiftKey) {
if (kdCode === 37 && value.charAt(start - 2) === aSep) {
this.setPosition(start - 1);
} else if (kdCode === 39 && value.charAt(start + 1) === aSep) {
this.setPosition(start + 1);
}
}
return true;
}
if (kdCode >= 34 && kdCode <= 40) {
return true;
}
return false;
},
/**
* process deletion of characters
* returns true if processing performed
*/
processAllways: function () {
var parts; /** process backspace or delete */
if (this.kdCode === 8 || this.kdCode === 46) {
if (!this.selection.length) {
parts = this.getBeforeAfterStriped();
if (this.kdCode === 8) {
parts[0] = parts[0].substring(0, parts[0].length - 1);
} else {
parts[1] = parts[1].substring(1, parts[1].length);
}
this.setValueParts(parts[0], parts[1]);
} else {
this.expandSelectionOnSign(false);
parts = this.getBeforeAfterStriped();
this.setValueParts(parts[0], parts[1]);
}
return true;
}
return false;
},
/**
* process insertion of characters
* returns true if processing performed
*/
processKeypress: function () {
var settingsClone = this.settingsClone,
cCode = String.fromCharCode(this.which),
parts = this.getBeforeAfterStriped(),
left = parts[0],
right = parts[1]; /** start rules when the decimal character key is pressed */
/** always use numeric pad dot to insert decimal separator */
if (cCode === settingsClone.aDec || (settingsClone.altDec && cCode === settingsClone.altDec) || ((cCode === '.' || cCode === ',') && this.kdCode === 110)) { /** do not allow decimal character if no decimal part allowed */
if (!settingsClone.mDec || !settingsClone.aDec) {
return true;
} /** do not allow decimal character before aNeg character */
if (settingsClone.aNeg && right.indexOf(settingsClone.aNeg) > -1) {
return true;
} /** do not allow decimal character if other decimal character present */
if (left.indexOf(settingsClone.aDec) > -1) {
return true;
}
if (right.indexOf(settingsClone.aDec) > 0) {
return true;
}
if (right.indexOf(settingsClone.aDec) === 0) {
right = right.substr(1);
}
this.setValueParts(left + settingsClone.aDec, right);
return true;
}
/**
* start rule on negative sign & prevent minus if not allowed
*/
if (cCode === '-' || cCode === '+') {
if (!settingsClone.aNeg) {
return true;
} /** caret is always after minus */
if (left === '' && right.indexOf(settingsClone.aNeg) > -1) {
left = settingsClone.aNeg;
right = right.substring(1, right.length);
} /** change sign of number, remove part if should */
if (left.charAt(0) === settingsClone.aNeg) {
left = left.substring(1, left.length);
} else {
left = (cCode === '-') ? settingsClone.aNeg + left : left;
}
this.setValueParts(left, right);
return true;
} /** digits */
if (cCode >= '0' && cCode <= '9') { /** if try to insert digit before minus */
if (settingsClone.aNeg && left === '' && right.indexOf(settingsClone.aNeg) > -1) {
left = settingsClone.aNeg;
right = right.substring(1, right.length);
}
if (settingsClone.vMax <= 0 && settingsClone.vMin < settingsClone.vMax && this.value.indexOf(settingsClone.aNeg) === -1 && cCode !== '0') {
left = settingsClone.aNeg + left;
}
this.setValueParts(left + cCode, right);
return true;
} /** prevent any other character */
return true;
},
/**
* formatting of just processed value with keeping of cursor position
*/
formatQuick: function () {
var settingsClone = this.settingsClone,
parts = this.getBeforeAfterStriped(),
leftLength = this.value;
if ((settingsClone.aSep === '' || (settingsClone.aSep !== '' && leftLength.indexOf(settingsClone.aSep) === -1)) && (settingsClone.aSign === '' || (settingsClone.aSign !== '' && leftLength.indexOf(settingsClone.aSign) === -1))) {
var subParts = [],
nSign = '';
subParts = leftLength.split(settingsClone.aDec);
if (subParts[0].indexOf('-') > -1) {
nSign = '-';
subParts[0] = subParts[0].replace('-', '');
parts[0] = parts[0].replace('-', '');
}
if (subParts[0].length > settingsClone.mInt && parts[0].charAt(0) === '0') { /** strip leading zero if need */
parts[0] = parts[0].slice(1);
}
parts[0] = nSign + parts[0];
}
var value = autoGroup(this.value, this.settingsClone),
position = value.length;
if (value) {
/** prepare regexp which searches for cursor position from unformatted left part */
var left_ar = parts[0].split(''),
i = 0;
for (i; i < left_ar.length; i += 1) { /** thanks Peter Kovari */
if (!left_ar[i].match('\\d')) {
left_ar[i] = '\\' + left_ar[i];
}
}
var leftReg = new RegExp('^.*?' + left_ar.join('.*?'));
/** search cursor position in formatted value */
var newLeft = value.match(leftReg);
if (newLeft) {
position = newLeft[0].length;
/** if we are just before sign which is in prefix position */
if (((position === 0 && value.charAt(0) !== settingsClone.aNeg) || (position === 1 && value.charAt(0) === settingsClone.aNeg)) && settingsClone.aSign && settingsClone.pSign === 'p') {
/** place caret after prefix sign */
position = this.settingsClone.aSign.length + (value.charAt(0) === '-' ? 1 : 0);
}
} else if (settingsClone.aSign && settingsClone.pSign === 's') {
/** if we could not find a place for cursor and have a sign as a suffix */
/** place carret before suffix currency sign */
position -= settingsClone.aSign.length;
}
}
this.that.value = value;
this.setPosition(position);
this.formatted = true;
}
};
/**
* thanks to Anthony & Evan C
*/
function autoGet(obj) {
if (typeof obj === 'string') {
obj = obj.replace(/\[/g, "\\[").replace(/\]/g, "\\]");
obj = '#' + obj.replace(/(:|\.)/g, '\\$1');
/** obj = '#' + obj.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); */
/** possible modification to replace the above 2 lines */
}
return $(obj);
}
/**
* function to attach data to the element
* and imitate the holder
*/
function getHolder($that, settings, update) {
var data = $that.data('autoNumeric');
if (!data) {
data = {};
$that.data('autoNumeric', data);
}
var holder = data.holder;
if ((holder === undefined && settings) || update) {
holder = new AutoNumericHolder($that.get(0), settings);
data.holder = holder;
}
return holder;
}
var methods = {
/**
* Method to initiate autoNumeric and attached the settings (default and options passed as a parameter
* $(someSelector).autoNumeric('init'); // initiate autoNumeric with defaults
* $(someSelector).autoNumeric('init', {option}); // initiate autoNumeric with options
* $(someSelector).autoNumeric(); // initiate autoNumeric with defaults
* $(someSelector).autoNumeric({option}); // initiate autoNumeric with options
* options passes as a parameter example '{aSep: '.', aDec: ',', aSign: 'โฌ '}
*/
init: function (options) {
return this.each(function () {
var $this = $(this),
settings = $this.data('autoNumeric'), /** attempt to grab 'autoNumeric' settings, if they don't exist returns "undefined". */
tagData = $this.data(), /** attempt to grab HTML5 data, if they don't exist we'll get "undefined".*/
$input = $this.is('input[type=text], input[type=hidden], input[type=tel], input:not([type])');
if (typeof settings !== 'object') { /** If we couldn't grab settings, create them from defaults and passed options. */
settings = $.extend({}, $.fn.autoNumeric.defaults, tagData, options, {
aNum: '0123456789',
hasFocus: false,
removeBrackets: false,
runOnce: false,
tagList: ['b', 'caption', 'cite', 'code', 'dd', 'del', 'div', 'dfn', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ins', 'kdb', 'label', 'li', 'output', 'p', 'q', 's', 'sample', 'span', 'strong', 'td', 'th', 'u', 'var']
}); /** Merge defaults, tagData and options */
if (settings.aDec === settings.aSep) {
$.error("autoNumeric will not function properly when the decimal character aDec: '" + settings.aDec + "' and thousand separator aSep: '" + settings.aSep + "' are the same character");
}
$this.data('autoNumeric', settings); /** Save our new settings */
} else {
return this;
}
var holder = getHolder($this, settings);
if (!$input && $this.prop('tagName').toLowerCase() === 'input') { /** checks for non-supported input types */
$.error('The input type "' + $this.prop('type') + '" is not supported by autoNumeric()');
}
if ($.inArray($this.prop('tagName').toLowerCase(), settings.tagList) === -1 && $this.prop('tagName').toLowerCase() !== 'input') {
$.error("The <" + $this.prop('tagName').toLowerCase() + "> is not supported by autoNumeric()");
}
if (settings.runOnce === false && settings.aForm) { /** routine to format default value on page load */
if ($input) {
var setValue = true;
if ($this[0].value === '' && settings.wEmpty === 'empty') {
$this[0].value = '';
setValue = false;
}
if ($this[0].value === '' && settings.wEmpty === 'sign') {
$this[0].value = settings.aSign;
setValue = false;
}
/** checks for page reload from back button
* also checks for ASP.net form post back
* the following HTML data attribute is REQUIRED (data-an-default="same value as the value attribute")
* example: <asp:TextBox runat="server" id="someID" value="1234.56" data-an-default="1234.56">
*/
if (setValue && $this.val() !== '' && ((settings.anDefault === null && $this[0].value === $this.prop('defaultValue')) || (settings.anDefault !== null && settings.anDefault.toString() === $this.val()))) {
$this.autoNumeric('set', $this.val());
}
}
if ($.inArray($this.prop('tagName').toLowerCase(), settings.tagList) !== -1 && $this.text() !== '') {
$this.autoNumeric('set', $this.text());
}
}
settings.runOnce = true;
if ($this.is('input[type=text], input[type=hidden], input[type=tel], input:not([type])')) { /**added hidden type */
$this.on('keydown.autoNumeric', function (e) {
holder = getHolder($this);
if (holder.settings.aDec === holder.settings.aSep) {
$.error("autoNumeric will not function properly when the decimal character aDec: '" + holder.settings.aDec + "' and thousand separator aSep: '" + holder.settings.aSep + "' are the same character");
}
if (holder.that.readOnly) {
holder.processed = true;
return true;
}
/** The below streamed code / comment allows the "enter" keydown to throw a change() event */
/** if (e.keyCode === 13 && holder.inVal !== $this.val()){
$this.change();
holder.inVal = $this.val();
}*/
holder.init(e);
if (holder.skipAllways(e)) {
holder.processed = true;
return true;
}
if (holder.processAllways()) {
holder.processed = true;
holder.formatQuick();
e.preventDefault();
return false;
}
holder.formatted = false;
return true;
});
$this.on('keypress.autoNumeric', function (e) {
holder = getHolder($this);
var processed = holder.processed;
holder.init(e);
if (holder.skipAllways(e)) {
return true;
}
if (processed) {
e.preventDefault();
return false;
}
if (holder.processAllways() || holder.processKeypress()) {
holder.formatQuick();
e.preventDefault();
return false;
}
holder.formatted = false;
});
$this.on('keyup.autoNumeric', function (e) {
holder = getHolder($this);
holder.init(e);
var skip = holder.skipAllways(e);
holder.kdCode = 0;
delete holder.valuePartsBeforePaste;
if ($this[0].value === holder.settings.aSign) { /** added to properly place the caret when only the currency is present */
if (holder.settings.pSign === 's') {
setElementSelection(this, 0, 0);
} else {
setElementSelection(this, holder.settings.aSign.length, holder.settings.aSign.length);
}
}
if (skip) {
return true;
}
if (this.value === '') {
return true;
}
if (!holder.formatted) {
holder.formatQuick();
}
});
$this.on('focusin.autoNumeric', function () {
holder = getHolder($this);
var $settings = holder.settingsClone;
$settings.hasFocus = true;
if ($settings.nBracket !== null) {
var checkVal = $this.val();
$this.val(negativeBracket(checkVal, $settings));
}
holder.inVal = $this.val();
var onEmpty = checkEmpty(holder.inVal, $settings, true);
if (onEmpty !== null && onEmpty !== '') {
$this.val(onEmpty);
}
});
$this.on('focusout.autoNumeric', function () {
holder = getHolder($this);
var $settings = holder.settingsClone,
value = $this.val(),
origValue = value;
$settings.hasFocus = false;
var strip_zero = ''; /** added to control leading zero */
if ($settings.lZero === 'allow') { /** added to control leading zero */
$settings.allowLeading = false;
strip_zero = 'leading';
}
if (value !== '') {
value = autoStrip(value, $settings, strip_zero);
if (checkEmpty(value, $settings) === null && autoCheck(value, $settings, $this[0])) {
value = fixNumber(value, $settings.aDec, $settings.aNeg);
value = autoRound(value, $settings);
value = presentNumber(value, $settings.aDec, $settings.aNeg);
} else {
value = '';
}
}
var groupedValue = checkEmpty(value, $settings, false);
if (groupedValue === null) {
groupedValue = autoGroup(value, $settings);
}
if (groupedValue !== holder.inVal || groupedValue !== origValue) {
$this.val(groupedValue);
$this.change();
delete holder.inVal;
}
});
}
});
},
/**
* method to remove settings and stop autoNumeric() - does not remove the formatting
* $(someSelector).autoNumeric('destroy'); // destroy autoNumeric
* no parameters accepted
*/
destroy: function () {
return $(this).each(function () {
var $this = $(this);
$this.off('.autoNumeric');
$this.removeData('autoNumeric');
});
},
/**
* method to update settings - can be call as many times
* $(someSelector).autoNumeric('update', {options}); // updates the settings
* options passes as a parameter example '{aSep: '.', aDec: ',', aSign: 'โฌ '}
*/
update: function (options) {
return $(this).each(function () {
var $this = autoGet($(this)),
settings = $this.data('autoNumeric');
if (typeof settings !== 'object') {
$.error("You must initialize autoNumeric('init', {options}) prior to calling the 'update' method");
}
var strip = $this.autoNumeric('get');
settings = $.extend(settings, options);
getHolder($this, settings, true);
if (settings.aDec === settings.aSep) {
$.error("autoNumeric will not function properly when the decimal character aDec: '" + settings.aDec + "' and thousand separator aSep: '" + settings.aSep + "' are the same character");
}
$this.data('autoNumeric', settings);
if ($this.val() !== '' || $this.text() !== '') {
return $this.autoNumeric('set', strip);
}
return;
});
},
/**
* method to format value sent as a parameter ""
* $(someSelector).autoNumeric('set', 'value'}); // formats the value being passed
* value passed as a string - can be a integer '1234' or double '1234.56789'
* must contain only numbers and one decimal (period) character
*/
set: function (valueIn) {
if (valueIn === null) {
return;
}
return $(this).each(function () {
var $this = autoGet($(this)),
settings = $this.data('autoNumeric'),
value = valueIn.toString(),
testValue = valueIn.toString(),
$input = $this.is('input[type=text], input[type=hidden], input[type=tel], input:not([type])');
if (typeof settings !== 'object') {
$.error("You must initialize autoNumeric('init', {options}) prior to calling the 'set' method");
}
/** allows locale decimal separator to be a comma */
if ((testValue === $this.attr('value') || testValue === $this.text()) && settings.runOnce === false) {
value = value.replace(',', '.');
}
if (!$.isNumeric(+value)) {
$.error("The value (" + value + ") being 'set' is not numeric and has caused a error to be thrown");
}
value = checkValue(value, settings);
settings.setEvent = true;
value.toString();
if (value !== '') {
value = autoRound(value, settings);
}
value = presentNumber(value, settings.aDec, settings.aNeg);
if (!autoCheck(value, settings)) {
value = autoRound('', settings);
}
value = autoGroup(value, settings);
if ($input) {
return $this.val(value);
}
if ($.inArray($this.prop('tagName').toLowerCase(), settings.tagList) !== -1) {
return $this.text(value);
}
return false;
});
},
/**
* method to get the unformatted that accepts up to one parameter
* $(someSelector).autoNumeric('get'); no parameters accepted
* values returned as ISO numeric string "1234.56" where the decimal character is a period
* only the first element in the selector is returned
*/
get: function () {
var $this = autoGet($(this)),
settings = $this.data('autoNumeric');
if (typeof settings !== 'object') {
$.error("You must initialize autoNumeric('init', {options}) prior to calling the 'get' method");
}
var getValue = '';
/** determine the element type then use .eq(0) selector to grab the value of the first element in selector */
if ($this.is('input[type=text], input[type=hidden], input[type=tel], input:not([type])')) { /**added hidden type */
getValue = $this.eq(0).val();
} else if ($.inArray($this.prop('tagName').toLowerCase(), settings.tagList) !== -1) {
getValue = $this.eq(0).text();
} else {
$.error("The <" + $this.prop('tagName').toLowerCase() + "> is not supported by autoNumeric()");
}
if ((getValue === '' && settings.wEmpty === 'empty') || (getValue === settings.aSign && (settings.wEmpty === 'sign' || settings.wEmpty === 'empty'))) {
return '';
}
if (getValue !== '' && settings.nBracket !== null) {
settings.removeBrackets = true;
getValue = negativeBracket(getValue, settings);
settings.removeBrackets = false;
}
if (settings.runOnce || settings.aForm === false) {
getValue = autoStrip(getValue, settings);
}
getValue = fixNumber(getValue, settings.aDec, settings.aNeg);
if (+getValue === 0 && settings.lZero !== 'keep') {
getValue = '0';
}
if (settings.lZero === 'keep') {
return getValue;
}
getValue = checkValue(getValue, settings);
return getValue; /** returned Numeric String */
},
/**
* The 'getString' method used jQuerys .serialize() method that creates a text string in standard URL-encoded notation
* it then loops through the string and un-formats the inputs with autoNumeric
* $(someSelector).autoNumeric('getString'); no parameter accepted
* values returned as ISO numeric string "1234.56" where the decimal character is a period
*/
getString: function () {
var isAutoNumeric = false,
$this = autoGet($(this)),
formFields = $this.serialize(),
formParts = formFields.split('&'),
formIndex = $('form').index($this),
allFormElements = $('form:eq(' + formIndex + ')'),
aiIndex = [], /* all input index */
scIndex = [], /* successful control index */
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, /* from jQuery serialize method */
rsubmittable = /^(?:input|select|textarea|keygen)/i, /* from jQuery serialize method */
rcheckableType = /^(?:checkbox|radio)$/i,
rnonAutoNumericTypes = /^(?:button|checkbox|color|date|datetime|datetime-local|email|file|image|month|number|password|radio|range|reset|search|submit|time|url|week)/i,
count = 0;
/*jslint unparam: true*/
/* index of successful elements */
$.each(allFormElements[0], function (i, field) {
if (field.name !== '' && rsubmittable.test(field.localName) && !rsubmitterTypes.test(field.type) && !field.disabled && (field.checked || !rcheckableType.test(field.type))) {
scIndex.push(count);
count = count + 1;
} else {
scIndex.push(-1);
}
});
/* index of all inputs tags except checkbox */
count = 0;
$.each(allFormElements[0], function (i, field) {
if (field.localName === 'input' && (field.type === '' || field.type === 'text' || field.type === 'hidden' || field.type === 'tel')) {
aiIndex.push(count);
count = count + 1;
} else {
aiIndex.push(-1);
if (field.localName === 'input' && rnonAutoNumericTypes.test(field.type)) {
count = count + 1;
}
}
});
$.each(formParts, function (i, miniParts) {
miniParts = formParts[i].split('=');
var scElement = $.inArray(i, scIndex);
if (scElement > -1 && aiIndex[scElement] > -1) {
var testInput = $('form:eq(' + formIndex + ') input:eq(' + aiIndex[scElement] + ')'),
settings = testInput.data('autoNumeric');
if (typeof settings === 'object') {
if (miniParts[1] !== null) {
miniParts[1] = $('form:eq(' + formIndex + ') input:eq(' + aiIndex[scElement] + ')').autoNumeric('get').toString();
formParts[i] = miniParts.join('=');
isAutoNumeric = true;
}
}
}
});
/*jslint unparam: false*/
if (!isAutoNumeric) {
$.error("You must initialize autoNumeric('init', {options}) prior to calling the 'getString' method");
}
return formParts.join('&');
},
/**
* The 'getString' method used jQuerys .serializeArray() method that creates array or objects that can be encoded as a JSON string
* it then loops through the string and un-formats the inputs with autoNumeric
* $(someSelector).autoNumeric('getArray'); no parameter accepted
* values returned as ISO numeric string "1234.56" where the decimal character is a period
*/
getArray: function () {
var isAutoNumeric = false,
$this = autoGet($(this)),
formFields = $this.serializeArray(),
formIndex = $('form').index($this),
allFormElements = $('form:eq(' + formIndex + ')'),
aiIndex = [], /* all input index */
scIndex = [], /* successful control index */
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, /* from jQuery serialize method */
rsubmittable = /^(?:input|select|textarea|keygen)/i, /* from jQuery serialize method */
rcheckableType = /^(?:checkbox|radio)$/i,
rnonAutoNumericTypes = /^(?:button|checkbox|color|date|datetime|datetime-local|email|file|image|month|number|password|radio|range|reset|search|submit|time|url|week)/i,
count = 0;
/*jslint unparam: true*/
/* index of successful elements */
$.each(allFormElements[0], function (i, field) {
if (field.name !== '' && rsubmittable.test(field.localName) && !rsubmitterTypes.test(field.type) && !field.disabled && (field.checked || !rcheckableType.test(field.type))) {
scIndex.push(count);
count = count + 1;
} else {
scIndex.push(-1);
}
});
/* index of all inputs tags */
count = 0;
$.each(allFormElements[0], function (i, field) {
if (field.localName === 'input' && (field.type === '' || field.type === 'text' || field.type === 'hidden' || field.type === 'tel')) {
aiIndex.push(count);
count = count + 1;
} else {
aiIndex.push(-1);
if (field.localName === 'input' && rnonAutoNumericTypes.test(field.type)) {
count = count + 1;
}
}
});
$.each(formFields, function (i, field) {
var scElement = $.inArray(i, scIndex);
if (scElement > -1 && aiIndex[scElement] > -1) {
var testInput = $('form:eq(' + formIndex + ') input:eq(' + aiIndex[scElement] + ')'),
settings = testInput.data('autoNumeric');
if (typeof settings === 'object') {
field.value = $('form:eq(' + formIndex + ') input:eq(' + aiIndex[scElement] + ')').autoNumeric('get').toString();
isAutoNumeric = true;
}
}
});
/*jslint unparam: false*/
if (!isAutoNumeric) {
$.error("None of the successful form inputs are initialized by autoNumeric.");
}
return formFields;
},
/**
* The 'getSteetings returns the object with autoNumeric settings for those who need to look under the hood
* $(someSelector).autoNumeric('getSettings'); // no parameters accepted
* $(someSelector).autoNumeric('getSettings').aDec; // return the aDec setting as a string - ant valid setting can be used
*/
getSettings: function () {
var $this = autoGet($(this));
return $this.eq(0).data('autoNumeric');
}
};
/**
* autoNumeric function
*/
$.fn.autoNumeric = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
}
$.error('Method "' + method + '" is not supported by autoNumeric()');
};
/**
* Defaults are public - these can be overridden by the following:
* HTML5 data attributes
* Options passed by the 'init' or 'update' methods
* Use jQuery's $.extend method - great way to pass ASP.NET current culture settings
*/
$.fn.autoNumeric.defaults = {
/** allowed thousand separator characters
* comma = ','
* period "full stop" = '.'
* apostrophe is escaped = '\''
* space = ' '
* none = ''
* NOTE: do not use numeric characters
*/
aSep: ',',
/** digital grouping for the thousand separator used in Format
* dGroup: '2', results in 99,99,99,999 common in India for values less than 1 billion and greater than -1 billion
* dGroup: '3', results in 999,999,999 default
* dGroup: '4', results in 9999,9999,9999 used in some Asian countries
*/
dGroup: '3',
/** allowed decimal separator characters
* period "full stop" = '.'
* comma = ','
*/
aDec: '.',
/** allow to declare alternative decimal separator which is automatically replaced by aDec
* developed for countries the use a comma ',' as the decimal character
* and have keyboards\numeric pads that have a period 'full stop' as the decimal characters (Spain is an example)
*/
altDec: null,
/** allowed currency symbol
* Must be in quotes aSign: '$', a space is allowed aSign: '$ '
*/
aSign: '',
/** placement of currency sign
* for prefix pSign: 'p',
* for suffix pSign: 's',
*/
pSign: 'p',
/** maximum possible value
* value must be enclosed in quotes and use the period for the decimal point
* value must be larger than vMin
*/
vMax: '9999999999999.99',
/** minimum possible value
* value must be enclosed in quotes and use the period for the decimal point
* value must be smaller than vMax
*/
vMin: '-9999999999999.99',
/** max number of decimal places = used to override decimal places set by the vMin & vMax values
* value must be enclosed in quotes example mDec: '3',
* This can also set the value via a call back function mDec: 'css:#
*/
mDec: null,
/** method used for rounding
* mRound: 'S', Round-Half-Up Symmetric (default)
* mRound: 'A', Round-Half-Up Asymmetric
* mRound: 's', Round-Half-Down Symmetric (lower case s)
* mRound: 'a', Round-Half-Down Asymmetric (lower case a)
* mRound: 'B', Round-Half-Even "Bankers Rounding"
* mRound: 'U', Round Up "Round-Away-From-Zero"
* mRound: 'D', Round Down "Round-Toward-Zero" - same as truncate
* mRound: 'C', Round to Ceiling "Toward Positive Infinity"
* mRound: 'F', Round to Floor "Toward Negative Infinity"
*/
mRound: 'S',
/** controls decimal padding
* aPad: true - always Pad decimals with zeros
* aPad: false - does not pad with zeros.
* aPad: `some number` - pad decimals with zero to number different from mDec
* thanks to Jonas Johansson for the suggestion
*/
aPad: true,
/** places brackets on negative value -$ 999.99 to (999.99)
* visible only when the field does NOT have focus the left and right symbols should be enclosed in quotes and seperated by a comma
* nBracket: null, nBracket: '(,)', nBracket: '[,]', nBracket: '<,>' or nBracket: '{,}'
*/
nBracket: null,
/** Displayed on empty string
* wEmpty: 'empty', - input can be blank
* wEmpty: 'zero', - displays zero
* wEmpty: 'sign', - displays the currency sign
*/
wEmpty: 'empty',
/** controls leading zero behavior
* lZero: 'allow', - allows leading zeros to be entered. Zeros will be truncated when entering additional digits. On focusout zeros will be deleted.
* lZero: 'deny', - allows only one leading zero on values less than one
* lZero: 'keep', - allows leading zeros to be entered. on fousout zeros will be retained.
*/
lZero: 'allow',
/** determine if the select all keyboard command will select
* the complete input text or only the input numeric value
* if the currency symbol is between the numeric value and the negative sign only the numeric value will sellected
*/
sNumber: true,
/** determine if the default value will be formatted on page ready.
* true = automatically formats the default value on page ready
* false = will not format the default value
*/
aForm: true,
/** helper option for ASP.NET postback
* should be the value of the unformatted default value
* examples:
* no default value='' {anDefault: ''}
* value=1234.56 {anDefault: '1234.56'}
*/
anDefault: null
};
}(jQuery));
|
import React, { Component } from 'react'
import axios from 'axios'
import Layout from '../../components/Layout'
import Footer from '../../components/Footer'
import Button from '../../components/Button'
import s from './Posts.css'
/** Content from a .md file */
import {key, user, userAvatar, title, atCreated, viewrs, comment, tags, html} from './Post.md'
/** Post Components */
import UserPost from '../../components/PostComponents/UserPost'
import Post from '../../components/PostComponents/Post'
import BannerPost from '../../components/PostComponents/BannerPost'
import CommentaryPost from '../../components/PostComponents/CommentaryPost'
/** Commentary Tester .json */
import CommentTeste from '../../options/CommentaryTeste.json'
const titleWeb = "Posts"
class Posts extends Component{
constructor(props){
super(props)
this.state = {content: ''}
}
componentDidMount() {
document.title = title
}
render(){
return(
<Layout className={`${s.posts}`}>
<div className={`${s.wrapperContainer}`}>
<div className={`${s.header}`}>
<UserPost avatar={userAvatar} alt={user} userName={user} />
<div className={`${s.actions}`}>
<Button label="Compartilhar">
<i className="material-icons">reply</i>
</Button>
<Button label={`Agradecer`}>
<i className="material-icons">thumb_up</i>
</Button>
</div>
</div>
<div className={`${s.body}`}>
<Post
key={key}
titlePost={title}
atCreated={atCreated}
viewrs={viewrs}
comments={comment}
tag={tags} >
<div dangerouslySetInnerHTML={{ __html: html }} />
</Post>
<div className={`${s.conteudoFooter}`}>
<div className={`${s.followUser}`}>
<UserPost avatar={userAvatar} alt={user} userName={user} />
<Button label="Seguir" />
</div>
<div className={`${s.contentFooterPost}`}>
<Button><i className="material-icons">share</i></Button>
</div>
</div>
</div>
</div>
<BannerPost>
<h3>Teste Banner</h3>
<p>Testando o banner do post...</p>
</BannerPost>
<div className={`${s.commentary}`}>
<h3>Comentรกrios</h3>
<div className={`${s.writer}`}>
<textarea className={`${s.textArea}`} placeholder="Deixe um Comentรกrio..." ></textarea>
<Button label="Faรงa Login para Comentar" />
</div>
<div className={`${s.comments}`}>
{CommentTeste.map((comments) => {
return(
<CommentaryPost
userAvatar={comments.userAvatar}
userName={comments.userName}
atCreated={atCreated}
key={comments.key} >
{comments.content}
</CommentaryPost>
)
})}
</div>
</div>
<Footer />
</Layout>
)
}
}
export default Posts
|
/*
gulpfile.js
gulp task runner for angular BeersApp
Copyright (c) 2015
Patrick Crager
*/
'use strict';
// required modules
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
minifyCSS = require('gulp-minify-css');
// lint task
gulp.task('lint', function() {
return gulp.src([
'js/controllers/**/*.js',
'js/data/**/*.js',
'js/directives/**/*.js',
'js/shared/**/*.js',
'js/*.js',
]).
pipe(jshint()).
pipe(jshint.reporter('default'));
});
var rightNow = new Date();
var yyyymmdd = rightNow.toISOString().slice(0,10).replace(/-/g,"");
// concat & minify js task
gulp.task('scripts', function() {
return gulp.src([
'js/vendor/jquery-1.11.0.min.js',
'js/vendor/bootstrap-3.2.0.min.js',
'js/vendor/star-rating.min.js',
'js/vendor/angular.min.js',
'js/vendor/angular-route.min.js',
'js/vendor/angular-touch.min.js',
'js/vendor/angular-cookies.min.js',
'js/vendor/ui-bootstrap-0.12.0.min.js',
'js/app.js',
'js/shared/**/*.js',
'js/data/**/*.js',
'js/controllers/**/*.js',
'js/directives/**/*.js'
]).
pipe(concat('beersapp.js')).
pipe(gulp.dest('release/js')).
pipe(rename('beersapp.min-' + yyyymmdd + '.js')).
pipe(uglify()).
pipe(gulp.dest('release/js'));
});
// concat & minify css task
gulp.task('css', function() {
return gulp.src([
'css/vendor/**/*',
'css/main.css'
]).
pipe(concat('beersapp.css')).
pipe(gulp.dest('release/css')).
pipe(rename('beersapp.min-' + yyyymmdd + '.css')).
pipe(minifyCSS({
keepSpecialComments: 0,
processImport: false
})).
pipe(gulp.dest('release/css'));
});
// copy glyphicon font files
gulp.task('copyfonts', function() {
return gulp.src('css/fonts/*.*').
pipe(gulp.dest('release/fonts'));
});
// watch task
gulp.task('watch', function() {
gulp.watch('js/**/*.js', ['lint', 'scripts']);
gulp.watch('css/**/*.css', ['css']);
});
// default task
gulp.task('default', ['lint', 'scripts', 'css', 'copyfonts', 'watch']);
|
{
var s = scale
.scaleSequential(function(t) {
return t;
})
.domain([-1, 100, 200]);
test.deepEqual(s.domain(), [-1, 100]);
test.end();
}
|
var reflux = require("reflux");
var imagesApi = require("../api/imagesApi");
var _ = require("lodash");
var Actions = reflux.createActions({
"load": {children: ["completed", "failed"]}
});
Actions.load.listen( function() {
imagesApi.getImages().then((res) => {
var sample = _.sample(res.data, 10);
this.completed(sample);
}, (res) => {
this.failed(res);
});
});
module.exports = Actions; |
ZRF = {
JUMP: 0,
IF: 1,
FORK: 2,
FUNCTION: 3,
IN_ZONE: 4,
FLAG: 5,
SET_FLAG: 6,
POS_FLAG: 7,
SET_POS_FLAG: 8,
ATTR: 9,
SET_ATTR: 10,
PROMOTE: 11,
MODE: 12,
ON_BOARD_DIR: 13,
ON_BOARD_POS: 14,
PARAM: 15,
LITERAL: 16,
VERIFY: 20
};
Dagaz.Model.BuildDesign = function(design) {
design.checkVersion("z2j", "1");
design.checkVersion("zrf", "2.0");
design.checkVersion("highlight-goals", "false");
design.addDirection("nw");
design.addDirection("se");
design.addDirection("ne");
design.addDirection("sw");
design.addDirection("e");
design.addDirection("w");
design.addPlayer("Black", [1, 0, 3, 2, 5, 4]);
design.addPlayer("White", [0, 1, 2, 3, 4, 5]);
design.addPosition("a7", [0, 5, 0, 4, 1, 0]);
design.addPosition("b7", [0, 5, 0, 4, 1, -1]);
design.addPosition("c7", [0, 5, 0, 4, 1, -1]);
design.addPosition("d7", [0, 5, 0, 4, 0, -1]);
design.addPosition("a6", [0, 5, -4, 0, 1, 0]);
design.addPosition("b6", [-5, 5, -4, 4, 1, -1]);
design.addPosition("c6", [-5, 5, -4, 4, 1, -1]);
design.addPosition("d6", [-5, 5, -4, 4, 1, -1]);
design.addPosition("e6", [-5, 0, 0, 4, 0, -1]);
design.addPosition("a5", [-5, 5, -4, 4, 1, 0]);
design.addPosition("b5", [-5, 5, -4, 4, 1, -1]);
design.addPosition("c5", [-5, 5, -4, 4, 1, -1]);
design.addPosition("d5", [-5, 5, -4, 4, 0, -1]);
design.addPosition("a4", [0, 5, -4, 0, 1, 0]);
design.addPosition("b4", [-5, 5, -4, 4, 1, -1]);
design.addPosition("c4", [-5, 5, -4, 4, 1, -1]);
design.addPosition("d4", [-5, 5, -4, 4, 1, -1]);
design.addPosition("e4", [-5, 0, 0, 4, 0, -1]);
design.addPosition("a3", [-5, 5, -4, 4, 1, 0]);
design.addPosition("b3", [-5, 5, -4, 4, 1, -1]);
design.addPosition("c3", [-5, 5, -4, 4, 1, -1]);
design.addPosition("d3", [-5, 5, -4, 4, 0, -1]);
design.addPosition("a2", [0, 5, -4, 0, 1, 0]);
design.addPosition("b2", [-5, 5, -4, 4, 1, -1]);
design.addPosition("c2", [-5, 5, -4, 4, 1, -1]);
design.addPosition("d2", [-5, 5, -4, 4, 1, -1]);
design.addPosition("e2", [-5, 0, 0, 4, 0, -1]);
design.addPosition("a1", [-5, 0, -4, 0, 1, 0]);
design.addPosition("b1", [-5, 0, -4, 0, 1, -1]);
design.addPosition("c1", [-5, 0, -4, 0, 1, -1]);
design.addPosition("d1", [-5, 0, -4, 0, 0, -1]);
design.addCommand(0, ZRF.FUNCTION, 24); // from
design.addCommand(0, ZRF.PARAM, 0); // $1
design.addCommand(0, ZRF.FUNCTION, 22); // navigate
design.addCommand(0, ZRF.FUNCTION, 1); // empty?
design.addCommand(0, ZRF.FUNCTION, 20); // verify
design.addCommand(0, ZRF.FUNCTION, 25); // to
design.addCommand(0, ZRF.FUNCTION, 28); // end
design.addPiece("BlackPiece", 0);
design.addMove(0, 0, [2], 0);
design.addMove(0, 0, [0], 0);
design.addPiece("WhitePiece", 1);
design.addMove(1, 0, [4], 0);
design.addMove(1, 0, [2], 0);
design.addMove(1, 0, [1], 0);
design.addMove(1, 0, [5], 0);
design.addMove(1, 0, [0], 0);
design.addMove(1, 0, [3], 0);
design.setup("White", "WhitePiece", 15);
design.setup("Black", "BlackPiece", 27);
design.setup("Black", "BlackPiece", 28);
design.setup("Black", "BlackPiece", 29);
design.setup("Black", "BlackPiece", 30);
design.setup("Black", "BlackPiece", 24);
design.goal(0, "White", "WhitePiece", [27]);
design.goal(1, "White", "WhitePiece", [28]);
design.goal(2, "White", "WhitePiece", [29]);
design.goal(3, "White", "WhitePiece", [30]);
}
Dagaz.View.configure = function(view) {
view.defBoard("Board");
view.defPiece("BlackBlackPiece", "Black BlackPiece");
view.defPiece("WhiteWhitePiece", "White WhitePiece");
view.defPosition("a7", 46, 10, 80, 70);
view.defPosition("b7", 126, 10, 80, 70);
view.defPosition("c7", 206, 10, 80, 70);
view.defPosition("d7", 286, 10, 80, 70);
view.defPosition("a6", 7, 82, 80, 70);
view.defPosition("b6", 87, 82, 80, 70);
view.defPosition("c6", 167, 82, 80, 70);
view.defPosition("d6", 247, 82, 80, 70);
view.defPosition("e6", 327, 82, 80, 70);
view.defPosition("a5", 46, 154, 80, 70);
view.defPosition("b5", 126, 154, 80, 70);
view.defPosition("c5", 206, 154, 80, 70);
view.defPosition("d5", 286, 154, 80, 70);
view.defPosition("a4", 7, 226, 80, 70);
view.defPosition("b4", 87, 226, 80, 70);
view.defPosition("c4", 167, 226, 80, 70);
view.defPosition("d4", 247, 226, 80, 70);
view.defPosition("e4", 327, 226, 80, 70);
view.defPosition("a3", 46, 298, 80, 70);
view.defPosition("b3", 126, 298, 80, 70);
view.defPosition("c3", 206, 298, 80, 70);
view.defPosition("d3", 286, 298, 80, 70);
view.defPosition("a2", 7, 370, 80, 70);
view.defPosition("b2", 87, 370, 80, 70);
view.defPosition("c2", 167, 370, 80, 70);
view.defPosition("d2", 247, 370, 80, 70);
view.defPosition("e2", 327, 370, 80, 70);
view.defPosition("a1", 46, 442, 80, 70);
view.defPosition("b1", 126, 442, 80, 70);
view.defPosition("c1", 206, 442, 80, 70);
view.defPosition("d1", 286, 442, 80, 70);
}
|
import { handleActions } from 'redux-actions';
import { mergeSubReducers } from 'utils/immutableReducerUtils.js';
import { Mission as InitialState } from 'store/mission/missionModels.js';
// Sub reducers and actions
import missionList from 'store/mission/missionList/missionListReducers.js';
import selectedMission from 'store/mission/selectedMission/selectedMissionReducers.js';
const mission = handleActions({
}, new InitialState());
// Mission Reducer
export const missionReducer = mergeSubReducers(
mission, {
missionList,
selectedMission
}
);
|
/**
* class CssoCompressor
*
* Engine for CSS minification. You will need `csso` Node module installed:
*
* npm install csso
*
*
* ##### SUBCLASS OF
*
* [[Template]]
**/
'use strict';
// 3rd-party
var csso; // initialized later
// internal
var Template = require('../template');
var prop = require('../common').prop;
////////////////////////////////////////////////////////////////////////////////
// Class constructor
var CssoCompressor = module.exports = function CssoCompressor() {
Template.apply(this, arguments);
csso = csso || Template.libs.csso || require('csso');
};
require('util').inherits(CssoCompressor, Template);
// Compress data
CssoCompressor.prototype.evaluate = function (/*context, locals*/) {
return csso.justDoIt(this.data);
};
// Expose default MimeType of an engine
prop(CssoCompressor, 'defaultMimeType', 'text/css');
|
if(!Array.prototype.indexOf)Array.prototype.indexOf=function(o,m,r){m=+m||0;for(var q=this.length;m<q;m++)if(this[m]===o||r&&this[m]==o)return m;return-1};
(function(){var o={},m=[],r=[],q=1200,v=function(a,e){$.extend(a,e)},z=function(a,e){a=a.attr("id");for(var b=o[a],c=0;c<b.length;c++)b[c].paint(a,e)},x=function(a,e){a=o[a];for(var b=0;b<a.length;b++){a[b].canvas.style.display=e;if(a[b].drawEndpoints){a[b].sourceEndpointCanvas.style.display=e;a[b].targetEndpointCanvas.style.display=e}}},y=function(a){var e=document.createElement("canvas");document.body.appendChild(e);e.style.position="absolute";if(a)e.className=a;if(/MSIE/.test(navigator.userAgent)&&
!window.opera){l.sizeCanvas(e,0,0,q,q);e=G_vmlCanvasManager.initElement(e)}return e},w=function(a){a!=null&&document.body.removeChild(a)},u=function(a){var e=this;this.x=a.x||0;this.y=a.y||0;this.orientation=a.orientation||[0,0];this.offsets=a.offsets||[0,0];this.compute=function(b,c){return[b[0]+e.x*c[0]+e.offsets[0],b[1]+e.y*c[1]+e.offsets[1]]}},l=window.jsPlumb={connectorClass:"_jsPlumb_connector",endpointClass:"_jsPlumb_endpoint",DEFAULT_PAINT_STYLE:{lineWidth:10,strokeStyle:"red"},DEFAULT_ENDPOINT_STYLE:{fillStyle:null},
DEFAULT_ENDPOINT_STYLES:[null,null],DEFAULT_DRAG_OPTIONS:{},DEFAULT_CONNECTOR:null,DEFAULT_ENDPOINT:null,DEFAULT_ENDPOINTS:[null,null],Anchors:{TopCenter:new u({x:0.5,y:0,orientation:[0,-1]}),BottomCenter:new u({x:0.5,y:1,orientation:[0,1]}),LeftMiddle:new u({x:0,y:0.5,orientation:[-1,0]}),RightMiddle:new u({x:1,y:0.5,orientation:[1,0]}),Center:new u({x:0.5,y:0.5,orientation:[0,0]}),TopRight:new u({x:1,y:0,orientation:[0,-1]}),BottomRight:new u({x:1,y:1,orientation:[0,1]}),TopLeft:new u({x:0,y:0,
orientation:[0,-1]}),BottomLeft:new u({x:0,y:1,orientation:[0,1]})},Connectors:{Straight:function(){this.compute=function(a,e,b,c,f){b=Math.abs(a[0]-e[0]);c=Math.abs(a[1]-e[1]);var h=0.45*b,d=0.45*c;b*=1.9;c*=1.9;var g=Math.min(a[0],e[0])-h,i=Math.min(a[1],e[1])-d;if(b<2*f){b=2*f;g=a[0]+(e[0]-a[0])/2-f;h=(b-Math.abs(a[0]-e[0]))/2}if(c<2*f){c=2*f;i=a[1]+(e[1]-a[1])/2-f;d=(c-Math.abs(a[1]-e[1]))/2}return[g,i,b,c,a[0]<e[0]?b-h:h,a[1]<e[1]?c-d:d,a[0]<e[0]?h:b-h,a[1]<e[1]?d:c-d]};this.paint=function(a,
e){e.beginPath();e.moveTo(a[4],a[5]);e.lineTo(a[6],a[7]);e.stroke()}},Bezier:function(a){var e=this;this.majorAnchor=a||150;this.minorAnchor=10;this._findControlPoint=function(b,c,f,h,d){var g=[],i=e.majorAnchor,n=e.minorAnchor;h.orientation[0]==0?g.push(c[0]<f[0]?b[0]+n:b[0]-n):g.push(b[0]-i*h.orientation[0]);h.orientation[1]==0?g.push(c[1]<f[1]?b[1]+n:b[1]-n):g.push(b[1]+i*d.orientation[1]);return g};this.compute=function(b,c,f,h,d){d=d||0;var g=Math.abs(b[0]-c[0])+d,i=Math.abs(b[1]-c[1])+d,n=Math.min(b[0],
c[0])-d/2,j=Math.min(b[1],c[1])-d/2,k=b[0]<c[0]?g-d/2:d/2,s=b[1]<c[1]?i-d/2:d/2,p=b[0]<c[0]?d/2:g-d/2;d=b[1]<c[1]?d/2:i-d/2;var t=e._findControlPoint([k,s],b,c,f,h);b=e._findControlPoint([p,d],c,b,h,f);c=Math.min(k,p);f=Math.min(t[0],b[0]);c=Math.min(c,f);f=Math.max(k,p);h=Math.max(t[0],b[0]);f=Math.max(f,h);if(f>g)g=f;if(c<0){n+=c;c=Math.abs(c);g+=c;t[0]+=c;k+=c;p+=c;b[0]+=c}c=Math.min(s,d);f=Math.min(t[1],b[1]);c=Math.min(c,f);f=Math.max(s,d);h=Math.max(t[1],b[1]);f=Math.max(f,h);if(f>i)i=f;if(c<
0){j+=c;c=Math.abs(c);i+=c;t[1]+=c;s+=c;d+=c;b[1]+=c}return[n,j,g,i,k,s,p,d,t[0],t[1],b[0],b[1]]};this.paint=function(b,c){c.beginPath();c.moveTo(b[4],b[5]);c.bezierCurveTo(b[8],b[9],b[10],b[11],b[6],b[7]);c.stroke()}}},Endpoints:{Dot:function(a){a=a||{radius:10};var e=this;this.radius=a.radius;var b=0.5*this.radius,c=this.radius/3,f=function(d){try{return parseInt(d)}catch(g){if(d.substring(d.length-1)=="%")return parseInt(d.substring(0,d-1))}},h=function(d){var g=b,i=c;if(d.offset)g=f(d.offset);
if(d.innerRadius)i=f(d.innerRadius);return[g,i]};this.paint=function(d,g,i,n,j){var k=n.radius||e.radius;l.sizeCanvas(i,d[0]-k,d[1]-k,k*2,k*2);d=i.getContext("2d");i={};v(i,n);if(i.fillStyle==null)i.fillStyle=j.strokeStyle;v(d,i);j=/MSIE/.test(navigator.userAgent)&&!window.opera;if(n.gradient&&!j){j=h(n.gradient);g=d.createRadialGradient(k,k,k,k+(g[0]==1?j[0]*-1:j[0]),k+(g[1]==1?j[0]*-1:j[0]),j[1]);for(j=0;j<n.gradient.stops.length;j++)g.addColorStop(n.gradient.stops[j][0],n.gradient.stops[j][1]);
d.fillStyle=g}d.beginPath();d.arc(k,k,k,0,Math.PI*2,true);d.closePath();d.fill()}},Rectangle:function(a){a=a||{width:20,height:20};var e=this;this.width=a.width;this.height=a.height;this.paint=function(b,c,f,h,d){var g=h.width||e.width,i=h.height||e.height;l.sizeCanvas(f,b[0]-g/2,b[1]-i/2,g,i);b=f.getContext("2d");f={};v(f,h);if(f.fillStyle==null)f.fillStyle=d.strokeStyle;v(b,f);d=/MSIE/.test(navigator.userAgent)&&!window.opera;if(h.gradient&&!d){c=b.createLinearGradient(c[0]==1?g:c[0]==0?g/2:0,c[1]==
1?i:c[1]==0?i/2:0,c[0]==-1?g:c[0]==0?i/2:0,c[1]==-1?i:c[1]==0?i/2:0);for(d=0;d<h.gradient.stops.length;d++)c.addColorStop(h.gradient.stops[d][0],h.gradient.stops[d][1]);b.fillStyle=c}b.beginPath();b.rect(0,0,g,i);b.closePath();b.fill()}},Image:function(a){var e=this;this.img=new Image;this.img.onload=function(){e.ready=true};this.img.src=a.url;var b=function(c,f,h,d){f=e.img.width||d.width;d=e.img.height||d.height;l.sizeCanvas(h,c[0]-f/2,c[1]-d/2,f,d);h.getContext("2d").drawImage(e.img,0,0)};this.paint=
function(c,f,h,d,g){e.ready?b(c,f,h,d,g):window.setTimeout(function(){e.paint(c,f,h,d,g)},200)}}},connect:function(a){a=new A(a);o[a.sourceId+"_"+a.targetId]=a;var e=function(b,c){var f=o[b];if(f==null){f=[];o[b]=f}f.push(c)};e(a.sourceId,a);e(a.targetId,a)},detach:function(a,e){for(var b=o[a],c=-1,f=0;f<b.length;f++)if(b[f].sourceId==a&&b[f].targetId==e||b[f].targetId==a&&b[f].sourceId==e){w(b[f].canvas);if(b[f].drawEndpoints){w(b[f].targetEndpointCanvas);w(b[f].sourceEndpointCanvas)}c=f;break}c!=
-1&&b.splice(c,1)},detachAll:function(a){for(var e=o[a],b=0;b<e.length;b++){w(e[b].canvas);if(e[b].drawEndpoints){w(e[b].targetEndpointCanvas);w(e[b].sourceEndpointCanvas)}}o[a]=[]},hide:function(a){x(a,"none")},makeAnchor:function(a,e){var b={};if(arguments.length==1)$.extend(b,a);else{b={x:a,y:e};if(arguments.length>=4)b.orientation=[arguments[2],arguments[3]];if(arguments.length==6)b.offsets=[arguments[4],arguments[5]]}return new u(b)},repaint:function(a){var e=function(f,h){var d=o[h];f={absolutePosition:f.offset()};
for(var g=0;g<d.length;g++)d[g].paint(h,f,true)},b=function(f){f=typeof f=="string"?$("#"+f):f;var h=f.attr("id");e(f,h)};if(typeof a=="object")for(var c=0;c<a.length;c++)b(a[c]);else b(a)},setDefaultNewCanvasSize:function(a){q=a},show:function(a){x(a,"block")},sizeCanvas:function(a,e,b,c,f){a.style.height=f+"px";a.height=f;a.style.width=c+"px";a.width=c;a.style.left=e+"px";a.style.top=b+"px"},toggle:function(a){var e=o[a];if(e.length>0)x(a,"none"==e[0].canvas.style.display?"block":"none")}},A=function(a){var e=
this;this.source=typeof a.source=="string"?$("#"+a.source):a.source;this.target=typeof a.target=="string"?$("#"+a.target):a.target;this.sourceId=$(this.source).attr("id");this.targetId=$(this.target).attr("id");this.drawEndpoints=a.drawEndpoints!=null?a.drawEndpoints:true;this.endpointsOnTop=a.endpointsOnTop!=null?a.endpointsOnTop:true;this.anchors=a.anchors||l.DEFAULT_ANCHORS||[l.Anchors.BottomCenter,l.Anchors.TopCenter];this.connector=a.connector||l.DEFAULT_CONNECTOR||new l.Connectors.Bezier;this.paintStyle=
a.paintStyle||l.DEFAULT_PAINT_STYLE;this.endpoints=[];if(!a.endpoints)a.endpoints=[null,null];this.endpoints[0]=a.endpoints[0]||a.endpoint||l.DEFAULT_ENDPOINTS[0]||l.DEFAULT_ENDPOINT||new l.Endpoints.Dot;this.endpoints[1]=a.endpoints[1]||a.endpoint||l.DEFAULT_ENDPOINTS[1]||l.DEFAULT_ENDPOINT||new l.Endpoints.Dot;this.endpointStyles=[];if(!a.endpointStyles)a.endpointStyles=[null,null];this.endpointStyles[0]=a.endpointStyles[0]||a.endpointStyle||l.DEFAULT_ENDPOINT_STYLES[0]||l.DEFAULT_ENDPOINT_STYLE;
this.endpointStyles[1]=a.endpointStyles[1]||a.endpointStyle||l.DEFAULT_ENDPOINT_STYLES[1]||l.DEFAULT_ENDPOINT_STYLE;m[this.sourceId]=this.source.offset();r[this.sourceId]=[this.source.outerWidth(),this.source.outerHeight()];m[this.targetId]=this.target.offset();r[this.targetId]=[this.target.outerWidth(),this.target.outerHeight()];var b=y(l.connectorClass);this.canvas=b;if(this.drawEndpoints){this.sourceEndpointCanvas=y(l.endpointClass);this.targetEndpointCanvas=y(l.endpointClass);if(this.endpointsOnTop){$(this.sourceEndpointCanvas).css("zIndex",
this.source.css("zIndex")+1);$(this.targetEndpointCanvas).css("zIndex",this.target.css("zIndex")+1)}}this.paint=function(h,d,g){var i=h!=this.sourceId,n=i?this.sourceId:this.targetId,j=i?0:1,k=i?1:0;if(this.canvas.getContext){d=d!=null?d.absolutePosition:$("#"+h).offset();m[h]=d;var s=m[n];if(g){g=$("#"+h);var p=$("#"+n);r[h]=[g.outerWidth(),g.outerHeight()];r[n]=[p.outerWidth(),p.outerHeight()]}p=r[h];var t=r[n];g=b.getContext("2d");n=this.anchors[k].compute([d.left,d.top],p,[s.left,s.top],t);h=
this.anchors[k].orientation;d=this.anchors[j].compute([s.left,s.top],t,[d.left,d.top],p);s=this.anchors[j].orientation;j=this.connector.compute(n,d,this.anchors[k],this.anchors[j],this.paintStyle.lineWidth);l.sizeCanvas(b,j[0],j[1],j[2],j[3]);v(g,this.paintStyle);k=/MSIE/.test(navigator.userAgent)&&!window.opera;if(this.paintStyle.gradient&&!k){k=i?g.createLinearGradient(j[4],j[5],j[6],j[7]):g.createLinearGradient(j[6],j[7],j[4],j[5]);for(p=0;p<this.paintStyle.gradient.stops.length;p++)k.addColorStop(this.paintStyle.gradient.stops[p][0],
this.paintStyle.gradient.stops[p][1]);g.strokeStyle=k}this.connector.paint(j,g);if(this.drawEndpoints){j=i?this.sourceEndpointCanvas:this.targetEndpointCanvas;this.endpoints[i?1:0].paint(n,h,i?this.targetEndpointCanvas:this.sourceEndpointCanvas,this.endpointStyles[i?1:0]||this.paintStyle,this.paintStyle);this.endpoints[i?0:1].paint(d,s,j,this.endpointStyles[i?0:1]||this.paintStyle,this.paintStyle)}}};if(a.draggable==null?true:a.draggable){var c=a.dragOptions||l.DEFAULT_DRAG_OPTIONS,f=c.drag||function(){};
a=function(h,d){var g={};for(var i in c)g[i]=c[i];g.drag=d;h.draggable(g)};a(this.source,function(h,d){z(e.source,d);f(h,d)});a(this.target,function(h,d){z(e.target,d);f(h,d)})}this.source.resize&&this.source.resize(function(){l.repaint(e.sourceId)});this.source.offset();this.paint(this.sourceId,{absolutePosition:this.source.offset()})}})();
(function(o){o.fn.plumb=function(m){m=o.extend({},m);return this.each(function(){var r=o(this),q={};q.source=r;for(var v in m)q[v]=m[v];jsPlumb.connect(q)})};o.fn.detach=function(m){return this.each(function(){var r=o(this).attr("id");if(typeof m=="string")m=[m];for(var q=0;q<m.length;q++)jsPlumb.detach(r,m[q])})};o.fn.detachAll=function(){return this.each(function(){var m=o(this).attr("id");jsPlumb.detachAll(m)})}})(jQuery);
|
(function(c){function g(b,a){this.element=b;this.options=c.extend({},h,a);c(this.element).data("max-height",this.options.maxHeight);c(this.element).data("height-margin",this.options.heightMargin);delete this.options.maxHeight;if(this.options.embedCSS&&!k){var d=".readmore-js-toggle, .readmore-js-section { "+this.options.sectionCSS+" } .readmore-js-section { overflow: hidden; }",e=document.createElement("style");e.type="text/css";e.styleSheet?e.styleSheet.cssText=d:e.appendChild(document.createTextNode(d));
document.getElementsByTagName("head")[0].appendChild(e);k=!0}this._defaults=h;this._name=f;this.init()}var f="readmore",h={speed:100,maxHeight:200,heightMargin:16,moreLink:'<a href="#">Voir plus</a>',lessLink:'<a href="#">Fermer</a>',embedCSS:!0,sectionCSS:"display: block; width: 100%;",startOpen:!1,expandedClass:"readmore-js-expanded",collapsedClass:"readmore-js-collapsed",beforeToggle:function(){},afterToggle:function(){}},k=!1;g.prototype={init:function(){var b=this;c(this.element).each(function(){var a=
c(this),d=a.css("max-height").replace(/[^-\d\.]/g,"")>a.data("max-height")?a.css("max-height").replace(/[^-\d\.]/g,""):a.data("max-height"),e=a.data("height-margin");"none"!=a.css("max-height")&&a.css("max-height","none");b.setBoxHeight(a);if(a.outerHeight(!0)<=d+e)return!0;a.addClass("readmore-js-section "+b.options.collapsedClass).data("collapsedHeight",d);a.after(c(b.options.startOpen?b.options.lessLink:b.options.moreLink).on("click",function(c){b.toggleSlider(this,a,c)}).addClass("readmore-js-toggle"));
b.options.startOpen||a.css({height:d})});c(window).on("resize",function(a){b.resizeBoxes()})},toggleSlider:function(b,a,d){d.preventDefault();var e=this;d=newLink=sectionClass="";var f=!1;d=c(a).data("collapsedHeight");c(a).height()<=d?(d=c(a).data("expandedHeight")+"px",newLink="lessLink",f=!0,sectionClass=e.options.expandedClass):(newLink="moreLink",sectionClass=e.options.collapsedClass);e.options.beforeToggle(b,a,f);c(a).animate({height:d},{duration:e.options.speed,complete:function(){e.options.afterToggle(b,
a,f);c(b).replaceWith(c(e.options[newLink]).on("click",function(b){e.toggleSlider(this,a,b)}).addClass("readmore-js-toggle"));c(this).removeClass(e.options.collapsedClass+" "+e.options.expandedClass).addClass(sectionClass)}})},setBoxHeight:function(b){var a=b.clone().css({height:"auto",width:b.width(),overflow:"hidden"}).insertAfter(b),c=a.outerHeight(!0);a.remove();b.data("expandedHeight",c)},resizeBoxes:function(){var b=this;c(".readmore-js-section").each(function(){var a=c(this);b.setBoxHeight(a);
(a.height()>a.data("expandedHeight")||a.hasClass(b.options.expandedClass)&&a.height()<a.data("expandedHeight"))&&a.css("height",a.data("expandedHeight"))})},destroy:function(){var b=this;c(this.element).each(function(){var a=c(this);a.removeClass("readmore-js-section "+b.options.collapsedClass+" "+b.options.expandedClass).css({"max-height":"",height:"auto"}).next(".readmore-js-toggle").remove();a.removeData()})}};c.fn[f]=function(b){var a=arguments;if(void 0===b||"object"===typeof b)return this.each(function(){if(c.data(this,
"plugin_"+f)){var a=c.data(this,"plugin_"+f);a.destroy.apply(a)}c.data(this,"plugin_"+f,new g(this,b))});if("string"===typeof b&&"_"!==b[0]&&"init"!==b)return this.each(function(){var d=c.data(this,"plugin_"+f);d instanceof g&&"function"===typeof d[b]&&d[b].apply(d,Array.prototype.slice.call(a,1))})}})(jQuery); |
/**
*
*
*/
angular.module('MRT').directive('termSearchPageview', termSearchPageview);
function termSearchPageview($parse) {
var directive = {
restrict: 'AE',
templateUrl: 'pension/tpls/term/term-search-pageview.html',
replace: false,
//our data source would be an array
//passed thru chart-data attribute
scope: {data: '=chartData'},
link: function(scope, element, attrs) {
//in D3, any selection[0] contains the group
//selection[0][0] is the DOM node
//but we won't need that this time
// var selector = element[0];
return true;
var chart;
//var color = d3.scale.linear().domain([0,1]).range(["#fed900","#39c"]);
var color = ["#fed900", "#39c"];
//var color = d3.scale.category10().range();
// console.log(color);
// alert(scope.data);
nv.addGraph(function() {
chart = nv.models.linePlusBarChart()
.margin({top: 30, right: 60, bottom: 50, left: 70})
.x(function(d, i) {
return i
})
.y(function(d) {
return d[1]
})
.color(color);
chart.xAxis
.showMaxMin(true)
.tickFormat(function(d) {
var dx = scope.data[0].values[d] && scope.data[0].values[d][0] || 0;
return d3.time.format('%m/%Y')(new Date(dx))
});
chart.y1Axis
.tickFormat(d3.format(',f'));
chart.y2Axis
.tickFormat(function(d) {
return d3.format(',f')(d)
});
chart.bars.forceY([0]);
chart.lines.forceY([0])
draw();
nv.utils.windowResize(chart.update);
});
function draw() {
d3.select(element[0])
.datum(scope.data)
.transition().duration(500).call(chart);
}
function transition() {
d3.select(element[0])
.transition().duration(500).call(chart);
}
scope.$watch('data', function() {
draw();
});
scope.getWidth = function() {
return element[0].offsetWidth;
};
scope.$watch(function() {
return element[0].offsetWidth;
}, function(newValue, oldValue)
{
// alert(newValue);
chart.update;
});
}
};
return directive;
}
;
|
'use strict';
let Helpers = rootRequire('helpers');
let logger = new Helpers().logger;
var className = 'CURRENCIES'
class Currencies {
constructor (currencies, ratesApi) {
//Save the current array of currencies in memory so API is only called
//once. WISH: Test the performance
this.currencies = currencies || [];
this._ratesApi = ratesApi;
this._currentRates = null;
}
receive (callback) {
var thisToChange = this;
this.currencies.forEach(function (currency) {
thisToChange._ratesApi.fetch(currency, function (err, currencyName, currencyRates) {
if (err) {
logger.error(err);
return callback(err);
}
callback(null, currencyName, currencyRates);
});
});
}
set currentRates (values) {
this._currentRates = values;
}
add (currency) {
if (this.currencies.indexOf(currency) === -1) {
this.currencies.push(currency);
}
return this;
}
// Might not be needed until unsuscribe. Delete after being in Github
remove (currency) {
let index = this.currencies.indexOf(currency);
if (index > -1) {
this.currencies.splice(index, 1);
}
return this;
}
}
module.exports = Currencies; |
#!/usr/bin/env node
/*
In the blog, it says to add the folloing to the package.json scripts.
Instead, we'll do the work in this script and call it from package.json
"relay": "curl https://graphql-demo.kriasoft.com/schema -o ./src/graphql.schema && relay-compiler --src ./src --schema ./src/graphql.schema
Main docs: https://facebook.github.io/relay/docs/relay-compiler.html
I believe the __generated__/ is created only if there are graphql queries in the code.
*/
const { execSync } = require('child_process');
const { join } = require('path');
const relayCompilerPath = join(__dirname, '../node_modules/relay-compiler/bin/relay-compiler');
const srcDir = join(__dirname, '../src');
const schemaDir = join(__dirname, '../src/relay-schema');
const schemaFileName = 'graphql.schema';
const schemaFilePath = join(schemaDir, schemaFileName);
execSync(`${relayCompilerPath} --src ${srcDir} --schema ${schemaFilePath}`);
|
"use strict"
const { withCategories } = require("../../scripts/lib/rules")
require("../../scripts/update-docs-headers")
require("../../scripts/update-docs-index")
module.exports = {
base: "/eslint-plugin-eslint-comments/",
title: "eslint-plugin-eslint-comments",
description: "Additional ESLint rules for ESLint directive comments.",
evergreen: true,
plugins: {
"@vuepress/pwa": { updatePopup: true },
},
themeConfig: {
repo: "mysticatea/eslint-plugin-eslint-comments",
docsRepo: "mysticatea/eslint-plugin-eslint-comments",
docsDir: "docs",
docsBranch: "master",
editLinks: true,
search: false,
nav: [
{
text: "Changelog",
link:
"https://github.com/mysticatea/eslint-plugin-eslint-comments/releases",
},
],
sidebarDepth: 0,
sidebar: {
"/": [
"/",
"/rules/",
...withCategories.map(({ category, rules }) => ({
title: `Rules in ${category}`,
collapsable: false,
children: rules.map(rule => `/rules/${rule.name}`),
})),
],
},
},
configureWebpack: {
module: {
rules: [
{
test: /internal[\\/]get-linters\.js$/u,
loader: "string-replace-loader",
options: {
search: "[\\s\\S]+", // whole file.
replace:
'module.exports = () => [require("eslint4b/dist/linter")]',
flags: "g",
},
},
],
},
},
}
|
/*@ngInject*/
function UserService($window, $log, Restangular, $state) {
const self = this;
if ($window.localStorage.mcuser) {
try {
self.mcuser = angular.fromJson($window.localStorage.mcuser);
} catch (err) {
$log.log('Error parse mcuser in localStorage');
self.mcuser = null;
}
}
$window.addEventListener('storage', (e) => {
if (e.key === 'mcuser' && e.newValue === 'null') {
self.mcuser = null;
$state.go('login');
}
});
return {
isAuthenticated: function() {
return self.mcuser;
},
setAuthenticated: function(authenticated, u) {
if (!authenticated) {
$window.localStorage.removeItem('mcuser');
$window.localStorage.mcuser = null;
self.mcuser = undefined;
} else {
if (!u.favorites) {
u.favorites = {};
}
$window.localStorage.mcuser = angular.toJson(u);
self.mcuser = u;
}
},
apikey: function() {
return self.mcuser ? self.mcuser.apikey : undefined;
},
u: function() {
return self.mcuser ? self.mcuser.email : 'Login';
},
attr: function() {
return self.mcuser;
},
isBetaUser: function () {
return self.mcuser ? self.mcuser.beta_user : false
},
toggleBetaUser: function() {
self.mcuser.beta_user = !self.mcuser.beta_user;
},
isTemplateAdmin: function () {
return self.mcuser ? self.mcuser.is_template_admin : false
},
favorites: function(projectID) {
if (!(projectID in self.mcuser.favorites)) {
self.mcuser.favorites[projectID] = {
processes: []
};
}
return self.mcuser.favorites[projectID];
},
addToFavorites: function(projectID, templateName) {
self.mcuser.favorites[projectID].processes.push(templateName);
$window.localStorage.mcuser = angular.toJson(self.mcuser);
},
removeFromFavorites: function(projectID, templateName) {
let i = _.indexOf(self.mcuser.favorites[projectID].processes, function(n) {
return n === templateName;
});
if (i !== -1) {
self.mcuser.favorites[projectID].processes.splice(i, 1);
$window.localStorage.mcuser = angular.toJson(self.mcuser);
}
},
reset_apikey: function(new_key) {
if (self.mcuser) {
self.mcuser.apikey = new_key;
$window.localStorage.mcuser = angular.toJson(self.mcuser);
}
},
save: function() {
if (self.mcuser) {
$window.localStorage.mcuser = angular.toJson(self.mcuser);
}
},
updateDefaultProject: function(projectId, experimentId) {
return Restangular.one('v2').one('users')
.customPUT({default_project: projectId, default_experiment: experimentId});
},
updateFullname: function(fullname) {
return Restangular.one('v2').one('users').customPUT({fullname: fullname});
},
updateAffiliation: function(affiliation) {
return Restangular.one('v2').one('users').customPUT({affiliation: affiliation});
},
updateGlobusUserName: function(globusName) {
return Restangular.one('v2').one('users').customPUT({globus_user: globusName});
},
updateDemoInstalled: function(demoInstalled) {
return Restangular.one('v2').one('users').customPUT({demo_installed: demoInstalled});
},
switchToUser: function(email) {
return Restangular.one('v2').one('users_become').customPUT({email: email});
}
};
}
angular.module('materialscommons').factory('User', UserService);
|
// Eloquent JavaScript
// Run this file in your terminal using
// `node my_solution.js`.
// Make sure it works before moving on!
// Program Structure
// Write your own variable and do something to it.
var x = 5
console.log(x*x)
// Write a short program that asks for a user to input
// their favorite food. After they hit return, have the
// program respond with "Hey! That's my favorite too!"
// (You will probably need to run this in the Chrome console
// rather than node since node does not support prompt or alert).
// Paste your program into the eloquent.js file.
// var anwer=prompt("What is your favorite food?");
// console.log("Hey! That is my favorite too!");
// Complete one of the exercises: Looping a Triangle,
//FizzBuzz, or Chess Board
for (var i = 1; i <=100; i++) {
if (i%5==0 && i%3==0)
console.log("FizzBuzz");
else if (i%5==0 && i%3!=0)
console.log("Buzz");
else if (i%3==0)
console.log("Fizz");
else console.log(i);
}
// Functions
// Complete the `minimum` exercise.
function min(num1, num2){
return Math.min(num1,num2);
};
// Data Structures: Objects and Arrays
// Create an object called "me" that stores your name, age, 3 favorite foods, and a quirk below.
var me = {
name: "Terry",
age: 30,
favorite_food: ["orange", "spinach", "apple"],
quirk: "I love writing code",
}
// Reflection
// What are the biggest similarities and differences between
//JavaScript and Ruby?
// Was some of your Ruby knowledge solidified by learning
//another language? If so, which concepts?
// How do you feel about diving into JavaScript after
//reading these chapters? |
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Drawer from '@material-ui/core/Drawer';
import CssBaseline from '@material-ui/core/CssBaseline';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import List from '@material-ui/core/List';
import Typography from '@material-ui/core/Typography';
import Divider from '@material-ui/core/Divider';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import MailIcon from '@material-ui/icons/Mail';
const drawerWidth = 240;
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
},
appBar: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
drawerPaper: {
width: drawerWidth,
},
toolbar: theme.mixins.toolbar,
content: {
flexGrow: 1,
backgroundColor: theme.palette.background.default,
padding: theme.spacing(3),
},
}));
function PermanentDrawerLeft() {
const classes = useStyles();
return (
<div className={classes.root}>
<CssBaseline />
<AppBar position="fixed" className={classes.appBar}>
<Toolbar>
<Typography variant="h6" noWrap>
Permanent drawer
</Typography>
</Toolbar>
</AppBar>
<Drawer
className={classes.drawer}
variant="permanent"
classes={{
paper: classes.drawerPaper,
}}
anchor="left"
>
<div className={classes.toolbar} />
<Divider />
<List>
{['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
<Divider />
<List>
{['All mail', 'Trash', 'Spam'].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
</Drawer>
<main className={classes.content}>
<div className={classes.toolbar} />
<Typography paragraph>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Rhoncus dolor purus non enim praesent elementum
facilisis leo vel. Risus at ultrices mi tempus imperdiet. Semper risus in hendrerit
gravida rutrum quisque non tellus. Convallis convallis tellus id interdum velit laoreet id
donec ultrices. Odio morbi quis commodo odio aenean sed adipiscing. Amet nisl suscipit
adipiscing bibendum est ultricies integer quis. Cursus euismod quis viverra nibh cras.
Metus vulputate eu scelerisque felis imperdiet proin fermentum leo. Mauris commodo quis
imperdiet massa tincidunt. Cras tincidunt lobortis feugiat vivamus at augue. At augue eget
arcu dictum varius duis at consectetur lorem. Velit sed ullamcorper morbi tincidunt. Lorem
donec massa sapien faucibus et molestie ac.
</Typography>
<Typography paragraph>
Consequat mauris nunc congue nisi vitae suscipit. Fringilla est ullamcorper eget nulla
facilisi etiam dignissim diam. Pulvinar elementum integer enim neque volutpat ac
tincidunt. Ornare suspendisse sed nisi lacus sed viverra tellus. Purus sit amet volutpat
consequat mauris. Elementum eu facilisis sed odio morbi. Euismod lacinia at quis risus sed
vulputate odio. Morbi tincidunt ornare massa eget egestas purus viverra accumsan in. In
hendrerit gravida rutrum quisque non tellus orci ac. Pellentesque nec nam aliquam sem et
tortor. Habitant morbi tristique senectus et. Adipiscing elit duis tristique sollicitudin
nibh sit. Ornare aenean euismod elementum nisi quis eleifend. Commodo viverra maecenas
accumsan lacus vel facilisis. Nulla posuere sollicitudin aliquam ultrices sagittis orci a.
</Typography>
</main>
</div>
);
}
export default PermanentDrawerLeft;
|
import React from 'react';
import PropTypes from 'prop-types';
import Card from '@material-ui/core/Card';
import Box from '@material-ui/core/Box';
import List from '@material-ui/core/List';
import TeamTasksListItem from './TeamTasksListItem';
const TeamTasksProject = props => props.project.teamTasks.length ? (
<Box className="team-tasks-project" my={2}>
{
props.project.title ?
<Box pb={2}>{props.project.title}</Box>
: null
}
<div>
<Card>
<List>
{props.project.teamTasks.map((task, index) =>
(<TeamTasksListItem
index={index + 1}
key={`${task.label}-${task.type}`}
task={task}
tasks={props.project.teamTasks}
fieldset={props.fieldset}
team={props.team}
about={props.about}
/>))}
</List>
</Card>
</div>
</Box>
) : null;
TeamTasksProject.propTypes = {
project: PropTypes.shape({
teamTasks: PropTypes.array,
title: PropTypes.string,
}).isRequired,
fieldset: PropTypes.string.isRequired,
team: PropTypes.object.isRequired,
about: PropTypes.object.isRequired,
};
export default TeamTasksProject;
|
'use strict';
var h = require('..');
// translations:
var tr = h.translator;
tr.ruleFor('goal', function(item) {
return {
name: item.value
};
});
tr.ruleFor('item', function(goal) {
return {
value: goal.name
};
});
var goal = { name: 'some item name' };
var item = { value: 'some item name' };
console.log('tr.to goal:', tr.to('goal', item));
console.log('tr.to item:', tr.to('item', goal));
|
module.exports = {
entry: {
app: [
'webpack-dev-server/client?http://localhost:9000',
'./src/index.js',
]
},
output: {
path: __dirname,
publicPath: '/',
filename: '[name].bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{
test: /\.(sass|scss)$/,
loader: 'style!css!sass'
},
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './',
port: 9000,
}
};
|
exports.up = function(knex, Promise) {
return knex.schema.createTableIfNotExists('users', function (table) {
table.increments('id')
table.bigInteger('passportId')
table.string('name')
table.string('shortlist')
table.timestamps()
})
};
exports.down = function(knex, Promise) {
return knex.schema.dropTableIfExists('users')
};
|
export class Tooltip {
constructor () {
this._div = document.getElementById('tooltip')
}
set (x, y, offsetX, offsetY, html) {
this._div.innerHTML = html
// Assign display: block so that the offsetWidth is valid
this._div.style.display = 'block'
// Prevent the div from overflowing the page width
const tooltipWidth = this._div.offsetWidth
// 1.2 is a magic number used to pad the offset to ensure the tooltip
// never gets close or surpasses the page's X width
if (x + offsetX + (tooltipWidth * 1.2) > window.innerWidth) {
x -= tooltipWidth
offsetX *= -1
}
this._div.style.top = `${y + offsetY}px`
this._div.style.left = `${x + offsetX}px`
}
hide = () => {
this._div.style.display = 'none'
}
}
export class Caption {
constructor () {
this._div = document.getElementById('status-text')
}
set (text) {
this._div.innerText = text
this._div.style.display = 'block'
}
hide () {
this._div.style.display = 'none'
}
}
// Minecraft Java Edition default server port: 25565
// Minecraft Bedrock Edition default server port: 19132
const MINECRAFT_DEFAULT_PORTS = [25565, 19132]
export function formatMinecraftServerAddress (ip, port) {
if (port && !MINECRAFT_DEFAULT_PORTS.includes(port)) {
return `${ip}:${port}`
}
return ip
}
// Detect gaps in versions by matching their indexes to knownVersions
export function formatMinecraftVersions (versions, knownVersions) {
if (!versions || !versions.length || !knownVersions || !knownVersions.length) {
return
}
let currentVersionGroup = []
const versionGroups = []
for (let i = 0; i < versions.length; i++) {
// Look for value mismatch between the previous index
// Require i > 0 since lastVersionIndex is undefined for i === 0
if (i > 0 && versions[i] - versions[i - 1] !== 1) {
versionGroups.push(currentVersionGroup)
currentVersionGroup = []
}
currentVersionGroup.push(versions[i])
}
// Ensure the last versionGroup is always pushed
if (currentVersionGroup.length > 0) {
versionGroups.push(currentVersionGroup)
}
if (versionGroups.length === 0) {
return
}
// Remap individual versionGroups values into named versions
return versionGroups.map(versionGroup => {
const startVersion = knownVersions[versionGroup[0]]
if (versionGroup.length === 1) {
// A versionGroup may contain a single version, only return its name
// This is a cosmetic catch to avoid version labels like 1.0-1.0
return startVersion
} else {
const endVersion = knownVersions[versionGroup[versionGroup.length - 1]]
return `${startVersion}-${endVersion}`
}
}).join(', ')
}
export function formatTimestampSeconds (secs) {
const date = new Date(0)
date.setUTCSeconds(secs)
return date.toLocaleTimeString()
}
export function formatDate (secs) {
const date = new Date(0)
date.setUTCSeconds(secs)
return date.toLocaleDateString()
}
export function formatPercent (x, over) {
const val = Math.round((x / over) * 100 * 10) / 10
return `${val}%`
}
export function formatNumber (x) {
if (typeof x !== 'number') {
return '-'
} else {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
}
|
var request = require('supertest-as-promised');
var api = require('../server.js');
var host = process.env.API_TEST_HOST || api;
var mongoose = require('mongoose');
// var host = 'http://localhost:3000';
var _ = require('lodash');
request = request(host);
describe('Admnistracion de tiquetes [/tickets]', function() {
before(function(done) {
mongoose.connect('mongodb://localhost/eticket-dev', done);
});
after(function(done) {
mongoose.disconnect(done);
mongoose.models = {};
});
/*
sucursal: String,
text: String,
status: Number, // 1.WAITING | 2.IN_PROCESS | 3.FINISHED | 4.CANCELED
initialTime: Date,
//initServiceTime:Date,
//endServiceTime:Date,
userId:String,
*/
describe('POST', function() {
it('deberia crear una ticket', function(done) {
var data = {
"ticket": {
"sucursal": "0",
"text": "testTicket",
"userId": "testUser1"
}
};
request
.post('/eticket')
.set('Accept', 'application/json')
.send(data)
.expect(201)
.expect('Content-Type', /application\/json/)
.end(function(err, res) {
var ticket;
var body = res.body;
// console.log('body', body);
// Nota existe
expect(body).to.have.property('ticket');
ticket = body.ticket;
// Propiedades
expect(ticket).to.have.property('sucursal', '0');
expect(ticket).to.have.property('text', 'testTicket');
expect(ticket).to.have.property('userId', 'testUser1');
expect(ticket).to.have.property('id');
expect(ticket).to.have.property('initialTime');
console.log("Ticket Generado");
console.log(ticket);
done(err);
});
});
});
});
|
app.controller( 'PlayerListController', PlayerListController );
function PlayerListController( $scope, rconService, $interval )
{
$scope.Output = [];
$scope.OrderBy = '-ConnectedSeconds';
$scope.Refresh = function ()
{
rconService.getPlayers($scope, function ( players )
{
$scope.Players = players;
});
}
$scope.Order = function( field )
{
if ( $scope.OrderBy === field )
{
field = '-' + field;
}
$scope.OrderBy = field;
}
$scope.SortClass = function( field )
{
if ( $scope.OrderBy === field ) return "sorting";
if ( $scope.OrderBy === "-" + field ) return "sorting descending";
return null;
}
$scope.KickPlayer = function ( id )
{
rconService.Command( 'kick ' + id );
$scope.Refresh();
}
$scope.BanPlayer = function ( id )
{
rconService.Command( 'banid ' + id );
$scope.Refresh();
}
$scope.OwnerPlayer = function ( id )
{
rconService.Command( 'ownerid ' + id );
$scope.Refresh();
}
$scope.ModPlayer = function ( id )
{
rconService.Command( 'moderatorid ' + id );
$scope.Refresh();
}
$scope.RemoveMod = function ( id )
{
rconService.Command( 'removemoderator ' + id );
$scope.Refresh();
}
$scope.RemoveOwner = function ( id )
{
rconService.Command( 'removeowner ' + id );
$scope.Refresh();
}
$scope.unban = function ( id )
{
rconService.Command( 'unban ' + id );
$scope.Refresh();
}
rconService.InstallService( $scope, $scope.Refresh )
// var timer = $interval( function ()
// {
// //$scope.Refresh();
// }.bind( this ), 1000 );
//$scope.$on( '$destroy', function () { $interval.cancel( timer ) } )
} |
/* global beforeEach, describe, process, afterEach, it, require */
'use strict';
const initCommand = require('../src/init');
const assert = require('chai').assert;
const fs = require('fs');
const mockFs = require('mock-fs');
const path = require('path');
const sinon = require('sinon');
const toml = require('toml');
const testCwd = path.resolve(process.cwd());
function assertNameExists(cwd, fileName) {
const files = fs.readdirSync(cwd);
assert.include(files, fileName);
}
function assertNameDoesntExist(cwd, fileName) {
const files = fs.readdirSync(cwd);
assert.notInclude(files, fileName);
}
function assertDirExists(cwd, dirName) {
assertNameExists(cwd, dirName);
assert.isTrue(fs.statSync(`${cwd}/${dirName}`).isDirectory());
}
function assertDirDoesntExist(cwd, dirName) {
assertNameDoesntExist(cwd, dirName);
}
function assertFileExists(cwd, fileName) {
assertNameExists(cwd, fileName);
assert.isTrue(fs.statSync(`${cwd}/${fileName}`).isFile());
}
function assertFileDoesntExist(cwd, fileName) {
assertNameDoesntExist(cwd, fileName);
}
function getFileString(filepath) {
return fs.readFileSync(filepath, { encoding: 'utf8' });
}
function readToml(filepath) {
const tomlData = getFileString(filepath);
return toml.parse(tomlData);
}
function assertValidConfig(filepath) {
const configObject = readToml(filepath);
// Need an uncommented project name
assert.property(configObject, 'project_name');
// Need an uncommented token_secret
assert.property(configObject, 'token_secret');
}
function assertConfigProjectName(filepath, expectedName) {
const configObject = readToml(filepath);
assert.propertyVal(configObject, 'project_name', expectedName);
}
describe('hz init', () => {
beforeEach(() => {
sinon.stub(console, 'error');
sinon.stub(console, 'info');
sinon.stub(process, 'exit');
});
afterEach(() => {
process.chdir(testCwd);
mockFs.restore();
console.error.restore();
console.info.restore();
process.exit.restore();
});
describe('when passed a project name,', () => {
const testDirName = 'test-app';
const projectDir = `${testCwd}/${testDirName}`;
const runOptions = { projectName: testDirName };
it("creates the project dir if it doesn't exist", (done) => {
mockFs();
initCommand.runCommand(runOptions);
assertDirExists(testCwd, testDirName);
done();
});
it('moves into the project dir', (done) => {
mockFs({
[testDirName]: {},
});
initCommand.runCommand(runOptions);
assert.equal(process.cwd(), `${testCwd}/${testDirName}`);
done();
});
describe('when the project dir is empty,', () => {
beforeEach(() => {
mockFs({ [projectDir]: {} });
});
it('creates the src dir', (done) => {
initCommand.runCommand(runOptions);
assertDirExists(projectDir, 'src');
done();
});
it('creates the dist dir', (done) => {
initCommand.runCommand(runOptions);
assertDirExists(projectDir, 'dist');
done();
});
it('creates an example dist/index.html', (done) => {
initCommand.runCommand(runOptions);
assertFileExists(`${projectDir}/dist`, 'index.html');
done();
});
it('creates the .hz dir', (done) => {
initCommand.runCommand(runOptions);
assertDirExists(projectDir, '.hz');
done();
});
it('creates the .hz/config.toml file', (done) => {
initCommand.runCommand(runOptions);
assertFileExists(`${projectDir}/.hz`, 'config.toml');
done();
});
});
describe('when the project dir is not empty,', () => {
beforeEach(() => {
mockFs({
[projectDir]: {
lib: { 'someFile.html': '<blink>Something</blink>' },
},
});
});
it("doesn't create the src dir", (done) => {
initCommand.runCommand(runOptions);
assertDirDoesntExist(projectDir, 'src');
done();
});
it("doesn't create the dist dir", (done) => {
initCommand.runCommand(runOptions);
assertDirDoesntExist(projectDir, 'dist');
done();
});
it("doesn't create an example dist/index.html", (done) => {
fs.mkdirSync(`${projectDir}/dist`);
initCommand.runCommand(runOptions);
assertFileDoesntExist(`${projectDir}/dist`, 'index.html');
done();
});
it("still creates the .hz dir if it doesn't exist", (done) => {
initCommand.runCommand(runOptions);
assertDirExists(projectDir, '.hz');
done();
});
it("doesn't create the .hz dir if it already exists", (done) => {
fs.mkdirSync(`${projectDir}/.hz`);
const beforeMtime = fs.statSync(`${projectDir}/.hz`).birthtime.getTime();
initCommand.runCommand(runOptions);
const afterMtime = fs.statSync(`${projectDir}/.hz`).birthtime.getTime();
assert.equal(beforeMtime, afterMtime, '.hz was modified');
done();
});
it("creates a valid config.toml if it doesn't exist", (done) => {
fs.mkdirSync(`${projectDir}/.hz`);
initCommand.runCommand(runOptions);
assertFileExists(`${projectDir}/.hz`, 'config.toml');
assertValidConfig(`${projectDir}/.hz/config.toml`);
done();
});
it("doesn't touch the config.toml if it already exists", (done) => {
fs.mkdirSync(`${projectDir}/.hz`);
const filename = `${projectDir}/.hz/config.toml`;
fs.appendFileSync(filename, '#Hoo\n');
const beforeMtime = fs.statSync(filename).mtime.getTime();
initCommand.runCommand(runOptions);
const afterMtime = fs.statSync(filename).mtime.getTime();
assert.equal(beforeMtime, afterMtime);
const afterContents = getFileString(filename);
assert.equal('#Hoo\n', afterContents);
done();
});
});
});
describe('when not passed a project name,', () => {
const runOptions = { };
it('stays in the current directory', (done) => {
mockFs();
const beforeCwd = process.cwd();
initCommand.runCommand(runOptions);
const afterCwd = process.cwd();
assert.equal(beforeCwd, afterCwd, 'init changed directories');
done();
});
describe('in an empty directory,', () => {
beforeEach(() => {
mockFs({});
});
it('creates the src dir', (done) => {
initCommand.runCommand(runOptions);
assertDirExists(testCwd, 'src');
done();
});
it('creates the dist dir', (done) => {
initCommand.runCommand(runOptions);
assertDirExists(testCwd, 'dist');
done();
});
it('creates an example dist/index.html', (done) => {
initCommand.runCommand(runOptions);
assertFileExists(`${testCwd}/dist`, 'index.html');
done();
});
it('creates the .hz dir', (done) => {
initCommand.runCommand(runOptions);
assertDirExists(testCwd, '.hz');
done();
});
it('creates the .hz/config.toml file', (done) => {
initCommand.runCommand(runOptions);
assertFileExists(`${testCwd}/.hz`, 'config.toml');
assertValidConfig(`${testCwd}/.hz/config.toml`);
done();
});
});
describe('in a directory with files in it', () => {
beforeEach(() => {
mockFs({
lib: { 'some_file.txt': 'Some file content' },
});
});
it("doesn't create the src dir", (done) => {
initCommand.runCommand(runOptions);
assertDirDoesntExist(testCwd, 'src');
done();
});
it("doesn't create the dist dir", (done) => {
initCommand.runCommand(runOptions);
assertDirDoesntExist(testCwd, 'dist');
done();
});
it("doesn't create an example dist/index.html", (done) => {
fs.mkdirSync(`${testCwd}/dist`);
initCommand.runCommand(runOptions);
assertFileDoesntExist(`${testCwd}/dist`, 'index.html');
done();
});
it("creates the .hz dir if it doesn't exist", (done) => {
initCommand.runCommand(runOptions);
assertDirExists(testCwd, '.hz');
done();
});
it("doesn't create the .hz dir if it exists", (done) => {
const hzDir = `${testCwd}/.hz`;
fs.mkdirSync(hzDir);
const beforeTime = fs.statSync(hzDir).birthtime.getTime();
initCommand.runCommand(runOptions);
assertDirExists(testCwd, '.hz');
const afterTime = fs.statSync(hzDir).birthtime.getTime();
assert.equal(beforeTime, afterTime, '.hz birthtime changed');
done();
});
it("creates the config.toml if it doesn't exist", (done) => {
initCommand.runCommand(runOptions);
assertFileExists(`${testCwd}/.hz`, 'config.toml');
assertValidConfig(`${testCwd}/.hz/config.toml`);
done();
});
it("doesn't touch the config.toml if it already exists", (done) => {
fs.mkdirSync(`${testCwd}/.hz`);
const filename = `${testCwd}/.hz/config.toml`;
fs.appendFileSync(filename, '#Hoo\n');
const beforeMtime = fs.statSync(filename).mtime.getTime();
initCommand.runCommand(runOptions);
const afterMtime = fs.statSync(filename).mtime.getTime();
assert.equal(beforeMtime, afterMtime);
const afterContents = getFileString(filename);
assert.equal('#Hoo\n', afterContents);
done();
});
});
});
});
|
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* @constant
* @type Number
*/
cc.TMX_PROPERTY_NONE = 0;
/**
* @constant
* @type Number
*/
cc.TMX_PROPERTY_MAP = 1;
/**
* @constant
* @type Number
*/
cc.TMX_PROPERTY_LAYER = 2;
/**
* @constant
* @type Number
*/
cc.TMX_PROPERTY_OBJECTGROUP = 3;
/**
* @constant
* @type Number
*/
cc.TMX_PROPERTY_OBJECT = 4;
/**
* @constant
* @type Number
*/
cc.TMX_PROPERTY_TILE = 5;
/**
* @constant
* @type Number
*/
cc.TMX_TILE_HORIZONTAL_FLAG = 0x80000000;
/**
* @constant
* @type Number
*/
cc.TMX_TILE_VERTICAL_FLAG = 0x40000000;
/**
* @constant
* @type Number
*/
cc.TMX_TILE_DIAGONAL_FLAG = 0x20000000;
/**
* @constant
* @type Number
*/
cc.TMX_TILE_FLIPPED_ALL = (cc.TMX_TILE_HORIZONTAL_FLAG | cc.TMX_TILE_VERTICAL_FLAG | cc.TMX_TILE_DIAGONAL_FLAG) >>> 0;
/**
* @constant
* @type Number
*/
cc.TMX_TILE_FLIPPED_MASK = (~(cc.TMX_TILE_FLIPPED_ALL)) >>> 0;
// Bits on the far end of the 32-bit global tile ID (GID's) are used for tile flags
/**
* <p>cc.TMXLayerInfo contains the information about the layers like: <br />
* - Layer name<br />
* - Layer size <br />
* - Layer opacity at creation time (it can be modified at runtime) <br />
* - Whether the layer is visible (if it's not visible, then the CocosNode won't be created) <br />
* <br />
* This information is obtained from the TMX file.</p>
* @class
* @extends cc.Class
*
* @property {Array} properties - Properties of the layer info.
*/
cc.TMXLayerInfo = cc.Class.extend(/** @lends cc.TMXLayerInfo# */{
properties:null,
name:"",
_layerSize:null,
_tiles:null,
visible:null,
_opacity:null,
ownTiles:true,
_minGID:100000,
_maxGID:0,
offset:null,
ctor:function () {
this.properties = [];
this.name = "";
this._layerSize = null;
this._tiles = [];
this.visible = true;
this._opacity = 0;
this.ownTiles = true;
this._minGID = 100000;
this._maxGID = 0;
this.offset = cc.p(0,0);
},
/**
* Gets the Properties.
* @return {Array}
*/
getProperties:function () {
return this.properties;
},
/**
* Set the Properties.
* @param {object} value
*/
setProperties:function (value) {
this.properties = value;
}
});
/**
* <p>cc.TMXTilesetInfo contains the information about the tilesets like: <br />
* - Tileset name<br />
* - Tileset spacing<br />
* - Tileset margin<br />
* - size of the tiles<br />
* - Image used for the tiles<br />
* - Image size<br />
*
* This information is obtained from the TMX file. </p>
* @class
* @extends cc.Class
*
* @property {string} name - Tileset name
* @property {number} firstGid - First grid
* @property {number} spacing - Spacing
* @property {number} margin - Margin
* @property {string} sourceImage - Filename containing the tiles (should be sprite sheet / texture atlas)
* @property {cc.Size|null} imageSize - Size in pixels of the image
*/
cc.TMXTilesetInfo = cc.Class.extend(/** @lends cc.TMXTilesetInfo# */{
//Tileset name
name:"",
//First grid
firstGid:0,
_tileSize:null,
//Spacing
spacing:0,
//Margin
margin:0,
//Filename containing the tiles (should be sprite sheet / texture atlas)
sourceImage:"",
//Size in pixels of the image
imageSize:null,
ctor:function () {
this._tileSize = cc.size(0, 0);
this.imageSize = cc.size(0, 0);
},
/**
* Return rect
* @param {Number} gid
* @return {cc.Rect}
*/
rectForGID:function (gid) {
var rect = cc.rect(0, 0, 0, 0);
rect.width = this._tileSize.width;
rect.height = this._tileSize.height;
gid &= cc.TMX_TILE_FLIPPED_MASK;
gid = gid - parseInt(this.firstGid, 10);
var max_x = parseInt((this.imageSize.width - this.margin * 2 + this.spacing) / (this._tileSize.width + this.spacing), 10);
rect.x = parseInt((gid % max_x) * (this._tileSize.width + this.spacing) + this.margin, 10);
rect.y = parseInt(parseInt(gid / max_x, 10) * (this._tileSize.height + this.spacing) + this.margin, 10);
return rect;
}
});
/**
* <p>cc.TMXMapInfo contains the information about the map like: <br/>
*- Map orientation (hexagonal, isometric or orthogonal)<br/>
*- Tile size<br/>
*- Map size</p>
*
* <p>And it also contains: <br/>
* - Layers (an array of TMXLayerInfo objects)<br/>
* - Tilesets (an array of TMXTilesetInfo objects) <br/>
* - ObjectGroups (an array of TMXObjectGroupInfo objects) </p>
*
* <p>This information is obtained from the TMX file. </p>
* @class
* @extends cc.saxParser
*
* @property {Array} properties - Properties of the map info.
* @property {Number} orientation - Map orientation.
* @property {Object} parentElement - Parent element.
* @property {Number} parentGID - Parent GID.
* @property {Object} layerAttrs - Layer attributes.
* @property {Boolean} storingCharacters - Is reading storing characters stream.
* @property {String} tmxFileName - TMX file name.
* @property {String} currentString - Current string stored from characters stream.
* @property {Number} mapWidth - Width of the map
* @property {Number} mapHeight - Height of the map
* @property {Number} tileWidth - Width of a tile
* @property {Number} tileHeight - Height of a tile
*
* @param {String} tmxFile fileName or content string
* @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required.
* @example
* 1.
* //create a TMXMapInfo with file name
* var tmxMapInfo = new cc.TMXMapInfo("res/orthogonal-test1.tmx");
* 2.
* //create a TMXMapInfo with content string and resource path
* var resources = "res/TileMaps";
* var filePath = "res/TileMaps/orthogonal-test1.tmx";
* var xmlStr = cc.loader.getRes(filePath);
* var tmxMapInfo = new cc.TMXMapInfo(xmlStr, resources);
*/
cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{
properties:null,
orientation:null,
parentElement:null,
parentGID:null,
layerAttrs:0,
storingCharacters:false,
tmxFileName:null,
currentString:null,
_objectGroups:null,
_mapSize:null,
_tileSize:null,
_layers:null,
_tilesets:null,
// tile properties
_tileProperties:null,
_resources:"",
_currentFirstGID:0,
/**
* Creates a TMX Format with a tmx file or content string <br/>
* Constructor of cc.TMXMapInfo
* @param {String} tmxFile fileName or content string
* @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required.
*/
ctor:function (tmxFile, resourcePath) {
cc.SAXParser.prototype.ctor.apply(this);
this._mapSize = cc.size(0, 0);
this._tileSize = cc.size(0, 0);
this._layers = [];
this._tilesets = [];
this._objectGroups = [];
this.properties = [];
this._tileProperties = {};
this._currentFirstGID = 0;
if (resourcePath !== undefined) {
this.initWithXML(tmxFile,resourcePath);
} else if(tmxFile !== undefined){
this.initWithTMXFile(tmxFile);
}
},
/**
* Gets Map orientation.
* @return {Number}
*/
getOrientation:function () {
return this.orientation;
},
/**
* Set the Map orientation.
* @param {Number} value
*/
setOrientation:function (value) {
this.orientation = value;
},
/**
* Map width & height
* @return {cc.Size}
*/
getMapSize:function () {
return cc.size(this._mapSize.width,this._mapSize.height);
},
/**
* Map width & height
* @param {cc.Size} value
*/
setMapSize:function (value) {
this._mapSize.width = value.width;
this._mapSize.height = value.height;
},
_getMapWidth: function () {
return this._mapSize.width;
},
_setMapWidth: function (width) {
this._mapSize.width = width;
},
_getMapHeight: function () {
return this._mapSize.height;
},
_setMapHeight: function (height) {
this._mapSize.height = height;
},
/**
* Tiles width & height
* @return {cc.Size}
*/
getTileSize:function () {
return cc.size(this._tileSize.width, this._tileSize.height);
},
/**
* Tiles width & height
* @param {cc.Size} value
*/
setTileSize:function (value) {
this._tileSize.width = value.width;
this._tileSize.height = value.height;
},
_getTileWidth: function () {
return this._tileSize.width;
},
_setTileWidth: function (width) {
this._tileSize.width = width;
},
_getTileHeight: function () {
return this._tileSize.height;
},
_setTileHeight: function (height) {
this._tileSize.height = height;
},
/**
* Layers
* @return {Array}
*/
getLayers:function () {
return this._layers;
},
/**
* Layers
* @param {cc.TMXLayerInfo} value
*/
setLayers:function (value) {
this._layers.push(value);
},
/**
* tilesets
* @return {Array}
*/
getTilesets:function () {
return this._tilesets;
},
/**
* tilesets
* @param {cc.TMXTilesetInfo} value
*/
setTilesets:function (value) {
this._tilesets.push(value);
},
/**
* ObjectGroups
* @return {Array}
*/
getObjectGroups:function () {
return this._objectGroups;
},
/**
* ObjectGroups
* @param {cc.TMXObjectGroup} value
*/
setObjectGroups:function (value) {
this._objectGroups.push(value);
},
/**
* parent element
* @return {Object}
*/
getParentElement:function () {
return this.parentElement;
},
/**
* parent element
* @param {Object} value
*/
setParentElement:function (value) {
this.parentElement = value;
},
/**
* parent GID
* @return {Number}
*/
getParentGID:function () {
return this.parentGID;
},
/**
* parent GID
* @param {Number} value
*/
setParentGID:function (value) {
this.parentGID = value;
},
/**
* Layer attribute
* @return {Object}
*/
getLayerAttribs:function () {
return this.layerAttrs;
},
/**
* Layer attribute
* @param {Object} value
*/
setLayerAttribs:function (value) {
this.layerAttrs = value;
},
/**
* Is reading storing characters stream
* @return {Boolean}
*/
getStoringCharacters:function () {
return this.storingCharacters;
},
/**
* Is reading storing characters stream
* @param {Boolean} value
*/
setStoringCharacters:function (value) {
this.storingCharacters = value;
},
/**
* Properties
* @return {Array}
*/
getProperties:function () {
return this.properties;
},
/**
* Properties
* @param {object} value
*/
setProperties:function (value) {
this.properties = value;
},
/**
* Initializes a TMX format with a tmx file
* @param {String} tmxFile
* @return {Element}
*/
initWithTMXFile:function (tmxFile) {
this._internalInit(tmxFile, null);
return this.parseXMLFile(tmxFile);
},
/**
* initializes a TMX format with an XML string and a TMX resource path
* @param {String} tmxString
* @param {String} resourcePath
* @return {Boolean}
*/
initWithXML:function (tmxString, resourcePath) {
this._internalInit(null, resourcePath);
return this.parseXMLString(tmxString);
},
/** Initalises parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file
* @param {String} tmxFile
* @param {boolean} [isXmlString=false]
* @return {Element}
*/
parseXMLFile:function (tmxFile, isXmlString) {
isXmlString = isXmlString || false;
var xmlStr = isXmlString ? tmxFile : cc.loader.getRes(tmxFile);
if(!xmlStr) throw new Error("Please load the resource first : " + tmxFile);
var mapXML = this._parseXML(xmlStr);
var i, j;
// PARSE <map>
var map = mapXML.documentElement;
var version = map.getAttribute('version');
var orientationStr = map.getAttribute('orientation');
if (map.nodeName === "map") {
if (version !== "1.0" && version !== null)
cc.log("cocos2d: TMXFormat: Unsupported TMX version:" + version);
if (orientationStr === "orthogonal")
this.orientation = cc.TMX_ORIENTATION_ORTHO;
else if (orientationStr === "isometric")
this.orientation = cc.TMX_ORIENTATION_ISO;
else if (orientationStr === "hexagonal")
this.orientation = cc.TMX_ORIENTATION_HEX;
else if (orientationStr !== null)
cc.log("cocos2d: TMXFomat: Unsupported orientation:" + orientationStr);
var mapSize = cc.size(0, 0);
mapSize.width = parseFloat(map.getAttribute('width'));
mapSize.height = parseFloat(map.getAttribute('height'));
this.setMapSize(mapSize);
mapSize = cc.size(0, 0);
mapSize.width = parseFloat(map.getAttribute('tilewidth'));
mapSize.height = parseFloat(map.getAttribute('tileheight'));
this.setTileSize(mapSize);
// The parent element is the map
var propertyArr = map.querySelectorAll("map > properties > property");
if (propertyArr) {
var aPropertyDict = {};
for (i = 0; i < propertyArr.length; i++) {
aPropertyDict[propertyArr[i].getAttribute('name')] = propertyArr[i].getAttribute('value');
}
this.properties = aPropertyDict;
}
}
// PARSE <tileset>
var tilesets = map.getElementsByTagName('tileset');
if (map.nodeName !== "map") {
tilesets = [];
tilesets.push(map);
}
for (i = 0; i < tilesets.length; i++) {
var selTileset = tilesets[i];
// If this is an external tileset then start parsing that
var tsxName = selTileset.getAttribute('source');
if (tsxName) {
//this._currentFirstGID = parseInt(selTileset.getAttribute('firstgid'));
var tsxPath = isXmlString ? cc.path.join(this._resources, tsxName) : cc.path.changeBasename(tmxFile, tsxName);
this.parseXMLFile(tsxPath);
} else {
var tileset = new cc.TMXTilesetInfo();
tileset.name = selTileset.getAttribute('name') || "";
//TODO need fix
//if(this._currentFirstGID === 0){
tileset.firstGid = parseInt(selTileset.getAttribute('firstgid')) || 0;
//}else{
// tileset.firstGid = this._currentFirstGID;
// this._currentFirstGID = 0;
//}
tileset.spacing = parseInt(selTileset.getAttribute('spacing')) || 0;
tileset.margin = parseInt(selTileset.getAttribute('margin')) || 0;
var tilesetSize = cc.size(0, 0);
tilesetSize.width = parseFloat(selTileset.getAttribute('tilewidth'));
tilesetSize.height = parseFloat(selTileset.getAttribute('tileheight'));
tileset._tileSize = tilesetSize;
var image = selTileset.getElementsByTagName('image')[0];
var imagename = image.getAttribute('source');
var num = -1;
if(this.tmxFileName)
num = this.tmxFileName.lastIndexOf("/");
if (num !== -1) {
var dir = this.tmxFileName.substr(0, num + 1);
tileset.sourceImage = dir + imagename;
} else {
tileset.sourceImage = this._resources + (this._resources ? "/" : "") + imagename;
}
this.setTilesets(tileset);
// PARSE <tile>
var tiles = selTileset.getElementsByTagName('tile');
if (tiles) {
for (var tIdx = 0; tIdx < tiles.length; tIdx++) {
var t = tiles[tIdx];
this.parentGID = parseInt(tileset.firstGid) + parseInt(t.getAttribute('id') || 0);
var tp = t.querySelectorAll("properties > property");
if (tp) {
var dict = {};
for (j = 0; j < tp.length; j++) {
var name = tp[j].getAttribute('name');
dict[name] = tp[j].getAttribute('value');
}
this._tileProperties[this.parentGID] = dict;
}
}
}
}
}
// PARSE <layer>
var layers = map.getElementsByTagName('layer');
if (layers) {
for (i = 0; i < layers.length; i++) {
var selLayer = layers[i];
var data = selLayer.getElementsByTagName('data')[0];
var layer = new cc.TMXLayerInfo();
layer.name = selLayer.getAttribute('name');
var layerSize = cc.size(0, 0);
layerSize.width = parseFloat(selLayer.getAttribute('width'));
layerSize.height = parseFloat(selLayer.getAttribute('height'));
layer._layerSize = layerSize;
var visible = selLayer.getAttribute('visible');
layer.visible = !(visible == "0");
var opacity = selLayer.getAttribute('opacity') || 1;
if (opacity)
layer._opacity = parseInt(255 * parseFloat(opacity));
else
layer._opacity = 255;
layer.offset = cc.p(parseFloat(selLayer.getAttribute('x')) || 0, parseFloat(selLayer.getAttribute('y')) || 0);
var nodeValue = '';
for (j = 0; j < data.childNodes.length; j++) {
nodeValue += data.childNodes[j].nodeValue
}
nodeValue = nodeValue.trim();
// Unpack the tilemap data
var compression = data.getAttribute('compression');
var encoding = data.getAttribute('encoding');
if(compression && compression !== "gzip" && compression !== "zlib"){
cc.log("cc.TMXMapInfo.parseXMLFile(): unsupported compression method");
return null;
}
switch (compression) {
case 'gzip':
layer._tiles = cc.unzipBase64AsArray(nodeValue, 4);
break;
case 'zlib':
var inflator = new Zlib.Inflate(cc.Codec.Base64.decodeAsArray(nodeValue, 1));
layer._tiles = cc.uint8ArrayToUint32Array(inflator.decompress());
break;
case null:
case '':
// Uncompressed
if (encoding === "base64")
layer._tiles = cc.Codec.Base64.decodeAsArray(nodeValue, 4);
else if (encoding === "csv") {
layer._tiles = [];
var csvTiles = nodeValue.split(',');
for (var csvIdx = 0; csvIdx < csvTiles.length; csvIdx++)
layer._tiles.push(parseInt(csvTiles[csvIdx]));
} else {
//XML format
var selDataTiles = data.getElementsByTagName("tile");
layer._tiles = [];
for (var xmlIdx = 0; xmlIdx < selDataTiles.length; xmlIdx++)
layer._tiles.push(parseInt(selDataTiles[xmlIdx].getAttribute("gid")));
}
break;
default:
if(this.layerAttrs === cc.TMXLayerInfo.ATTRIB_NONE)
cc.log("cc.TMXMapInfo.parseXMLFile(): Only base64 and/or gzip/zlib maps are supported");
break;
}
// The parent element is the last layer
var layerProps = selLayer.querySelectorAll("properties > property");
if (layerProps) {
var layerProp = {};
for (j = 0; j < layerProps.length; j++) {
layerProp[layerProps[j].getAttribute('name')] = layerProps[j].getAttribute('value');
}
layer.properties = layerProp;
}
this.setLayers(layer);
}
}
// PARSE <objectgroup>
var objectGroups = map.getElementsByTagName('objectgroup');
if (objectGroups) {
for (i = 0; i < objectGroups.length; i++) {
var selGroup = objectGroups[i];
var objectGroup = new cc.TMXObjectGroup();
objectGroup.groupName = selGroup.getAttribute('name');
objectGroup.setPositionOffset(cc.p(parseFloat(selGroup.getAttribute('x')) * this.getTileSize().width || 0,
parseFloat(selGroup.getAttribute('y')) * this.getTileSize().height || 0));
var groupProps = selGroup.querySelectorAll("objectgroup > properties > property");
if (groupProps) {
for (j = 0; j < groupProps.length; j++) {
var groupProp = {};
groupProp[groupProps[j].getAttribute('name')] = groupProps[j].getAttribute('value');
// Add the property to the layer
objectGroup.properties = groupProp;
}
}
var objects = selGroup.querySelectorAll('object');
var getContentScaleFactor = cc.director.getContentScaleFactor();
if (objects) {
for (j = 0; j < objects.length; j++) {
var selObj = objects[j];
// The value for "type" was blank or not a valid class name
// Create an instance of TMXObjectInfo to store the object and its properties
var objectProp = {};
// Set the name of the object to the value for "name"
objectProp["name"] = selObj.getAttribute('name') || "";
// Assign all the attributes as key/name pairs in the properties dictionary
objectProp["type"] = selObj.getAttribute('type') || "";
objectProp["width"] = parseInt(selObj.getAttribute('width')) || 0;
objectProp["height"] = parseInt(selObj.getAttribute('height')) || 0;
objectProp["x"] = (((selObj.getAttribute('x') || 0) | 0) + objectGroup.getPositionOffset().x) / getContentScaleFactor;
var y = ((selObj.getAttribute('y') || 0) | 0) + objectGroup.getPositionOffset().y / getContentScaleFactor;
// Correct y position. (Tiled uses Flipped, cocos2d uses Standard)
objectProp["y"] = (parseInt(this.getMapSize().height * this.getTileSize().height) - y - objectProp["height"]) / cc.director.getContentScaleFactor();
objectProp["rotation"] = parseInt(selObj.getAttribute('rotation')) || 0;
var docObjProps = selObj.querySelectorAll("properties > property");
if (docObjProps) {
for (var k = 0; k < docObjProps.length; k++)
objectProp[docObjProps[k].getAttribute('name')] = docObjProps[k].getAttribute('value');
}
//polygon
var polygonProps = selObj.querySelectorAll("polygon");
if(polygonProps && polygonProps.length > 0) {
var selPgPointStr = polygonProps[0].getAttribute('points');
if(selPgPointStr)
objectProp["points"] = this._parsePointsString(selPgPointStr);
}
//polyline
var polylineProps = selObj.querySelectorAll("polyline");
if(polylineProps && polylineProps.length > 0) {
var selPlPointStr = polylineProps[0].getAttribute('points');
if(selPlPointStr)
objectProp["polylinePoints"] = this._parsePointsString(selPlPointStr);
}
// Add the object to the objectGroup
objectGroup.setObjects(objectProp);
}
}
this.setObjectGroups(objectGroup);
}
}
return map;
},
_parsePointsString:function(pointsString){
if(!pointsString)
return null;
var points = [];
var pointsStr = pointsString.split(' ');
for(var i = 0; i < pointsStr.length; i++){
var selPointStr = pointsStr[i].split(',');
points.push({'x':selPointStr[0], 'y':selPointStr[1]});
}
return points;
},
/**
* initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string
* @param {String} xmlString
* @return {Boolean}
*/
parseXMLString:function (xmlString) {
return this.parseXMLFile(xmlString, true);
},
/**
* Gets the tile properties.
* @return {object}
*/
getTileProperties:function () {
return this._tileProperties;
},
/**
* Set the tile properties.
* @param {object} tileProperties
*/
setTileProperties:function (tileProperties) {
this._tileProperties.push(tileProperties);
},
/**
* Gets the currentString
* @return {String}
*/
getCurrentString:function () {
return this.currentString;
},
/**
* Set the currentString
* @param {String} currentString
*/
setCurrentString:function (currentString) {
this.currentString = currentString;
},
/**
* Gets the tmxFileName
* @return {String}
*/
getTMXFileName:function () {
return this.tmxFileName;
},
/**
* Set the tmxFileName
* @param {String} fileName
*/
setTMXFileName:function (fileName) {
this.tmxFileName = fileName;
},
_internalInit:function (tmxFileName, resourcePath) {
this._tilesets.length = 0;
this._layers.length = 0;
this.tmxFileName = tmxFileName;
if (resourcePath)
this._resources = resourcePath;
this._objectGroups.length = 0;
this.properties.length = 0;
this._tileProperties.length = 0;
// tmp vars
this.currentString = "";
this.storingCharacters = false;
this.layerAttrs = cc.TMXLayerInfo.ATTRIB_NONE;
this.parentElement = cc.TMX_PROPERTY_NONE;
this._currentFirstGID = 0;
}
});
var _p = cc.TMXMapInfo.prototype;
// Extended properties
/** @expose */
_p.mapWidth;
cc.defineGetterSetter(_p, "mapWidth", _p._getMapWidth, _p._setMapWidth);
/** @expose */
_p.mapHeight;
cc.defineGetterSetter(_p, "mapHeight", _p._getMapHeight, _p._setMapHeight);
/** @expose */
_p.tileWidth;
cc.defineGetterSetter(_p, "tileWidth", _p._getTileWidth, _p._setTileWidth);
/** @expose */
_p.tileHeight;
cc.defineGetterSetter(_p, "tileHeight", _p._getTileHeight, _p._setTileHeight);
/**
* Creates a TMX Format with a tmx file or content string
* @deprecated since v3.0 please use new cc.TMXMapInfo(tmxFile, resourcePath) instead.
* @param {String} tmxFile fileName or content string
* @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required.
* @return {cc.TMXMapInfo}
*/
cc.TMXMapInfo.create = function (tmxFile, resourcePath) {
return new cc.TMXMapInfo(tmxFile, resourcePath);
};
cc.loader.register(["tmx", "tsx"], cc._txtLoader);
/**
* @constant
* @type Number
*/
cc.TMXLayerInfo.ATTRIB_NONE = 1 << 0;
/**
* @constant
* @type Number
*/
cc.TMXLayerInfo.ATTRIB_BASE64 = 1 << 1;
/**
* @constant
* @type Number
*/
cc.TMXLayerInfo.ATTRIB_GZIP = 1 << 2;
/**
* @constant
* @type Number
*/
cc.TMXLayerInfo.ATTRIB_ZLIB = 1 << 3;
|
'use strict';
module.exports = function(app) {
app.directive('headerDirective', function() {
return {
restrict: 'AC',
templateUrl: '../templates/header_directive_template.html'
}
});
};
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import {Router} from 'react-routing';
import http from './core/HttpClient';
import App from './components/App';
import ContentPage from './components/ContentPage';
import ContactPage from './components/ContactPage';
import LoginPage from './components/LoginPage';
import RegisterPage from './components/RegisterPage';
import NotFoundPage from './components/NotFoundPage';
import ErrorPage from './components/ErrorPage';
const router = new Router(on => {
on('*', async (state, next) => {
const component = await next();
return component && <App context={state.context}>{component}</App>;
});
on('/contact', async () => <ContactPage />);
on('/login', async () => <LoginPage />);
on('/register', async () => <RegisterPage />);
on('*', async (state) => {
const content = await http.get(`/api/content?path=${state.path}`);
return content && <ContentPage {...content} />;
});
on('error', (state, error) => state.statusCode === 404 ?
<App context={state.context} error={error}><NotFoundPage /></App> :
<App context={state.context} error={error}><ErrorPage /></App>
);
});
export default router;
|
var test = require('tape');
var View = require('..');
test('view init', function (t) {
var view = View();
view.init();
t.ok(view, 'All is well with `view`');
t.end();
});
test('view events', function (t) {
document.body = document.createElement('body');
document.body.appendChild(document.createElement('button'));
var view = View({
events: {
'button': {
click: function (e) {}
}
}
});
view.init();
t.ok(view, 'All is well with `view`');
t.end();
});
test('view remove', function (t) {
document.body = document.createElement('body');
document.body.appendChild(document.createElement('button'));
var view = View({});
view.init();
t.ok(view, 'All is well with `view`');
t.equal(view.el instanceof Node, true, 'Container has type `Node`');
view.remove();
t.notok(view.el, 'Container is gone after `remove`');
t.end();
});
test('view set container attribute', function (t) {
var view = View({
container: '#main-view'
});
view.init();
t.ok(view, 'All is well with `view`');
t.ok(document.querySelector('#main-view'), 'Container has id of `main-view`');
t.end();
});
|
import 'whatwg-fetch';
/**
* Utility function that returns a function that can be called by sagas
* to parse a network response JSON.
*
* @param {object} response A response from a network request
*
* @return {function}
*/
export function parseResponse(response) {
return () => {
return response.json();
};
}
/**
* Parses the JSON returned by a network request
*
* @param {object} response A response from a network request
*
* @return {object} The parsed JSON from the request
*/
function parseJSON(response) {
if (response.status === 204 || response.status === 205) {
return null;
}
return response.json();
}
/**
* Checks if a network request came back fine, and throws an error if not
*
* @param {object} response A response from a network request
*
* @return {object|undefined} Returns either the response, or throws an error
*/
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
const error = new Error(response.statusText);
error.response = response;
throw error;
}
/**
* Requests a URL, returning a promise
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
*
* @return {object} The response data
*/
export default function request(url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON);
}
|
'use strict';
/*globals eventsApp,alert*/
eventsApp.directive('greeting', function () {
return {
restrict: 'E',
replace: true,
transclude: true,
template: "<div><button class='btn btn-default' ng-click='sayHello()'>Say Hello</button><div ng-transclude></div></div>",
controller: function($scope) {
var greetings = ['Hello'];
$scope.sayHello = function() {
alert(greetings.join(", "));
};
this.addGreeting = function(greeting) {
greetings.push(greeting);
};
}
};
})
.directive('finnish', function () {
return {
restrict: 'A',
terminal: true,
require: '^greeting', // use parent element's controller
replace: true,
link: function(scope, element, attrs, controller) {
controller.addGreeting('Hei');
}
};
})
.directive('hindi', function () {
return {
restrict: 'A',
require: '^greeting', // use parent element's controller
replace: true,
link: function(scope, element, attrs, controller) {
controller.addGreeting('เคจเคฎเคธเฅเคคเฅ');
}
};
});
|
"use strict";
const chai = require('chai');
const expect = chai.expect;
// 1 red: design what the function looks like in terms of how it is tested
function timeString(string) {
return '?';
}
describe('timeString test', function() {
it('Returns single output when string is inputed', function() {
expect(timeString('00:01')).to.equal('0:00:01');
});
}); |
var config = require('../../config');
var gulp = require('gulp-help')(require('gulp'));
var revReplace = require('gulp-rev-replace');
var path = require('path');
// 3) Update asset references with reved filenames in compiled css + js
gulp.task('rev-update-references', false, ['rev-iconfont-workaround'], function(){
var manifest = gulp.src(path.join(config.publicDirectory, '/rev-manifest.json'));
return gulp.src(config.publicDirectory + '/**/**.{css,js}')
.pipe(revReplace({manifest: manifest}))
.pipe(gulp.dest(config.publicDirectory));
});
|
/*
* Copyright (c) 2014.
*
* @author Andy Tang
*/
(function GameSquareSpec(whereIt) {
'use strict';
describe('GameSquare Model', function gameSquareModelSpec() {
var GameSquareModel;
var GameObjectModel;
var SaberModel;
var CharacterModel;
beforeEach(module('jsWars'));
beforeEach(inject(function injection(GameObject, GameSquare, Saber, Character) {
GameSquareModel = GameSquare;
GameObjectModel = GameObject;
SaberModel = Saber;
CharacterModel = Character;
}));
whereIt('should be able to create a game square', function createGameSquare(getGameObject, isOccupied) {
var gameSquare = new GameSquareModel(0, 0, getGameObject());
expect(gameSquare.isOccupied()).toEqual(isOccupied);
expect(gameSquare.canAttack()).toEqual(isOccupied);
expect(gameSquare.canMove()).toEqual(isOccupied);
}, [
{
getGameObject: function getGameObject() {
return new SaberModel();
},
isOccupied: true
},
{
getGameObject: function getGameObject() {
return null;
},
isOccupied: false
}
]);
it('should be able to open and close the panel', function closePanel() {
var gameSquare = new GameSquareModel(0, 0, new SaberModel());
gameSquare.openActionPanel();
expect(gameSquare.isOpened());
gameSquare.closeActionPanel();
expect(gameSquare.isOpened());
});
it('should be able to get the available attacks', function availableAttacks() {
var gameSquare = new GameSquareModel(0, 0, new SaberModel());
gameSquare.startSelectingAttack();
var list = gameSquare.getAttackList();
expect(list[0].getName()).toEqual('Clean cut');
expect(list[1].getName()).toEqual('Excalibur');
});
whereIt('should be able to select a skill', function selectSkill(isOccupied, skillIndex, result) {
var gameSquare = new GameSquareModel();
if (isOccupied) {
gameSquare.setGameObject(new SaberModel());
}
gameSquare.startSelectingAttack();
gameSquare.selectSkill(skillIndex);
expect(gameSquare.getSelectedSkill() === null).toEqual(result);
expect(gameSquare.isInAttackMode()).toEqual(true);
expect(gameSquare.isSelectingAttack()).toEqual(false);
}, [
{
isOccupied: true,
skillIndex: 1,
result: false
},
{
isOccupied: false,
skillIndex: 1,
result: true
},
{
isOccupied: true,
skillIndex: 5,
result: true
}
]);
it('should be able to close the panel', function closePanel() {
var square = new GameSquareModel();
square.openActionPanel();
square.startAttackMode();
square.closeActionPanel();
expect(square.isOpened()).toEqual(false);
expect(square.isInAttackMode()).toEqual(false);
});
it('should return an empty list when no moves are available', function noMoves() {
var square = new GameSquareModel(0, 0, new CharacterModel());
square.startSelectingAttack();
expect(square.isSelectingAttack()).toEqual(true);
expect(square.getAttackList()).toEqual([]);
});
it('should return false when no character is on the square', function noCharacter() {
var square = new GameSquareModel();
expect(square.hasAttacked()).toEqual(false);
expect(square.hasMoved()).toEqual(false);
});
});
}(window.whereIt)); |
๏ปฟvar systemNormalize = System.normalize;
System.normalize = function (name, parentName, parentAddress) {
if (name.indexOf('availpro-') > -1) {
var defaultJSExtension = this.defaultJSExtensions ? '.js' : '';
name = this.baseURL + this.paths['availpro-*'].replace(new RegExp('availpro-\\*', 'g'), name) + defaultJSExtension;
}
return systemNormalize.call(this, name, parentName, parentAddress);
}
System.locate = function (load) {
console.log(load.name)
return load.name;
} |
'use strict';
/* Services */
angular.module('alienMail.services', ['ngResource']).
factory('Messages', function($resource){
return $resource('/messages/:messageId.json', {}, {
query: {method:'GET', params:{messageId:'summaries'}, isArray:true}
});
});
|
'use strict';
var React = require('react');
var d3 = require('d3');
var BarContainer = require('./BarContainer');
module.exports = React.createClass({
displayName: 'DataSeries',
propTypes: {
_data: React.PropTypes.array,
series: React.PropTypes.array,
colors: React.PropTypes.func,
colorAccessor: React.PropTypes.func,
height: React.PropTypes.number,
width: React.PropTypes.number,
valuesAccessor: React.PropTypes.func,
},
render:function() {
return (
React.createElement("g", null, this._renderBarSeries())
);
},
_renderBarSeries:function() {
var $__0= this.props,_data=$__0._data,valuesAccessor=$__0.valuesAccessor;
return _data.map(function(layer, seriesIdx) {
return valuesAccessor(layer)
.map(function(segment) {return this._renderBarContainer(segment, seriesIdx);}.bind(this))
}.bind(this));
},
_renderBarContainer:function(segment, seriesIdx) {
var $__0= this.props,colors=$__0.colors,colorAccessor=$__0.colorAccessor,height=$__0.height,hoverAnimation=$__0.hoverAnimation,xScale=$__0.xScale,yScale=$__0.yScale;
var barHeight = Math.abs(yScale(0) - yScale(segment.y));
var y = yScale( segment.y0 + segment.y );
return (
React.createElement(BarContainer, {
height: barHeight,
width: xScale.rangeBand(),
x: xScale(segment.x),
y: (segment.y >= 0) ? y : y - barHeight,
fill: colors(colorAccessor(segment, seriesIdx)),
hoverAnimation: hoverAnimation,
onMouseOver: this.props.onMouseOver,
onMouseLeave: this.props.onMouseLeave,
dataPoint: {xValue: segment.x, yValue: segment.hoverValue ? segment.hoverValue : segment.y, seriesName: this.props.series[seriesIdx]}}
)
)
}
});
|
'use strict';
/*jshint -W079 */
var expect = require('chai').expect;
var victim = require('../src/muton');
describe('When entering user properties and feature instructions', function () {
it('should ignore null user properties', function () {
var instructions = {
feature1: {
toggle: true
}
};
var features = victim.getFeatureMutations(null, instructions);
expect(features).to.have.property('feature1').that.equals(true);
});
it('should ignore undefined user properties', function () {
var instructions = {
feature1: {
toggle: true
}
};
var features = victim.getFeatureMutations(undefined, instructions);
expect(features).to.have.property('feature1').that.equals(true);
});
it('should ignore empty user properties', function () {
var instructions = {
feature1: {
toggle: true
}
};
var features = victim.getFeatureMutations({}, instructions);
expect(features).to.have.property('feature1').that.equals(true);
});
it('should ignore invalid user properties', function () {
var instructions = {
feature1: {
toggle: true
}
};
var features = victim.getFeatureMutations([1, 2], instructions);
expect(features).to.have.property('feature1').that.equals(true);
});
it('should return empty on empty instructions', function () {
var features = victim.getFeatureMutations({}, {});
/*jshint -W030 */
expect(features).to.be.empty;
});
it('should return empty on undefined instructions', function () {
var features = victim.getFeatureMutations({});
/*jshint -W030 */
expect(features).to.be.empty;
});
it('should return empty on null instructions', function () {
var features = victim.getFeatureMutations({}, null);
/*jshint -W030 */
expect(features).to.be.empty;
});
it('should return empty on undefined arguments', function () {
var features = victim.getFeatureMutations();
/*jshint -W030 */
expect(features).to.be.empty;
});
it('should throw error on invalid feature instructions', function () {
expect(victim.getFeatureMutations.bind(victim, {}, [1, 2])).to.throw(Error);
});
}); |
// @flow
// Copyright (c) 2016 Uber Technologies, 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 * as opentracing from 'opentracing';
import Span from './span';
import Utils from './util';
export default class TestUtils {
static hasTags(span: Span, expectedTags: any): boolean {
// TODO(oibe) make this work for duplicate tags
let actualTags = {};
for (let i = 0; i < span._tags.length; i++) {
let key = span._tags[i].key;
actualTags[key] = span._tags[i].value;
}
for (let tag in expectedTags) {
if (
Object.prototype.hasOwnProperty.call(expectedTags, tag) &&
Object.prototype.hasOwnProperty.call(actualTags, tag)
) {
if (actualTags[tag] !== expectedTags[tag]) {
console.log('expected tag:', expectedTags[tag], ', actual tag: ', actualTags[tag]);
return false;
}
} else {
// mismatch in tag keys
return false;
}
}
return true;
}
/**
* Returns tags stored in the span. If tags with the same key are present,
* only the last tag is returned.
* @param {Object} span - span from which to read the tags.
* @param {Array} [keys] - if specified, only tags with these keys are returned.
*/
static getTags(span: Span, keys: ?Array<string>): any {
let actualTags = {};
for (let i = 0; i < span._tags.length; i++) {
let key = span._tags[i].key;
actualTags[key] = span._tags[i].value;
}
if (keys) {
let filteredTags = {};
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
if (actualTags.hasOwnProperty(key)) {
filteredTags[key] = actualTags[key];
}
}
return filteredTags;
}
return actualTags;
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:3dbc8ecec3670ca22d0e94e29ec4be517714202962d7e0a84e1ca18c0ecd7f48
size 282868
|
import createRouter from '@alias/blog-router'
const router = createRouter()
export default { router }
|
version https://git-lfs.github.com/spec/v1
oid sha256:023b957e9bfe0310712c45b750a8a14c27828409753a561ef2fb876566260455
size 637
|
'use strict';
// Declare app level module which depends on filters, and services
var autoExpo = angular.module('autoExpoApp', [
'ngRoute',
'autoExpoAppControllers',
'autoExpoAppDirectives',
'autoExpoAppServices'
]);
autoExpo.config(['$routeProvider',
function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'partials/homePartial.html',
controller: 'AutoListCtrl'
})
.when('/auto/compare', {
templateUrl: 'partials/autoCompare.html',
controller: 'AutoCompareCtrl'
})
.when('/auto/:id', {
templateUrl: 'partials/autoDetail.html',
controller: 'AutoDetailCtrl'
})
.when('/admin', {
templateUrl: 'partials/listAutos.html',
controller: 'AdminListCtrl'
})
.otherwise('/', {
templateUrl: 'partials/homePartial.html',
controller: 'AutoListCtrl'
});
}
]); |
/*
่ฏดๆ: ่ฏทๅฟไฟฎๆน header.js ๅ footer.js
็จ้: ่ชๅจๆผๆฅๆด้ฒๆนๅผ
ๅฝไปค: grunt release ไธญ concat
*/
(function(global, factory) {
if (typeof exports === 'object' && typeof module !== 'undefined') {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define(factory);
} else {
var tempIMLib = factory();
var tempClient = tempIMLib.RongIMClient;
var isExists = (!!global.RongIMLib);
if (isExists) {
var currentClient = RongIMLib.RongIMClient || {};
for(var key in currentClient){
tempClient[key] = currentClient[key];
}
}
global.RongIMLib = tempIMLib;
global.RongIMClient = tempClient;
}
})(this, function(){
var Polling = {
DeleteMsgInput:function(){
var a = {};
this.setType = function(b){
a.type = b;
};
this.setConversationId = function(b){
a.conversationId = b;
};
this.setMsgs = function(b){
a.msgs = b;
};
this.toArrayBuffer = function () {
return a;
}
},
DeleteMsg:function(){
var a = {};
this.setMsgId = function(b){
a.msgId = b;
};
this.setMsgDataTime = function(b){
a.msgDataTime = b;
};
this.setDirect = function(b){
a.direct = b;
};
this.toArrayBuffer = function () {
return a;
}
},
DeleteMsgOutput:function(){
var a = {};
this.setNothing = function(b){
a.nothing = b;
};
this.toArrayBuffer = function () {
return a;
}
},
SearchMpInput:function(){
var a = {};
this.setType = function (b) {
a.type = b;
};
this.setId = function (b) {
a.id = b;
};
this.toArrayBuffer = function () {
return a;
}
},
SearchMpOutput:function(){
var a = {};
this.setNothing = function (b) {
a.nothing = b;
};
this.setInfo = function (b) {
a.info = b;
};
this.toArrayBuffer = function () {
return a;
}
},
MpInfo:function(){
var a = {};
this.setMpid = function(b){
a.mpid = b;
};
this.setName = function(b){
a.name = b;
};
this.setType = function(b){
a.type = b;
};
this.setTime = function(b){
a.time = b;
};
this.setPortraitUri = function(b){
a.portraitUrl = b;
};
this.setExtra = function(b){
a.extra = b;
};
this.toArrayBuffer = function () {
return a;
}
},
PullMpInput:function(){
var a = {};
this.setMpid = function(b){
a.mpid = b;
};
this.setTime = function(b){
a.time = b;
};
this.toArrayBuffer = function () {
return a;
};
},
PullMpOutput:function(){
var a = {};
this.setStatus = function(b){
a.status = b;
}
this.setInfo = function(b){
a.info = b;
};
this.toArrayBuffer = function () {
return a;
};
},
MPFollowInput:function(){
var a = {};
this.setId = function(b){
a.id = b;
};
this.toArrayBuffer = function () {
return a;
};
},
MPFollowOutput:function(){
var a = {};
this.setNothing = function(b){
a.nothing = b;
};
this.setInfo = function(b){
a.info = b;
};
this.toArrayBuffer = function () {
return a;
};
},
NotifyMsg: function () {
var a = {};
this.setType = function (b) {
a.type = b;
};
this.setTime = function (b) {
a.time = b;
};
this.setChrmId = function(b){
a.chrmId = b;
};
this.toArrayBuffer = function () {
return a;
};
},
SyncRequestMsg: function () {
var a = {};
this.setSyncTime = function (b) {
a.syncTime = b || 0;
};
this.setIspolling = function (b) {
a.ispolling = !!b;
};
this.setIsweb = function (b) {
a.isweb = !!b;
};
this.setIsPullSend = function (b) {
a.isPullSend = !!b;
};
this.toArrayBuffer = function () {
return a;
};
},
UpStreamMessage: function () {
var a = {};
this.setSessionId = function (b) {
a.sessionId = b
};
this.setClassname = function (b) {
a.classname = b
};
this.setContent = function (b) {
if (b) a.content = b;
};
this.setPushText = function (b) {
a.pushText = b
};
this.setUserId = function(b){
a.userId = b;
};
this.setAppData = function(b){
a.appData = b;
};
this.toArrayBuffer = function () {
return a
};
},
DownStreamMessages: function () {
var a = {};
this.setList = function (b) {
a.list = b
};
this.setSyncTime = function (b) {
a.syncTime = b;
};
this.toArrayBuffer = function () {
return a
};
},
DownStreamMessage: function () {
var a = {};
this.setFromUserId = function (b) {
a.fromUserId = b
};
this.setType = function (b) {
a.type = b
};
this.setGroupId = function (b) {
a.groupId = b
};
this.setClassname = function (b) {
a.classname = b
};
this.setContent = function (b) {
if (b)
a.content = b
};
this.setDataTime = function (b) {
a.dataTime = b;
};
this.setStatus = function (b) {
a.status = b;
};
this.setMsgId = function (b) {
a.msgId = b;
};
this.toArrayBuffer = function () {
return a;
};
},
CreateDiscussionInput: function () {
var a = {};
this.setName = function (b) {
a.name = b
};
this.toArrayBuffer = function () {
return a
}
},
CreateDiscussionOutput: function () {
var a = {};
this.setId = function (b) {
a.id = b
};
this.toArrayBuffer = function () {
return a
};
},
ChannelInvitationInput: function () {
var a = {};
this.setUsers = function (b) {
a.users = b
};
this.toArrayBuffer = function () {
return a
};
},
LeaveChannelInput: function () {
var a = {};
this.setNothing = function (b) {
a.nothing = b
};
this.toArrayBuffer = function () {
return a
};
},
QueryChatroomInfoInput:function(){
var a = {};
this.setCount = function (b) {
a.count = b;
};
this.setOrder = function (b) {
a.order = b;
};
this.toArrayBuffer = function () {
return a
};
},
QueryChatroomInfoOutput:function(){
var a = {};
this.setUserTotalNums = function (b) {
a.userTotalNums = b;
};
this.setUserInfos = function (b) {
a.userInfos = b;
};
this.toArrayBuffer = function () {
return a;
};
},
ChannelEvictionInput: function () {
var a = {};
this.setUser = function (b) {
a.user = b
};
this.toArrayBuffer = function () {
return a
};
},
RenameChannelInput: function () {
var a = {};
this.setName = function (b) {
a.name = b
};
this.toArrayBuffer = function () {
return a
}
},
ChannelInfoInput: function () {
var a = {};
this.setNothing = function (b) {
a.nothing = b
};
this.toArrayBuffer = function () {
return a
}
},
ChannelInfoOutput: function () {
var a = {};
this.setType = function (b) {
a.type = b
};
this.setChannelId = function (b) {
a.channelId = b
};
this.setChannelName = function (b) {
a.channelName = b
};
this.setAdminUserId = function (b) {
a.adminUserId = b
};
this.setFirstTenUserIds = function (b) {
a.firstTenUserIds = b
};
this.setOpenStatus = function (b) {
a.openStatus = b
};
this.toArrayBuffer = function () {
return a
}
},
ChannelInfosInput: function () {
var a = {};
this.setPage = function (b) {
a.page = b
};
this.setNumber = function (b) {
a.number = b
};
this.toArrayBuffer = function () {
return a
};
},
ChannelInfosOutput: function () {
var a = {};
this.setChannels = function (b) {
a.channels = b
};
this.setTotal = function (b) {
a.total = b
};
this.toArrayBuffer = function () {
return a
};
},
MemberInfo: function () {
var a = {};
this.setUserId = function (b) {
a.userId = b
};
this.setUserName = function (b) {
a.userName = b
};
this.setUserPortrait = function (b) {
a.userPortrait = b
};
this.setExtension = function (b) {
a.extension = b
};
this.toArrayBuffer = function () {
return a
};
},
GroupMembersInput: function () {
var a = {};
this.setPage = function (b) {
a.page = b
};
this.setNumber = function (b) {
a.number = b
};
this.toArrayBuffer = function () {
return a
};
},
GroupMembersOutput: function () {
var a = {};
this.setMembers = function (b) {
a.members = b
};
this.setTotal = function (b) {
a.total = b
};
this.toArrayBuffer = function () {
return a
};
},
GetUserInfoInput: function () {
var a = {};
this.setNothing = function (b) {
a.nothing = b
};
this.toArrayBuffer = function () {
return a
};
},
GetUserInfoOutput: function () {
var a = {};
this.setUserId = function (b) {
a.userId = b
};
this.setUserName = function (b) {
a.userName = b
};
this.setUserPortrait = function (b) {
a.userPortrait = b
};
this.toArrayBuffer = function () {
return a
};
},
GetSessionIdInput: function () {
var a = {};
this.setNothing = function (b) {
a.nothing = b
};
this.toArrayBuffer = function () {
return a
};
},
GetSessionIdOutput: function () {
var a = {};
this.setSessionId = function (b) {
a.sessionId = b
};
this.toArrayBuffer = function () {
return a
};
},
GetQNupTokenInput: function () {
var a = {};
this.setType = function (b) {
a.type = b;
}
this.toArrayBuffer = function () {
return a
}
},
GetQNupTokenOutput: function () {
var a = {};
this.setDeadline = function (b) {
a.deadline = b
};
this.setToken = function (b) {
a.token = b;
};
this.toArrayBuffer = function () {
return a
}
},
GetQNdownloadUrlInput: function () {
var a = {};
this.setType = function (b) {
a.type = b;
};
this.setKey = function (b) {
a.key = b;
};
this.setFileName = function(b){
a.fileName = b;
};
this.toArrayBuffer = function () {
return a
}
},
GetQNdownloadUrlOutput: function () {
var a = {};
this.setDownloadUrl = function (b) {
a.downloadUrl = b;
};
this.toArrayBuffer = function () {
return a
}
},
Add2BlackListInput: function () {
var a = {};
this.setUserId = function (b) {
a.userId = b;
};
this.toArrayBuffer = function () {
return a
}
},
RemoveFromBlackListInput: function () {
var a = {};
this.setUserId = function (b) {
a.userId = b;
};
this.toArrayBuffer = function () {
return a
}
},
QueryBlackListInput: function () {
var a = {};
this.setNothing = function (b) {
a.nothing = b;
};
this.toArrayBuffer = function () {
return a
}
},
QueryBlackListOutput: function () {
var a = {};
this.setUserIds = function (b) {
a.userIds = b;
};
this.toArrayBuffer = function () {
return a
}
},
BlackListStatusInput: function () {
var a = {};
this.setUserId = function (b) {
a.userId = b;
};
this.toArrayBuffer = function () {
return a
}
},
BlockPushInput: function () {
var a = {};
this.setBlockeeId = function (b) {
a.blockeeId = b;
};
this.toArrayBuffer = function () {
return a
}
},
ModifyPermissionInput: function () {
var a = {};
this.setOpenStatus = function (b) {
a.openStatus = b;
};
this.toArrayBuffer = function () {
return a
};
},
GroupInput: function () {
var a = {};
this.setGroupInfo = function (b) {
for (var i = 0, arr = []; i < b.length; i++) {
arr.push({id: b[i].getContent().id, name: b[i].getContent().name})
}
a.groupInfo = arr;
};
this.toArrayBuffer = function () {
return a
};
},
GroupOutput: function () {
var a = {};
this.setNothing = function (b) {
a.nothing = b;
};
this.toArrayBuffer = function () {
return a
};
},
GroupInfo: function () {
var a = {};
this.setId = function (b) {
a.id = b;
};
this.setName = function (b) {
a.name = b;
};
this.getContent = function () {
return a;
};
this.toArrayBuffer = function () {
return a
};
},
GroupHashInput: function () {
var a = {};
this.setUserId = function (b) {
a.userId = b;
};
this.setGroupHashCode = function (b) {
a.groupHashCode = b;
};
this.toArrayBuffer = function () {
return a
};
},
GroupHashOutput: function () {
var a = {};
this.setResult = function (b) {
a.result = b;
};
this.toArrayBuffer = function () {
return a
};
},
ChrmInput: function () {
var a = {};
this.setNothing = function (b) {
a.nothing = b;
};
this.toArrayBuffer = function () {
return a
};
},
ChrmOutput: function () {
var a = {};
this.setNothing = function (b) {
a.nothing = b;
};
this.toArrayBuffer = function () {
return a
};
},
ChrmPullMsg: function () {
var a = {};
this.setSyncTime = function (b) {
a.syncTime = b
};
this.setCount = function (b) {
a.count = b;
};
this.toArrayBuffer = function () {
return a
};
},
RelationsInput: function () {
var a = {};
this.setType = function (b) {
a.type = b;
};
this.setMsg = function(b){
a.msg = b;
};
this.setCount = function(b){
a.count = b;
};
this.toArrayBuffer = function () {
return a
};
},
RelationsOutput: function () {
var a = {};
this.setInfo = function (b) {
a.info = b;
};
this.toArrayBuffer = function () {
return a
}
},
RelationInfo: function () {
var a = {};
this.setType = function (b) {
a.type = b;
};
this.setUserId = function (b) {
a.userId = b;
};
this.setMsg = function(b){
a.msg = b;
};
this.toArrayBuffer = function () {
return a
}
},
HistoryMessageInput: function () {
var a={};
this.setTargetId=function(b){
a.targetId=b;
};
this.setDataTime=function(b){
a.dataTime=b;
};
this.setSize=function(b){
a.size=b;
};
this.toArrayBuffer = function () {
return a
}
},
HistoryMessagesOuput: function () {
var a={};
this.setList=function(b){
a.list=b;
};
this.setSyncTime=function(b){
a.syncTime=b;
};
this.setHasMsg=function(b){
a.hasMsg=b;
};
this.toArrayBuffer = function () {
return a
}
},
HistoryMsgInput: function(){
var a = {};
this.setTargetId = function(b){
a.targetId = b;
};
this.setTime = function(b){
a.time = b;
};
this.setCount = function(b){
a.count = b;
};
this.setOrder = function(b){
a.order = b;
};
this.toArrayBuffer = function(){
return a;
};
},
HistoryMsgOuput: function(){
var a = {};
this.setList = function(b){
a.list = b;
};
this.setSyncTime = function(b){
a.syncTime = b;
};
this.setHasMsg = function(b){
a.hasMsg = b;
};
this.toArrayBuffer = function(){
return a;
};
}
};
for (var f in Polling) {
Polling[f].decode = function (b) {
var back = {}, val = JSON.parse(b) || eval("(" + b + ")");
for (var i in val) {
back[i]=val[i];
back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){
return val[i];
}
}
return back;
}
}
/*
* JavaScript MD5
* https://github.com/blueimp/JavaScript-MD5
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*
* Based on
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*jslint bitwise: true */
/*global unescape, define, module */
(function ($) {
'use strict';
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
}
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
function binl_md5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << (len % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var i, olda, oldb, oldc, oldd,
a = 1732584193,
b = -271733879,
c = -1732584194,
d = 271733878;
for (i = 0; i < x.length; i += 16) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5_ff(a, b, c, d, x[i], 7, -680876936);
d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i], 20, -373897302);
a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5_hh(d, a, b, c, x[i], 11, -358537222);
c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i], 6, -198630844);
d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return [a, b, c, d];
}
/*
* Convert an array of little-endian words to a string
*/
function binl2rstr(input) {
var i,
output = '';
for (i = 0; i < input.length * 32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
}
return output;
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
function rstr2binl(input) {
var i,
output = [];
output[(input.length >> 2) - 1] = undefined;
for (i = 0; i < output.length; i += 1) {
output[i] = 0;
}
for (i = 0; i < input.length * 8; i += 8) {
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
}
return output;
}
/*
* Calculate the MD5 of a raw string
*/
function rstr_md5(s) {
return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
}
/*
* Calculate the HMAC-MD5, of a key and some data (raw strings)
*/
function rstr_hmac_md5(key, data) {
var i,
bkey = rstr2binl(key),
ipad = [],
opad = [],
hash;
ipad[15] = opad[15] = undefined;
if (bkey.length > 16) {
bkey = binl_md5(bkey, key.length * 8);
}
for (i = 0; i < 16; i += 1) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
}
/*
* Convert a raw string to a hex string
*/
function rstr2hex(input) {
var hex_tab = '0123456789abcdef',
output = '',
x,
i;
for (i = 0; i < input.length; i += 1) {
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F) +
hex_tab.charAt(x & 0x0F);
}
return output;
}
/*
* Encode a string as utf-8
*/
function str2rstr_utf8(input) {
return unescape(encodeURIComponent(input));
}
/*
* Take string arguments and return either raw or hex encoded strings
*/
function raw_md5(s) {
return rstr_md5(str2rstr_utf8(s));
}
function hex_md5(s) {
return rstr2hex(raw_md5(s));
}
function raw_hmac_md5(k, d) {
return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d));
}
function hex_hmac_md5(k, d) {
return rstr2hex(raw_hmac_md5(k, d));
}
function md5(string, key, raw) {
if (!key) {
if (!raw) {
return hex_md5(string);
}
return raw_md5(string);
}
if (!raw) {
return hex_hmac_md5(key, string);
}
return raw_hmac_md5(key, string);
}
$.md5 = md5;
if (typeof define === 'function' && define.amd) {
define('md5',function () {
return md5;
});
} else if (typeof module === 'object' && module.exports) {
module.exports = md5;
} else {
$.md5 = md5;
}
}(this));
var RongIMLib;
(function (RongIMLib) {
(function (MentionedType) {
MentionedType[MentionedType["ALL"] = 1] = "ALL";
MentionedType[MentionedType["PART"] = 2] = "PART";
})(RongIMLib.MentionedType || (RongIMLib.MentionedType = {}));
var MentionedType = RongIMLib.MentionedType;
(function (MethodType) {
MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE";
MethodType[MethodType["RECALL"] = 2] = "RECALL";
})(RongIMLib.MethodType || (RongIMLib.MethodType = {}));
var MethodType = RongIMLib.MethodType;
(function (BlacklistStatus) {
/**
* ๅจ้ปๅๅไธญใ
*/
BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST";
/**
* ไธๅจ้ปๅๅไธญใ
*/
BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST";
})(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {}));
var BlacklistStatus = RongIMLib.BlacklistStatus;
(function (ConnectionChannel) {
ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING";
ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET";
//ๅค้จ่ฐ็จ
ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP";
//ๅค้จ่ฐ็จ
ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS";
})(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {}));
var ConnectionChannel = RongIMLib.ConnectionChannel;
(function (CustomerType) {
CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT";
CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN";
CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST";
CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST";
})(RongIMLib.CustomerType || (RongIMLib.CustomerType = {}));
var CustomerType = RongIMLib.CustomerType;
(function (GetChatRoomType) {
GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE";
GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE";
GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE";
})(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {}));
var GetChatRoomType = RongIMLib.GetChatRoomType;
(function (ConnectionStatus) {
/**
* ่ฟๆฅๆๅใ
*/
ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED";
/**
* ่ฟๆฅไธญใ
*/
ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING";
/**
* ๆญๅผ่ฟๆฅใ
*/
ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED";
/**
* ็จๆท่ดฆๆทๅจๅ
ถไป่ฎพๅค็ปๅฝ๏ผๆฌๆบไผ่ขซ่ธขๆ็บฟใ
*/
ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT";
/**
* ็ฝ็ปไธๅฏ็จใ
*/
ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE";
/**
* ๅๅ้่ฏฏ
*/
ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT";
/**
* ่ฟๆฅๅ
ณ้ญใ
*/
ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED";
})(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {}));
var ConnectionStatus = RongIMLib.ConnectionStatus;
(function (ConversationNotificationStatus) {
/**
* ๅ
ๆๆฐ็ถๆ๏ผๅ
ณ้ญๅฏนๅบไผ่ฏ็้็ฅๆ้ใ
*/
ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 0] = "DO_NOT_DISTURB";
/**
* ๆ้ใ
*/
ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 1] = "NOTIFY";
})(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {}));
var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus;
(function (ConversationType) {
ConversationType[ConversationType["NONE"] = 0] = "NONE";
ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE";
ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION";
ConversationType[ConversationType["GROUP"] = 3] = "GROUP";
ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM";
ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE";
ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM";
//้ป่ฎคๅ
ณๆณจ MC
ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE";
//ๆๅทฅๅ
ณๆณจ MP
ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE";
})(RongIMLib.ConversationType || (RongIMLib.ConversationType = {}));
var ConversationType = RongIMLib.ConversationType;
(function (DiscussionInviteStatus) {
/**
* ๅผๆพ้่ฏทใ
*/
DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED";
/**
* ๅ
ณ้ญ้่ฏทใ
*/
DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED";
})(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {}));
var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus;
(function (ErrorCode) {
/**
* ๅ้้ข็่ฟๅฟซ
*/
ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST";
ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED";
/**
* ็พค็ป Id ๆ ๆ
*/
ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID";
/**
* ็พค็ป่ขซ็ฆ่จ
*/
ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP";
/**
* ไธๅจ่ฎจ่ฎบ็ปใ
*/
ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION";
/**
* ไธๅจ็พค็ปใ
*/
ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP";
/**
* ไธๅจ่ๅคฉๅฎคใ
*/
ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM";
/**
*่ๅคฉๅฎค่ขซ็ฆ่จ
*/
ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM";
/**
* ่ๅคฉๅฎคไธญๆๅ่ขซ่ธขๅบ
*/
ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED";
/**
* ่ๅคฉๅฎคไธๅญๅจ
*/
ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST";
/**
* ่ๅคฉๅฎคๆๅๅทฒๆปก
*/
ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL";
/**
* ่ทๅ่ๅคฉๅฎคไฟกๆฏๅๆฐๆ ๆ
*/
ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID";
/**
* ่ๅคฉๅฎคๅผๅธธ
*/
ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR";
/**
* ๆฒกๆๆๅผ่ๅคฉๅฎคๆถๆฏๅญๅจ
*/
ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE";
ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT";
/**
* ๆช็ฅๅๅ ๅคฑ่ดฅใ
*/
ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN";
/**
* ๅ ๅ
ฅ่ฎจ่ฎบๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION";
/**
* ๅๅปบ่ฎจ่ฎบ็ปๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION";
/**
* ่ฎพ็ฝฎ่ฎจ่ฎบ็ป้่ฏท็ถๆๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION";
/**
*่ทๅ็จๆทๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR";
/**
* ๅจ้ปๅๅไธญใ
*/
ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST";
/**
* ้ไฟก่ฟ็จไธญ๏ผๅฝๅ Socket ไธๅญๅจใ
*/
ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID";
/**
* Socket ่ฟๆฅไธๅฏ็จใ
*/
ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE";
/**
* ้ไฟก่ถ
ๆถใ
*/
ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT";
/**
* ๅฏผ่ชๆไฝๆถ๏ผHttp ่ฏทๆฑๅคฑ่ดฅใ
*/
ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL";
/**
* HTTP ่ฏทๆฑๅคฑ่ดฅใ
*/
ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT";
/**
* HTTP ๆฅๆถๅคฑ่ดฅใ
*/
ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL";
/**
* ๅฏผ่ชๆไฝ็ HTTP ่ฏทๆฑ๏ผ่ฟๅไธๆฏ200ใ
*/
ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR";
/**
* ๅฏผ่ชๆฐๆฎ่งฃๆๅ๏ผๅ
ถไธญไธๅญๅจๆๆๆฐๆฎใ
*/
ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND";
/**
* ๅฏผ่ชๆฐๆฎ่งฃๆๅ๏ผๅ
ถไธญไธๅญๅจๆๆ IP ๅฐๅใ
*/
ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE";
/**
* ๅๅปบ Socket ๅคฑ่ดฅใ
*/
ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED";
/**
* Socket ่ขซๆญๅผใ
*/
ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED";
/**
* PING ๆไฝๅคฑ่ดฅใ
*/
ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL";
/**
* PING ่ถ
ๆถใ
*/
ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL";
/**
* ๆถๆฏๅ้ๅคฑ่ดฅใ
*/
ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL";
/**
* ๅ connect ่ฟๆฅๆถ๏ผๆถๅฐ็ ACK ่ถ
ๆถใ
*/
ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT";
/**
* ๅๆฐ้่ฏฏใ
*/
ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR";
/**
* ๅๆฐ้่ฏฏ๏ผApp Id ้่ฏฏใ
*/
ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT";
/**
* ๆๅกๅจไธๅฏ็จใ
*/
ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE";
/**
* Token ้่ฏฏใ
*/
ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR";
/**
* App Id ไธ Token ไธๅน้
ใ
*/
ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED";
/**
* ้ๅฎๅ๏ผๅฐๅ้่ฏฏใ
*/
ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED";
/**
* NAME ไธๅๅฐๆณจๅไฟกๆฏไธไธ่ดใ
*/
ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID";
/**
* APP ่ขซๅฑ่ฝใๅ ้คๆไธๅญๅจใ
*/
ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED";
/**
* ็จๆท่ขซๅฑ่ฝใ
*/
ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED";
/**
* Disconnect๏ผ็ฑๆๅกๅจ่ฟๅ๏ผๆฏๅฆ็จๆทไบ่ธขใ
*/
ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK";
/**
* Disconnect๏ผ็ฑๆๅกๅจ่ฟๅ๏ผๆฏๅฆ็จๆทไบ่ธขใ
*/
ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION";
/**
* ๅ่ฎฎๅฑๅ
้จ้่ฏฏใquery๏ผไธไผ ไธ่ฝฝ่ฟ็จไธญๆฐๆฎ้่ฏฏใ
*/
ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA";
/**
* ๅ่ฎฎๅฑๅ
้จ้่ฏฏใ
*/
ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE";
/**
* ๆช่ฐ็จ init ๅๅงๅๅฝๆฐใ
*/
ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT";
/**
* ๆฐๆฎๅบๅๅงๅๅคฑ่ดฅใ
*/
ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR";
/**
* ไผ ๅ
ฅๅๆฐๆ ๆใ
*/
ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER";
/**
* ้้ๆ ๆใ
*/
ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL";
/**
* ้ๆฐ่ฟๆฅๆๅใ
*/
ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS";
/**
* ่ฟๆฅไธญ๏ผๅ่ฐ็จ connect ่ขซๆ็ปใ
*/
ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING";
/**
* ๆถๆฏๆผซๆธธๆๅกๆชๅผ้
*/
ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE";
ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR";
ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR";
/**
* ๅ ้คไผ่ฏๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR";
/**
*ๆๅๅๅฒๆถๆฏ
*/
ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR";
/**
* ไผ่ฏๆๅฎๅผๅธธ
*/
ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR";
/**
* ่ทๅไผ่ฏๆช่ฏปๆถๆฏๆปๆฐๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR";
/**
* ่ทๅๆๅฎไผ่ฏ็ฑปๅๆช่ฏปๆถๆฏๆฐๅผๅธธ
*/
ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR";
/**
* ่ทๅๆๅฎ็จๆทID&ไผ่ฏ็ฑปๅๆช่ฏปๆถๆฏๆฐๅผๅธธ
*/
ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR";
ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR";
ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34008] = "CONVER_GET_ERROR";
//็พค็ปๅผๅธธไฟกๆฏ
/**
*
*/
ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR";
/**
* ๅน้
็พคไฟกๆฏ็ณปๅผๅธธ
*/
ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR";
//่ๅคฉๅฎคๅผๅธธ
/**
* ๅ ๅ
ฅ่ๅคฉๅฎคIdไธบ็ฉบ
*/
ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL";
/**
* ๅ ๅ
ฅ่ๅคฉๅฎคๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR";
/**
* ๆๅ่ๅคฉๅฎคๅๅฒๆถๆฏๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR";
//้ปๅๅๅผๅธธ
/**
* ๅ ๅ
ฅ้ปๅๅๅผๅธธ
*/
ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR";
/**
* ่ทๅพๆๅฎไบบๅๅ้ปๅๅไธญ็็ถๆๅผๅธธ
*/
ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR";
/**
* ็งป้ค้ปๅๅๅผๅธธ
*/
ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR";
/**
* ่ทๅ่็จฟๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR";
/**
* ไฟๅญ่็จฟๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR";
/**
* ๅ ้ค่็จฟๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR";
/**
* ๅ
ณๆณจๅ
ฌไผๅทๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR";
/**
* ๅ
ณๆณจๅ
ฌไผๅทๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR";
/**
* ่ทๅไธ็tokenๅคฑ่ดฅ
*/
ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR";
/**
* cookie่ขซ็ฆ็จ
*/
ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE";
ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR";
// ๆฒกๆๆณจๅDeviveId ไนๅฐฑๆฏ็จๆทๆฒกๆ็ป้
ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID";
// ๅทฒ็ปๅญๅจ
ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE";
// ๆๅ
ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS";
// ๆฒกๆๅฏนๅบ็็จๆทๆtoken
ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD";
// voipไธบ็ฉบ
ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL";
// ไธๆฏๆ็Voipๅผๆ
ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE";
// channleName ๆฏ็ฉบ
ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME";
// ็ๆVoipkeyๅคฑ่ดฅ
ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR";
// ๆฒกๆ้
็ฝฎvoip
ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP";
// ๆๅกๅจๅ
้จ้่ฏฏ
ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR";
//VOIP close
ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE";
ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN";
ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE";
ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME";
ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL";
/**
* ๅ ้คๆถๆฏๆฐ็ป้ฟๅบฆไธบ 0 .
*/
ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL";
/*!
ๅทฑๆนๅๆถๅทฒๅๅบ็้่ฏ่ฏทๆฑ
*/
ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL";
/*!
ๅทฑๆนๆ็ปๆถๅฐ็้่ฏ่ฏทๆฑ
*/
ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT";
/*!
ๅทฑๆนๆๆญ
*/
ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP";
/*!
ๅทฑๆนๅฟ็ข
*/
ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE";
/*!
ๅทฑๆนๆชๆฅๅฌ
*/
ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE";
/*!
ๅทฑๆนไธๆฏๆๅฝๅๅผๆ
*/
ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED";
/*!
ๅทฑๆน็ฝ็ปๅบ้
*/
ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR";
/*!
ๅฏนๆนๅๆถๅทฒๅๅบ็้่ฏ่ฏทๆฑ
*/
ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL";
/*!
ๅฏนๆนๆ็ปๆถๅฐ็้่ฏ่ฏทๆฑ
*/
ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT";
/*!
้่ฏ่ฟ็จๅฏนๆนๆๆญ
*/
ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP";
/*!
ๅฏนๆนๅฟ็ข
*/
ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE";
/*!
ๅฏนๆนๆชๆฅๅฌ
*/
ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE";
/*!
ๅฏนๆน็ฝ็ป้่ฏฏ
*/
ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED";
/*!
ๅฏนๆน็ฝ็ป้่ฏฏ
*/
ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR";
/*!
VoIP ไธๅฏ็จ
*/
ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE";
})(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {}));
var ErrorCode = RongIMLib.ErrorCode;
(function (VoIPMediaType) {
VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO";
VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO";
})(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {}));
var VoIPMediaType = RongIMLib.VoIPMediaType;
(function (MediaType) {
/**
* ๅพ็ใ
*/
MediaType[MediaType["IMAGE"] = 1] = "IMAGE";
/**
* ๅฃฐ้ณใ
*/
MediaType[MediaType["AUDIO"] = 2] = "AUDIO";
/**
* ่ง้ขใ
*/
MediaType[MediaType["VIDEO"] = 3] = "VIDEO";
/**
* ้็จๆไปถใ
*/
MediaType[MediaType["FILE"] = 100] = "FILE";
})(RongIMLib.MediaType || (RongIMLib.MediaType = {}));
var MediaType = RongIMLib.MediaType;
(function (MessageDirection) {
/**
* ๅ้ๆถๆฏใ
*/
MessageDirection[MessageDirection["SEND"] = 1] = "SEND";
/**
* ๆฅๆถๆถๆฏใ
*/
MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE";
})(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {}));
var MessageDirection = RongIMLib.MessageDirection;
(function (FileType) {
FileType[FileType["IMAGE"] = 1] = "IMAGE";
FileType[FileType["AUDIO"] = 2] = "AUDIO";
FileType[FileType["VIDEO"] = 3] = "VIDEO";
FileType[FileType["FILE"] = 4] = "FILE";
})(RongIMLib.FileType || (RongIMLib.FileType = {}));
var FileType = RongIMLib.FileType;
(function (RealTimeLocationErrorCode) {
/**
* ๆชๅๅงๅ RealTimeLocation ๅฎไพ
*/
RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT";
/**
* ๆง่กๆๅใ
*/
RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS";
/**
* ่ทๅ RealTimeLocation ๅฎไพๆถ่ฟๅ
* GPS ๆชๆๅผใ
*/
RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED";
/**
* ่ทๅ RealTimeLocation ๅฎไพๆถ่ฟๅ
* ๅฝๅไผ่ฏไธๆฏๆไฝ็ฝฎๅ
ฑไบซใ
*/
RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT";
/**
* ่ทๅ RealTimeLocation ๅฎไพๆถ่ฟๅ
* ๅฏนๆนๅทฒๅ่ตทไฝ็ฝฎๅ
ฑไบซใ
*/
RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING";
/**
* Join ๆถ่ฟๅ
* ๅฝๅไฝ็ฝฎๅ
ฑไบซๅทฒ่ถ
่ฟๆๅคงๆฏๆไบบๆฐใ
*/
RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT";
/**
* Join ๆถ่ฟๅ
* ๅ ๅ
ฅไฝ็ฝฎๅ
ฑไบซๅคฑ่ดฅใ
*/
RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE";
/**
* Start ๆถ่ฟๅ
* ๅ่ตทไฝ็ฝฎๅ
ฑไบซๅคฑ่ดฅใ
*/
RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE";
/**
* ็ฝ็ปไธๅฏ็จใ
*/
RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE";
})(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {}));
var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode;
(function (RealTimeLocationStatus) {
/**
* ็ฉบ้ฒ็ถๆ ๏ผ้ป่ฎค็ถๆ๏ผ
* ๅฏนๆนๆ่
่ชๅทฑ้ฝๆชๅ่ตทไฝ็ฝฎๅ
ฑไบซไธๅก๏ผๆ่
ไฝ็ฝฎๅ
ฑไบซไธๅกๅทฒ็ปๆใ
*/
RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE";
/**
* ๅผๅ
ฅ็ถๆ ๏ผๅพ
ๅ ๅ
ฅ๏ผ
* 1. ๅฏนๆนๅ่ตทไบไฝ็ฝฎๅ
ฑไบซไธๅก๏ผๆญค็ถๆไธ๏ผ่ชๅทฑๅช่ฝ้ๆฉๅ ๅ
ฅใ
* 2. ่ชๅทฑไปๅทฒ่ฟๆฅ็ไฝ็ฝฎๅ
ฑไบซไธญ้ๅบใ
*/
RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING";
/**
* ๅผๅบ็ถๆ =๏ผ่ชๅทฑๅๅปบ๏ผ
* 1. ่ชๅทฑๅ่ตทไฝ็ฝฎๅ
ฑไบซไธๅก๏ผๅฏนๆนๅช่ฝ้ๆฉๅ ๅ
ฅใ
* 2. ๅฏนๆนไปๅทฒ่ฟๆฅ็ไฝ็ฝฎๅ
ฑไบซไธๅกไธญ้ๅบใ
*/
RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING";
/**
* ่ฟๆฅ็ถๆ ๏ผ่ชๅทฑๅ ๅ
ฅ๏ผ
* ๅฏนๆนๅ ๅ
ฅไบ่ชๅทฑๅ่ตท็ไฝ็ฝฎๅ
ฑไบซ๏ผๆ่
่ชๅทฑๅ ๅ
ฅไบๅฏนๆนๅ่ตท็ไฝ็ฝฎๅ
ฑไบซใ
*/
RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED";
})(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {}));
var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus;
(function (ReceivedStatus) {
ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ";
ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED";
ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED";
ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED";
ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD";
})(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {}));
var ReceivedStatus = RongIMLib.ReceivedStatus;
(function (SearchType) {
/**
* ็ฒพ็กฎใ
*/
SearchType[SearchType["EXACT"] = 0] = "EXACT";
/**
* ๆจก็ณใ
*/
SearchType[SearchType["FUZZY"] = 1] = "FUZZY";
})(RongIMLib.SearchType || (RongIMLib.SearchType = {}));
var SearchType = RongIMLib.SearchType;
(function (SentStatus) {
/**
* ๅ้ไธญใ
*/
SentStatus[SentStatus["SENDING"] = 10] = "SENDING";
/**
* ๅ้ๅคฑ่ดฅใ
*/
SentStatus[SentStatus["FAILED"] = 20] = "FAILED";
/**
* ๅทฒๅ้ใ
*/
SentStatus[SentStatus["SENT"] = 30] = "SENT";
/**
* ๅฏนๆนๅทฒๆฅๆถใ
*/
SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED";
/**
* ๅฏนๆนๅทฒ่ฏปใ
*/
SentStatus[SentStatus["READ"] = 50] = "READ";
/**
* ๅฏนๆนๅทฒ้ๆฏใ
*/
SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED";
})(RongIMLib.SentStatus || (RongIMLib.SentStatus = {}));
var SentStatus = RongIMLib.SentStatus;
(function (ConnectionState) {
ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED";
ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION";
ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED";
ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE";
/**
* tokenๆ ๆ
*/
ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT";
ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED";
ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT";
ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR";
ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE";
ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK";
ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE";
ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR";
})(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {}));
var ConnectionState = RongIMLib.ConnectionState;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var RongIMClient = (function () {
function RongIMClient() {
}
RongIMClient.getInstance = function () {
if (!RongIMClient._instance) {
throw new Error("RongIMClient is not initialized. Call .init() method first.");
}
return RongIMClient._instance;
};
/**
* ๅๅงๅ SDK๏ผๅจๆดไธชๅบ็จๅ
จๅฑๅช้่ฆ่ฐ็จไธๆฌกใ
* @param appKey ๅผๅ่
ๅๅฐ็ณ่ฏท็ AppKey๏ผ็จๆฅๆ ่ฏๅบ็จใ
* @param dataAccessProvider ๅฟ
้กปๆฏDataAccessProvider็ๅฎไพ
*/
RongIMClient.init = function (appKey, dataAccessProvider, options, callback) {
if (!RongIMClient._instance) {
RongIMClient._instance = new RongIMClient();
}
options = options || {};
var protocol = "//", wsScheme = 'ws://';
var protocols = 'http:,https:';
if (protocols.indexOf(location.protocol) == -1) {
protocol = 'http://';
}
if (location.protocol == 'https:') {
wsScheme = 'wss://';
}
var isPolling = false;
if (typeof WebSocket != 'function') {
isPolling = true;
}
var supportUserData = function () {
var element = document.documentElement;
return element.addBehavior;
};
if (RongIMLib.RongUtil.supportLocalStorage()) {
RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider();
}
else if (supportUserData()) {
RongIMClient._storageProvider = new RongIMLib.UserDataProvider();
}
else {
RongIMClient._storageProvider = new RongIMLib.MemeoryProvider();
}
var pathTmpl = '{0}{1}';
var _serverPath = {
navi: 'nav.cn.ronghub.com',
api: 'api.cn.ronghub.com'
};
RongIMLib.RongUtil.forEach(_serverPath, function (path, key) {
_serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]);
});
RongIMLib.RongUtil.forEach(_serverPath, function (path, key) {
var hasProto = (key in options);
var config = {
path: options[key],
tmpl: pathTmpl,
protocol: protocol,
sub: true
};
path = hasProto ? RongIMLib.RongUtil.formatProtoclPath(config) : path;
options[key] = path;
});
var _sourcePath = {
protobuf: 'cdn.ronghub.com/protobuf-2.2.7.min.js'
};
RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) {
_sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]);
});
RongIMLib.RongUtil.extends(_sourcePath, options);
var _defaultOpts = {
isPolling: isPolling,
wsScheme: wsScheme,
protocol: protocol,
openMp: true
};
RongIMLib.RongUtil.extends(_defaultOpts, options);
if (RongIMLib.RongUtil.isFunction(options.protobuf)) {
RongIMClient.Protobuf = options.protobuf;
}
var pather = new RongIMLib.FeaturePatcher();
pather.patchAll();
var tempStore = {
token: "",
callback: null,
lastReadTime: new RongIMLib.LimitableMap(),
conversationList: [],
appKey: appKey,
publicServiceMap: new RongIMLib.PublicServiceMap(),
providerType: 1,
deltaTime: 0,
filterMessages: [],
isSyncRemoteConverList: true,
otherDevice: false,
custStore: {},
converStore: { latestMessage: {} },
connectAckTime: 0,
voipStategy: 0,
isFirstPingMsg: true,
depend: options,
listenerList: RongIMClient._memoryStore.listenerList,
notification: {}
};
RongIMClient._memoryStore = tempStore;
if (dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]") {
RongIMClient._dataAccessProvider = dataAccessProvider;
}
else {
RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider();
}
RongIMClient._dataAccessProvider.init(appKey, callback);
// ๅ
ผๅฎน c++ ่ฎพ็ฝฎๅฏผ่ช๏ผWeb ็ซฏไธ็ๆ
RongIMClient._dataAccessProvider.setServerInfo({ navi: options.navi + '/navi.xml' });
RongIMClient.MessageParams = {
TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) },
ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) },
DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(true, true) },
VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) },
RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) },
FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) },
HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) },
UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) },
LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) },
InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(true, true) },
ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(true, true) },
ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(true, true) },
CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(true, true) },
PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) },
PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) },
JrmfReadPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) },
JrmfReadPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) },
GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(true, true) },
CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) },
TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) },
PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) },
RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) },
SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) },
ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) },
ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) },
ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) },
ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) },
EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) },
CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) },
HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) },
HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) },
SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) },
TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) },
CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) },
ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) },
RCEUpdateStatusMessage: { objectName: "RCE:UpdateStatus", msgTag: new RongIMLib.MessageTag(false, false) }
};
RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) };
RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) };
RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) };
RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) };
RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) };
RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) };
RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) };
RongIMClient.MessageType = {
TextMessage: "TextMessage",
ImageMessage: "ImageMessage",
DiscussionNotificationMessage: "DiscussionNotificationMessage",
VoiceMessage: "VoiceMessage",
RichContentMessage: "RichContentMessage",
HandshakeMessage: "HandshakeMessage",
UnknownMessage: "UnknownMessage",
LocationMessage: "LocationMessage",
InformationNotificationMessage: "InformationNotificationMessage",
ContactNotificationMessage: "ContactNotificationMessage",
ProfileNotificationMessage: "ProfileNotificationMessage",
CommandNotificationMessage: "CommandNotificationMessage",
CommandMessage: "CommandMessage",
TypingStatusMessage: "TypingStatusMessage",
ChangeModeResponseMessage: "ChangeModeResponseMessage",
ChangeModeMessage: "ChangeModeMessage",
EvaluateMessage: "EvaluateMessage",
HandShakeMessage: "HandShakeMessage",
HandShakeResponseMessage: "HandShakeResponseMessage",
SuspendMessage: "SuspendMessage",
TerminateMessage: "TerminateMessage",
CustomerContact: "CustomerContact",
CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage",
SyncReadStatusMessage: "SyncReadStatusMessage",
ReadReceiptRequestMessage: "ReadReceiptRequestMessage",
ReadReceiptResponseMessage: "ReadReceiptResponseMessage",
FileMessage: 'FileMessage',
AcceptMessage: "AcceptMessage",
RingingMessage: "RingingMessage",
SummaryMessage: "SummaryMessage",
HungupMessage: "HungupMessage",
InviteMessage: "InviteMessage",
MediaModifyMessage: "MediaModifyMessage",
MemberModifyMessage: "MemberModifyMessage",
JrmfReadPacketMessage: "JrmfReadPacketMessage",
JrmfReadPacketOpenedMessage: "JrmfReadPacketOpenedMessage",
RCEUpdateStatusMessage: "RCEUpdateStatusMessage",
GroupNotificationMessage: "GroupNotificationMessage",
PublicServiceRichContentMessage: "PublicServiceRichContentMessage",
PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage",
PublicServiceCommandMessage: "PublicServiceCommandMessage",
RecallCommandMessage: "RecallCommandMessage",
ReadReceiptMessage: "ReadReceiptMessage"
};
};
/**
var config = {
appkey: appkey,
token: token,
dataAccessProvider:dataAccessProvider,
opts: opts
};
callback(_instance, userId);
*/
RongIMClient.initApp = function (config, callback) {
RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () {
var instance = RongIMClient._instance;
//ๅค็จ
var error = null;
callback(error, instance);
});
};
/**
* ่ฟๆฅๆๅกๅจ๏ผๅจๆดไธชๅบ็จๅ
จๅฑๅช้่ฆ่ฐ็จไธๆฌก๏ผๆญ็บฟๅ SDK ไผ่ชๅจ้่ฟใ
*
* @param token ไปๆๅก็ซฏ่ทๅ็็จๆท่บซไปฝไปค็๏ผToken๏ผใ
* @param callback ่ฟๆฅๅ่ฐ๏ผ่ฟๅ่ฟๆฅ็ๆๅๆ่
ๅคฑ่ดฅ็ถๆใ
*/
RongIMClient.connect = function (token, callback, userId) {
RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined"], "connect", true, arguments);
RongIMClient._dataAccessProvider.connect(token, callback, userId);
};
RongIMClient.reconnect = function (callback, config) {
RongIMClient._dataAccessProvider.reconnect(callback, config);
};
/**
* ๆณจๅๆถๆฏ็ฑปๅ๏ผ็จไบๆณจๅ็จๆท่ชๅฎไน็ๆถๆฏใ
* ๅ
ๅปบ็ๆถๆฏ็ฑปๅๅทฒ็ปๆณจๅ่ฟ๏ผไธ้่ฆๅๆฌกๆณจๅใ
* ่ชๅฎไนๆถๆฏๅฃฐๆ้ๆพๅจๆง่ก้กบๅบๆ้ซ็ไฝ็ฝฎ๏ผๅจRongIMClient.init(appkey)ไนๅๅณๅฏ๏ผ
* @param objectName ๆถๆฏๅ
็ฝฎๅ็งฐ
*/
RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent) {
RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent);
RongIMClient.RegisterMessage[messageType].messageName = messageType;
RongIMClient.MessageType[messageType] = messageType;
RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag };
};
/**
* ่ฎพ็ฝฎ่ฟๆฅ็ถๆๅๅ็็ๅฌๅจใ
*
* @param listener ่ฟๆฅ็ถๆๅๅ็็ๅฌๅจใ
*/
RongIMClient.setConnectionStatusListener = function (listener) {
if (RongIMClient._dataAccessProvider) {
RongIMClient._dataAccessProvider.setConnectionStatusListener(listener);
}
else {
RongIMClient._memoryStore.listenerList.push(listener);
}
};
/**
* ่ฎพ็ฝฎๆฅๆถๆถๆฏ็็ๅฌๅจใ
*
* @param listener ๆฅๆถๆถๆฏ็็ๅฌๅจใ
*/
RongIMClient.setOnReceiveMessageListener = function (listener) {
if (RongIMClient._dataAccessProvider) {
RongIMClient._dataAccessProvider.setOnReceiveMessageListener(listener);
}
else {
RongIMClient._memoryStore.listenerList.push(listener);
}
};
/**
* ๆธ
็ๆๆ่ฟๆฅ็ธๅ
ณ็ๅ้
*/
RongIMClient.prototype.logout = function () {
RongIMClient._dataAccessProvider.logout();
};
/**
* ๆญๅผ่ฟๆฅใ
*/
RongIMClient.prototype.disconnect = function () {
RongIMClient._dataAccessProvider.disconnect();
};
RongIMClient.prototype.startCustomService = function (custId, callback, groupId) {
if (!custId || !callback)
return;
var msg;
if (typeof groupId == 'undefined') {
msg = new RongIMLib.HandShakeMessage();
}
else {
msg = new RongIMLib.HandShakeMessage({ groupid: groupId });
}
var me = this;
RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true;
RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, {
onSuccess: function (data) {
if (data.isBlack) {
callback.onError();
me.stopCustomeService(custId, {
onSuccess: function () { },
onError: function () { }
});
}
else {
callback.onSuccess();
}
},
onError: function () {
callback.onError();
},
onBefore: function () { }
});
};
RongIMClient.prototype.stopCustomeService = function (custId, callback) {
if (!custId || !callback)
return;
var session = RongIMClient._memoryStore.custStore[custId];
if (!session)
return;
var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid });
this.sendCustMessage(custId, msg, {
onSuccess: function () {
// delete RongIMClient._memoryStore.custStore[custId];
setTimeout(function () {
callback.onSuccess();
});
},
onError: function () {
setTimeout(function () {
callback.onError();
});
}
});
};
RongIMClient.prototype.switchToHumanMode = function (custId, callback) {
if (!custId || !callback)
return;
var session = RongIMClient._memoryStore.custStore[custId];
if (!session)
return;
var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid });
this.sendCustMessage(custId, msg, callback);
};
RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) {
if (!custId || !callback)
return;
var session = RongIMClient._memoryStore.custStore[custId];
if (!session)
return;
var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 });
this.sendCustMessage(custId, msg, callback);
};
RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) {
if (!custId || !callback)
return;
var session = RongIMClient._memoryStore.custStore[custId];
if (!session)
return;
var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 });
this.sendCustMessage(custId, msg, callback);
};
RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) {
RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, {
onSuccess: function (data) {
callback.onSuccess();
},
onError: function () {
callback.onError();
},
onBefore: function () { }
});
};
/**
* ่ทๅๅฝๅ่ฟๆฅ็็ถๆใ
*/
RongIMClient.prototype.getCurrentConnectionStatus = function () {
return RongIMClient._dataAccessProvider.getCurrentConnectionStatus();
};
/**
* ่ทๅๅฝๅไฝฟ็จ็่ฟๆฅ้้ใ
*/
RongIMClient.prototype.getConnectionChannel = function () {
if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) {
return RongIMLib.ConnectionChannel.XHR_POLLING;
}
else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) {
return RongIMLib.ConnectionChannel.WEBSOCKET;
}
};
/**
* ่ทๅๅฝๅไฝฟ็จ็ๆฌๅฐๅจๅญๆไพ่
ใ TODO
*/
RongIMClient.prototype.getStorageProvider = function () {
if (RongIMClient._memoryStore.providerType == 1) {
return "ServerDataProvider";
}
else {
return "OtherDataProvider";
}
};
/**
* ่ฟๆปค่ๅคฉๅฎคๆถๆฏ๏ผๆๅๆ่ฟ่ๅคฉๆถๆฏ๏ผ
* @param {string[]} msgFilterNames
*/
RongIMClient.prototype.setFilterMessages = function (msgFilterNames) {
if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") {
RongIMClient._memoryStore.filterMessages = msgFilterNames;
}
};
RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) {
RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "getAgoraDynamicKey", false, arguments);
var modules = new RongIMClient.Protobuf.VoipDynamicInput();
modules.setEngineType(engineType);
modules.setChannelName(channelName);
RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, callback, "VoipDynamicOutput");
};
/**
* ่ทๅๅฝๅ่ฟๆฅ็จๆท็ UserIdใ
*/
RongIMClient.prototype.getCurrentUserId = function () {
return RongIMLib.Bridge._client.userId;
};
/**
* ่ทๅๆๅกๅจๆถ้ดไธๆฌๅฐๆถ้ด็ๅทฎๅผ๏ผๅไฝไธบๆฏซ็งใ
* ่ฎก็ฎๅ
ฌๅผ๏ผๅทฎๅผ = ๆฌๅฐๆถ้ดๆฏซ็งๆฐ - ๆๅกๅจๆถ้ดๆฏซ็งๆฐ
* @param callback ่ทๅ็ๅ่ฐ๏ผ่ฟๅๅทฎๅผใ
*/
RongIMClient.prototype.getDeltaTime = function () {
return RongIMClient._dataAccessProvider.getDelaTime();
};
// #region Message
RongIMClient.prototype.getMessage = function (messageId, callback) {
RongIMClient._dataAccessProvider.getMessage(messageId, callback);
};
RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) {
RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, callback);
};
RongIMClient.prototype.updateMessage = function (message, callback) {
RongIMClient._dataAccessProvider.updateMessage(message, callback);
};
RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) {
RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, {
onSuccess: function (bool) {
setTimeout(function () {
callback.onSuccess(bool);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
});
};
/**TODO ๆธ
ๆฅๆฌๅฐๅญๅจ็ๆช่ฏปๆถๆฏ๏ผ็ฎๅๆธ
็ฉบๅ
ๅญไธญ็ๆช่ฏปๆถๆฏ
* [clearMessagesUnreadStatus ๆธ
็ฉบๆๅฎไผ่ฏๆช่ฏปๆถๆฏ]
* @param {ConversationType} conversationType [ไผ่ฏ็ฑปๅ]
* @param {string} targetId [็จๆทid]
* @param {ResultCallback<boolean>} callback [่ฟๅๅผ๏ผๅๆฐๅ่ฐ]
*/
RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) {
RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, {
onSuccess: function (bool) {
setTimeout(function () {
callback.onSuccess(bool);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
});
};
RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, delMsgs, callback) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments);
if (delMsgs.length == 0) {
callback.onError(RongIMLib.ErrorCode.DELETE_MESSAGE_ID_IS_NULL);
return;
}
else if (delMsgs.length > 100) {
delMsgs.length = 100;
}
// ๅ็ปญๅขๅ ๏ผๅปๆๆณจ้ๅณๅฏ
callback.onSuccess(true);
// var modules = new RongIMClient.Protobuf.DeleteMsgInput();
// modules.setType(conversationType);
// modules.setConversationId(targetId);
// modules.setMsgs(delMsgs);
// RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, {
// onSuccess: function(info: any) {
// callback.onSuccess(true);
// },
// onError: function(err: any) {
// callback.onError(err);
// }
// }, "DeleteMsgOutput");
};
/**
* [deleteMessages ๅ ้คๆถๆฏ่ฎฐๅฝใ]
* @param {ConversationType} conversationType [description]
* @param {string} targetId [description]
* @param {number[]} messageIds [description]
* @param {ResultCallback<boolean>} callback [description]
*/
RongIMClient.prototype.deleteMessages = function (conversationType, targetId, delMsgs, callback) {
RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, delMsgs, {
onSuccess: function (bool) {
setTimeout(function () {
callback.onSuccess(bool);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
});
};
RongIMClient.prototype.sendLocalMessage = function (message, callback) {
RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments);
RongIMClient._dataAccessProvider.updateMessage(message);
this.sendMessage(message.conversationType, message.targetId, message.content, callback);
};
/**
* [sendMessage ๅ้ๆถๆฏใ]
* @param {ConversationType} conversationType [ไผ่ฏ็ฑปๅ]
* @param {string} targetId [็ฎๆ Id]
* @param {MessageContent} messageContent [ๆถๆฏ็ฑปๅ]
* @param {SendMessageCallback} sendCallback []
* @param {ResultCallback<Message>} resultCallback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
* @param {string} pushContent []
* @param {string} pushData []
*/
RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global"], "sendMessage", false, arguments);
RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params);
};
RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) {
RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, sendCallback);
};
RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) {
RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, sendCallback);
};
/**
* [sendStatusMessage description]
* @param {MessageContent} messageContent [description]
* @param {SendMessageCallback} sendCallback [description]
* @param {ResultCallback<Message>} resultCallback [description]
*/
RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) {
throw new Error("Not implemented yet");
};
/**
* [sendTextMessage ๅ้TextMessageๅฟซๆทๆนๅผ]
* @param {string} content [ๆถๆฏๅ
ๅฎน]
* @param {ResultCallback<Message>} resultCallback [่ฟๅๅผ๏ผๅๆฐๅ่ฐ]
*/
RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) {
RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, sendMessageCallback);
};
RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback) {
RongIMClient._dataAccessProvider.sendRecallMessage(content, sendMessageCallback);
};
/**
* [insertMessage ๅๆฌๅฐๆๅ
ฅไธๆกๆถๆฏ๏ผไธๅ้ๅฐๆๅกๅจใ]
* @param {ConversationType} conversationType [description]
* @param {string} targetId [description]
* @param {string} senderUserId [description]
* @param {MessageContent} content [description]
* @param {ResultCallback<Message>} callback [description]
*/
RongIMClient.prototype.insertMessage = function (conversationType, targetId, senderUserId, content, callback) {
RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, callback);
};
/**
* [getHistoryMessages ๆๅๅๅฒๆถๆฏ่ฎฐๅฝใ]
* @param {ConversationType} conversationType [ไผ่ฏ็ฑปๅ]
* @param {string} targetId [็จๆทId]
* @param {number|null} pullMessageTime [ๆๅๅๅฒๆถๆฏ่ตทๅงไฝ็ฝฎ(ๆ ผๅผไธบๆฏซ็งๆฐ)๏ผๅฏไปฅไธบnull]
* @param {number} count [ๅๅฒๆถๆฏๆฐ้]
* @param {ResultCallback<Message[]>} callback [ๅ่ฐๅฝๆฐ]
* @param {string} objectName [objectName]
*/
RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "boolean|null|global|object"], "getHistoryMessages", false, arguments);
if (count > 20) {
throw new Error("HistroyMessage count must be less than or equal to 20!");
}
if (conversationType.valueOf() < 0) {
throw new Error("ConversationType must be greater than -1");
}
RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, callback, objectname, direction);
};
RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) {
RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName);
};
;
/**
* [getRemoteHistoryMessages ๆๅๆไธชๆถ้ดๆณไนๅ็ๆถๆฏ]
* @param {ConversationType} conversationType [description]
* @param {string} targetId [description]
* @param {Date} dateTime [description]
* @param {number} count [description]
* @param {ResultCallback<Message[]>} callback [description]
*/
RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object"], "getRemoteHistoryMessages", false, arguments);
if (count > 20) {
callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR);
return;
}
if (conversationType.valueOf() < 0) {
callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR);
return;
}
RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback);
};
/**
* [hasRemoteUnreadMessages ๆฏๅฆๆๆชๆฅๆถ็ๆถๆฏ๏ผjsonpๆนๆณ]
* @param {string} appkey [appkey]
* @param {string} token [token]
* @param {ConnectCallback} callback [่ฟๅๅผ๏ผๅๆฐๅ่ฐ]
*/
RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) {
RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, callback);
};
RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) {
RongIMClient._dataAccessProvider.getTotalUnreadCount({
onSuccess: function (count) {
setTimeout(function () {
callback.onSuccess(count);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
}, conversationTypes);
};
/**
* [getConversationUnreadCount ๆๅฎๅค็งไผ่ฏ็ฑปๅ่ทๅๆช่ฏปๆถๆฏๆฐ]
* @param {ResultCallback<number>} callback [่ฟๅๅผ๏ผๅๆฐๅ่ฐใ]
* @param {ConversationType[]} ...conversationTypes [ไผ่ฏ็ฑปๅใ]
*/
RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) {
RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, {
onSuccess: function (count) {
setTimeout(function () {
callback.onSuccess(count);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
});
};
/**
* [getUnreadCount ๆๅฎ็จๆทใไผ่ฏ็ฑปๅ็ๆช่ฏปๆถๆฏๆปๆฐใ]
* @param {ConversationType} conversationType [ไผ่ฏ็ฑปๅ]
* @param {string} targetId [็จๆทId]
*/
RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) {
RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, {
onSuccess: function (count) {
setTimeout(function () {
callback.onSuccess(count);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
});
};
RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) {
RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, callback);
};
/**
* ๆธ
ๆฅไผ่ฏๆช่ฏปๆถๆฏๆฐ
* @param {ConversationType} conversationType ไผ่ฏ็ฑปๅ
* @param {string} targetId ็ฎๆ Id
* @param {ResultCallback<boolean>} callback ่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ
*/
RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) {
RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, {
onSuccess: function (bool) {
setTimeout(function () {
callback.onSuccess(bool);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
});
};
RongIMClient.prototype.clearLocalStorage = function (callback) {
RongIMClient._storageProvider.clearItem();
callback();
};
RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) {
RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, {
onSuccess: function (bool) {
setTimeout(function () {
callback.onSuccess(bool);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
});
};
RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) {
RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, {
onSuccess: function (bool) {
setTimeout(function () {
callback.onSuccess(bool);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
});
};
RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) {
RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, callback);
};
RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) {
RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, {
onSuccess: function (bool) {
setTimeout(function () {
callback.onSuccess(bool);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
});
};
// #endregion Message
// #region TextMessage Draft
/**
* clearTextMessageDraft ๆธ
้คๆๅฎไผ่ฏๅๆถๆฏ็ฑปๅ็่็จฟใ
* @param {ConversationType} conversationType ไผ่ฏ็ฑปๅ
* @param {string} targetId ็ฎๆ Id
*/
RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments);
var key = "darf_" + conversationType + "_" + targetId;
delete RongIMClient._memoryStore[key];
return true;
};
/**
* [getTextMessageDraft ่ทๅๆๅฎๆถๆฏๅไผ่ฏ็่็จฟใ]
* @param {ConversationType} conversationType [ไผ่ฏ็ฑปๅ]
* @param {string} targetId [็ฎๆ Id]
*/
RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments);
if (targetId == "" || conversationType < 0) {
throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR);
}
var key = "darf_" + conversationType + "_" + targetId;
return RongIMClient._memoryStore[key];
};
/**
* [saveTextMessageDraft description]
* @param {ConversationType} conversationType [ไผ่ฏ็ฑปๅ]
* @param {string} targetId [็ฎๆ Id]
* @param {string} value [่็จฟๅผ]
*/
RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments);
var key = "darf_" + conversationType + "_" + targetId;
RongIMClient._memoryStore[key] = value;
return true;
};
// #endregion TextMessage Draft
// #region Conversation
RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) {
RongIMClient._dataAccessProvider.searchConversationByContent(keyword, callback, conversationTypes);
};
RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) {
RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, callback);
};
RongIMClient.prototype.clearConversations = function (callback) {
var conversationTypes = [];
for (var _i = 1; _i < arguments.length; _i++) {
conversationTypes[_i - 1] = arguments[_i];
}
if (conversationTypes.length == 0) {
conversationTypes = [RongIMLib.ConversationType.CHATROOM,
RongIMLib.ConversationType.CUSTOMER_SERVICE,
RongIMLib.ConversationType.DISCUSSION,
RongIMLib.ConversationType.GROUP,
RongIMLib.ConversationType.PRIVATE,
RongIMLib.ConversationType.SYSTEM,
RongIMLib.ConversationType.PUBLIC_SERVICE,
RongIMLib.ConversationType.APP_PUBLIC_SERVICE];
}
RongIMClient._dataAccessProvider.clearConversations(conversationTypes, {
onSuccess: function (bool) {
setTimeout(function () {
callback.onSuccess(bool);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
});
};
/**
* [getConversation ่ทๅๆๅฎไผ่ฏ๏ผๆญคๆนๆณ้ๅจgetConversationListไนๅๆง่ก]
* @param {ConversationType} conversationType [ไผ่ฏ็ฑปๅ]
* @param {string} targetId [็ฎๆ Id]
* @param {ResultCallback<Conversation>} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments);
RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, {
onSuccess: function (conver) {
setTimeout(function () {
callback.onSuccess(conver);
});
},
onError: function (error) {
setTimeout(function () {
callback.onError(error);
});
}
});
};
/**
* [pottingConversation ็ป่ฃ
ไผ่ฏๅ่กจ]
* @param {any} tempConver [ไธดๆถไผ่ฏ]
* conver_conversationType_targetId_no.
* msg_conversationType_targetId_no.
*/
RongIMClient.prototype.pottingConversation = function (tempConver) {
var self = this, isUseReplace = false;
RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, {
onSuccess: function (conver) {
if (!conver) {
conver = new RongIMLib.Conversation();
}
else {
isUseReplace = true;
}
conver.conversationType = tempConver.type;
conver.targetId = tempConver.userId;
conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg);
conver.latestMessageId = conver.latestMessage.messageId;
conver.objectName = conver.latestMessage.objectName;
conver.receivedStatus = conver.latestMessage.receivedStatus;
conver.receivedTime = conver.latestMessage.receiveTime;
conver.sentStatus = conver.latestMessage.sentStatus;
conver.sentTime = conver.latestMessage.sentTime;
var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId);
if (mentioneds) {
var info = JSON.parse(mentioneds);
conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId];
}
if (!isUseReplace) {
if (RongIMLib.RongUtil.supportLocalStorage()) {
var count = RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + tempConver.type + tempConver.userId);
conver.unreadMessageCount = Number(count);
}
else {
conver.unreadMessageCount = 0;
}
}
// if (conver.conversationType == ConversationType.PRIVATE) {
// self.getUserInfo(tempConver.userId, <ResultCallback<UserInfo>>{
// onSuccess: function(info: UserInfo) {
// conver.conversationTitle = info.name;
// conver.senderUserName = info.name;
// conver.senderUserId = info.userId;
// conver.senderPortraitUri = info.portraitUri;
// },
// onError: function(error: ErrorCode) { }
// });
// } else
if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) {
self.getDiscussion(tempConver.userId, {
onSuccess: function (info) {
conver.conversationTitle = info.name;
},
onError: function (error) { }
});
}
RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } });
},
onError: function (error) { }
});
};
RongIMClient.prototype.sortConversationList = function (conversationList) {
var convers = [];
for (var i = 0, len = conversationList.length; i < len; i++) {
if (!conversationList[i]) {
continue;
}
if (conversationList[i].isTop) {
convers.push(conversationList[i]);
conversationList.splice(i, 1);
continue;
}
for (var j = 0; j < len - i - 1; j++) {
if (conversationList[j].sentTime < conversationList[j + 1].sentTime) {
var swap = conversationList[j];
conversationList[j] = conversationList[j + 1];
conversationList[j + 1] = swap;
}
}
}
return RongIMClient._memoryStore.conversationList = convers.concat(conversationList);
};
RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) {
RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments);
var me = this;
RongIMClient._dataAccessProvider.getConversationList({
onSuccess: function (data) {
if (conversationTypes || RongIMClient._dataAccessProvider) {
setTimeout(function () {
callback.onSuccess(data);
});
}
else {
setTimeout(function () {
callback.onSuccess(RongIMClient._memoryStore.conversationList);
});
}
},
onError: function (error) {
setTimeout(function () {
callback.onError(error);
});
}
}, conversationTypes, count, isGetHiddenConvers);
};
RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) {
RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments);
RongIMClient._dataAccessProvider.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers);
};
RongIMClient.prototype.updateConversation = function (conversation) {
return RongIMClient._dataAccessProvider.updateConversation(conversation);
};
/**
* [createConversation ๅๅปบไผ่ฏใ]
* @param {number} conversationType [ไผ่ฏ็ฑปๅ]
* @param {string} targetId [็ฎๆ Id]
* @param {string} converTitle [ไผ่ฏๆ ้ข]
* @param {boolean} islocal [ๆฏๅฆๅๆญฅๅฐๆๅกๅจ๏ผture๏ผๅๆญฅ๏ผfalse:ไธๅๆญฅ]
*/
RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments);
var conver = new RongIMLib.Conversation();
conver.targetId = targetId;
conver.conversationType = conversationType;
conver.conversationTitle = converTitle;
conver.latestMessage = {};
conver.unreadMessageCount = 0;
return conver;
};
//TODO ๅ ้คๆฌๅฐๅๆๅกๅจใๅ ้คๆฌๅฐๅๆๅกๅจๅๅผ
RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments);
RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, callback);
};
RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments);
RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden);
};
RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments);
RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, {
onSuccess: function (bool) {
setTimeout(function () {
callback.onSuccess(bool);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
});
};
// #endregion Conversation
// #region Notifications
/**
* [getConversationNotificationStatus ่ทๅๆๅฎ็จๆทๅไผ่ฏ็ฑปๅๅ
ๆ้ใ]
* @param {ConversationType} conversationType [ไผ่ฏ็ฑปๅ]
* @param {string} targetId [็ฎๆ Id]
* @param {ResultCallback<ConversationNotificationStatus>} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) {
var params = {
conversationType: conversationType,
targetId: targetId
};
RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, callback);
};
/**
* [setConversationNotificationStatus ่ฎพ็ฝฎๆๅฎ็จๆทๅไผ่ฏ็ฑปๅๅ
ๆ้ใ]
* @param {ConversationType} conversationType [ไผ่ฏ็ฑปๅ]
* @param {string} targetId [็ฎๆ Id]
* @param {ResultCallback<ConversationNotificationStatus>} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) {
var params = {
conversationType: conversationType,
targetId: targetId,
status: status
};
RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, callback);
};
/**
* [getNotificationQuietHours ่ทๅๅ
ๆ้ๆถๆฏๆถ้ดใ]
* @param {GetNotificationQuietHoursCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.getNotificationQuietHours = function (callback) {
throw new Error("Not implemented yet");
};
/**
* [removeNotificationQuietHours ็งป้คๅ
ๆ้ๆถๆฏๆถ้ดใ]
* @param {GetNotificationQuietHoursCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.removeNotificationQuietHours = function (callback) {
throw new Error("Not implemented yet");
};
/**
* [setNotificationQuietHours ่ฎพ็ฝฎๅ
ๆ้ๆถๆฏๆถ้ดใ]
* @param {GetNotificationQuietHoursCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) {
throw new Error("Not implemented yet");
};
// #endregion Notifications
// #region Discussion
/**
* [addMemberToDiscussion ๅ ๅ
ฅ่ฎจ่ฎบ็ป]
* @param {string} discussionId [่ฎจ่ฎบ็ปId]
* @param {string[]} userIdList [่ฎจ่ฎบไธญๆๅ]
* @param {OperationCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) {
RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments);
RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, callback);
};
/**
* [createDiscussion ๅๅปบ่ฎจ่ฎบ็ป]
* @param {string} name [่ฎจ่ฎบ็ปๅ็งฐ]
* @param {string[]} userIdList [่ฎจ่ฎบ็ปๆๅ]
* @param {CreateDiscussionCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) {
RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments);
RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback);
};
/**
* [getDiscussion ่ทๅ่ฎจ่ฎบ็ปไฟกๆฏ]
* @param {string} discussionId [่ฎจ่ฎบ็ปId]
* @param {ResultCallback<Discussion>} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.getDiscussion = function (discussionId, callback) {
RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments);
RongIMClient._dataAccessProvider.getDiscussion(discussionId, callback);
};
/**
* [quitDiscussion ้ๅบ่ฎจ่ฎบ็ป]
* @param {string} discussionId [่ฎจ่ฎบ็ปId]
* @param {OperationCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.quitDiscussion = function (discussionId, callback) {
RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments);
RongIMClient._dataAccessProvider.quitDiscussion(discussionId, callback);
};
/**
* [removeMemberFromDiscussion ๅฐๆๅฎๆๅ็งป้ค่ฎจ่ฎบ็ง]
* @param {string} discussionId [่ฎจ่ฎบ็ปId]
* @param {string} userId [่ขซ็งป้ค็็จๆทId]
* @param {OperationCallback} callback [่ฟๅๅผ๏ผๅๆฐๅ่ฐ]
*/
RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) {
RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments);
RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, callback);
};
/**
* [setDiscussionInviteStatus ่ฎพ็ฝฎ่ฎจ่ฎบ็ป้่ฏท็ถๆ]
* @param {string} discussionId [่ฎจ่ฎบ็ปId]
* @param {DiscussionInviteStatus} status [้่ฏท็ถๆ]
* @param {OperationCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) {
RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments);
RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, callback);
};
/**
* [setDiscussionName ่ฎพ็ฝฎ่ฎจ่ฎบ็ปๅ็งฐ]
* @param {string} discussionId [่ฎจ่ฎบ็ปId]
* @param {string} name [่ฎจ่ฎบ็ปๅ็งฐ]
* @param {OperationCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) {
RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments);
RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, callback);
};
// #endregion Discussion
// #region ChatRoom
/**
* [ๅ ๅ
ฅ่ๅคฉๅฎคใ]
* @param {string} chatroomId [่ๅคฉๅฎคId]
* @param {number} messageCount [ๆๅๆถๆฏๆฐ้๏ผ-1ไธบไธๆๅปๆถๆฏ]
* @param {OperationCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) {
RongIMLib.CheckParam.getInstance().check(["string|number", "number", "object"], "joinChatRoom", false, arguments);
if (chatroomId == "") {
setTimeout(function () {
callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL);
});
return;
}
RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, callback);
};
RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) {
RongIMLib.CheckParam.getInstance().check(["string|number", "number"], "setChatroomHisMessageTimestamp", false, arguments);
RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp);
};
RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) {
RongIMLib.CheckParam.getInstance().check(["string|number", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments);
RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, callback);
};
RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) {
RongIMLib.CheckParam.getInstance().check(["string|number", "number", "number", "object"], "getChatRoomInfo", false, arguments);
RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, callback);
};
/**
* [้ๅบ่ๅคฉๅฎค]
* @param {string} chatroomId [่ๅคฉๅฎคId]
* @param {OperationCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) {
RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "quitChatRoom", false, arguments);
RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, callback);
};
// #endregion ChatRoom
// #region Public Service
RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) {
if (RongIMClient._memoryStore.depend.openMp) {
var modules = new RongIMClient.Protobuf.PullMpInput(), self = this;
if (!pullMessageTime) {
modules.setTime(0);
}
else {
modules.setTime(pullMessageTime);
}
modules.setMpid("");
RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, {
onSuccess: function (data) {
//TODO ๆพๅบๆๅคงๆถ้ด
// self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime));
RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0;
RongIMClient._memoryStore.publicServiceMap.publicServiceList = data;
callback.onSuccess(data);
},
onError: function () { }
}, "PullMpOutput");
}
};
/**
* [getPublicServiceList ]่ทๅๆฌๅฐ็ๅ
ฌๅ
ฑ่ดฆๅทๅ่กจ
* @param {ResultCallback<PublicServiceProfile[]>} callback [่ฟๅๅผ๏ผๅๆฐๅ่ฐ]
*/
RongIMClient.prototype.getPublicServiceList = function (callback) {
if (RongIMClient._memoryStore.depend.openMp) {
RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments);
this.getRemotePublicServiceList(callback);
}
};
/**
* [getPublicServiceProfile ] ่ทๅๆๅ
ฌๅ
ฑๆๅกไฟกๆฏใ
* @param {PublicServiceType} publicServiceType [ๅ
ฌไผๆๅก็ฑปๅใ]
* @param {string} publicServiceId [ๅ
ฌๅ
ฑๆๅก Idใ]
* @param {ResultCallback<PublicServiceProfile>} callback [ๅ
ฌๅ
ฑ่ดฆๅทไฟกๆฏๅ่ฐใ]
*/
RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) {
if (RongIMClient._memoryStore.depend.openMp) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments);
var profile = RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId);
callback.onSuccess(profile);
}
};
/**
* [pottingPublicSearchType ] ๅ
ฌไผๅฅฝๆฅ่ฏข็ฑปๅ
* @param {number} bussinessType [ 0-all 1-mp 2-mc]
* @param {number} searchType [0-exact 1-fuzzy]
*/
RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) {
if (RongIMClient._memoryStore.depend.openMp) {
var bits = 0;
if (bussinessType == 0) {
bits |= 3;
if (searchType == 0) {
bits |= 12;
}
else {
bits |= 48;
}
}
else if (bussinessType == 1) {
bits |= 1;
if (searchType == 0) {
bits |= 8;
}
else {
bits |= 32;
}
}
else {
bits |= 2;
if (bussinessType == 0) {
bits |= 4;
}
else {
bits |= 16;
}
}
return bits;
}
};
/**
* [searchPublicService ]ๆๅ
ฌไผๆๅก็ฑปๅๆ็ดขๅ
ฌไผๆๅกใ
* @param {SearchType} searchType [ๆ็ดข็ฑปๅๆไธพใ]
* @param {string} keywords [ๆ็ดขๅ
ณ้ฎๅญใ]
* @param {ResultCallback<PublicServiceProfile[]>} callback [ๆ็ดข็ปๆๅ่ฐใ]
*/
RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) {
if (RongIMClient._memoryStore.depend.openMp) {
RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments);
var modules = new RongIMClient.Protobuf.SearchMpInput();
modules.setType(this.pottingPublicSearchType(0, searchType));
modules.setId(keywords);
RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, callback, "SearchMpOutput");
}
};
/**
* [searchPublicServiceByType ]ๆๅ
ฌไผๆๅก็ฑปๅๆ็ดขๅ
ฌไผๆๅกใ
* @param {PublicServiceType} publicServiceType [ๅ
ฌไผๆๅก็ฑปๅใ]
* @param {SearchType} searchType [ๆ็ดข็ฑปๅๆไธพใ]
* @param {string} keywords [ๆ็ดขๅ
ณ้ฎๅญใ]
* @param {ResultCallback<PublicServiceProfile[]>} callback [ๆ็ดข็ปๆๅ่ฐใ]
*/
RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) {
if (RongIMClient._memoryStore.depend.openMp) {
RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments);
var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1;
var modules = new RongIMClient.Protobuf.SearchMpInput();
modules.setType(this.pottingPublicSearchType(type, searchType));
modules.setId(keywords);
RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, callback, "SearchMpOutput");
}
};
/**
* [subscribePublicService ] ่ฎข้
ๅ
ฌไผๅทใ
* @param {PublicServiceType} publicServiceType [ๅ
ฌไผๆๅก็ฑปๅใ]
* @param {string} publicServiceId [ๅ
ฌๅ
ฑๆๅก Idใ]
* @param {OperationCallback} callback [่ฎข้
ๅ
ฌไผๅทๅ่ฐใ]
*/
RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) {
if (RongIMClient._memoryStore.depend.openMp) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments);
var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow";
modules.setId(publicServiceId);
RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, {
onSuccess: function () {
me.getRemotePublicServiceList({
onSuccess: function () { },
onError: function () { }
});
callback.onSuccess();
},
onError: function (code) {
callback.onError(code);
}
}, "MPFollowOutput");
}
};
/**
* [unsubscribePublicService ] ๅๆถ่ฎข้
ๅ
ฌไผๅทใ
* @param {PublicServiceType} publicServiceType [ๅ
ฌไผๆๅก็ฑปๅใ]
* @param {string} publicServiceId [ๅ
ฌๅ
ฑๆๅก Idใ]
* @param {OperationCallback} callback [ๅๆถ่ฎข้
ๅ
ฌไผๅทๅ่ฐใ]
*/
RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) {
if (RongIMClient._memoryStore.depend.openMp) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments);
var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow";
modules.setId(publicServiceId);
RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, {
onSuccess: function () {
RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId);
callback.onSuccess();
},
onError: function (code) {
callback.onError(code);
}
}, "MPFollowOutput");
}
};
// #endregion Public Service
// #region Blacklist
/**
* [ๅ ๅ
ฅ้ปๅๅ]
* @param {string} userId [ๅฐ่ขซๅ ๅ
ฅ้ปๅๅ็็จๆทId]
* @param {OperationCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.addToBlacklist = function (userId, callback) {
RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments);
RongIMClient._dataAccessProvider.addToBlacklist(userId, callback);
};
/**
* [่ทๅ้ปๅๅๅ่กจ]
* @param {GetBlacklistCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.getBlacklist = function (callback) {
RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments);
RongIMClient._dataAccessProvider.getBlacklist(callback);
};
/**
* [ๅพๅฐๆๅฎไบบๅๅ้ปๅๅไธญ็็ถๆ]
* @param {string} userId [description]
* @param {ResultCallback<BlacklistStatus>} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
//TODO ๅฆๆไบบๅไธๅจ้ปๅๅไธญ๏ผ่ทๅ็ถๆไผๅบ็ฐๅผๅธธ
RongIMClient.prototype.getBlacklistStatus = function (userId, callback) {
RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments);
RongIMClient._dataAccessProvider.getBlacklistStatus(userId, callback);
};
/**
* [ๅฐๆๅฎ็จๆท็งป้ค้ปๅๅ]
* @param {string} userId [ๅฐ่ขซ็งป้ค็็จๆทId]
* @param {OperationCallback} callback [่ฟๅๅผ๏ผๅฝๆฐๅ่ฐ]
*/
RongIMClient.prototype.removeFromBlacklist = function (userId, callback) {
RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments);
RongIMClient._dataAccessProvider.removeFromBlacklist(userId, callback);
};
RongIMClient.prototype.getFileToken = function (fileType, callback) {
RongIMLib.CheckParam.getInstance().check(["number", "object"], "getQnTkn", false, arguments);
RongIMClient._dataAccessProvider.getFileToken(fileType, callback);
};
RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback) {
RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object"], "getQnTkn", false, arguments);
RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, callback);
};
;
// #endregion Blacklist
// #region Real-time Location Service
RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) {
throw new Error("Not implemented yet");
};
RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) {
throw new Error("Not implemented yet");
};
RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) {
throw new Error("Not implemented yet");
};
RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) {
throw new Error("Not implemented yet");
};
RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) {
throw new Error("Not implemented yet");
};
RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) {
throw new Error("Not implemented yet");
};
RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) {
throw new Error("Not implemented yet");
};
RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) {
throw new Error("Not implemented yet");
};
// #endregion Real-time Location Service
// # startVoIP
RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) {
RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments);
if (RongIMClient._memoryStore.voipStategy) {
RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, callback);
}
else {
callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE);
}
};
RongIMClient.prototype.joinCall = function (mediaType, callback) {
RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments);
if (RongIMClient._memoryStore.voipStategy) {
RongIMClient._voipProvider.joinCall(mediaType, callback);
}
else {
callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE);
}
};
RongIMClient.prototype.hungupCall = function (converType, targetId, reason) {
RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments);
if (RongIMClient._memoryStore.voipStategy) {
RongIMClient._voipProvider.hungupCall(converType, targetId, reason);
}
};
RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) {
RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments);
if (RongIMClient._memoryStore.voipStategy) {
RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, callback);
}
else {
callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE);
}
};
// # endVoIP
RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) {
return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId);
};
RongIMClient.prototype.clearListeners = function () {
RongIMClient._dataAccessProvider.clearListeners();
};
// UserStatus start
RongIMClient.prototype.getUserStatus = function (userId, callback) {
RongIMClient._dataAccessProvider.getUserStatus(userId, callback);
};
RongIMClient.prototype.setUserStatus = function (status, callback) {
RongIMClient._dataAccessProvider.setUserStatus(status, callback);
};
RongIMClient.prototype.subscribeUserStatus = function (userIds, callback) {
RongIMClient._dataAccessProvider.subscribeUserStatus(userIds, callback);
};
RongIMClient.prototype.setOnReceiveStatusListener = function (callback) {
RongIMClient._dataAccessProvider.setOnReceiveStatusListener(callback);
};
RongIMClient.MessageType = {};
RongIMClient.RegisterMessage = {};
RongIMClient._memoryStore = { listenerList: [] };
RongIMClient.isNotPullMsg = false;
return RongIMClient;
})();
RongIMLib.RongIMClient = RongIMClient;
})(RongIMLib || (RongIMLib = {}));
//็จไบ่ฟๆฅ้้
var RongIMLib;
(function (RongIMLib) {
(function (Qos) {
Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE";
Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE";
Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE";
Qos[Qos["DEFAULT"] = 3] = "DEFAULT";
})(RongIMLib.Qos || (RongIMLib.Qos = {}));
var Qos = RongIMLib.Qos;
(function (Type) {
Type[Type["CONNECT"] = 1] = "CONNECT";
Type[Type["CONNACK"] = 2] = "CONNACK";
Type[Type["PUBLISH"] = 3] = "PUBLISH";
Type[Type["PUBACK"] = 4] = "PUBACK";
Type[Type["QUERY"] = 5] = "QUERY";
Type[Type["QUERYACK"] = 6] = "QUERYACK";
Type[Type["QUERYCON"] = 7] = "QUERYCON";
Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE";
Type[Type["SUBACK"] = 9] = "SUBACK";
Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE";
Type[Type["UNSUBACK"] = 11] = "UNSUBACK";
Type[Type["PINGREQ"] = 12] = "PINGREQ";
Type[Type["PINGRESP"] = 13] = "PINGRESP";
Type[Type["DISCONNECT"] = 14] = "DISCONNECT";
})(RongIMLib.Type || (RongIMLib.Type = {}));
var Type = RongIMLib.Type;
var _topic = ["invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz",
["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm",
"createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg"];
var Channel = (function () {
function Channel(address, cb, self) {
this.connectionStatus = -1;
this.delOnChangedCount = 0;
this.url = address.host + "/websocket?appId=" + self.appId + "&token=" + encodeURIComponent(self.token) + "&sdkVer=" + self.sdkVer + "&apiVer=" + self.apiVer;
this.self = self;
this.socket = Socket.getInstance().createServer();
this.socket.connect(this.url, cb);
//ๆณจๅ็ถๆๆนๅ่งๅฏ่
if (typeof Channel._ConnectionStatusListener == "object" && "onChanged" in Channel._ConnectionStatusListener) {
var me = this;
me.socket.on("StatusChanged", function (code) {
me.connectionStatus = code;
if (code === RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE) {
var temp = RongIMLib.RongIMClient._storageProvider.getItemKey("navi");
var naviServer = RongIMLib.RongIMClient._storageProvider.getItem(temp);
var naviPort = naviServer.split(",")[0].split(":")[1];
naviPort && naviPort.length < 4 || RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", "");
// TODO ๅคๆญๆๅ naviServer ๅ็ๆฐ็ป้ฟๅบฆใ
if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && naviPort && naviPort.length < 4) {
Bridge._client.handler.connectCallback.pauseTimer();
var temp = RongIMLib.RongIMClient._storageProvider.getItemKey("navi");
var server = RongIMLib.RongIMClient._storageProvider.getItem("RongBackupServer");
if (server) {
var arrs = server.split(",");
if (arrs.length < 2) {
throw new Error("navi server is empty,postion:StatusChanged");
}
RongIMLib.RongIMClient._storageProvider.setItem(temp, RongIMLib.RongIMClient._storageProvider.getItem("RongBackupServer"));
var url = RongIMLib.Bridge._client.channel.socket.currentURL;
Bridge._client.channel.socket.currentURL = arrs[0] + url.substring(url.indexOf("/"), url.length);
if (Bridge._client.channel && Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) {
RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback);
}
}
}
}
if (code === RongIMLib.ConnectionStatus.DISCONNECTED && !RongIMLib.RongIMClient._memoryStore.otherDevice) {
Channel._ConnectionStatusListener.onChanged(RongIMLib.ConnectionStatus.DISCONNECTED);
self.clearHeartbeat();
return;
}
else if (code === RongIMLib.ConnectionStatus.DISCONNECTED && RongIMLib.RongIMClient._memoryStore.otherDevice) {
return;
}
Channel._ConnectionStatusListener.onChanged(code);
if (RongIMLib.RongIMClient._memoryStore.otherDevice) {
if (me.delOnChangedCount > 5) {
delete Channel._ConnectionStatusListener["onChanged"];
}
me.delOnChangedCount++;
}
});
}
else {
throw new Error("setConnectStatusListener:Parameter format is incorrect");
}
//ๆณจๅmessage่งๅฏ่
this.socket.on("message", self.handler.handleMessage);
//ๆณจๅๆญๅผ่ฟๆฅ่งๅฏ่
this.socket.on("disconnect", function (status) {
self.channel.socket.fire("StatusChanged", status ? status : 2);
});
}
Channel.prototype.writeAndFlush = function (val) {
this.socket.send(val);
};
Channel.prototype.reconnect = function (callback) {
RongIMLib.MessageIdHandler.clearMessageId();
this.socket = this.socket.reconnect();
if (callback) {
this.self.reconnectObj = callback;
}
};
Channel.prototype.disconnect = function (status) {
this.socket.disconnect(status);
};
return Channel;
})();
RongIMLib.Channel = Channel;
var Socket = (function () {
function Socket() {
this.socket = null;
this._events = {};
}
Socket.getInstance = function () {
return new Socket();
};
Socket.prototype.connect = function (url, cb) {
if (this.socket) {
if (url) {
RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport());
this.on("connect", cb || new Function);
}
if (url) {
this.currentURL = url;
}
this.socket.createTransport(url);
}
return this;
};
Socket.prototype.createServer = function () {
var transport = this.getTransport(this.checkTransport());
if (transport === null) {
throw new Error("the channel was not supported");
}
return transport;
};
Socket.prototype.getTransport = function (transportType) {
if (transportType == Socket.XHR_POLLING) {
this.socket = new RongIMLib.PollingTransportation(this);
}
else if (transportType == Socket.WEBSOCKET) {
this.socket = new RongIMLib.SocketTransportation(this);
}
return this;
};
Socket.prototype.send = function (data) {
if (this.socket) {
if (this.checkTransport() == Socket.WEBSOCKET) {
this.socket.send(data);
}
else {
this.socket.send(this._encode(data));
}
}
};
Socket.prototype.onMessage = function (data) {
this.fire("message", data);
};
Socket.prototype.disconnect = function (status) {
if (RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT === status) {
RongIMLib.RongIMClient._memoryStore.otherDevice = true;
}
this.socket.disconnect(status);
this.fire("disconnect", status);
return this;
};
Socket.prototype.reconnect = function () {
if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) {
return this.connect(this.currentURL, null);
}
else {
throw new Error("reconnect:no have URL");
}
};
/**
* [checkTransport ่ฟๅ้้็ฑปๅ]
*/
Socket.prototype.checkTransport = function () {
if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) {
RongIMLib.Transportations._TransportType = Socket.XHR_POLLING;
}
return RongIMLib.Transportations._TransportType;
};
Socket.prototype.fire = function (x, args) {
if (x in this._events) {
for (var i = 0, ii = this._events[x].length; i < ii; i++) {
this._events[x][i](args);
}
}
return this;
};
Socket.prototype.on = function (x, func) {
if (!(typeof func == "function" && x)) {
return this;
}
if (x in this._events) {
RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func);
}
else {
this._events[x] = [func];
}
return this;
};
Socket.prototype.removeEvent = function (x, fn) {
if (x in this._events) {
for (var a = 0, l = this._events[x].length; a < l; a++) {
if (this._events[x][a] == fn) {
this._events[x].splice(a, 1);
}
}
}
return this;
};
Socket.prototype._encode = function (x) {
var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId);
if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) {
str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || "");
}
return {
url: str,
data: "getData" in x ? x.getData() : ""
};
};
//ๆถๆฏ้้ๅธธ้๏ผๆๆๅ้้็ธๅ
ณๅคๆญๅ็จ XHR_POLLING WEBSOCKETไธคๅฑๆง
Socket.XHR_POLLING = "xhr-polling";
Socket.WEBSOCKET = "websocket";
return Socket;
})();
RongIMLib.Socket = Socket;
//่ฟๆฅ็ซฏๆถๆฏ็ดฏ
var Client = (function () {
function Client(token, appId) {
this.timeoutMillis = 100000;
this.timeout_ = 0;
this.sdkVer = "2.2.7";
this.apiVer = Math.floor(Math.random() * 1e6);
this.channel = null;
this.handler = null;
this.userId = "";
this.reconnectObj = {};
this.heartbeat = 0;
this.pullMsgHearbeat = 0;
this.chatroomId = "";
this.SyncTimeQueue = [];
this.cacheMessageIds = [];
this.token = token;
this.appId = appId;
this.SyncTimeQueue.state = "complete";
}
Client.prototype.resumeTimer = function () {
if (!this.timeout_) {
this.timeout_ = setTimeout(function () {
if (!this.timeout_) {
return;
}
try {
this.channel.disconnect();
}
catch (e) {
throw new Error(e);
}
clearTimeout(this.timeout_);
this.timeout_ = 0;
this.channel.reconnect();
this.channel.socket.fire("StatusChanged", 5);
}, this.timeoutMillis);
}
};
Client.prototype.pauseTimer = function () {
if (this.timeout_) {
clearTimeout(this.timeout_);
this.timeout_ = 0;
}
};
Client.prototype.connect = function (_callback) {
if (RongIMLib.Navigation.Endpoint.host) {
if (RongIMLib.Transportations._TransportType == Socket.WEBSOCKET) {
if (!window.WebSocket) {
_callback.onError(RongIMLib.ConnectionState.UNACCEPTABLE_PROTOCOL_VERSION);
return;
}
}
//ๅฎไพๆถๆฏๅค็็ฑป
this.handler = new MessageHandler(this);
//่ฎพ็ฝฎ่ฟๆฅๅ่ฐ
this.handler.setConnectCallback(_callback);
//ๅฎไพ้้็ฑปๅ
var me = this;
this.channel = new Channel(RongIMLib.Navigation.Endpoint, function () {
RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive();
}, this);
//่งฆๅ็ถๆๆนๅ่งๅฏ่
this.channel.socket.fire("StatusChanged", 1);
}
else {
//ๆฒกๆ่ฟๅๅฐๅๅฐฑๆๅจๆๅบ้่ฏฏ
_callback.onError(RongIMLib.ConnectionState.NOT_AUTHORIZED);
}
};
Client.prototype.checkSocket = function (callback) {
var me = this;
me.channel.writeAndFlush(new RongIMLib.PingReqMessage());
var checkTimeout = setInterval(function () {
if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) {
callback.onSuccess();
clearInterval(checkTimeout);
}
else {
if (count > 15) {
clearInterval(checkTimeout);
callback.onError();
}
}
count++;
}, 200), count = 0;
};
Client.prototype.keepLive = function () {
if (this.heartbeat > 0) {
clearInterval(this.heartbeat);
}
var me = this;
me.heartbeat = setInterval(function () {
me.resumeTimer();
me.channel.writeAndFlush(new RongIMLib.PingReqMessage());
}, 30000);
if (me.pullMsgHearbeat > 0) {
clearInterval(me.pullMsgHearbeat);
}
me.pullMsgHearbeat = setInterval(function () {
me.syncTime(true, undefined, undefined, false);
}, 180000);
};
Client.prototype.clearHeartbeat = function () {
clearInterval(this.heartbeat);
this.heartbeat = 0;
this.pauseTimer();
clearInterval(this.pullMsgHearbeat);
this.pullMsgHearbeat = 0;
};
Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg) {
var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect);
if (!msgId) {
return;
}
var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId);
msg.setMessageId(msgId);
if (_callback) {
msg.setQos(Qos.AT_LEAST_ONCE);
this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg);
}
else {
msg.setQos(Qos.AT_MOST_ONCE);
}
this.channel.writeAndFlush(msg);
};
Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) {
if (_topic == "userInf") {
if (Client.userInfoMapping[_targetId]) {
_callback.onSuccess(Client.userInfoMapping[_targetId]);
return;
}
}
var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect);
if (!msgId) {
return;
}
var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId);
msg.setMessageId(msgId);
msg.setQos(_qos);
this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype);
this.channel.writeAndFlush(msg);
};
Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) {
var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift();
if (temp == undefined) {
return;
}
this.SyncTimeQueue.state = "pending";
if (temp.type != 2) {
//ๆฎ้ๆถๆฏ
time = RongIMLib.RongIMClient._storageProvider.getItem(this.userId) || '0';
modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg();
modules.setIspolling(false);
str = "pullMsg";
target = this.userId;
}
else {
//่ๅคฉๅฎคๆถๆฏ
target = chrmId || me.chatroomId;
time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0;
modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg();
modules.setCount(0);
str = "chrmPull";
if (!target) {
throw new Error("syncTime:Received messages of chatroom but was not init");
}
}
//ๅคๆญๆๅกๅจ็ป็ๆถ้ดๆฏๅฆๆถๆฏๆฌๅฐๅญๅจ็ๆถ้ด๏ผๅฐไบ็่ฏไธๆง่กๆๅๆไฝ๏ผ่ฟ่กไธไธๆญฅ้ๅๆไฝ
if (temp.pulltime <= time) {
this.SyncTimeQueue.state = "complete";
this.invoke(isPullMsg, target);
return;
}
if (isPullMsg && 'setIsPullSend' in modules) {
modules.setIsPullSend(true);
}
modules.setSyncTime(time);
//ๅ้queryMessage่ฏทๆฑ
this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, {
onSuccess: function (collection) {
var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target;
//ๆ่ฟๅๆถ้ดๆณๅญๅ
ฅๆฌๅฐ๏ผๆฎ้ๆถๆฏkeyไธบuserid๏ผ่ๅคฉๅฎคๆถๆฏkeyไธบuserid๏ผ'CST'๏ผvalue้ฝไธบๆๅกๅจ่ฟๅ็ๆถ้ดๆณ
if (str == "chrmPull") {
symbol += Bridge._client.userId + "CST";
RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync);
}
else {
var storage = RongIMLib.RongIMClient._storageProvider;
if (sync > storage.getItem(symbol)) {
storage.setItem(symbol, sync);
}
}
//้ฒๆญขๅ ็ฆป็บฟๆถๆฏ้ ๆไผ่ฏๅ่กจไธไธบ็ฉบ่ๆ ๆณไปๆๅกๅจๆๅไผ่ฏๅ่กจใ
//offlineMsg && (RongIMClient._memoryStore.isSyncRemoteConverList = true);
me.SyncTimeQueue.state = "complete";
me.invoke(isPullMsg, target);
//ๆๆๅๅฐ็ๆถๆฏ้ๆกไผ ็ปๆถๆฏ็ๅฌๅจ
var list = collection.list;
for (var i = 0, len = list.length, count = len; i < len; i++) {
if (!(list[i].msgId in me.cacheMessageIds)) {
Bridge._client.handler.onReceived(list[i], undefined, offlineMsg, --count);
var arrLen = me.cacheMessageIds.unshift(list[i].msgId);
if (arrLen > 20)
me.cacheMessageIds.length = 20;
}
}
},
onError: function (error) {
me.SyncTimeQueue.state = "complete";
me.invoke(isPullMsg, target);
}
}, "DownStreamMessages");
};
Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) {
this.SyncTimeQueue.push({ type: _type, pulltime: pullTime });
//ๅฆๆ้ๅไธญๅชๆไธไธชๆๅๅนถไธ็ถๆๅทฒ็ปๅฎๆๅฐฑๆง่กinvokeๆนๆณ
if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") {
this.invoke(!_type, chrmId, offlineMsg);
}
};
Client.prototype.__init = function (f) {
this.channel = new Channel(RongIMLib.Navigation.Endpoint, f, this);
};
Client.userInfoMapping = {};
return Client;
})();
RongIMLib.Client = Client;
//่ฟๆฅ็ฑป๏ผๅฎ็ฐimclientไธconnect_client็่ฟๆฅ
var Bridge = (function () {
function Bridge() {
}
Bridge.getInstance = function () {
return new Bridge();
};
//่ฟๆฅๆๅกๅจ
Bridge.prototype.connect = function (appKey, token, callback) {
if (!RongIMLib.RongIMClient.Protobuf) {
return;
}
Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback);
return Bridge._client;
};
Bridge.prototype.setListener = function (_changer) {
if (typeof _changer == "object") {
if (typeof _changer.onChanged == "function") {
Channel._ConnectionStatusListener = _changer;
}
else if (typeof _changer.onReceived == "function") {
Channel._ReceiveMessageListener = _changer;
}
}
};
Bridge.prototype.reconnect = function (callabck) {
Bridge._client.channel.reconnect(callabck);
};
Bridge.prototype.disconnect = function () {
Bridge._client.clearHeartbeat();
Bridge._client.channel.disconnect(2);
};
//ๆง่กqueryMessage่ฏทๆฑ
Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) {
if (typeof topic != "string") {
topic = _topic[topic];
}
Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname);
};
//ๅ้ๆถๆฏ ๆง่กpublishMessage ่ฏทๆฑ
Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType) {
if (typeof methodType == 'number') {
if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) {
Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg);
}
else if (methodType == RongIMLib.MethodType.RECALL) {
Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg);
}
}
else {
Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg);
}
};
return Bridge;
})();
RongIMLib.Bridge = Bridge;
var MessageHandler = (function () {
function MessageHandler(client) {
this.map = {};
this.connectCallback = null;
if (!Channel._ReceiveMessageListener) {
throw new Error("please set onReceiveMessageListener");
}
this._onReceived = Channel._ReceiveMessageListener.onReceived;
this._client = client;
this.syncMsgMap = new Object;
}
//ๆๅฏน่ฑกๆจๅ
ฅๅ่ฐๅฏน่ฑก้ๅไธญ๏ผๅนถๅฏๅจๅฎๆถๅจ
MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) {
var item = {
Callback: callbackObj,
Message: _msg
};
item.Callback.resumeTimer();
this.map[_publishMessageId] = item;
};
//่ฎพ็ฝฎ่ฟๆฅๅ่ฐๅฏน่ฑก๏ผๅฏๅจๅฎๆถๅจ
MessageHandler.prototype.setConnectCallback = function (_connectCallback) {
if (_connectCallback) {
this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client);
this.connectCallback.resumeTimer();
}
};
MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount) {
//ๅฎไฝๅฏน่ฑก
var entity,
//่งฃๆๅฎๆ็ๆถๆฏๅฏน่ฑก
message,
//ไผ่ฏๅฏน่ฑก
con;
if (msg._name != "PublishMessage") {
entity = msg;
RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime));
}
else {
if (msg.getTopic() == "s_ntf") {
entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData());
this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId);
return;
}
else if (msg.getTopic() == "s_msg") {
entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData());
var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime);
RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp);
RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp);
}
else {
if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") {
return;
}
entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData());
var tmpTopic = msg.getTopic();
var tmpType = tmpTopic.substr(0, 2);
if (tmpType == "pp") {
entity.type = 1;
}
else if (tmpType == "pd") {
entity.type = 2;
}
else if (tmpType == "pg") {
entity.type = 3;
}
else if (tmpType == "ch") {
entity.type = 4;
}
else if (tmpType == "pc") {
entity.type = 5;
}
//ๅค็จๅญๆฎต๏ผtargetId ไปฅๆญคไธบๅ
entity.groupId = msg.getTargetId();
entity.fromUserId = this._client.userId;
entity.dataTime = Date.parse(new Date().toString());
}
if (!entity) {
return;
}
}
//่งฃๆๅฎไฝๅฏน่ฑกไธบๆถๆฏๅฏน่ฑกใ
message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg);
if (pubAckItem) {
message.messageUId = pubAckItem.getMessageUId();
message.sentTime = pubAckItem.getTimestamp();
}
if (message === null) {
return;
}
// ่ฎพ็ฝฎไผ่ฏๆถ้ดๆณๅนถไธๅคๆญๆฏๅฆไผ ้ message ๅ้ๆถๆฏๆชๅค็ไผ่ฏๆถ้ดๆณ
// key๏ผ'converST_' + ๅฝๅ็จๆท + conversationType + targetId
// RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime);
var stKey = 'converST_' + Bridge._client.userId + message.conversationType + message.targetId;
var stValue = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(stKey);
if (stValue) {
if (message.sentTime > stValue) {
RongIMLib.RongIMClient._memoryStore.lastReadTime.set(stKey, message.sentTime);
}
else {
return;
}
}
else {
RongIMLib.RongIMClient._memoryStore.lastReadTime.set(stKey, message.sentTime);
}
if (RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag() > 0) {
RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, {
onSuccess: function (con) {
if (!con) {
con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, "");
}
if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) {
var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId);
var key = message.conversationType + '_' + message.targetId, info = {};
if (message.content && message.content.mentionedInfo) {
info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo };
RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info));
mentioneds = JSON.stringify(info);
}
if (mentioneds) {
var info = JSON.parse(mentioneds);
con.mentionedMsg = info[key];
}
}
if (con.conversationType != 0 && message.senderUserId != Bridge._client.userId && message.receivedStatus != RongIMLib.ReceivedStatus.RETRIEVED && message.messageType != RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && message.messageType != RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) {
con.unreadMessageCount = con.unreadMessageCount + 1;
if (RongIMLib.RongUtil.supportLocalStorage()) {
var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // ไธๆฌๅฐๅญๅจไผ่ฏๅๅนถ
RongIMLib.RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, Number(count) + 1);
}
}
con.receivedTime = new Date().getTime();
con.receivedStatus = message.receivedStatus;
con.senderUserId = message.sendUserId;
con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB;
con.latestMessageId = message.messageId;
con.latestMessage = message;
con.sentTime = message.sentTime;
RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { }, onError: function () { } });
},
onError: function (error) { }
});
}
if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" ||
message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) {
if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) {
return;
}
}
if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") {
if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) {
return;
}
if (message.messageType == "TerminateMessage") {
if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) {
return;
}
}
}
if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) {
var session = message.content.data;
RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session;
if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) {
if (session.notAutoCha == "1") {
RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, {
onSuccess: function () { },
onError: function () { }
});
}
}
}
var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate();
//new Date(date).getTime() - message.sentTime < 1 ้ป่พๅคๆญ ่ถ
่ฟ 1 ๅคฉๆชๆถ็ ReadReceiptRequestMessage ็ฆป็บฟๆถๆฏ่ชๅจๅฟฝ็ฅใ
var dealtime = new Date(date).getTime() - message.sentTime < 0;
if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) {
var sentkey = Bridge._client.userId + message.content.messageUId + "SENT";
RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} }));
}
else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) {
var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey));
if (recData) {
if (message.senderUserId in recData) {
if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) {
// ๅฆๆๆฏๅไธๅคฉ็ MessaageUId ๆๆฐ็ปๆธ
็ฉบใ
new Date(date).getTime() - recData[message.senderUserId].dealtime < 0 || (recData[message.senderUserId].uIds.length = 0);
recData[message.senderUserId].uIds.push(message.content.messageUId);
recData[message.senderUserId].dealtime = message.sentTime;
recData[message.senderUserId].isResponse = false;
RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData));
}
else {
return;
}
}
else {
var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false };
recData[message.senderUserId] = objSon;
RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData));
}
}
else {
var obj = {};
obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false };
RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj));
}
}
if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) {
var receiptResponseMsg = message.content, uIds = receiptResponseMsg.receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj;
message.receiptResponse || (message.receiptResponse = {});
if (uIds) {
var cbuIds = [];
for (var i = 0, len = uIds.length; i < len; i++) {
sentkey = Bridge._client.userId + uIds[i] + "SENT";
sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey));
if (sentObj && !(message.senderUserId in sentObj.userIds)) {
if (new Date(date).getTime() - sentObj.dealtime > 0) {
RongIMLib.RongIMClient._storageProvider.removeItem(sentkey);
}
else {
cbuIds.push(uIds[i]);
sentObj.count += 1;
sentObj.userIds[message.senderUserId] = message.sentTime;
message.receiptResponse[uIds[i]] = sentObj.count;
RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj));
}
}
}
receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds;
message.content = receiptResponseMsg;
}
}
var that = this;
if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) {
RongIMLib.RongIMClient._voipProvider.onReceived(message);
}
else {
var lcount = leftCount || 0;
RongIMLib.RongIMClient._dataAccessProvider.addMessage(message.conversationType, message.targetId, message, {
onSuccess: function (ret) {
that._onReceived(ret, lcount);
},
onError: function (error) {
that._onReceived(message, lcount);
}
});
}
};
MessageHandler.prototype.handleMessage = function (msg) {
if (!msg) {
return;
}
switch (msg._name) {
case "ConnAckMessage":
Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp());
break;
case "PublishMessage":
if (!msg.getSyncMsg() && msg.getQos() != 0) {
Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId()));
}
// TODO && ->
if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) {
Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg;
}
else {
//ๅฆๆๆฏPublishMessageๅฐฑๆ่ฏฅๅฏน่ฑก็ปonReceivedๆนๆณๆง่กๅค็
Bridge._client.handler.onReceived(msg);
}
break;
case "QueryAckMessage":
if (msg.getQos() != 0) {
Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId()));
}
var temp = Bridge._client.handler.map[msg.getMessageId()];
if (temp) {
//ๆง่กๅ่ฐๆไฝ
temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message);
delete Bridge._client.handler.map[msg.getMessageId()];
}
break;
case "PubAckMessage":
var item = Bridge._client.handler.map[msg.getMessageId()];
if (item) {
item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId());
delete Bridge._client.handler.map[msg.getMessageId()];
}
else {
Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg);
delete Bridge._client.handler.syncMsgMap[msg.getMessageId()];
}
break;
case "PingRespMessage":
if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) {
RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false;
}
else {
Bridge._client.pauseTimer();
}
break;
case "DisconnectMessage":
Bridge._client.channel.disconnect(msg.getStatus());
break;
default:
}
};
return MessageHandler;
})();
RongIMLib.MessageHandler = MessageHandler;
})(RongIMLib || (RongIMLib = {}));
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/// <reference path="../dts/helper.d.ts"/>
var RongIMLib;
(function (RongIMLib) {
var MessageCallback = (function () {
function MessageCallback(error) {
this.timeout = null;
this.onError = null;
if (error && typeof error == "number") {
this.timeoutMillis = error;
}
else {
this.timeoutMillis = 30000;
this.onError = error;
}
}
MessageCallback.prototype.resumeTimer = function () {
var me = this;
if (this.timeoutMillis > 0 && !this.timeout) {
this.timeout = setTimeout(function () {
me.readTimeOut(true);
}, this.timeoutMillis);
}
};
MessageCallback.prototype.pauseTimer = function () {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
};
MessageCallback.prototype.readTimeOut = function (isTimeout) {
if (isTimeout && this.onError) {
this.onError(RongIMLib.ErrorCode.TIMEOUT);
}
else {
this.pauseTimer();
}
};
return MessageCallback;
})();
RongIMLib.MessageCallback = MessageCallback;
var CallbackMapping = (function () {
function CallbackMapping() {
this.publicServiceList = [];
}
CallbackMapping.getInstance = function () {
return new CallbackMapping();
};
CallbackMapping.prototype.pottingProfile = function (item) {
var temp;
this.profile = new RongIMLib.PublicServiceProfile();
temp = JSON.parse(item.extra);
this.profile.isGlobal = temp.isGlobal;
this.profile.introduction = temp.introduction;
this.profile.menu = temp.menu;
this.profile.hasFollowed = temp.follow;
this.profile.publicServiceId = item.mpid;
this.profile.name = item.name;
this.profile.portraitUri = item.portraitUrl;
this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE;
this.publicServiceList.push(this.profile);
};
CallbackMapping.prototype.mapping = function (entity, tag) {
switch (tag) {
case "GetUserInfoOutput":
var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait);
return userInfo;
case "GetQNupTokenOutput":
return {
deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline),
token: entity.token
};
case "GetQNdownloadUrlOutput":
return {
downloadUrl: entity.downloadUrl
};
case "CreateDiscussionOutput":
return entity.id;
case "ChannelInfoOutput":
var disInfo = new RongIMLib.Discussion();
disInfo.creatorId = entity.adminUserId;
disInfo.id = entity.channelId;
disInfo.memberIdList = entity.firstTenUserIds;
disInfo.name = entity.channelName;
disInfo.isOpen = entity.openStatus;
return disInfo;
case "GroupHashOutput":
return entity.result;
case "QueryBlackListOutput":
return entity.userIds;
case "SearchMpOutput":
case "PullMpOutput":
if (entity.info) {
var self = this;
Array.forEach(entity.info, function (item) {
setTimeout(self.pottingProfile(item), 100);
});
}
return this.publicServiceList;
default:
return entity;
}
};
return CallbackMapping;
})();
RongIMLib.CallbackMapping = CallbackMapping;
var PublishCallback = (function (_super) {
__extends(PublishCallback, _super);
function PublishCallback(_cb, _timeout) {
_super.call(this, _timeout);
this._cb = _cb;
this._timeout = _timeout;
}
PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) {
this.readTimeOut();
if (_status == 0) {
if (_msg) {
_msg.setSentStatus = _status;
}
RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Bridge._client.userId, timestamp);
RongIMLib.RongIMClient._memoryStore.lastReadTime.get(RongIMLib.Bridge._client.userId, timestamp);
this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId });
}
else {
this._timeout(_status);
}
};
PublishCallback.prototype.readTimeOut = function (x) {
MessageCallback.prototype.readTimeOut.call(this, x);
};
return PublishCallback;
})(MessageCallback);
RongIMLib.PublishCallback = PublishCallback;
var QueryCallback = (function (_super) {
__extends(QueryCallback, _super);
function QueryCallback(_cb, _timeout) {
_super.call(this, _timeout);
this._cb = _cb;
this._timeout = _timeout;
}
QueryCallback.prototype.process = function (status, data, serverTime, pbtype) {
this.readTimeOut();
if (pbtype && data && status == 0) {
try {
data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype);
}
catch (e) {
this._timeout(RongIMLib.ErrorCode.UNKNOWN);
return;
}
if ("GetUserInfoOutput" == pbtype) {
//pb็ฑปๅไธบGetUserInfoOutput็่ฏๅฐฑๆdataๆพๅ
ฅuserinfo็ผๅญ้ๅ
RongIMLib.Client.userInfoMapping[data.userId] = data;
}
this._cb(data);
}
else {
status > 0 ? this._timeout(status) : this._cb(status);
}
};
QueryCallback.prototype.readTimeOut = function (x) {
MessageCallback.prototype.readTimeOut.call(this, x);
};
return QueryCallback;
})(MessageCallback);
RongIMLib.QueryCallback = QueryCallback;
var ConnectAck = (function (_super) {
__extends(ConnectAck, _super);
function ConnectAck(_cb, _timeout, client) {
_super.call(this, _timeout);
this._client = client;
this._cb = _cb;
this._timeout = _timeout;
}
ConnectAck.prototype.process = function (status, userId, timestamp) {
this.readTimeOut();
if (status == 0) {
if (RongIMLib.RongIMClient._memoryStore.depend.isPrivate) {
var date = new Date();
var qryOpt, dateStr = date.getFullYear() + "" + (date.getMonth() + 1) + "" + date.getDate();
if (RongIMLib.RongUtil.supportLocalStorage()) {
qryOpt = RongIMLib.RongIMClient._storageProvider.getItem("RongQryOpt" + dateStr);
}
else {
qryOpt = RongIMLib.RongIMClient._storageProvider.getItem("RongQryOpt" + dateStr);
}
if (!qryOpt) {
var modules = new RongIMLib.RongIMClient.Protobuf.GetUserInfoInput();
modules.setNothing(0);
RongIMLib.RongIMClient.bridge.queryMsg("qryCfg", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, {
onSuccess: function (data) {
if (!data)
return;
var naviArrs = RongIMLib.RongIMClient._memoryStore.depend.navi.split('//');
new RongIMLib.RongAjax({
url: "https://stats.cn.ronghub.com/active.json",
appKey: RongIMLib.RongIMClient._memoryStore.appKey,
deviceId: Math.floor(Math.random() * 10000),
timestamp: new Date().getTime(),
deviceInfo: "",
type: 1,
privateInfo: {
code: encodeURIComponent(data.name),
ip: RongIMLib.RongIMClient._storageProvider._host,
customId: data.id,
nip: naviArrs.length > 1 ? naviArrs[1] : ""
}
}).send(function () {
if (RongIMLib.RongUtil.supportLocalStorage()) {
qryOpt = RongIMLib.RongIMClient._storageProvider.setItem("RongQryOpt" + dateStr, dateStr);
}
else {
qryOpt = RongIMLib.RongIMClient._storageProvider.setItem("RongQryOpt" + dateStr, dateStr);
}
});
},
onError: function () { }
}, "GroupInfo");
}
}
var naviStr = RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.RongIMClient._storageProvider.getItemKey("navi"));
var naviKey = RongIMLib.RongIMClient._storageProvider.getItemKey("navi");
var arr = decodeURIComponent(naviStr).split(",");
if (!arr[1]) {
naviStr = encodeURIComponent(naviStr) + userId;
RongIMLib.RongIMClient._storageProvider.setItem(naviKey, naviStr);
}
this._client.userId = userId;
var self = this, temp = RongIMLib.RongIMClient._storageProvider.getItemKey("navi");
var naviServer = RongIMLib.RongIMClient._storageProvider.getItem(temp);
// TODO ๅคๆญๆๅ naviServer ๅ็ๆฐ็ป้ฟๅบฆใ
var naviPort = naviServer.split(",")[0].split(":")[1];
if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg && naviPort.length < 4) {
RongIMLib.Bridge._client.checkSocket({
onSuccess: function () {
if (!RongIMLib.RongIMClient.isNotPullMsg) {
self._client.syncTime(undefined, undefined, undefined, true);
}
},
onError: function () {
RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false;
RongIMLib.RongIMClient.getInstance().disconnect();
var temp = RongIMLib.RongIMClient._storageProvider.getItemKey("navi");
var server = RongIMLib.RongIMClient._storageProvider.getItem("RongBackupServer");
var arrs = server.split(",");
if (arrs.length < 2) {
throw new Error("navi server is empty");
}
RongIMLib.RongIMClient._storageProvider.setItem(temp, RongIMLib.RongIMClient._storageProvider.getItem("RongBackupServer"));
var url = RongIMLib.Bridge._client.channel.socket.currentURL;
RongIMLib.Bridge._client.channel.socket.currentURL = arrs[0] + url.substring(url.indexOf("/"), url.length);
RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback);
}
});
}
else {
if (!RongIMLib.RongIMClient.isNotPullMsg) {
self._client.syncTime(undefined, undefined, undefined, true);
}
}
if (this._client.reconnectObj.onSuccess) {
this._client.reconnectObj.onSuccess(userId);
delete this._client.reconnectObj.onSuccess;
}
else {
var me = this;
setTimeout(function () { me._cb(userId); }, 500);
}
RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0);
RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp;
if (!(new Date().getTime() - timestamp)) {
RongIMLib.RongIMClient._memoryStore.deltaTime = 0;
}
else {
RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - timestamp;
}
}
else if (status == 6) {
//้ๅฎๅ ่ฟ้ CMP
var x = {};
var me = this;
new RongIMLib.Navigation().getServerEndpoint(this._client.token, this._client.appId, function () {
me._client.clearHeartbeat();
new RongIMLib.Client(me._client.token, me._client.appId).__init.call(x, function () {
RongIMLib.Transportations._TransportType == "websocket" && me._client.keepLive();
});
me._client.channel.socket.fire("StatusChanged", 2);
}, me._timeout, false);
}
else {
RongIMLib.Bridge._client.channel.socket.socket._status = status;
if (this._client.reconnectObj.onError) {
this._client.reconnectObj.onError(status);
delete this._client.reconnectObj.onError;
}
else {
this._timeout(status);
}
}
};
ConnectAck.prototype.readTimeOut = function (x) {
MessageCallback.prototype.readTimeOut.call(this, x);
};
return ConnectAck;
})(MessageCallback);
RongIMLib.ConnectAck = ConnectAck;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var Navigation = (function () {
function Navigation() {
window.getServerEndpoint = function (x) {
//ๆๅฏผ่ช่ฟๅ็serverๅญๆฎต่ตๅผ็ปCookieHelper._host๏ผๅ ไธบflash widget้่ฆไฝฟ็จ decodeURIComponent
RongIMLib.RongIMClient._storageProvider._host = Navigation.Endpoint.host = x["server"];
RongIMLib.RongIMClient._storageProvider.setItem("RongBackupServer", x["backupServer"] + "," + (x.userId || ""));
//่ฎพ็ฝฎๅฝๅ็จๆท Id ๅชๆ comet ไฝฟ็จใ
Navigation.Endpoint.userId = x["userId"];
if (x["voipCallInfo"]) {
var callInfo = JSON.parse(x["voipCallInfo"]);
RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy;
RongIMLib.RongIMClient._storageProvider.setItem("voipStrategy", callInfo.strategy);
}
//ๆฟๆขๆฌๅฐๅญๅจ็ๅฏผ่ชไฟกๆฏ
// var temp = RongIMClient._storageProvider.getItemKey("navi");
// temp !== null && RongIMClient._storageProvider.removeItem(temp);
// ๆณจ๏ผไปฅไธไธค่กไปฃ็ ๅบๅผ๏ผ่ฏ็จๅๅ ้คใ
var md5Token = md5(RongIMLib.Bridge._client.token).slice(8, 16), openMp = x['openMp'] == 0 ? 0 : 1;
RongIMLib.RongIMClient._storageProvider.setItem("navi" + md5Token, x["server"] + "," + (x.userId || ""));
RongIMLib.RongIMClient._storageProvider.setItem('openMp' + md5Token, openMp);
if (!openMp) {
RongIMLib.RongIMClient._memoryStore.depend.openMp = false;
}
};
}
Navigation.prototype.connect = function (appId, token, callback) {
var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId");
//ๅฆๆappidๅๆฌๅฐๅญๅจ็ไธไธๆ ท๏ผๆธ
็ฉบๆๆๆฌๅฐๅญๅจๆฐๆฎ
if (oldAppId && oldAppId != appId) {
RongIMLib.RongIMClient._storageProvider.clearItem();
RongIMLib.RongIMClient._storageProvider.setItem("appId", appId);
}
if (!oldAppId) {
RongIMLib.RongIMClient._storageProvider.setItem("appId", appId);
}
var client = new RongIMLib.Client(token, appId);
var me = this;
this.getServerEndpoint(token, appId, function () {
client.connect(callback);
}, callback.onError, true);
return client;
};
Navigation.prototype.getServerEndpoint = function (_token, _appId, _onsuccess, _onerror, unignore) {
if (unignore) {
//ๆ นๆฎtoken็ๆMD5ๆชๅ8-16ไธๆ ็ๆฐๆฎไธๆฌๅฐๅญๅจ็ๅฏผ่ชไฟกๆฏ่ฟ่กๆฏๅฏน
//ๅฆๆไฟกๆฏๅไธๆฌก็้้็ฑปๅ้ฝไธๆ ท๏ผไธๆง่กnavi่ฏทๆฑ๏ผ็จๆฌๅฐๅญๅจ็ๅฏผ่ชไฟกๆฏ่ฟๆฅๆๅกๅจ
var naviStr = md5(_token).slice(8, 16), _old = RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.RongIMClient._storageProvider.getItemKey("navi")), _new = RongIMLib.RongIMClient._storageProvider.getItem("navi" + naviStr);
if (_old == _new && _new !== null && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK") == RongIMLib.Transportations._TransportType) {
var obj = decodeURIComponent(_old).split(",");
setTimeout(function () {
RongIMLib.RongIMClient._storageProvider._host = Navigation.Endpoint.host = obj[0];
RongIMLib.RongIMClient._memoryStore.voipStategy = RongIMLib.RongIMClient._storageProvider.getItem("voipStrategy");
if (!RongIMLib.RongIMClient._storageProvider.getItem('openMp' + naviStr)) {
RongIMLib.RongIMClient._memoryStore.depend.openMp = false;
}
Navigation.Endpoint.userId = obj[1];
_onsuccess();
}, 500);
return;
}
}
//ๅฏผ่ชไฟกๆฏ๏ผๅๆขUrlๅฏน่ฑก็key่ฟ่ก็บฟไธ็บฟไธๆต่ฏๆไฝ
var xss = document.createElement("script");
//่ฟ่กjsonp่ฏทๆฑ
xss.src = RongIMLib.RongIMClient._memoryStore.depend.navi + (RongIMLib.RongIMClient._memoryStore.depend.isPolling ? "/cometnavi.js" : "/navi.js") + "?appId=" + _appId + "&token=" + encodeURIComponent(_token) + "&" + "callBack=getServerEndpoint&t=" + (new Date).getTime();
document.body.appendChild(xss);
xss.onerror = function () {
_onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT);
};
if ("onload" in xss) {
xss.onload = _onsuccess;
}
else {
xss.onreadystatechange = function () {
xss.readyState == "loaded" && _onsuccess();
};
}
};
Navigation.Endpoint = new Object;
return Navigation;
})();
RongIMLib.Navigation = Navigation;
})(RongIMLib || (RongIMLib = {}));
// TODO: ็ปไธๅ้ใๆนๆณ็ญๅฝๅ่ง่
var RongIMLib;
(function (RongIMLib) {
/**
* ๆถๆฏๅบ็ฑป
*/
var BaseMessage = (function () {
function BaseMessage(arg) {
this._name = "BaseMessage";
this.lengthSize = 0;
if (arg instanceof RongIMLib.Header) {
this._header = arg;
}
else {
this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false);
}
}
BaseMessage.prototype.read = function (In, length) {
this.readMessage(In, length);
};
BaseMessage.prototype.write = function (Out) {
var binaryHelper = new RongIMLib.BinaryHelper();
var out = binaryHelper.convertStream(Out);
this._headerCode = this.getHeaderFlag();
out.write(this._headerCode);
this.writeMessage(out);
return out;
};
BaseMessage.prototype.getHeaderFlag = function () {
return this._header.encode();
};
BaseMessage.prototype.getLengthSize = function () {
return this.lengthSize;
};
BaseMessage.prototype.toBytes = function () {
return this.write([]).getBytesArray();
};
BaseMessage.prototype.isRetained = function () {
return this._header.retain;
};
BaseMessage.prototype.setRetained = function (retain) {
this._header.retain = retain;
};
BaseMessage.prototype.setQos = function (qos) {
this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos];
};
BaseMessage.prototype.setDup = function (dup) {
this._header.dup = dup;
};
BaseMessage.prototype.isDup = function () {
return this._header.dup;
};
BaseMessage.prototype.getType = function () {
return this._header.type;
};
BaseMessage.prototype.getQos = function () {
return this._header.qos;
};
BaseMessage.prototype.messageLength = function () {
return 0;
};
BaseMessage.prototype.writeMessage = function (out) { };
BaseMessage.prototype.readMessage = function (In, length) { };
BaseMessage.prototype.init = function (args) {
var valName, nana, me = this;
for (nana in args) {
if (!args.hasOwnProperty(nana)) {
continue;
}
valName = nana.replace(/^\w/, function (x) {
var tt = x.charCodeAt(0);
return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x);
});
if (valName in me) {
if (nana == "status") {
me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]);
}
else {
me[valName](args[nana]);
}
}
}
};
return BaseMessage;
})();
RongIMLib.BaseMessage = BaseMessage;
/**
*่ฟๆฅๆถๆฏ็ฑปๅ
*/
var ConnectMessage = (function (_super) {
__extends(ConnectMessage, _super);
function ConnectMessage(header) {
_super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]);
this._name = "ConnectMessage";
this.CONNECT_HEADER_SIZE = 12;
this.protocolId = "RCloud";
this.binaryHelper = new RongIMLib.BinaryHelper();
this.protocolVersion = 3;
switch (arguments.length) {
case 0:
case 1:
case 3:
if (!arguments[0] || arguments[0].length > 64) {
throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]);
}
this.clientId = arguments[0];
this.cleanSession = arguments[1];
this.keepAlive = arguments[2];
break;
}
}
ConnectMessage.prototype.messageLength = function () {
var payloadSize = this.binaryHelper.toMQttString(this.clientId).length;
payloadSize += this.binaryHelper.toMQttString(this.willTopic).length;
payloadSize += this.binaryHelper.toMQttString(this.will).length;
payloadSize += this.binaryHelper.toMQttString(this.appId).length;
payloadSize += this.binaryHelper.toMQttString(this.token).length;
return payloadSize + this.CONNECT_HEADER_SIZE;
};
ConnectMessage.prototype.readMessage = function (stream) {
this.protocolId = stream.readUTF();
this.protocolVersion = stream.readByte();
var cFlags = stream.readByte();
this.hasAppId = (cFlags & 128) > 0;
this.hasToken = (cFlags & 64) > 0;
this.retainWill = (cFlags & 32) > 0;
this.willQos = cFlags >> 3 & 3;
this.hasWill = (cFlags & 4) > 0;
this.cleanSession = (cFlags & 32) > 0;
this.keepAlive = stream.read() * 256 + stream.read();
this.clientId = stream.readUTF();
if (this.hasWill) {
this.willTopic = stream.readUTF();
this.will = stream.readUTF();
}
if (this.hasAppId) {
try {
this.appId = stream.readUTF();
}
catch (ex) {
throw new Error(ex);
}
}
if (this.hasToken) {
try {
this.token = stream.readUTF();
}
catch (ex) {
throw new Error(ex);
}
}
return stream;
};
ConnectMessage.prototype.writeMessage = function (out) {
var stream = this.binaryHelper.convertStream(out);
stream.writeUTF(this.protocolId);
stream.write(this.protocolVersion);
var flags = this.cleanSession ? 2 : 0;
flags |= this.hasWill ? 4 : 0;
flags |= this.willQos ? this.willQos >> 3 : 0;
flags |= this.retainWill ? 32 : 0;
flags |= this.hasToken ? 64 : 0;
flags |= this.hasAppId ? 128 : 0;
stream.write(flags);
stream.writeChar(this.keepAlive);
stream.writeUTF(this.clientId);
if (this.hasWill) {
stream.writeUTF(this.willTopic);
stream.writeUTF(this.will);
}
if (this.hasAppId) {
stream.writeUTF(this.appId);
}
if (this.hasToken) {
stream.writeUTF(this.token);
}
return stream;
};
return ConnectMessage;
})(BaseMessage);
RongIMLib.ConnectMessage = ConnectMessage;
/**
*่ฟๆฅๅบ็ญ็ฑปๅ
*/
var ConnAckMessage = (function (_super) {
__extends(ConnAckMessage, _super);
function ConnAckMessage(header) {
_super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null);
this._name = "ConnAckMessage";
this.MESSAGE_LENGTH = 2;
this.binaryHelper = new RongIMLib.BinaryHelper();
var me = this;
switch (arguments.length) {
case 0:
case 1:
if (!(arguments[0] instanceof RongIMLib.Header)) {
if (arguments[0] in RongIMLib.ConnectionState) {
if (arguments[0] == null) {
throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null");
}
me.setStatus(arguments[0]);
}
}
break;
}
}
;
ConnAckMessage.prototype.messageLength = function () {
var length = this.MESSAGE_LENGTH;
if (this.userId) {
length += this.binaryHelper.toMQttString(this.userId).length;
}
return length;
};
;
ConnAckMessage.prototype.readMessage = function (_in, msglength) {
_in.read();
var result = +_in.read();
if (result >= 0 && result <= 12) {
this.setStatus(result);
}
else {
throw new Error("Unsupported CONNACK code:" + result);
}
if (msglength > this.MESSAGE_LENGTH) {
this.setUserId(_in.readUTF());
var sessionId = _in.readUTF();
var timestamp = _in.readLong();
this.setTimestamp(timestamp);
}
};
;
ConnAckMessage.prototype.writeMessage = function (out) {
var stream = this.binaryHelper.convertStream(out);
stream.write(128);
switch (+status) {
case 0:
case 1:
case 2:
case 5:
case 6:
stream.write(+status);
break;
case 3:
case 4:
stream.write(3);
break;
default:
throw new Error("Unsupported CONNACK code:" + status);
}
if (this.userId) {
stream.writeUTF(this.userId);
}
return stream;
};
;
ConnAckMessage.prototype.setStatus = function (x) {
this.status = x;
};
;
ConnAckMessage.prototype.setUserId = function (_userId) {
this.userId = _userId;
};
;
ConnAckMessage.prototype.getStatus = function () {
return this.status;
};
;
ConnAckMessage.prototype.getUserId = function () {
return this.userId;
};
;
ConnAckMessage.prototype.setTimestamp = function (x) {
this.timestrap = x;
};
;
ConnAckMessage.prototype.getTimestamp = function () {
return this.timestrap;
};
return ConnAckMessage;
})(BaseMessage);
RongIMLib.ConnAckMessage = ConnAckMessage;
/**
*ๆญๅผๆถๆฏ็ฑปๅ
*/
var DisconnectMessage = (function (_super) {
__extends(DisconnectMessage, _super);
function DisconnectMessage(header) {
_super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT);
this._name = "DisconnectMessage";
this.MESSAGE_LENGTH = 2;
this.binaryHelper = new RongIMLib.BinaryHelper();
if (!(header instanceof RongIMLib.Header)) {
if (header in RongIMLib.ConnectionStatus) {
this.status = header;
}
}
}
DisconnectMessage.prototype.messageLength = function () {
return this.MESSAGE_LENGTH;
};
DisconnectMessage.prototype.readMessage = function (_in) {
_in.read();
var result = +_in.read();
if (result >= 0 && result <= 5) {
this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result);
}
else {
throw new Error("Unsupported CONNACK code:" + result);
}
};
DisconnectMessage.prototype.writeMessage = function (Out) {
var out = this.binaryHelper.convertStream(Out);
out.write(0);
if (+status >= 1 && +status <= 3) {
out.write((+status) - 1);
}
else {
throw new Error("Unsupported CONNACK code:" + status);
}
};
DisconnectMessage.prototype.setStatus = function (x) {
this.status = x;
};
;
DisconnectMessage.prototype.getStatus = function () {
return this.status;
};
;
return DisconnectMessage;
})(BaseMessage);
RongIMLib.DisconnectMessage = DisconnectMessage;
/**
*่ฏทๆฑๆถๆฏไฟกไปค
*/
var PingReqMessage = (function (_super) {
__extends(PingReqMessage, _super);
function PingReqMessage(header) {
_super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ);
this._name = "PingReqMessage";
}
return PingReqMessage;
})(BaseMessage);
RongIMLib.PingReqMessage = PingReqMessage;
/**
*ๅๅบๆถๆฏไฟกไปค
*/
var PingRespMessage = (function (_super) {
__extends(PingRespMessage, _super);
function PingRespMessage(header) {
_super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP);
this._name = "PingRespMessage";
}
return PingRespMessage;
})(BaseMessage);
RongIMLib.PingRespMessage = PingRespMessage;
/**
*ๅฐ่ฃ
MesssageId
*/
var RetryableMessage = (function (_super) {
__extends(RetryableMessage, _super);
function RetryableMessage(argu) {
_super.call(this, argu);
this._name = "RetryableMessage";
this.binaryHelper = new RongIMLib.BinaryHelper();
}
RetryableMessage.prototype.messageLength = function () {
return 2;
};
RetryableMessage.prototype.writeMessage = function (Out) {
var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8;
out.write(msb);
out.write(lsb);
return out;
};
RetryableMessage.prototype.readMessage = function (_in, msgLength) {
var msgId = _in.read() * 256 + _in.read();
this.setMessageId(parseInt(msgId, 10));
};
RetryableMessage.prototype.setMessageId = function (_messageId) {
this.messageId = _messageId;
};
RetryableMessage.prototype.getMessageId = function () {
return this.messageId;
};
return RetryableMessage;
})(BaseMessage);
RongIMLib.RetryableMessage = RetryableMessage;
/**
*ๅ้ๆถๆฏๅบ็ญ๏ผๅๅ๏ผ
*qosไธบ1ๅฟ
้กป็ปๅบๅบ็ญ๏ผๆๆๆถๆฏ็ฑปๅไธๆ ท๏ผ
*/
var PubAckMessage = (function (_super) {
__extends(PubAckMessage, _super);
function PubAckMessage(header) {
_super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK);
this.msgLen = 2;
this.date = 0;
this.millisecond = 0;
this.timestamp = 0;
this.binaryHelper = new RongIMLib.BinaryHelper();
this._name = "PubAckMessage";
if (!(header instanceof RongIMLib.Header)) {
_super.prototype.setMessageId.call(this, header);
}
}
PubAckMessage.prototype.messageLength = function () {
return this.msgLen;
};
PubAckMessage.prototype.writeMessage = function (Out) {
var out = this.binaryHelper.convertStream(Out);
RetryableMessage.prototype.writeMessage.call(this, out);
};
PubAckMessage.prototype.readMessage = function (_in, msgLength) {
RetryableMessage.prototype.readMessage.call(this, _in);
this.date = _in.readInt();
this.status = _in.read() * 256 + _in.read();
this.millisecond = _in.read() * 256 + _in.read();
this.timestamp = this.date * 1000 + this.millisecond;
this.messageUId = _in.readUTF();
};
PubAckMessage.prototype.setStatus = function (x) {
this.status = x;
};
PubAckMessage.prototype.setTimestamp = function (timestamp) {
this.timestamp = timestamp;
};
PubAckMessage.prototype.setMessageUId = function (messageUId) {
this.messageUId = messageUId;
};
PubAckMessage.prototype.getStatus = function () {
return this.status;
};
PubAckMessage.prototype.getDate = function () {
return this.date;
};
PubAckMessage.prototype.getTimestamp = function () {
return this.timestamp;
};
PubAckMessage.prototype.getMessageUId = function () {
return this.messageUId;
};
return PubAckMessage;
})(RetryableMessage);
RongIMLib.PubAckMessage = PubAckMessage;
/**
*ๅๅธๆถๆฏ
*/
var PublishMessage = (function (_super) {
__extends(PublishMessage, _super);
function PublishMessage(header, two, three) {
_super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0);
this._name = "PublishMessage";
this.binaryHelper = new RongIMLib.BinaryHelper();
this.syncMsg = false;
if (arguments.length == 3) {
this.topic = header;
this.targetId = three;
this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two;
}
}
PublishMessage.prototype.messageLength = function () {
var length = 10;
length += this.binaryHelper.toMQttString(this.topic).length;
length += this.binaryHelper.toMQttString(this.targetId).length;
length += this.data.length;
return length;
};
PublishMessage.prototype.writeMessage = function (Out) {
var out = this.binaryHelper.convertStream(Out);
out.writeUTF(this.topic);
out.writeUTF(this.targetId);
RetryableMessage.prototype.writeMessage.apply(this, arguments);
out.write(this.data);
};
;
PublishMessage.prototype.readMessage = function (_in, msgLength) {
var pos = 6;
this.date = _in.readInt();
this.topic = _in.readUTF();
pos += this.binaryHelper.toMQttString(this.topic).length;
this.targetId = _in.readUTF();
pos += this.binaryHelper.toMQttString(this.targetId).length;
RetryableMessage.prototype.readMessage.apply(this, arguments);
this.data = new Array(msgLength - pos);
this.data = _in.read(this.data);
};
;
PublishMessage.prototype.setTopic = function (x) {
this.topic = x;
};
PublishMessage.prototype.setData = function (x) {
this.data = x;
};
PublishMessage.prototype.setTargetId = function (x) {
this.targetId = x;
};
PublishMessage.prototype.setDate = function (x) {
this.date = x;
};
PublishMessage.prototype.setSyncMsg = function (x) {
this.syncMsg = x;
};
//ๆฏๅฆๆฏๅ
ถไป็ซฏๅๆญฅ่ฟๆฅ็ๆถๆฏ
PublishMessage.prototype.getSyncMsg = function () {
return this.syncMsg;
};
PublishMessage.prototype.getTopic = function () {
return this.topic;
};
PublishMessage.prototype.getData = function () {
return this.data;
};
PublishMessage.prototype.getTargetId = function () {
return this.targetId;
};
PublishMessage.prototype.getDate = function () {
return this.date;
};
return PublishMessage;
})(RetryableMessage);
RongIMLib.PublishMessage = PublishMessage;
/**
*่ฏทๆฑๆฅ่ฏข
*/
var QueryMessage = (function (_super) {
__extends(QueryMessage, _super);
function QueryMessage(header, two, three) {
_super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null);
this.binaryHelper = new RongIMLib.BinaryHelper();
this._name = "QueryMessage";
if (arguments.length == 3) {
this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two;
this.topic = header;
this.targetId = three;
}
}
QueryMessage.prototype.messageLength = function () {
var length = 0;
length += this.binaryHelper.toMQttString(this.topic).length;
length += this.binaryHelper.toMQttString(this.targetId).length;
length += 2;
length += this.data.length;
return length;
};
QueryMessage.prototype.writeMessage = function (Out) {
var out = this.binaryHelper.convertStream(Out);
out.writeUTF(this.topic);
out.writeUTF(this.targetId);
RetryableMessage.prototype.writeMessage.call(this, out);
out.write(this.data);
};
QueryMessage.prototype.readMessage = function (_in, msgLength) {
var pos = 0;
this.topic = _in.readUTF();
this.targetId = _in.readUTF();
pos += this.binaryHelper.toMQttString(this.topic).length;
pos += this.binaryHelper.toMQttString(this.targetId).length;
this.readMessage.apply(this, arguments);
pos += 2;
this.data = new Array(msgLength - pos);
_in.read(this.data);
};
QueryMessage.prototype.setTopic = function (x) {
this.topic = x;
};
QueryMessage.prototype.setData = function (x) {
this.data = x;
};
QueryMessage.prototype.setTargetId = function (x) {
this.targetId = x;
};
QueryMessage.prototype.getTopic = function () {
return this.topic;
};
QueryMessage.prototype.getData = function () {
return this.data;
};
QueryMessage.prototype.getTargetId = function () {
return this.targetId;
};
return QueryMessage;
})(RetryableMessage);
RongIMLib.QueryMessage = QueryMessage;
/**
*่ฏทๆฑๆฅ่ฏข็กฎ่ฎค
*/
var QueryConMessage = (function (_super) {
__extends(QueryConMessage, _super);
function QueryConMessage(messageId) {
_super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON);
this._name = "QueryConMessage";
if (!(messageId instanceof RongIMLib.Header)) {
_super.prototype.setMessageId.call(this, messageId);
}
}
return QueryConMessage;
})(RetryableMessage);
RongIMLib.QueryConMessage = QueryConMessage;
/**
*่ฏทๆฑๆฅ่ฏขๅบ็ญ
*/
var QueryAckMessage = (function (_super) {
__extends(QueryAckMessage, _super);
function QueryAckMessage(header) {
_super.call(this, header);
this._name = "QueryAckMessage";
this.binaryHelper = new RongIMLib.BinaryHelper();
}
QueryAckMessage.prototype.readMessage = function (In, msgLength) {
RetryableMessage.prototype.readMessage.call(this, In);
this.date = In.readInt();
this.setStatus(In.read() * 256 + In.read());
if (msgLength > 0) {
this.data = new Array(msgLength - 8);
this.data = In.read(this.data);
}
};
QueryAckMessage.prototype.getData = function () {
return this.data;
};
QueryAckMessage.prototype.getStatus = function () {
return this.status;
};
QueryAckMessage.prototype.getDate = function () {
return this.date;
};
QueryAckMessage.prototype.setDate = function (x) {
this.date = x;
};
QueryAckMessage.prototype.setStatus = function (x) {
this.status = x;
};
QueryAckMessage.prototype.setData = function (x) {
this.data = x;
};
return QueryAckMessage;
})(RetryableMessage);
RongIMLib.QueryAckMessage = QueryAckMessage;
})(RongIMLib || (RongIMLib = {}));
/// <reference path="../../dts/helper.d.ts"/>
var RongIMLib;
(function (RongIMLib) {
/**
* ๆๆถๆฏๅฏน่ฑกๅๅ
ฅๆตไธญ
* ๅ้ๆถๆฏๆถ็จๅฐ
*/
var MessageOutputStream = (function () {
function MessageOutputStream(_out) {
var binaryHelper = new RongIMLib.BinaryHelper();
this.out = binaryHelper.convertStream(_out);
}
MessageOutputStream.prototype.writeMessage = function (msg) {
if (msg instanceof RongIMLib.BaseMessage) {
msg.write(this.out);
}
};
return MessageOutputStream;
})();
RongIMLib.MessageOutputStream = MessageOutputStream;
/**
* ๆต่ฝฌๆขไธบๆถๆฏๅฏน่ฑก
* ๆๅกๅจ่ฟๅๆถๆฏๆถ็จๅฐ
*/
var MessageInputStream = (function () {
function MessageInputStream(In, isPolling) {
if (!isPolling) {
var _in = new RongIMLib.BinaryHelper().convertStream(In);
this.flags = _in.readByte();
this._in = _in;
}
else {
this.flags = In["headerCode"];
}
this.header = new RongIMLib.Header(this.flags);
this.isPolling = isPolling;
this.In = In;
}
MessageInputStream.prototype.readMessage = function () {
switch (this.header.getType()) {
case 1:
this.msg = new RongIMLib.ConnectMessage(this.header);
break;
case 2:
this.msg = new RongIMLib.ConnAckMessage(this.header);
break;
case 3:
this.msg = new RongIMLib.PublishMessage(this.header);
this.msg.setSyncMsg(this.header.getSyncMsg());
break;
case 4:
this.msg = new RongIMLib.PubAckMessage(this.header);
break;
case 5:
this.msg = new RongIMLib.QueryMessage(this.header);
break;
case 6:
this.msg = new RongIMLib.QueryAckMessage(this.header);
break;
case 7:
this.msg = new RongIMLib.QueryConMessage(this.header);
break;
case 9:
case 11:
case 13:
this.msg = new RongIMLib.PingRespMessage(this.header);
break;
case 8:
case 10:
case 12:
this.msg = new RongIMLib.PingReqMessage(this.header);
break;
case 14:
this.msg = new RongIMLib.DisconnectMessage(this.header);
break;
default:
throw new Error("No support for deserializing " + this.header.getType() + " messages");
}
if (this.isPolling) {
this.msg.init(this.In);
}
else {
this.msg.read(this._in, this.In.length - 1);
}
return this.msg;
};
return MessageInputStream;
})();
RongIMLib.MessageInputStream = MessageInputStream;
var Header = (function () {
function Header(_type, _retain, _qos, _dup) {
this.retain = false;
this.qos = RongIMLib.Qos.AT_LEAST_ONCE;
this.dup = false;
this.syncMsg = false;
if (_type && +_type == _type && arguments.length == 1) {
this.retain = (_type & 1) > 0;
this.qos = (_type & 6) >> 1;
this.dup = (_type & 8) > 0;
this.type = (_type >> 4) & 15;
this.syncMsg = (_type & 8) == 8;
}
else {
this.type = _type;
this.retain = _retain;
this.qos = _qos;
this.dup = _dup;
}
}
Header.prototype.getSyncMsg = function () {
return this.syncMsg;
};
Header.prototype.getType = function () {
return this.type;
};
Header.prototype.encode = function () {
var me = this;
switch (this.qos) {
case RongIMLib.Qos[0]:
me.qos = RongIMLib.Qos.AT_MOST_ONCE;
break;
case RongIMLib.Qos[1]:
me.qos = RongIMLib.Qos.AT_LEAST_ONCE;
break;
case RongIMLib.Qos[2]:
me.qos = RongIMLib.Qos.EXACTLY_ONCE;
break;
case RongIMLib.Qos[3]:
me.qos = RongIMLib.Qos.DEFAULT;
break;
}
var _byte = (this.type << 4);
_byte |= this.retain ? 1 : 0;
_byte |= this.qos << 1;
_byte |= this.dup ? 8 : 0;
return _byte;
};
Header.prototype.toString = function () {
return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]";
};
return Header;
})();
RongIMLib.Header = Header;
/**
* ไบ่ฟๅถๅธฎๅฉๅฏน่ฑก
*/
var BinaryHelper = (function () {
function BinaryHelper() {
}
BinaryHelper.prototype.writeUTF = function (str, isGetBytes) {
var back = [], byteSize = 0;
for (var i = 0, len = str.length; i < len; i++) {
var code = str.charCodeAt(i);
if (code >= 0 && code <= 127) {
byteSize += 1;
back.push(code);
}
else if (code >= 128 && code <= 2047) {
byteSize += 2;
back.push((192 | (31 & (code >> 6))));
back.push((128 | (63 & code)));
}
else if (code >= 2048 && code <= 65535) {
byteSize += 3;
back.push((224 | (15 & (code >> 12))));
back.push((128 | (63 & (code >> 6))));
back.push((128 | (63 & code)));
}
}
for (var i = 0, len = back.length; i < len; i++) {
if (back[i] > 255) {
back[i] &= 255;
}
}
if (isGetBytes) {
return back;
}
if (byteSize <= 255) {
return [0, byteSize].concat(back);
}
else {
return [byteSize >> 8, byteSize & 255].concat(back);
}
};
BinaryHelper.prototype.readUTF = function (arr) {
if (Object.prototype.toString.call(arr) == "[object String]") {
return arr;
}
var UTF = "", _arr = arr;
for (var i = 0, len = _arr.length; i < len; i++) {
if (_arr[i] < 0) {
_arr[i] += 256;
}
;
var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/);
if (v && one.length == 8) {
var bytesLength = v[0].length,
// store = _arr[i].toString(2).slice(7 - bytesLength);
store = '';
for (var st = 0; st < bytesLength; st++) {
store += _arr[st + i].toString(2).slice(2);
}
UTF += String.fromCharCode(parseInt(store, 2));
i += bytesLength - 1;
}
else {
UTF += String.fromCharCode(_arr[i]);
}
}
return UTF;
};
/**
* [convertStream ๅฐๅๆฐx่ฝฌๅไธบRongIMStreamๅฏน่ฑก]
* @param {any} x [ๅๆฐ]
*/
BinaryHelper.prototype.convertStream = function (x) {
if (x instanceof RongIMStream) {
return x;
}
else {
return new RongIMStream(x);
}
};
BinaryHelper.prototype.toMQttString = function (str) {
return this.writeUTF(str);
};
return BinaryHelper;
})();
RongIMLib.BinaryHelper = BinaryHelper;
var RongIMStream = (function () {
function RongIMStream(arr) {
//ๅฝๅๆตๆง่ก็่ตทๅงไฝ็ฝฎ
this.position = 0;
//ๅฝๅๆตๅๅ
ฅ็ๅคๅฐๅญ่
this.writen = 0;
this.poolLen = 0;
this.binaryHelper = new BinaryHelper();
this.pool = arr;
this.poolLen = arr.length;
}
RongIMStream.prototype.check = function () {
return this.position >= this.pool.length;
};
RongIMStream.prototype.readInt = function () {
if (this.check()) {
return -1;
}
var end = "";
for (var i = 0; i < 4; i++) {
var t = this.pool[this.position++].toString(16);
if (t.length == 1) {
t = "0" + t;
}
end += t.toString(16);
}
return parseInt(end, 16);
};
RongIMStream.prototype.readLong = function () {
if (this.check()) {
return -1;
}
var end = "";
for (var i = 0; i < 8; i++) {
var t = this.pool[this.position++].toString(16);
if (t.length == 1) {
t = "0" + t;
}
end += t;
}
return parseInt(end, 16);
};
RongIMStream.prototype.readTimestamp = function () {
if (this.check()) {
return -1;
}
var end = "";
for (var i = 0; i < 8; i++) {
end += this.pool[this.position++].toString(16);
}
end = end.substring(2, 8);
return parseInt(end, 16);
};
RongIMStream.prototype.readUTF = function () {
if (this.check()) {
return -1;
}
var big = (this.readByte() << 8) | this.readByte();
return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big));
};
RongIMStream.prototype.readByte = function () {
if (this.check()) {
return -1;
}
var val = this.pool[this.position++];
if (val > 255) {
val &= 255;
}
return val;
};
RongIMStream.prototype.read = function (bytesArray) {
if (bytesArray) {
return this.pool.subarray(this.position, this.poolLen);
}
else {
return this.readByte();
}
};
RongIMStream.prototype.write = function (_byte) {
var b = _byte;
if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") {
[].push.apply(this.pool, b);
}
else {
if (+b == b) {
if (b > 255) {
b &= 255;
}
this.pool.push(b);
this.writen++;
}
}
return b;
};
RongIMStream.prototype.writeChar = function (v) {
if (+v != v) {
throw new Error("writeChar:arguments type is error");
}
this.write(v >> 8 & 255);
this.write(v & 255);
this.writen += 2;
};
RongIMStream.prototype.writeUTF = function (str) {
var val = this.binaryHelper.writeUTF(str);
[].push.apply(this.pool, val);
this.writen += val.length;
};
RongIMStream.prototype.toComplements = function () {
var _tPool = this.pool;
for (var i = 0; i < this.poolLen; i++) {
if (_tPool[i] > 128) {
_tPool[i] -= 256;
}
}
return _tPool;
};
RongIMStream.prototype.getBytesArray = function (isCom) {
if (isCom) {
return this.toComplements();
}
return this.pool;
};
return RongIMStream;
})();
RongIMLib.RongIMStream = RongIMStream;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var SocketTransportation = (function () {
/**
* [constructor]
* @param {string} url [่ฟๆฅๅฐๅ๏ผๅ
ๅซtokenใversion]
*/
function SocketTransportation(_socket) {
//่ฟๆฅ็ถๆ true:ๅทฒ่ฟๆฅ false:ๆช่ฟๆฅ
this.connected = false;
//ๆฏๅฆๅ
ณ้ญ๏ผ true:ๅทฒๅ
ณ้ญ false๏ผๆชๅ
ณ้ญ
this.isClose = false;
//ๅญๆพๆถๆฏ้ๅ็ไธดๆถๅ้
this.queue = [];
this.empty = new Function;
this._socket = _socket;
return this;
}
/**
* [createTransport ๅๅปบWebScoketๅฏน่ฑก]
*/
SocketTransportation.prototype.createTransport = function (url, method) {
if (!url) {
throw new Error("URL can't be empty");
}
;
this.url = url;
this.socket = new WebSocket(RongIMLib.RongIMClient._memoryStore.depend.wsScheme + url);
this.socket.binaryType = "arraybuffer";
this.addEvent();
return this.socket;
};
/**
* [send ไผ ้ๆถๆฏๆต]
* @param {ArrayBuffer} data [ไบ่ฟๅถๆถๆฏๆต]
*/
SocketTransportation.prototype.send = function (data) {
if (!this.connected && !this.isClose) {
//ๅฝ้้ไธๅฏ็จๆถ๏ผๅ ๅ
ฅๆถๆฏ้ๅ
this.queue.push(data);
return;
}
if (this.isClose) {
this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED);
return;
}
var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream);
msg.writeMessage(data);
var val = stream.getBytesArray(true);
var binary = new Int8Array(val);
this.socket.send(binary.buffer);
return this;
};
/**
* [onData ้้่ฟๅๆฐๆฎๆถ่ฐ็จ็ๆนๆณ๏ผ็จๆฅๆณไธๅฑไผ ้ๆๅกๅจ่ฟๅ็ไบ่ฟๅถๆถๆฏๆต]
* @param {ArrayBuffer} data [ไบ่ฟๅถๆถๆฏๆต]
*/
SocketTransportation.prototype.onData = function (data) {
if (RongIMLib.MessageUtil.isArray(data)) {
this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage());
}
else {
this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage());
}
return "";
};
/**
* [onClose ้้ๅ
ณ้ญๆถ่งฆๅ็ๆนๆณ]
*/
SocketTransportation.prototype.onClose = function (ev) {
var me = this;
me.isClose = true;
me.socket = this.empty;
RongIMLib.Bridge._client.clearHeartbeat();
if (ev.code == 1006 && !this._status) {
me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE);
}
else {
me._status = 0;
}
};
/**
* [onError ้้ๆฅ้ๆถ่งฆๅ็ๆนๆณ]
* @param {any} error [ๆๅบๅผๅธธ]
*/
SocketTransportation.prototype.onError = function (error) {
throw new Error(error);
};
/**
* [addEvent ไธบ้้็ปๅฎไบไปถ]
*/
SocketTransportation.prototype.addEvent = function () {
var self = this;
self.socket.onopen = function () {
self.connected = true;
self.isClose = false;
//้้ๅฏไปฅ็จๅ๏ผ่ฐ็จๅ้้ๅๆนๆณ๏ผๆๆๆ็ญๅพๅ้็ๆถๆฏๅๅบ
self.doQueue();
self._socket.fire("connect");
};
self.socket.onmessage = function (ev) {
//ๅคๆญๆฐๆฎๆฏไธๆฏๅญ็ฌฆไธฒ๏ผๅฆๆๆฏๅญ็ฌฆไธฒ้ฃไนๅฐฑๆฏflashไผ ่ฟๆฅ็ใ
if (typeof ev.data == "string") {
self.onData(ev.data.split(","));
}
else {
self.onData(ev.data);
}
};
self.socket.onerror = function (ev) {
self.onError(ev);
};
self.socket.onclose = function (ev) {
self.onClose(ev);
};
};
/**
* [doQueue ๆถๆฏ้ๅ๏ผๆ้ๅไธญๆถๆฏๅๅบ]
*/
SocketTransportation.prototype.doQueue = function () {
var self = this;
for (var i = 0, len = self.queue.length; i < len; i++) {
self.send(self.queue[i]);
}
};
/**
* [disconnect ๆญๅผ่ฟๆฅ]
*/
SocketTransportation.prototype.disconnect = function (status) {
var me = this;
if (me.socket.readyState) {
me.isClose = true;
if (status) {
me._status = status;
}
this.socket.close();
}
};
/**
* [reconnect ้ๆฐ่ฟๆฅ]
*/
SocketTransportation.prototype.reconnect = function () {
this.disconnect();
this.createTransport(this.url);
};
return SocketTransportation;
})();
RongIMLib.SocketTransportation = SocketTransportation;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var PollingTransportation = (function () {
function PollingTransportation(socket) {
this.empty = new Function;
this.connected = false;
this.pid = +new Date + Math.random() + "";
this.queue = [];
this.socket = socket;
return this;
}
PollingTransportation.prototype.createTransport = function (url, method) {
if (!url) {
throw new Error("Url is empty,Please check it!");
}
;
this.url = url;
var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this;
if (sid) {
setTimeout(function () {
me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}");
me.connected = true;
}, 500);
return this;
}
this.getRequest(url, true);
return this;
};
PollingTransportation.prototype.requestFactory = function (url, method, multipart) {
var reqest = this.XmlHttpRequest();
if (multipart) {
reqest.multipart = true;
}
reqest.timeout = 60000;
reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url);
if (method == "POST" && "setRequestHeader" in reqest) {
reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
}
return reqest;
};
PollingTransportation.prototype.getRequest = function (url, isconnect) {
var me = this;
me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET");
if ("onload" in me.xhr) {
me.xhr.onload = function () {
me.xhr.onload = me.empty;
if (this.responseText == "lost params") {
me.onError();
}
else {
me.onSuccess(this.responseText, isconnect);
}
};
me.xhr.onerror = function () {
me.disconnect();
};
}
else {
me.xhr.onreadystatechange = function () {
if (me.xhr.readyState == 4) {
me.xhr.onreadystatechange = me.empty;
if (/^(200|202)$/.test(me.xhr.status)) {
me.onSuccess(me.xhr.responseText, isconnect);
}
else if (/^(400|403)$/.test(me.xhr.status)) {
me.onError();
}
else {
me.disconnect();
}
}
};
}
me.xhr.send();
};
/**
* [send ๅ้ๆถๆฏ๏ผMethod:POST]
* queue ไธบๆถๆฏ้ๅ๏ผๅพ
้้ๅฏ็จๅ้ๆๆ็ญๅพ
ๆถๆฏ
* @param {string} data [้่ฆไผ ๅ
ฅcometๆ ผๅผๆฐๆฎ๏ผๆญคๅคๅช่ด่ดฃ้่ฎฏ้้๏ผๆฐๆฎ่ฝฌๆขๅจๅคๅฑๅค็]
*/
PollingTransportation.prototype.send = function (data) {
var me = this;
var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST");
if ("onload" in _send) {
_send.onload = function () {
_send.onload = me.empty;
me.onData(_send.responseText);
};
_send.onerror = function () {
_send.onerror = me.empty;
};
}
else {
_send.onreadystatechange = function () {
if (_send.readyState == 4) {
this.onreadystatechange = this.empty;
if (/^(202|200)$/.test(_send.status)) {
me.onData(_send.responseText);
}
}
};
}
_send.send(JSON.stringify(data.data));
};
PollingTransportation.prototype.onData = function (data, header) {
if (!data || data == "lost params") {
return;
}
var self = this, val = JSON.parse(data);
if (val.userId) {
RongIMLib.Navigation.Endpoint.userId = val.userId;
}
if (header) {
RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header);
}
if (!RongIMLib.MessageUtil.isArray(val)) {
val = [val];
}
Array.forEach(val, function (m) {
self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage());
});
return "";
};
PollingTransportation.prototype.XmlHttpRequest = function () {
var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this;
if ("undefined" != typeof XMLHttpRequest && hasCORS) {
return new XMLHttpRequest();
}
else if ("undefined" != typeof XDomainRequest) {
return new XDomainRequest();
}
else {
return new ActiveXObject("Microsoft.XMLHTTP");
}
};
PollingTransportation.prototype.onClose = function () {
if (this.xhr) {
if (this.xhr.onload) {
this.xhr.onreadystatechange = this.xhr.onload = this.empty;
}
else {
this.xhr.onreadystatechange = this.empty;
}
this.xhr.abort();
this.xhr = null;
}
if (this.sendxhr) {
if (this.sendxhr.onload) {
this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty;
}
else {
this.sendxhr.onreadystatechange = this.empty;
}
this.sendxhr.abort();
this.sendxhr = null;
}
};
PollingTransportation.prototype.disconnect = function () {
RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId);
RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId");
this.onClose();
};
PollingTransportation.prototype.reconnect = function () {
this.disconnect();
this.createTransport(this.url);
};
PollingTransportation.prototype.onSuccess = function (responseText, isconnect) {
var txt = responseText.match(/"sessionid":"\S+?(?=")/);
this.onData(responseText, txt ? txt[0].slice(13) : 0);
if (/"headerCode":-32,/.test(responseText)) {
RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId);
RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId");
return;
}
this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + ""));
this.connected = true;
isconnect && this.socket.fire("connect");
};
PollingTransportation.prototype.onError = function () {
RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId);
RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId");
this.onClose();
this.connected = false;
this.socket.fire("disconnect");
};
return PollingTransportation;
})();
RongIMLib.PollingTransportation = PollingTransportation;
})(RongIMLib || (RongIMLib = {}));
//objectnameๆ ๅฐ
var typeMapping = {
"RC:TxtMsg": "TextMessage",
"RC:ImgMsg": "ImageMessage",
"RC:VcMsg": "VoiceMessage",
"RC:ImgTextMsg": "RichContentMessage",
"RC:FileMsg": "FileMessage",
"RC:LBSMsg": "LocationMessage",
"RC:InfoNtf": "InformationNotificationMessage",
"RC:ContactNtf": "ContactNotificationMessage",
"RC:ProfileNtf": "ProfileNotificationMessage",
"RC:CmdNtf": "CommandNotificationMessage",
"RC:DizNtf": "DiscussionNotificationMessage",
"RC:CmdMsg": "CommandMessage",
"RC:TypSts": "TypingStatusMessage",
"RC:CsChaR": "ChangeModeResponseMessage",
"RC:CsHsR": "HandShakeResponseMessage",
"RC:CsEnd": "TerminateMessage",
"RC:CsSp": "SuspendMessage",
"RC:CsUpdate": "CustomerStatusUpdateMessage",
"RC:ReadNtf": "ReadReceiptMessage",
"RC:VCAccept": "AcceptMessage",
"RC:VCRinging": "RingingMessage",
"RC:VCSummary": "SummaryMessage",
"RC:VCHangup": "HungupMessage",
"RC:VCInvite": "InviteMessage",
"RC:VCModifyMedia": "MediaModifyMessage",
"RC:VCModifyMem": "MemberModifyMessage",
"RC:CsContact": "CustomerContact",
"RC:PSImgTxtMsg": "PublicServiceRichContentMessage",
"RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage",
"RC:GrpNtf": "GroupNotificationMessage",
"RC:PSCmd": "PublicServiceCommandMessage",
"RC:RcCmd": "RecallCommandMessage",
"RC:SRSMsg": "SyncReadStatusMessage",
"RC:RRReqMsg": "ReadReceiptRequestMessage",
"RC:RRRspMsg": "ReadReceiptResponseMessage",
"RCJrmf:RpMsg": "JrmfReadPacketMessage",
"RCJrmf:RpOpendMsg": "JrmfReadPacketOpenedMessage",
"RCE:UpdateStatus": "RCEUpdateStatusMessage"
},
//่ชๅฎไนๆถๆฏ็ฑปๅ
registerMessageTypeMapping = {}, HistoryMsgType = {
4: "qryCMsg",
2: "qryDMsg",
3: "qryGMsg",
1: "qryPMsg",
6: "qrySMsg",
7: "qryPMsg",
8: "qryPMsg",
5: "qryCMsg"
}, disconnectStatus = { 1: 6 };
var RongIMLib;
(function (RongIMLib) {
/**
* ้้ๆ ่ฏ็ฑป
*/
var Transportations = (function () {
function Transportations() {
}
Transportations._TransportType = RongIMLib.Socket.WEBSOCKET;
return Transportations;
})();
RongIMLib.Transportations = Transportations;
var MessageUtil = (function () {
function MessageUtil() {
}
/**
*4680000 ไธบlocalstorageๆๅฐๅฎน้5200000ๅญ่็90%๏ผ่ถ
่ฟ90%ๅฐๅ ้คไนๅ่ฟๆฉ็ๅญๅจ
*/
MessageUtil.checkStorageSize = function () {
return JSON.stringify(localStorage).length < 4680000;
};
MessageUtil.getFirstKey = function (obj) {
var str = "";
for (var key in obj) {
str = key;
break;
}
return str;
};
MessageUtil.isEmpty = function (obj) {
var empty = true;
for (var key in obj) {
empty = false;
break;
}
return empty;
};
MessageUtil.ArrayForm = function (typearray) {
if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") {
var arr = new Int8Array(typearray);
return [].slice.call(arr);
}
return typearray;
};
MessageUtil.ArrayFormInput = function (typearray) {
if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") {
var arr = new Uint8Array(typearray);
return arr;
}
return typearray;
};
MessageUtil.indexOf = function (arr, item, from) {
for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) {
if (arr[i] == item) {
return i;
}
}
return -1;
};
MessageUtil.isArray = function (obj) {
return Object.prototype.toString.call(obj) == "[object Array]";
};
//้ๅ๏ผๅช่ฝ้ๅๆฐ็ป
MessageUtil.forEach = function (arr, func) {
if ([].forEach) {
return function (arr, func) {
[].forEach.call(arr, func);
};
}
else {
return function (arr, func) {
for (var i = 0; i < arr.length; i++) {
func.call(arr, arr[i], i, arr);
}
};
}
};
MessageUtil.remove = function (array, func) {
for (var i = 0, len = array.length; i < len; i++) {
if (func(array[i])) {
return array.splice(i, 1)[0];
}
}
return null;
};
MessageUtil.int64ToTimestamp = function (obj, isDate) {
if (obj.low === undefined) {
return obj;
}
var low = obj.low;
if (low < 0) {
low += 0xffffffff + 1;
}
low = low.toString(16);
var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16);
if (isDate) {
return new Date(timestamp);
}
return timestamp;
};
//ๆถๆฏ่ฝฌๆขๆนๆณ
MessageUtil.messageParser = function (entity, onReceived, offlineMsg) {
var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false;
try {
if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) {
val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content);
de = JSON.parse(val);
}
else {
val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content);
de = JSON.parse(val);
}
}
catch (ex) {
de = val;
isUseDef = true;
}
//ๆ ๅฐไธบๅ
ทไฝๆถๆฏๅฏน่ฑก
if (objectName in typeMapping) {
var str = "new RongIMLib." + typeMapping[objectName] + "(de)";
message.content = eval(str);
message.messageType = typeMapping[objectName];
}
else if (objectName in registerMessageTypeMapping) {
var str = "new RongIMLib.RongIMClient.RegisterMessage." + registerMessageTypeMapping[objectName] + "(de)";
if (isUseDef) {
message.content = eval(str).decode(de);
}
else {
message.content = eval(str);
}
message.messageType = registerMessageTypeMapping[objectName];
}
else {
message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName });
message.messageType = "UnknownMessage";
}
//ๆ นๆฎๅฎไฝๅฏน่ฑก่ฎพ็ฝฎmessageๅฏน่ฑก]
var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime);
if (dateTime > 0) {
message.sentTime = dateTime;
}
else {
message.sentTime = +new Date;
}
message.senderUserId = entity.fromUserId;
message.conversationType = entity.type;
if (entity.fromUserId == RongIMLib.Bridge._client.userId) {
message.targetId = entity.groupId;
}
else {
message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId);
}
if (entity.direction == 1) {
message.messageDirection = RongIMLib.MessageDirection.SEND;
message.senderUserId = RongIMLib.Bridge._client.userId;
}
else {
if (message.senderUserId == RongIMLib.Bridge._client.userId) {
message.messageDirection = RongIMLib.MessageDirection.SEND;
}
else {
message.messageDirection = RongIMLib.MessageDirection.RECEIVE;
}
}
message.messageUId = entity.msgId;
message.receivedTime = new Date().getTime();
message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff));
message.objectName = objectName;
message.receivedStatus = RongIMLib.ReceivedStatus.READ;
if ((entity.status & 2) == 2) {
message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED;
}
message.offLineMessage = offlineMsg ? true : false;
if (!offlineMsg) {
if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) {
message.offLineMessage = true;
}
}
return message;
};
//้้
SSL
// static schemeArrs: Array<any> = [["http", "ws"], ["https", "wss"]];
MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true };
return MessageUtil;
})();
RongIMLib.MessageUtil = MessageUtil;
/**
* ๅทฅๅ
ท็ฑป
*/
var MessageIdHandler = (function () {
function MessageIdHandler() {
}
MessageIdHandler.init = function () {
this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0);
};
MessageIdHandler.messageIdPlus = function (method) {
RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init();
if (this.messageId >= 65535) {
method();
return false;
}
this.messageId++;
RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId);
return this.messageId;
};
MessageIdHandler.clearMessageId = function () {
this.messageId = 0;
RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId);
};
MessageIdHandler.getMessageId = function () {
RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init();
return this.messageId;
};
MessageIdHandler.messageId = 0;
return MessageIdHandler;
})();
RongIMLib.MessageIdHandler = MessageIdHandler;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var MessageContent = (function () {
function MessageContent(data) {
throw new Error("This method is abstract, you must implement this method in inherited class.");
}
MessageContent.obtain = function () {
throw new Error("This method is abstract, you must implement this method in inherited class.");
};
return MessageContent;
})();
RongIMLib.MessageContent = MessageContent;
var NotificationMessage = (function (_super) {
__extends(NotificationMessage, _super);
function NotificationMessage() {
_super.apply(this, arguments);
}
return NotificationMessage;
})(MessageContent);
RongIMLib.NotificationMessage = NotificationMessage;
var StatusMessage = (function (_super) {
__extends(StatusMessage, _super);
function StatusMessage() {
_super.apply(this, arguments);
}
return StatusMessage;
})(MessageContent);
RongIMLib.StatusMessage = StatusMessage;
var ModelUtil = (function () {
function ModelUtil() {
}
ModelUtil.modelClone = function (object) {
var obj = {};
for (var item in object) {
if (item != "messageName" && "encode" != item) {
obj[item] = object[item];
}
}
return obj;
};
ModelUtil.modleCreate = function (fields, msgType) {
if (fields.length < 1) {
throw new Error("Array is empty -> registerMessageType.modleCreate");
}
var Object = function (message) {
var me = this;
for (var index in fields) {
if (message[fields[index]]) {
me[fields[index]] = message[fields[index]];
}
}
Object.prototype.messageName = msgType;
Object.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
};
return Object;
};
return ModelUtil;
})();
RongIMLib.ModelUtil = ModelUtil;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var CustomerStatusMessage = (function () {
function CustomerStatusMessage(message) {
this.messageName = "CustomerStatusMessage";
this.status = message.status;
}
CustomerStatusMessage.obtain = function () {
return null;
};
CustomerStatusMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return CustomerStatusMessage;
})();
RongIMLib.CustomerStatusMessage = CustomerStatusMessage;
/**
* ๅฎขๆ่ฝฌๆขๅๅบๆถๆฏ็็ฑปๅๅ
*/
var ChangeModeResponseMessage = (function () {
function ChangeModeResponseMessage(message) {
this.messageName = "ChangeModeResponseMessage";
this.code = message.code;
this.data = message.data;
this.msg = message.msg;
}
ChangeModeResponseMessage.obtain = function () {
return null;
};
ChangeModeResponseMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return ChangeModeResponseMessage;
})();
RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage;
/**
* ๅฎขๆ่ฝฌๆขๆถๆฏ็็ฑปๅๅ
* ๆญคๆถๆฏไธ่ฎกๅ
ฅๆช่ฏปๆถๆฏๆฐ
*/
var ChangeModeMessage = (function () {
function ChangeModeMessage(message) {
this.messageName = "ChangeModeMessage";
this.uid = message.uid;
this.sid = message.sid;
this.pid = message.pid;
}
ChangeModeMessage.obtain = function () {
return null;
};
ChangeModeMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return ChangeModeMessage;
})();
RongIMLib.ChangeModeMessage = ChangeModeMessage;
var CustomerStatusUpdateMessage = (function () {
function CustomerStatusUpdateMessage(message) {
this.messageName = "CustomerStatusUpdateMessage";
this.serviceStatus = message.serviceStatus;
this.sid = message.sid;
}
CustomerStatusUpdateMessage.obtain = function () {
return null;
};
CustomerStatusUpdateMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return CustomerStatusUpdateMessage;
})();
RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage;
var HandShakeMessage = (function () {
function HandShakeMessage(message) {
this.messageName = "HandShakeMessage";
message && (this.groupid = message.groupid);
}
HandShakeMessage.obtain = function () {
return null;
};
HandShakeMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return HandShakeMessage;
})();
RongIMLib.HandShakeMessage = HandShakeMessage;
var CustomerContact = (function () {
function CustomerContact(message) {
this.messageName = "CustomerContact";
this.page = message.page;
this.nickName = message.nickName;
this.routingInfo = message.routingInfo;
this.info = message.info;
this.requestInfo = message.requestInfo;
}
CustomerContact.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return CustomerContact;
})();
RongIMLib.CustomerContact = CustomerContact;
var EvaluateMessage = (function () {
function EvaluateMessage(message) {
this.messageName = "EvaluateMessage";
this.uid = message.uid;
this.sid = message.sid;
this.pid = message.pid;
this.source = message.source;
this.suggest = message.suggest;
this.isresolve = message.isresolve;
this.type = message.type;
}
EvaluateMessage.obtain = function () {
return null;
};
EvaluateMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return EvaluateMessage;
})();
RongIMLib.EvaluateMessage = EvaluateMessage;
/**
* ๅฎขๆๆกๆๅๅบๆถๆฏ็็ฑปๅๅ
*/
var HandShakeResponseMessage = (function () {
function HandShakeResponseMessage(message) {
this.messageName = "HandShakeResponseMessage";
this.msg = message.msg;
this.status = message.status;
this.data = message.data;
}
HandShakeResponseMessage.obtain = function () {
return null;
};
HandShakeResponseMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return HandShakeResponseMessage;
})();
RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage;
var SuspendMessage = (function () {
function SuspendMessage(message) {
this.messageName = "SuspendMessage";
this.uid = message.uid;
this.sid = message.sid;
this.pid = message.pid;
}
SuspendMessage.obtain = function () {
return null;
};
SuspendMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return SuspendMessage;
})();
RongIMLib.SuspendMessage = SuspendMessage;
var TerminateMessage = (function () {
function TerminateMessage(message) {
this.messageName = "TerminateMessage";
this.code = message.code;
this.msg = message.msg;
this.sid = message.sid;
}
TerminateMessage.obtain = function () {
return null;
};
TerminateMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return TerminateMessage;
})();
RongIMLib.TerminateMessage = TerminateMessage;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var IsTypingStatusMessage = (function () {
function IsTypingStatusMessage(data) {
this.messageName = "IsTypingStatusMessage";
var msg = data;
}
IsTypingStatusMessage.prototype.encode = function () {
return undefined;
};
IsTypingStatusMessage.prototype.getMessage = function () {
return null;
};
return IsTypingStatusMessage;
})();
RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var InformationNotificationMessage = (function () {
function InformationNotificationMessage(message) {
this.messageName = "InformationNotificationMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage.");
}
this.message = message.message;
this.extra = message.extra;
if (message.user) {
this.user = message.user;
}
}
InformationNotificationMessage.obtain = function (message) {
return new InformationNotificationMessage({ message: message, extra: "" });
};
InformationNotificationMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return InformationNotificationMessage;
})();
RongIMLib.InformationNotificationMessage = InformationNotificationMessage;
var CommandMessage = (function () {
function CommandMessage(message) {
this.messageName = "CommandMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage.");
}
try {
if (Object.prototype.toString.call(message.data) == "[object String]") {
this.data = JSON.parse(message.data);
}
else {
this.data = message.data;
}
}
catch (e) {
this.data = message.data;
}
this.name = message.name;
this.extra = message.extra;
}
CommandMessage.obtain = function (data) {
return new CommandMessage({ data: data, extra: "" });
};
CommandMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return CommandMessage;
})();
RongIMLib.CommandMessage = CommandMessage;
var ContactNotificationMessage = (function () {
function ContactNotificationMessage(message) {
this.messageName = "ContactNotificationMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage.");
}
this.operation = message.operation;
this.targetUserId = message.targetUserId;
this.message = message.message;
this.extra = message.extra;
this.sourceUserId = message.sourceUserId;
if (message.user) {
this.user = message.user;
}
}
ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) {
return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message });
};
ContactNotificationMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse";
ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse";
ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest";
return ContactNotificationMessage;
})();
RongIMLib.ContactNotificationMessage = ContactNotificationMessage;
var ProfileNotificationMessage = (function () {
function ProfileNotificationMessage(message) {
this.messageName = "ProfileNotificationMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage.");
}
this.operation = message.operation;
try {
if (Object.prototype.toString.call(message.data) == "[object String]") {
this.data = JSON.parse(message.data);
}
else {
this.data = message.data;
}
}
catch (e) {
this.data = message.data;
}
this.extra = message.extra;
if (message.user) {
this.user = message.user;
}
}
ProfileNotificationMessage.obtain = function (operation, data) {
return new ProfileNotificationMessage({ operation: operation, data: data });
};
ProfileNotificationMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return ProfileNotificationMessage;
})();
RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage;
var CommandNotificationMessage = (function () {
function CommandNotificationMessage(message) {
this.messageName = "CommandNotificationMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage.");
}
try {
if (Object.prototype.toString.call(message.data) == "[object String]") {
this.data = JSON.parse(message.data);
}
else {
this.data = message.data;
}
}
catch (e) {
this.data = message.data;
}
this.name = message.name;
this.extra = message.extra;
if (message.user) {
this.user = message.user;
}
}
CommandNotificationMessage.obtain = function (name, data) {
return new CommandNotificationMessage({ name: name, data: data, extra: "" });
};
CommandNotificationMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return CommandNotificationMessage;
})();
RongIMLib.CommandNotificationMessage = CommandNotificationMessage;
var DiscussionNotificationMessage = (function () {
function DiscussionNotificationMessage(message) {
this.messageName = "DiscussionNotificationMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage.");
}
this.extra = message.extra;
this.extension = message.extension;
this.type = message.type;
this.isHasReceived = message.isHasReceived;
this.operation = message.operation;
this.user = message.user;
if (message.user) {
this.user = message.user;
}
}
DiscussionNotificationMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return DiscussionNotificationMessage;
})();
RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage;
var GroupNotificationMessage = (function () {
function GroupNotificationMessage(msg) {
this.messageName = "GroupNotificationMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage.");
}
msg.operatorUserId && (this.operatorUserId = msg.operatorUserId);
msg.operation && (this.operation = msg.operation);
msg.data && (this.data = msg.data);
msg.message && (this.message = msg.message);
msg.extra && (this.extra = msg.extra);
}
GroupNotificationMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return GroupNotificationMessage;
})();
RongIMLib.GroupNotificationMessage = GroupNotificationMessage;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var TextMessage = (function () {
function TextMessage(message) {
this.messageName = "TextMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage.");
}
this.content = message.content;
this.extra = message.extra;
if (message.user) {
this.user = message.user;
}
if (message.mentionedInfo) {
this.mentionedInfo = message.mentionedInfo;
}
}
TextMessage.obtain = function (text) {
return new TextMessage({ extra: "", content: text });
};
TextMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return TextMessage;
})();
RongIMLib.TextMessage = TextMessage;
var TypingStatusMessage = (function () {
function TypingStatusMessage(message) {
this.messageName = "TypingStatusMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage.");
}
this.typingContentType = message.typingContentType;
this.data = message.data;
}
TypingStatusMessage.obtain = function (typingContentType, data) {
return new TypingStatusMessage({ typingContentType: typingContentType, data: data });
};
TypingStatusMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return TypingStatusMessage;
})();
RongIMLib.TypingStatusMessage = TypingStatusMessage;
var ReadReceiptMessage = (function () {
function ReadReceiptMessage(message) {
this.messageName = "ReadReceiptMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage.");
}
this.lastMessageSendTime = message.lastMessageSendTime;
this.messageUId = message.messageUId;
this.type = message.type;
}
ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) {
return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type });
};
ReadReceiptMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return ReadReceiptMessage;
})();
RongIMLib.ReadReceiptMessage = ReadReceiptMessage;
var VoiceMessage = (function () {
function VoiceMessage(message) {
this.messageName = "VoiceMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage.");
}
this.content = message.content;
this.duration = message.duration;
this.extra = message.extra;
if (message.user) {
this.user = message.user;
}
if (message.mentionedInfo) {
this.mentionedInfo = message.mentionedInfo;
}
}
VoiceMessage.obtain = function (base64Content, duration) {
return new VoiceMessage({ content: base64Content, duration: duration, extra: "" });
};
VoiceMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return VoiceMessage;
})();
RongIMLib.VoiceMessage = VoiceMessage;
var RecallCommandMessage = (function () {
function RecallCommandMessage(message) {
this.messageName = "RecallCommandMessage";
this.messageUId = message.messageUId;
this.conversationType = message.conversationType;
this.targetId = message.targetId;
this.sentTime = message.sentTime;
message.extra && (this.extra = message.extra);
message.user && (this.user = message.user);
}
RecallCommandMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return RecallCommandMessage;
})();
RongIMLib.RecallCommandMessage = RecallCommandMessage;
var ImageMessage = (function () {
function ImageMessage(message) {
this.messageName = "ImageMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage.");
}
this.content = message.content;
this.imageUri = message.imageUri;
message.extra && (this.extra = message.extra);
message.user && (this.user = message.user);
if (message.mentionedInfo) {
this.mentionedInfo = message.mentionedInfo;
}
}
ImageMessage.obtain = function (content, imageUri) {
return new ImageMessage({ content: content, imageUri: imageUri, extra: "" });
};
ImageMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return ImageMessage;
})();
RongIMLib.ImageMessage = ImageMessage;
var LocationMessage = (function () {
function LocationMessage(message) {
this.messageName = "LocationMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage.");
}
this.latitude = message.latitude;
this.longitude = message.longitude;
this.poi = message.poi;
this.content = message.content;
this.extra = message.extra;
if (message.user) {
this.user = message.user;
}
if (message.mentionedInfo) {
this.mentionedInfo = message.mentionedInfo;
}
}
LocationMessage.obtain = function (latitude, longitude, poi, content) {
return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" });
};
LocationMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return LocationMessage;
})();
RongIMLib.LocationMessage = LocationMessage;
var RichContentMessage = (function () {
function RichContentMessage(message) {
this.messageName = "RichContentMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage.");
}
this.title = message.title;
this.content = message.content;
this.imageUri = message.imageUri;
this.extra = message.extra;
this.url = message.url;
if (message.user) {
this.user = message.user;
}
}
RichContentMessage.obtain = function (title, content, imageUri, url) {
return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" });
};
RichContentMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return RichContentMessage;
})();
RongIMLib.RichContentMessage = RichContentMessage;
var JrmfReadPacketMessage = (function () {
function JrmfReadPacketMessage(message) {
this.messageName = 'JrmfReadPacketMessage';
message && (this.message = message);
}
JrmfReadPacketMessage.prototype.encode = function () {
return "";
};
return JrmfReadPacketMessage;
})();
RongIMLib.JrmfReadPacketMessage = JrmfReadPacketMessage;
var JrmfReadPacketOpenedMessage = (function () {
function JrmfReadPacketOpenedMessage(message) {
this.messageName = 'JrmfReadPacketOpenedMessage';
message && (this.message = message);
}
JrmfReadPacketOpenedMessage.prototype.encode = function () {
return "";
};
return JrmfReadPacketOpenedMessage;
})();
RongIMLib.JrmfReadPacketOpenedMessage = JrmfReadPacketOpenedMessage;
var UnknownMessage = (function () {
function UnknownMessage(message) {
this.messageName = "UnknownMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage.");
}
this.message = message;
}
UnknownMessage.prototype.encode = function () {
return "";
};
return UnknownMessage;
})();
RongIMLib.UnknownMessage = UnknownMessage;
var PublicServiceCommandMessage = (function () {
function PublicServiceCommandMessage(message) {
this.messageName = "PublicServiceCommandMessage";
if (arguments.length == 0) {
throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage.");
}
this.content = message.content;
this.extra = message.extra;
this.menuItem = message.menuItem;
if (message.user) {
this.user = message.user;
}
if (message.mentionedInfo) {
this.mentionedInfo = message.mentionedInfo;
}
}
PublicServiceCommandMessage.obtain = function (item) {
return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" });
};
PublicServiceCommandMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return PublicServiceCommandMessage;
})();
RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage;
var PublicServiceMultiRichContentMessage = (function () {
function PublicServiceMultiRichContentMessage(messages) {
this.messageName = "PublicServiceMultiRichContentMessage";
this.richContentMessages = messages;
}
PublicServiceMultiRichContentMessage.prototype.encode = function () {
return null;
};
return PublicServiceMultiRichContentMessage;
})();
RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage;
var SyncReadStatusMessage = (function () {
function SyncReadStatusMessage(message) {
this.messageName = "SyncReadStatusMessage";
message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime);
}
SyncReadStatusMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return SyncReadStatusMessage;
})();
RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage;
var ReadReceiptRequestMessage = (function () {
function ReadReceiptRequestMessage(message) {
this.messageName = "ReadReceiptRequestMessage";
message.messageUId && (this.messageUId = message.messageUId);
}
ReadReceiptRequestMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return ReadReceiptRequestMessage;
})();
RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage;
var ReadReceiptResponseMessage = (function () {
function ReadReceiptResponseMessage(message) {
this.messageName = "ReadReceiptResponseMessage";
message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic);
}
ReadReceiptResponseMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return ReadReceiptResponseMessage;
})();
RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage;
var PublicServiceRichContentMessage = (function () {
function PublicServiceRichContentMessage(message) {
this.messageName = "PublicServiceRichContentMessage";
this.richContentMessage = message;
}
PublicServiceRichContentMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return PublicServiceRichContentMessage;
})();
RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage;
var FileMessage = (function () {
function FileMessage(message) {
this.messageName = "FileMessage";
message.name && (this.name = message.name);
message.size && (this.size = message.size);
message.type && (this.type = message.type);
message.fileUrl && (this.fileUrl = message.fileUrl);
message.extra && (this.extra = message.extra);
message.user && (this.user = message.user);
}
FileMessage.obtain = function (msg) {
return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl });
};
FileMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return FileMessage;
})();
RongIMLib.FileMessage = FileMessage;
var AcceptMessage = (function () {
function AcceptMessage(message) {
this.messageName = "AcceptMessage";
this.callId = message.callId;
this.mediaType = message.mediaType;
}
AcceptMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return AcceptMessage;
})();
RongIMLib.AcceptMessage = AcceptMessage;
var RingingMessage = (function () {
function RingingMessage(message) {
this.messageName = "RingingMessage";
this.callId = message.callId;
}
RingingMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return RingingMessage;
})();
RongIMLib.RingingMessage = RingingMessage;
var SummaryMessage = (function () {
function SummaryMessage(message) {
this.messageName = "SummaryMessage";
this.caller = message.caller;
this.inviter = message.inviter;
this.mediaType = message.mediaType;
this.memberIdList = message.memberIdList;
this.startTime = message.startTime;
this.connectedTime = message.connectedTime;
this.duration = message.duration;
this.status = message.status;
}
SummaryMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return SummaryMessage;
})();
RongIMLib.SummaryMessage = SummaryMessage;
var HungupMessage = (function () {
function HungupMessage(message) {
this.messageName = "HungupMessage";
this.callId = message.callId;
this.reason = message.reason;
}
HungupMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return HungupMessage;
})();
RongIMLib.HungupMessage = HungupMessage;
var InviteMessage = (function () {
function InviteMessage(message) {
this.messageName = "InviteMessage";
this.callId = message.callId;
this.engineType = message.engineType;
this.channelInfo = message.channelInfo;
this.mediaType = message.mediaType;
this.extra = message.extra;
this.inviteUserIds = message.inviteUserIds;
}
InviteMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return InviteMessage;
})();
RongIMLib.InviteMessage = InviteMessage;
var MediaModifyMessage = (function () {
function MediaModifyMessage(message) {
this.messageName = "MediaModifyMessage";
this.callId = message.callId;
this.mediaType = message.mediaType;
}
MediaModifyMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return MediaModifyMessage;
})();
RongIMLib.MediaModifyMessage = MediaModifyMessage;
var MemberModifyMessage = (function () {
function MemberModifyMessage(message) {
this.messageName = "MemberModifyMessage";
this.modifyMemType = message.modifyMemType;
this.callId = message.callId;
this.caller = message.caller;
this.engineType = message.engineType;
this.channelInfo = message.channelInfo;
this.mediaType = message.mediaType;
this.extra = message.extra;
this.inviteUserIds = message.inviteUserIds;
this.existedMemberStatusList = message.existedMemberStatusList;
}
MemberModifyMessage.prototype.encode = function () {
return JSON.stringify(RongIMLib.ModelUtil.modelClone(this));
};
return MemberModifyMessage;
})();
RongIMLib.MemberModifyMessage = MemberModifyMessage;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var ChannelInfo = (function () {
function ChannelInfo(Id, Key) {
this.Id = Id;
this.Key = Key;
}
return ChannelInfo;
})();
RongIMLib.ChannelInfo = ChannelInfo;
var UserStatus = (function () {
function UserStatus(platform, online, status) {
this.platform = platform;
this.online = online;
this.status = status;
}
return UserStatus;
})();
RongIMLib.UserStatus = UserStatus;
var MentionedInfo = (function () {
function MentionedInfo(type, userIdList, mentionedContent) {
}
return MentionedInfo;
})();
RongIMLib.MentionedInfo = MentionedInfo;
var DeleteMessage = (function () {
function DeleteMessage(msgId, msgDataTime, direct) {
this.msgId = msgId;
this.msgDataTime = msgDataTime;
this.direct = direct;
}
return DeleteMessage;
})();
RongIMLib.DeleteMessage = DeleteMessage;
var CustomServiceConfig = (function () {
function CustomServiceConfig(isBlack, companyName, companyUrl) {
}
return CustomServiceConfig;
})();
RongIMLib.CustomServiceConfig = CustomServiceConfig;
var CustomServiceSession = (function () {
function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) {
}
return CustomServiceSession;
})();
RongIMLib.CustomServiceSession = CustomServiceSession;
var Conversation = (function () {
function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention) {
this.conversationTitle = conversationTitle;
this.conversationType = conversationType;
this.draft = draft;
this.isTop = isTop;
this.latestMessage = latestMessage;
this.latestMessageId = latestMessageId;
this.notificationStatus = notificationStatus;
this.objectName = objectName;
this.receivedStatus = receivedStatus;
this.receivedTime = receivedTime;
this.senderUserId = senderUserId;
this.senderUserName = senderUserName;
this.sentStatus = sentStatus;
this.sentTime = sentTime;
this.targetId = targetId;
this.unreadMessageCount = unreadMessageCount;
this.senderPortraitUri = senderPortraitUri;
this.isHidden = isHidden;
this.mentionedMsg = mentionedMsg;
this.hasUnreadMention = hasUnreadMention;
}
Conversation.prototype.setTop = function () {
RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } });
};
return Conversation;
})();
RongIMLib.Conversation = Conversation;
var Discussion = (function () {
function Discussion(creatorId, id, memberIdList, name, isOpen) {
this.creatorId = creatorId;
this.id = id;
this.memberIdList = memberIdList;
this.name = name;
this.isOpen = isOpen;
}
return Discussion;
})();
RongIMLib.Discussion = Discussion;
var Group = (function () {
function Group(id, name, portraitUri) {
this.id = id;
this.name = name;
this.portraitUri = portraitUri;
}
return Group;
})();
RongIMLib.Group = Group;
var Message = (function () {
function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse) {
this.content = content;
this.conversationType = conversationType;
this.extra = extra;
this.objectName = objectName;
this.messageDirection = messageDirection;
this.messageId = messageId;
this.receivedStatus = receivedStatus;
this.receivedTime = receivedTime;
this.senderUserId = senderUserId;
this.sentStatus = sentStatus;
this.sentTime = sentTime;
this.targetId = targetId;
this.messageType = messageType;
this.messageUId = messageUId;
this.isLocalMessage = isLocalMessage;
this.offLineMessage = offLineMessage;
this.receiptResponse = receiptResponse;
}
return Message;
})();
RongIMLib.Message = Message;
var MessageTag = (function () {
function MessageTag(isCounted, isPersited) {
this.isCounted = isCounted;
this.isPersited = isPersited;
}
MessageTag.prototype.getMessageTag = function () {
if (this.isCounted && this.isPersited) {
return 3;
}
else if (this.isCounted) {
return 2;
}
else if (this.isPersited) {
return 1;
}
else if (!this.isCounted && !this.isPersited) {
return 0;
}
};
return MessageTag;
})();
RongIMLib.MessageTag = MessageTag;
var PublicServiceMenuItem = (function () {
function PublicServiceMenuItem(id, name, type, sunMenuItems, url) {
this.id = id;
this.name = name;
this.type = type;
this.sunMenuItems = sunMenuItems;
this.url = url;
}
return PublicServiceMenuItem;
})();
RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem;
// TODO: TBD
var PublicServiceProfile = (function () {
function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) {
this.conversationType = conversationType;
this.introduction = introduction;
this.menu = menu;
this.name = name;
this.portraitUri = portraitUri;
this.publicServiceId = publicServiceId;
this.hasFollowed = hasFollowed;
this.isGlobal = isGlobal;
}
return PublicServiceProfile;
})();
RongIMLib.PublicServiceProfile = PublicServiceProfile;
var UserInfo = (function () {
function UserInfo(id, name, portraitUri) {
this.id = id;
this.name = name;
this.portraitUri = portraitUri;
}
return UserInfo;
})();
RongIMLib.UserInfo = UserInfo;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var ServerDataProvider = (function () {
function ServerDataProvider() {
}
ServerDataProvider.prototype.init = function (appKey, callback) {
new RongIMLib.FeatureDectector(callback);
};
ServerDataProvider.prototype.connect = function (token, callback) {
RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance();
RongIMLib.RongIMClient._memoryStore.token = token;
RongIMLib.RongIMClient._memoryStore.callback = callback;
if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING) {
return;
}
//ๅพช็ฏ่ฎพ็ฝฎ็ๅฌไบไปถ๏ผ่ฟฝๅ ไนๅๆธ
็ฉบๅญๆพไบไปถๆฐๆฎ
for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.listenerList.length; i < len; i++) {
RongIMLib.RongIMClient.bridge["setListener"](RongIMLib.RongIMClient._memoryStore.listenerList[i]);
}
RongIMLib.RongIMClient._memoryStore.listenerList.length = 0;
RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, {
onSuccess: function (data) {
setTimeout(function () {
callback.onSuccess(data);
});
},
onError: function (e) {
if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) {
setTimeout(function () {
callback.onTokenIncorrect();
});
}
else {
setTimeout(function () {
callback.onError(e);
});
}
}
});
};
/*
config.auto: ้ป่ฎค false, true ๅฏ็จ่ชๅจ้่ฟ๏ผๅฏ็จๅไธบๅฟ
้ๅๆฐ
config.rate: ้่ฏ้ข็ [100, 1000, 3000, 6000, 10000, 18000] ๅไฝไธบๆฏซ็ง๏ผๅฏ้
config.url: ็ฝ็ปๅ
ๆขๅฐๅ [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js ๅฏ้
*/
ServerDataProvider.prototype.reconnect = function (callback, config) {
var store = RongIMLib.RongIMClient._memoryStore;
var token = store.token;
if (!token) {
throw new Error('reconnect: token is empty.');
}
if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) {
config = config || {};
var key = config.auto ? 'auto' : 'custom';
var handler = {
auto: function () {
var repeatConnect = function (options) {
var step = options.step();
var done = 'done';
var url = options.url;
var ping = function () {
RongIMLib.RongUtil.request({
url: url,
success: function () {
options.done();
},
error: function () {
repeat();
}
});
};
var repeat = function () {
var next = step();
if (next == 'done') {
var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE;
options.done(error);
return;
}
setTimeout(ping, next);
};
repeat();
};
var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol;
var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js';
var pathConfig = {
protocol: protocol,
path: url
};
url = RongIMLib.RongUtil.formatProtoclPath(pathConfig);
var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000];
//็ปๆๆ ่ฏ
rate.push('done');
var opts = {
url: url,
step: function () {
var index = 0;
return function () {
var time = rate[index];
index++;
return time;
};
},
done: function (error) {
if (error) {
callback.onError(error);
return;
}
RongIMLib.RongIMClient.connect(token, callback);
}
};
repeatConnect(opts);
},
custom: function () {
RongIMLib.RongIMClient.connect(token, callback);
}
};
handler[key]();
}
};
ServerDataProvider.prototype.logout = function () {
RongIMLib.RongIMClient.bridge.disconnect();
RongIMLib.RongIMClient.bridge = null;
};
ServerDataProvider.prototype.disconnect = function () {
RongIMLib.RongIMClient.bridge.disconnect();
};
ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) {
var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this;
if (RongIMLib.RongUtil.supportLocalStorage()) {
var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey));
if (valObj) {
var vals = [];
for (var key in valObj) {
var tmp = {};
tmp[key] = valObj[key].uIds;
valObj[key].isResponse || vals.push(tmp);
}
if (vals.length == 0) {
sendCallback.onSuccess();
return;
}
var interval = setInterval(function () {
if (vals.length == 1) {
clearInterval(interval);
}
var obj = vals.splice(0, 1)[0];
var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj });
me.sendMessage(conversationType, targetId, rspMsg, {
onSuccess: function (msg) {
var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj);
valObj[senderUserId].isResponse = true;
RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj));
sendCallback.onSuccess(msg);
},
onError: function (error, msg) {
sendCallback.onError(error, msg);
}
});
}, 200);
}
else {
sendCallback.onSuccess();
}
}
else {
sendCallback.onSuccess();
}
};
ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) {
var me = this;
if (messageName in RongIMLib.RongIMClient.MessageParams) {
me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), {
onSuccess: function () {
setTimeout(function () {
sendCallback.onSuccess();
});
},
onError: function (errorCode) {
setTimeout(function () {
sendCallback.onError(errorCode, null);
});
},
onBefore: function () { }
});
}
};
ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) {
var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user });
this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2);
};
ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) {
var msgContent = RongIMLib.TextMessage.obtain(content);
this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback);
};
ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback) {
if (count <= 1) {
throw new Error("the count must be greater than 1.");
}
var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMessageInput(), self = this;
modules.setTargetId(targetId);
if (timestamp === 0 || timestamp > 0) {
modules.setDataTime(timestamp);
}
else {
modules.setDataTime(RongIMLib.RongIMClient._memoryStore.lastReadTime.get(conversationType + targetId));
}
modules.setSize(count);
RongIMLib.RongIMClient.bridge.queryMsg(HistoryMsgType[conversationType], RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, {
onSuccess: function (data) {
RongIMLib.RongIMClient._memoryStore.lastReadTime.set(conversationType + targetId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime));
var list = data.list.reverse(), tempMsg = null, tempDir;
var read = RongIMLib.SentStatus.READ;
if (RongIMLib.RongUtil.supportLocalStorage()) {
for (var i = 0, len = list.length; i < len; i++) {
tempMsg = RongIMLib.MessageUtil.messageParser(list[i]);
tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT"));
if (tempDir) {
tempMsg.receiptResponse || (tempMsg.receiptResponse = {});
tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count;
}
tempMsg.sentStatus = read;
list[i] = tempMsg;
}
}
else {
for (var i = 0, len = list.length; i < len; i++) {
var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]);
tempMsg.sentStatus = read;
list[i] = tempMsg;
}
}
setTimeout(function () {
callback.onSuccess(list, !!data.hasMsg);
});
},
onError: function (error) {
callback.onError(error);
}
}, "HistoryMessagesOuput");
};
ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) {
var xss = null;
window.RCCallback = function (x) {
setTimeout(function () { callback.onSuccess(!!+x.status); });
xss.parentNode.removeChild(xss);
};
xss = document.createElement("script");
xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + Date.now();
document.body.appendChild(xss);
xss.onerror = function () {
setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); });
xss.parentNode.removeChild(xss);
};
};
ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) {
var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this;
modules.setType(1);
if (typeof count == 'undefined') {
modules.setCount(0);
}
else {
modules.setCount(count);
}
RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, {
onSuccess: function (list) {
if (list.info) {
list.info = list.info.reverse();
for (var i = 0, len = list.info.length; i < len; i++) {
RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]);
}
}
if (conversationTypes) {
var convers = [];
Array.forEach(conversationTypes, function (converType) {
Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) {
if (item.conversationType == converType) {
convers.push(item);
}
});
});
callback.onSuccess(convers);
}
else {
callback.onSuccess(RongIMLib.RongIMClient._memoryStore.conversationList);
}
},
onError: function (error) {
callback.onError(error);
}
}, "RelationsOutput");
};
ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput();
modules.setUsers(userIdList);
RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, {
onSuccess: function () {
setTimeout(function () {
callback.onSuccess();
});
},
onError: function (error) {
callback.onError(error);
}
});
};
ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this;
modules.setName(name);
RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, {
onSuccess: function (discussId) {
if (userIdList.length > 0) {
self.addMemberToDiscussion(discussId, userIdList, {
onSuccess: function () { },
onError: function (error) {
setTimeout(function () {
callback.onError(error);
});
}
});
}
setTimeout(function () {
callback.onSuccess(discussId);
});
},
onError: function (error) {
setTimeout(function () {
callback.onError(error);
});
}
}, "CreateDiscussionOutput");
};
ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput();
modules.setNothing(1);
RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, {
onSuccess: function (data) {
setTimeout(function () {
callback.onSuccess(data);
});
},
onError: function (errorCode) {
setTimeout(function () {
callback.onError(errorCode);
});
}
}, "ChannelInfoOutput");
};
ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput();
modules.setNothing(1);
RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, callback);
};
ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput();
modules.setUser(userId);
RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, callback);
};
ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput();
modules.setOpenStatus(status.valueOf());
RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, {
onSuccess: function (x) {
setTimeout(function () {
callback.onSuccess();
});
}, onError: function (error) {
setTimeout(function () {
callback.onError(error);
});
}
});
};
ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput();
modules.setName(name);
RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, {
onSuccess: function () {
setTimeout(function () {
callback.onSuccess();
});
},
onError: function (errcode) {
callback.onError(errcode);
}
});
};
ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) {
var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput();
e.setNothing(1);
RongIMLib.Bridge._client.chatroomId = chatroomId;
RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, {
onSuccess: function () {
callback.onSuccess();
var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg();
messageCount == 0 && (messageCount = -1);
modules.setCount(messageCount);
modules.setSyncTime(0);
RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, {
onSuccess: function (collection) {
var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime);
RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync);
var list = collection.list;
if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) {
for (var i = 0, mlen = list.length; i < mlen; i++) {
for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) {
if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) {
RongIMLib.Bridge._client.handler.onReceived(list[i]);
}
}
}
}
else {
for (var i = 0, len = list.length; i < len; i++) {
RongIMLib.Bridge._client.handler.onReceived(list[i]);
}
}
},
onError: function (x) {
setTimeout(function () {
callback.onError(RongIMLib.ErrorCode.CHATROOM_HISMESSAGE_ERROR);
});
}
}, "DownStreamMessages");
},
onError: function (error) {
setTimeout(function () {
callback.onError(error);
});
}
}, "ChrmOutput");
};
ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput();
modules.setCount(count);
modules.setOrder(order);
RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, {
onSuccess: function (ret) {
var userInfos = ret.userInfos;
userInfos.forEach(function (item) {
item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time);
});
setTimeout(function () {
callback.onSuccess(ret);
});
},
onError: function (errcode) {
callback.onError(errcode);
}
}, "QueryChatroomInfoOutput");
};
ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) {
var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput();
e.setNothing(1);
RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, {
onSuccess: function () {
setTimeout(function () {
callback.onSuccess();
});
},
onError: function (errcode) {
callback.onError(errcode);
}
}, "ChrmOutput");
};
ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) {
RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp);
};
ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput();
modules.setTargetId(chatRoomId);
var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0;
modules.setTime(timestamp);
modules.setCount(count);
modules.setOrder(order);
RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, {
onSuccess: function (data) {
RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime));
var list = data.list.reverse();
for (var i = 0, len = list.length; i < len; i++) {
list[i] = RongIMLib.MessageUtil.messageParser(list[i]);
}
setTimeout(function () {
callback.onSuccess(list, !!data.hasMsg);
});
},
onError: function (error) {
setTimeout(function () {
callback.onError(error);
});
}
}, "HistoryMsgOuput");
};
ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) {
callback.onSuccess(true);
};
ServerDataProvider.prototype.addToBlacklist = function (userId, callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput();
modules.setUserId(userId);
RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, {
onSuccess: function () {
callback.onSuccess();
},
onError: function (error) {
callback.onError(error);
}
});
};
ServerDataProvider.prototype.getBlacklist = function (callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput();
modules.setNothing(1);
RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, callback, "QueryBlackListOutput");
};
ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput();
modules.setUserId(userId);
RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, {
onSuccess: function (status) {
setTimeout(function () {
callback.onSuccess(RongIMLib.BlacklistStatus[status]);
});
}, onError: function (error) {
setTimeout(function () {
callback.onError(error);
});
}
});
};
ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) {
var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput();
modules.setUserId(userId);
RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, {
onSuccess: function () {
callback.onSuccess();
},
onError: function (error) {
callback.onError(error);
}
});
};
ServerDataProvider.prototype.getFileToken = function (fileType, callback) {
if (!(/(1|2|3|4)/.test(fileType.toString()))) {
callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR);
return;
}
var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput();
modules.setType(fileType);
RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, {
onSuccess: function (data) {
setTimeout(function () {
callback.onSuccess(data);
});
},
onError: function (errcode) {
callback.onError(errcode);
}
}, "GetQNupTokenOutput");
};
ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) {
if (!(/(1|2|3|4)/.test(fileType.toString()))) {
setTimeout(function () {
callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR);
});
return;
}
var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput();
modules.setType(fileType);
modules.setKey(fileName);
if (oriName) {
modules.setFileName(oriName);
}
RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, {
onSuccess: function (data) {
setTimeout(function () {
callback.onSuccess(data);
});
},
onError: function (errcode) {
callback.onError(errcode);
}
}, "GetQNdownloadUrlOutput");
};
/*
methodType 1 : ๅคๅฎขๆ(ๅฎขๆๅๅฐไฝฟ็จ); 2 : ๆถๆฏๆคๅ
params.userIds : ๅฎๅๆถๆฏๆฅๆถ่
*/
ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) {
if (!RongIMLib.Bridge._client.channel) {
sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null);
return;
}
if (!RongIMLib.Bridge._client.channel.socket.socket.connected) {
sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null);
throw new Error("connect is timeout! postion:sendMessage");
}
var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP);
var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage();
if (mentiondMsg && isGroup) {
modules.setSessionId(7);
}
else {
modules.setSessionId(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag());
}
pushText && modules.setPushText(pushText);
appData && modules.setAppData(appData);
if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) {
var rspMsg = messageContent;
if (rspMsg.receiptMessageDic) {
var ids = [];
for (var key in rspMsg.receiptMessageDic) {
ids.push(key);
}
modules.setUserId(ids);
}
}
if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) {
modules.setUserId(RongIMLib.Bridge._client.userId);
}
params = params || {};
var userIds = params.userIds;
if (isGroup && userIds) {
modules.setUserId(userIds);
}
modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName);
modules.setContent(messageContent.encode());
var content = modules.toArrayBuffer();
if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") {
content = [].slice.call(new Int8Array(content));
}
var c = null, me = this, msg = new RongIMLib.Message();
this.getConversation(conversationType, targetId, {
onSuccess: function (conver) {
c = conver;
if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) {
if (!c) {
c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, "");
}
c.sentTime = new Date().getTime();
c.sentStatus = RongIMLib.SentStatus.SENDING;
c.senderUserName = "";
c.senderUserId = RongIMLib.Bridge._client.userId;
c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB;
c.latestMessage = msg;
c.unreadMessageCount = 0;
RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } });
}
RongIMLib.RongIMClient._memoryStore.converStore = c;
}
});
msg.content = messageContent;
msg.conversationType = conversationType;
msg.senderUserId = RongIMLib.Bridge._client.userId;
msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName;
msg.targetId = targetId;
msg.sentTime = new Date().getTime();
msg.messageDirection = RongIMLib.MessageDirection.SEND;
msg.sentStatus = RongIMLib.SentStatus.SENT;
msg.messageType = messageContent.messageName;
RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, {
onSuccess: function (data) {
if (data && data.timestamp) {
RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp);
}
if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) {
var reqMsg = msg.content;
var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT";
RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} }));
}
if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) {
var cacheConversation = RongIMLib.RongIMClient._memoryStore.converStore;
cacheConversation.sentStatus = msg.sentStatus;
cacheConversation.latestMessage = msg;
me.updateConversation(cacheConversation);
RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, {
onSuccess: function (ret) {
msg = ret;
msg.messageUId = data.messageUId;
msg.sentTime = data.timestamp;
msg.sentStatus = RongIMLib.SentStatus.SENT;
msg.messageId = data.messageId;
RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg);
},
onError: function () { }
});
}
setTimeout(function () {
cacheConversation && me.updateConversation(cacheConversation);
msg.sentTime = data.timestamp;
sendCallback.onSuccess(msg);
});
},
onError: function (errorCode) {
msg.sentStatus = RongIMLib.SentStatus.FAILED;
if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) {
RongIMLib.RongIMClient._memoryStore.converStore.latestMessage = msg;
}
RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, {
onSuccess: function (ret) {
msg.messageId = ret.messageId;
RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg);
},
onError: function () { }
});
setTimeout(function () {
sendCallback.onError(errorCode, msg);
});
}
}, null, methodType);
sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId);
msg.messageId = RongIMLib.MessageIdHandler.messageId + "";
};
ServerDataProvider.prototype.setConnectionStatusListener = function (listener) {
if (RongIMLib.RongIMClient.bridge) {
RongIMLib.RongIMClient.bridge.setListener(listener);
}
else {
RongIMLib.RongIMClient._memoryStore.listenerList.push(listener);
}
};
ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) {
if (RongIMLib.RongIMClient.bridge) {
RongIMLib.RongIMClient.bridge.setListener(listener);
}
else {
RongIMLib.RongIMClient._memoryStore.listenerList.push(listener);
}
};
ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent) {
if (!messageType) {
throw new Error("messageType can't be empty,postion -> registerMessageType");
}
if (!objectName) {
throw new Error("objectName can't be empty,postion -> registerMessageType");
}
if (Object.prototype.toString.call(messageContent) == "[object Array]") {
var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType);
RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg;
}
else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") {
if (!messageContent.encode) {
throw new Error("encode method has not realized or messageName is undefined-> registerMessageType");
}
if (!messageContent.decode) {
throw new Error("decode method has not realized -> registerMessageType");
}
}
else {
throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType");
}
registerMessageTypeMapping[objectName] = messageType;
};
ServerDataProvider.prototype.addConversation = function (conversation, callback) {
var isAdd = true;
for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) {
if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) {
RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]);
isAdd = false;
break;
}
}
if (isAdd) {
RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation);
}
callback.onSuccess(true);
};
ServerDataProvider.prototype.updateConversation = function (conversation) {
var conver;
for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) {
var item = RongIMLib.RongIMClient._memoryStore.conversationList[i];
if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) {
conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle);
conversation.senderUserName && (item.senderUserName = conversation.senderUserName);
conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri);
conversation.latestMessage && (item.latestMessage = conversation.latestMessage);
conversation.sentStatus && (item.sentStatus = conversation.sentStatus);
break;
}
}
return conver;
};
ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) {
var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput();
mod.setType(conversationType);
RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, {
onSuccess: function () {
var conversations = RongIMLib.RongIMClient._memoryStore.conversationList;
var len = conversations.length;
for (var i = 0; i < len; i++) {
if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) {
conversations.splice(i, 1);
break;
}
}
callback.onSuccess(true);
}, onError: function (error) {
setTimeout(function () {
callback.onError(error);
});
}
});
};
ServerDataProvider.prototype.getMessage = function (messageId, callback) {
callback.onSuccess(new RongIMLib.Message());
};
ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) {
if (callback) {
callback.onSuccess(message);
}
};
ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messageIds, callback) {
RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messageIds, callback);
};
ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) {
callback.onSuccess(true);
};
ServerDataProvider.prototype.updateMessage = function (message, callback) {
if (callback) {
callback.onSuccess(message);
}
};
ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) {
callback.onSuccess(true);
};
ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) {
var me = this;
if (key == "readStatus") {
if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) {
me.getConversationList({
onSuccess: function (list) {
Array.forEach(list, function (conver) {
if (conver.conversationType == conversationType && conver.targetId == targetId) {
conver.unreadMessageCount = 0;
}
});
},
onError: function (errorCode) {
callback.onError(errorCode);
}
}, null);
}
}
callback.onSuccess(true);
};
ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) {
var conver = null;
for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) {
if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) {
conver = RongIMLib.RongIMClient._memoryStore.conversationList[i];
if (RongIMLib.RongUtil.supportLocalStorage()) {
var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + conversationType + targetId);
if (conver.unreadMessageCount == 0) {
conver.unreadMessageCount = Number(count);
}
}
}
}
callback.onSuccess(conver);
};
ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) {
var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList;
var list = RongIMLib.RongIMClient._memoryStore.conversationList;
if (!isSync) {
callback.onSuccess(list);
return;
}
RongIMLib.RongIMClient.getInstance().getRemoteConversationList({
onSuccess: function (list) {
if (RongIMLib.RongUtil.supportLocalStorage()) {
Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) {
var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + item.conversationType + item.targetId);
if (item.unreadMessageCount == 0) {
item.unreadMessageCount = Number(count);
}
});
}
RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false;
callback.onSuccess(list);
},
onError: function (errorcode) {
callback.onError(errorcode);
}
}, conversationTypes, count, isHidden);
};
ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) {
Array.forEach(conversationTypes, function (conversationType) {
Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) {
if (conversationType == conver.conversationType) {
RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } });
}
});
});
callback.onSuccess(true);
};
ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) {
};
;
ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback) {
RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback);
};
ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) {
var count = 0;
if (conversationTypes) {
for (var i = 0, len = conversationTypes.length; i < len; i++) {
Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) {
if (conver.conversationType == conversationTypes[i]) {
count += conver.unreadMessageCount;
}
});
}
}
else {
Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) {
count += conver.unreadMessageCount;
});
}
callback.onSuccess(count);
};
ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) {
var count = 0;
Array.forEach(conversationTypes, function (converType) {
Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) {
if (conver.conversationType == converType) {
count += conver.unreadMessageCount;
}
});
});
callback.onSuccess(count);
};
ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) {
this.getConversation(conversationType, targetId, {
onSuccess: function (conver) {
callback.onSuccess(conver ? conver.unreadMessageCount : 0);
},
onError: function (error) {
callback.onError(error);
}
});
};
ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) {
callback.onSuccess(true);
};
ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) {
RongIMLib.RongIMClient._storageProvider.removeItem("cu" + RongIMLib.Bridge._client.userId + conversationType + targetId);
this.getConversation(conversationType, targetId, {
onSuccess: function (conver) {
if (conver) {
conver.unreadMessageCount = 0;
conver.mentionedMsg = null;
var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId);
if (mentioneds) {
var info = JSON.parse(mentioneds);
delete info[conversationType + "_" + targetId];
if (!RongIMLib.MessageUtil.isEmpty(info)) {
RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info));
}
else {
RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId);
}
}
}
callback.onSuccess(true);
},
onError: function (error) {
callback.onError(error);
}
});
};
ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) {
var me = this;
this.getConversation(conversationType, targetId, {
onSuccess: function (conver) {
conver.isTop = isTop;
me.addConversation(conver, callback);
callback.onSuccess(true);
},
onError: function (error) {
callback.onError(error);
}
});
};
ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) {
var targetId = params.targetId;
var conversationType = params.conversationType;
var notification = RongIMLib.RongIMClient._memoryStore.notification;
var getKey = function () {
return conversationType + '_' + targetId;
};
var key = getKey();
var status = notification[key];
if (typeof status == 'number') {
callback.onSuccess(status);
return;
}
var topics = {
1: 'qryPPush',
3: 'qryDPush'
};
var topic = topics[conversationType];
if (!topic) {
var error = 8001;
callback.onError(error);
return;
}
var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput();
modules.setBlockeeId(targetId);
var userId = RongIMLib.Bridge._client.userId;
var success = function (status) {
notification[key] = status;
callback.onSuccess(status);
};
RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, {
onSuccess: function (status) {
success(status);
}, onError: function (e) {
if (e == 1) {
success(e);
}
else {
callback.onError(e);
}
}
});
};
ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) {
var conversationType = params.conversationType;
var targetId = params.targetId;
var status = params.status;
var getKey = function () {
return conversationType + '_' + status;
};
var topics = {
'1_1': 'blkPPush',
'3_1': 'blkDPush',
'1_0': 'unblkPPush',
'3_0': 'unblkDPush'
};
var key = getKey();
var notification = RongIMLib.RongIMClient._memoryStore.notification;
notification[key] = status;
var topic = topics[key];
if (!topic) {
var error = 8001;
callback.onError(error);
return;
}
var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput();
modules.setBlockeeId(targetId);
var userId = RongIMLib.Bridge._client.userId;
RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, {
onSuccess: function (status) {
callback.onSuccess(status);
}, onError: function (e) {
callback.onError(e);
}
});
};
ServerDataProvider.prototype.clearListeners = function () {
};
ServerDataProvider.prototype.setServerInfo = function (info) {
};
ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) {
return null;
};
ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) {
};
ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) {
callback.onSuccess(true);
};
ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) {
callback.onSuccess(true);
};
ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) {
callback.onSuccess(true);
};
ServerDataProvider.prototype.getAllConversations = function (callback) {
callback.onSuccess([]);
};
ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) {
callback.onSuccess([]);
};
ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) {
callback.onSuccess([]);
};
ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) {
callback.onSuccess([]);
};
ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) {
callback.onSuccess([]);
};
ServerDataProvider.prototype.getDelaTime = function () {
return RongIMLib.RongIMClient._memoryStore.deltaTime;
};
ServerDataProvider.prototype.getUserStatus = function (userId, callback) {
callback.onSuccess(new RongIMLib.UserStatus());
};
ServerDataProvider.prototype.setUserStatus = function (userId, callback) {
callback.onSuccess(true);
};
ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) {
callback.onSuccess(true);
};
ServerDataProvider.prototype.setOnReceiveStatusListener = function (callback) {
callback();
};
ServerDataProvider.prototype.getCurrentConnectionStatus = function () {
return RongIMLib.Bridge._client.channel.connectionStatus;
};
return ServerDataProvider;
})();
RongIMLib.ServerDataProvider = ServerDataProvider;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var VCDataProvider = (function () {
function VCDataProvider(addon) {
this.userId = "";
this.useConsole = false;
this.addon = addon;
}
VCDataProvider.prototype.init = function (appKey) {
this.useConsole && console.log("init");
this.addon.initWithAppkey(appKey);
// 0 ไธๅญไธ่ฎกๆฐ 1 ๅชๅญไธ่ฎกๆฐ 3 ๅญไธ่ฎกๆฐ
this.addon.registerMessageType("RC:VcMsg", 3);
this.addon.registerMessageType("RC:ImgTextMsg", 3);
this.addon.registerMessageType("RC:FileMsg", 3);
this.addon.registerMessageType("RC:LBSMsg", 3);
this.addon.registerMessageType("RC:PSImgTxtMsg", 3);
this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3);
this.addon.registerMessageType("RCJrmf:RpMsg", 3);
this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1);
this.addon.registerMessageType("RC:GrpNtf", 1);
this.addon.registerMessageType("RC:DizNtf", 0);
this.addon.registerMessageType("RC:InfoNtf", 0);
this.addon.registerMessageType("RC:ContactNtf", 0);
this.addon.registerMessageType("RC:ProfileNtf", 0);
this.addon.registerMessageType("RC:CmdNtf", 0);
this.addon.registerMessageType("RC:CmdMsg", 0);
this.addon.registerMessageType("RC:TypSts", 0);
this.addon.registerMessageType("RC:CsChaR", 0);
this.addon.registerMessageType("RC:CsHsR", 0);
this.addon.registerMessageType("RC:CsEnd", 0);
this.addon.registerMessageType("RC:CsSp", 0);
this.addon.registerMessageType("RC:CsUpdate", 0);
this.addon.registerMessageType("RC:CsContact", 0);
this.addon.registerMessageType("RC:ReadNtf", 0);
this.addon.registerMessageType("RC:VCAccept", 0);
this.addon.registerMessageType("RC:VCRinging", 0);
this.addon.registerMessageType("RC:VCSummary", 0);
this.addon.registerMessageType("RC:VCHangup", 0);
this.addon.registerMessageType("RC:VCInvite", 0);
this.addon.registerMessageType("RC:VCModifyMedia", 0);
this.addon.registerMessageType("RC:VCModifyMem", 0);
this.addon.registerMessageType("RC:PSCmd", 0);
this.addon.registerMessageType("RC:RcCmd", 0);
this.addon.registerMessageType("RC:SRSMsg", 0);
this.addon.registerMessageType("RC:RRReqMsg", 0);
this.addon.registerMessageType("RC:RRRspMsg", 0);
};
VCDataProvider.prototype.connect = function (token, callback, userId) {
this.useConsole && console.log("connect");
this.userId = userId;
this.connectCallback = callback;
this.addon.connectWithToken(token, userId);
};
VCDataProvider.prototype.setServerInfo = function (info) {
'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi);
};
VCDataProvider.prototype.logout = function () {
this.useConsole && console.log("logout");
this.disconnect();
};
VCDataProvider.prototype.disconnect = function () {
this.useConsole && console.log("disconnect");
this.addon.disconnect(true);
};
VCDataProvider.prototype.clearListeners = function () {
this.addon.setOnReceiveStatusListener();
this.addon.setConnectionStatusListener();
this.addon.setOnReceiveMessageListener();
};
VCDataProvider.prototype.setConnectionStatusListener = function (listener) {
var me = this;
/**
ConnectionStatus_TokenIncorrect = 31004,
ConnectionStatus_Connected = 0,
ConnectionStatus_KickedOff = 6, // ๅ
ถไป่ฎพๅค็ปๅฝ
ConnectionStatus_Connecting = 10,// ่ฟๆฅไธญ
ConnectionStatus_SignUp = 12, // ๆช็ปๅฝ
ConnectionStatus_NetworkUnavailable = 1, // ่ฟๆฅๆญๅผ
ConnectionStatus_ServerInvalid = 8, // ๆญๅผ
ConnectionStatus_ValidateFailure = 9,//ๆญๅผ
ConnectionStatus_Unconnected = 11,//ๆญๅผ
ConnectionStatus_DisconnExecption = 31011 //ๆญๅผ
RC_NAVI_MALLOC_ERROR = 30000,//ๆญๅผ
RC_NAVI_NET_UNAVAILABLE= 30002,//ๆญๅผ
RC_NAVI_SEND_FAIL = 30004,//ๆญๅผ
RC_NAVI_REQ_TIMEOUT = 30005,//ๆญๅผ
RC_NAVI_RECV_FAIL = 30006,//ๆญๅผ
RC_NAVI_RESOURCE_ERROR = 30007,//ๆญๅผ
RC_NAVI_NODE_NOT_FOUND = 30008,//ๆญๅผ
RC_NAVI_DNS_ERROR = 30009,//ๆญๅผ
*/
me.connectListener = listener;
this.useConsole && console.log("setConnectionStatusListener");
me.addon && me.addon.setConnectionStatusListener(function (result) {
switch (result) {
case 10:
listener.onChanged(RongIMLib.ConnectionStatus.CONNECTING);
break;
case 31004:
me.connectCallback.onTokenIncorrect();
break;
case 1:
case 8:
case 9:
case 11:
case 12:
case 31011:
case 30000:
case 30002:
case 30004:
case 30005:
case 30006:
case 30007:
case 30008:
case 30009:
listener.onChanged(RongIMLib.ConnectionStatus.DISCONNECTED);
break;
case 0:
case 33005:
me.connectCallback.onSuccess(me.userId);
listener.onChanged(RongIMLib.ConnectionStatus.CONNECTED);
break;
case 6:
listener.onChanged(RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT);
break;
}
});
};
VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) {
var me = this, localCount = 0;
me.messageListener = listener;
this.useConsole && console.log("setOnReceiveMessageListener");
me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount) {
var message = me.buildMessage(result);
if ((leftCount == 0 && localCount == 1) || leftCount > 0) {
message.offLineMessage = true;
}
else {
message.offLineMessage = false;
}
localCount = leftCount;
listener.onReceived(message, leftCount);
});
};
VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) {
var me = this;
this.useConsole && console.log("sendTypingStatusMessage");
if (messageName in RongIMLib.RongIMClient.MessageParams) {
me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), {
onSuccess: function () {
setTimeout(function () {
sendCallback.onSuccess();
});
},
onError: function (errorCode) {
setTimeout(function () {
sendCallback.onError(errorCode, null);
});
},
onBefore: function () { }
});
}
};
VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) {
this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp);
callback.onSuccess(true);
};
VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) {
var msgContent = RongIMLib.TextMessage.obtain(content);
this.useConsole && console.log("sendTextMessage");
this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback);
};
VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback) {
try {
var me = this;
me.useConsole && console.log("getRemoteHistoryMessages");
me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) {
var list = ret ? JSON.parse(ret).list : [], msgs = [];
list.reverse();
for (var i = 0, len = list.length; i < len; i++) {
var message = me.buildMessage(list[i].obj);
message.sentStatus = RongIMLib.SentStatus.READ;
msgs[i] = message;
}
callback.onSuccess(msgs, hasMore ? true : false);
}, function (errorCode) {
callback.onError(errorCode);
});
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) {
try {
this.useConsole && console.log("getRemoteConversationList");
var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8];
var result = this.addon.getConversationList(converTypes);
var list = JSON.parse(result).list, convers = [], me = this, index = 0;
list.reverse();
isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false;
for (var i = 0, len = list.length; i < len; i++) {
var tmpObj = list[i].obj, obj = JSON.parse(tmpObj);
if (obj.isHidden == 1 && isGetHiddenConvers) {
continue;
}
convers[index] = me.buildConversation(tmpObj);
index++;
}
convers.reverse();
callback.onSuccess(convers);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) {
try {
this.useConsole && console.log("removeConversation");
this.addon.removeConversation(conversationType, targetId);
var conversations = RongIMLib.RongIMClient._memoryStore.conversationList;
var len = conversations.length;
for (var i = 0; i < len; i++) {
if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) {
conversations.splice(i, 1);
break;
}
}
callback.onSuccess(true);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) {
this.useConsole && console.log("joinChatRoom");
this.addon.joinChatRoom(chatRoomId, messageCount, function () {
callback.onSuccess();
}, function (error) {
callback.onError(error);
});
};
VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) {
this.useConsole && console.log("quitChatRoom");
this.addon.quitChatRoom(chatRoomId, function () {
callback.onSuccess();
}, function (error) {
callback.onError(error);
});
};
VCDataProvider.prototype.addToBlacklist = function (userId, callback) {
this.useConsole && console.log("addToBlacklist");
this.addon.addToBlacklist(userId, function () {
callback.onSuccess();
}, function (error) {
callback.onError(error);
});
};
VCDataProvider.prototype.getBlacklist = function (callback) {
this.useConsole && console.log("getBlacklist");
this.addon.getBlacklist(function (blacklistors) {
callback.onSuccess(blacklistors);
}, function (error) {
callback.onError(error);
});
};
VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) {
this.useConsole && console.log("getBlacklistStatus");
this.addon.getBlacklistStatus(userId, function (result) {
callback.onSuccess(result);
}, function (error) {
callback.onError(error);
});
};
VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) {
this.useConsole && console.log("removeFromBlacklist");
this.addon.removeFromBlacklist(userId, function () {
callback.onSuccess();
}, function (error) {
callback.onError(error);
});
};
VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) {
var me = this, users = [];
me.useConsole && console.log("sendMessage");
params = params || {};
var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP);
if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) {
users = [];
var rspMsg = messageContent;
if (rspMsg.receiptMessageDic) {
var ids = [];
for (var key in rspMsg.receiptMessageDic) {
ids.push(key);
}
users = ids;
}
}
if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) {
users = [];
users.push(me.userId);
}
var userIds = params.userIds;
if (isGroup && userIds) {
users = userIds;
}
var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) {
}, function (message) {
sendCallback.onSuccess(me.buildMessage(message));
}, function (message, code) {
sendCallback.onError(code, me.buildMessage(message));
}, users);
var tempMessage = JSON.parse(msg);
sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId);
RongIMLib.MessageIdHandler.messageId = tempMessage.messageId;
};
VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent) {
this.useConsole && console.log("registerMessageType");
this.addon.registerMessageType(objectName, messageTag.getMessageTag());
var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType);
RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg;
RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType;
registerMessageTypeMapping[objectName] = messageType;
RongIMLib.RongIMClient.MessageType[messageType] = messageType;
RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag };
typeMapping[objectName] = messageType;
};
VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) {
this.useConsole && console.log("addMessage");
var direction = message.direction;
var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () {
callback.onSuccess(me.buildMessage(msg));
}, function () {
callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR);
}, direction), me = this;
};
VCDataProvider.prototype.removeMessage = function (conversationType, targetId, delMsgs, callback) {
};
VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) {
try {
this.useConsole && console.log("removeLocalMessage");
this.addon.deleteMessages(timestamps);
callback.onSuccess(true);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.getMessage = function (messageId, callback) {
try {
this.useConsole && console.log("getMessage");
var msg = this.buildMessage(this.addon.getMessage(messageId));
callback.onSuccess(msg);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) {
try {
this.useConsole && console.log("clearMessages");
this.addon.clearMessages(conversationType, targetId);
callback.onSuccess(true);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) {
try {
this.useConsole && console.log("getConversation");
var ret = this.addon.getConversation(conversationType, targetId);
callback.onSuccess(this.buildConversation(ret));
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) {
this.useConsole && console.log("getConversationList");
this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers);
};
VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) {
try {
this.useConsole && console.log("clearConversations");
this.addon.clearConversations();
callback.onSuccess(true);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) {
this.addon.setMessageContent(messageId, content, objectName);
};
VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) {
this.useConsole && console.log("getHistoryMessages");
if (count <= 0) {
callback.onError(RongIMLib.ErrorCode.TIMEOUT);
return;
}
objectname = objectname || '';
try {
var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction);
var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this;
list.reverse();
for (var i = 0, len = list.length; i < len; i++) {
var message = me.buildMessage(list[i].obj);
message.sentStatus = RongIMLib.SentStatus.READ;
msgs[i] = message;
}
callback.onSuccess(msgs, len == count);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) {
try {
var result;
this.useConsole && console.log("getTotalUnreadCount");
if (conversationTypes) {
result = this.addon.getTotalUnreadCount(conversationTypes);
}
else {
result = this.addon.getTotalUnreadCount();
}
callback.onSuccess(result);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) {
this.useConsole && console.log("getConversationUnreadCount");
this.getTotalUnreadCount(callback, conversationTypes);
};
VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) {
try {
this.useConsole && console.log("getUnreadCount");
var result = this.addon.getUnreadCount(conversationType, targetId);
callback.onSuccess(result);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) {
try {
this.useConsole && console.log("clearUnreadCount");
var result = this.addon.clearUnreadCount(conversationType, targetId);
callback.onSuccess(true);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) {
try {
this.useConsole && console.log("clearUnreadCountByTimestamp");
var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp);
callback.onSuccess(true);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) {
try {
this.useConsole && console.log("setConversationToTop");
this.addon.setConversationToTop(conversationType, targetId, isTop);
callback.onSuccess(true);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) {
this.addon.setConversationHidden(conversationType, targetId, isHidden);
};
VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) {
try {
this.useConsole && console.log("setMessageReceivedStatus");
this.addon.setMessageReceivedStatus(messageId, receivedStatus);
callback.onSuccess(true);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) {
try {
this.useConsole && console.log("setMessageSentStatus");
this.addon.setMessageSentStatus(messageId, sentStatus);
callback.onSuccess(true);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.getFileToken = function (fileType, callback) {
this.useConsole && console.log("getFileToken");
this.addon.getUploadToken(fileType, function (token) {
callback.onSuccess({ token: token });
}, function (errorCode) {
callback.onError(errorCode);
});
};
VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) {
this.useConsole && console.log("getFileUrl");
this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) {
callback.onSuccess({ downloadUrl: url });
}, function (errorCode) {
callback.onError(errorCode);
});
};
VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) {
var converTypes = [];
if (typeof conversationTypes == 'undefined') {
converTypes = [1, 2, 3, 4, 5, 6, 7];
}
else {
converTypes = conversationTypes;
}
try {
this.useConsole && console.log("searchConversationByContent");
var result = this.addon.searchConversationByContent(converTypes, keyword);
var list = JSON.parse(result).list, convers = [], me = this;
list.reverse();
for (var i = 0, len = list.length; i < len; i++) {
convers[i] = me.buildConversation(list[i].obj);
}
callback.onSuccess(convers);
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) {
var me = this;
try {
this.useConsole && console.log("searchMessageByContent");
this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) {
var list = ret ? JSON.parse(ret).list : [], msgs = [];
list.reverse();
for (var i = 0, len = list.length; i < len; i++) {
msgs[i] = me.buildMessage(list[i].obj);
}
callback.onSuccess(msgs, matched);
});
}
catch (e) {
callback.onError(e);
}
};
VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) {
this.useConsole && console.log("getChatRoomInfo");
this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) {
var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count };
if (list.length > 0) {
for (var i = 0, len = list.length; i < len; i++) {
chatRoomInfo.userInfos.push(JSON.parse(list[i].obj));
}
}
callback.onSuccess(chatRoomInfo);
}, function (errcode) {
callback.onError(errcode);
});
};
VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) {
};
VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) {
};
VCDataProvider.prototype.getDelaTime = function () {
return this.addon.getDeltaTime();
};
VCDataProvider.prototype.getUserStatus = function (userId, callback) {
var me = this;
this.addon.getUserStatus(userId, function (status) {
callback.onSuccess(me.buildUserStatus(status));
}, function (code) {
callback.onError(code);
});
};
VCDataProvider.prototype.setUserStatus = function (userId, callback) {
this.addon.setUserStatus(userId, function () {
callback.onSuccess(true);
}, function (code) {
callback.onError(code);
});
};
VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) {
this.addon.subscribeUserStatus(userIds, function () {
callback.onSuccess(true);
}, function (code) {
callback.onError(code);
});
};
VCDataProvider.prototype.setOnReceiveStatusListener = function (callback) {
var me = this;
this.addon.setOnReceiveStatusListener(function (userId, status) {
callback(userId, me.buildUserStatus(status));
});
};
VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) {
var me = this;
var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list;
for (var i = 0, len = mentions.length; i < len; i++) {
var temp = JSON.parse(mentions[i].obj);
temp.content = JSON.parse(temp.content);
mentions[i] = temp;
}
return mentions;
};
VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) {
callback.onSuccess(false);
};
VCDataProvider.prototype.sendRecallMessage = function (conent, sendMessageCallback) {
// new RecallCommandMessage({conversationType : conent.conversationType, targetId : conent.targetId, sentTime:content.sentTime, messageUId : conent.messageUId, extra : conent.extra, user : conent.user});
};
VCDataProvider.prototype.updateMessage = function (message, callback) { };
VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { };
VCDataProvider.prototype.reconnect = function (callback) { };
VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { };
VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { };
VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { };
VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { };
VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { };
VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { };
VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { };
VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { };
VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { };
VCDataProvider.prototype.joinGroup = function (groupId, groupName, callback) { };
VCDataProvider.prototype.quitGroup = function (groupId, callback) { };
VCDataProvider.prototype.syncGroup = function (groups, callback) { };
VCDataProvider.prototype.addConversation = function (conversation, callback) { };
VCDataProvider.prototype.updateConversation = function (conversation) {
return null;
};
VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) {
var conversationType = params.conversationType;
var targetId = params.targetId;
var notification = RongIMLib.RongIMClient._memoryStore.notification;
var key = conversationType + '_' + targetId;
var status = notification[key];
if (typeof status == 'number') {
callback.onSuccess(status);
return;
}
this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) {
notification[key] = status;
callback.onSuccess(status);
}, function (error) {
callback.onError(error);
});
};
VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) {
var conversationType = params.conversationType;
var targetId = params.targetId;
var status = params.status;
var notification = RongIMLib.RongIMClient._memoryStore.notification;
var key = conversationType + '_' + targetId;
notification[key] = status;
var notify = !!status;
this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () {
callback.onSuccess(status);
}, function (error) {
callback.onError(error);
});
};
VCDataProvider.prototype.getCurrentConnectionStatus = function () {
return this.addon.getConnectionStatus();
};
VCDataProvider.prototype.buildUserStatus = function (result) {
var userStatus = new RongIMLib.UserStatus();
var obj = JSON.parse(result);
if (obj.us && obj.us[0]) {
userStatus.platform = obj.us[0].p;
userStatus.online = !!obj.us[0].o;
userStatus.status = obj.us[0].s;
}
return userStatus;
};
VCDataProvider.prototype.buildMessage = function (result) {
var message = new RongIMLib.Message(), ret = JSON.parse(result);
message.conversationType = ret.conversationType;
message.targetId = ret.targetId;
message.messageDirection = ret.direction;
message.senderUserId = ret.senderUserId;
if (ret.direction == RongIMLib.MessageDirection.RECEIVE) {
message.receivedStatus = ret.status;
}
else if (ret.direction == RongIMLib.MessageDirection.SEND) {
message.sentStatus = ret.status;
}
message.sentTime = ret.sentTime;
message.objectName = ret.objectName;
var content = ret.content ? JSON.parse(ret.content) : ret.content;
var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName];
if (content) {
content.messageName = messageType;
}
message.content = content;
message.messageId = ret.messageId;
message.messageUId = ret.messageUid;
message.messageType = messageType;
return message;
};
VCDataProvider.prototype.buildConversation = function (val) {
var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {};
conver.conversationTitle = c.title;
conver.conversationType = c.conversationType;
conver.draft = c.draft;
conver.isTop = c.isTop;
conver.isHidden = c.isHidden;
lastestMsg.conversationType = c.conversationType;
lastestMsg.targetId = c.targetId;
conver.latestMessage = lastestMsg;
conver.latestMessageId = lastestMsg.messageId;
conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName];
conver.objectName = lastestMsg.objectName;
conver.receivedStatus = RongIMLib.ReceivedStatus.READ;
conver.sentTime = lastestMsg.sentTime;
conver.senderUserId = lastestMsg.senderUserId;
conver.sentStatus = lastestMsg.status;
conver.targetId = c.targetId;
conver.unreadMessageCount = c.unreadCount;
conver.hasUnreadMention = c.m_hasUnreadMention;
var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId);
if (mentions.length > 0) {
// ๅๆๅไธๆก @ ๆถๆฏ,ๅๅ ๏ผๅ web ไบ็ธๅ
ผๅฎน
var mention = mentions.pop();
conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId };
}
return conver;
};
return VCDataProvider;
})();
RongIMLib.VCDataProvider = VCDataProvider;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var MemeoryProvider = (function () {
function MemeoryProvider() {
this._memeoryStore = {};
this.prefix = "rong_";
}
MemeoryProvider.prototype.setItem = function (composedKey, object) {
this._memeoryStore[composedKey] = decodeURIComponent(object);
};
MemeoryProvider.prototype.getItem = function (composedKey) {
return this._memeoryStore[composedKey];
};
MemeoryProvider.prototype.removeItem = function (composedKey) {
if (this.getItem(composedKey)) {
delete this._memeoryStore[composedKey];
}
};
MemeoryProvider.prototype.getItemKey = function (regStr) {
var me = this, item = null, reg = new RegExp(regStr + "\\w+");
for (var key in me._memeoryStore) {
var arr = key.match(reg);
if (arr) {
item = key;
}
}
return item;
};
MemeoryProvider.prototype.clearItem = function () {
var me = this;
for (var key in me._memeoryStore) {
delete me._memeoryStore[key];
}
};
//ๅไฝ๏ผๅญ่
MemeoryProvider.prototype.onOutOfQuota = function () {
return 4 * 1024;
};
return MemeoryProvider;
})();
RongIMLib.MemeoryProvider = MemeoryProvider;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var LocalStorageProvider = (function () {
// static _instance: LocalStorageProvider = new LocalStorageProvider();
function LocalStorageProvider() {
this.prefix = 'rong_';
this._host = "";
var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime();
for (var key in localStorage) {
if (key.lastIndexOf('RECEIVED') > -1) {
var recObj = JSON.parse(localStorage.getItem(key));
for (var key_1 in recObj) {
nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]);
}
if (RongIMLib.RongUtil.isEmpty(recObj)) {
localStorage.removeItem(key);
}
else {
localStorage.setItem(key, JSON.stringify(recObj));
}
}
if (key.lastIndexOf('SENT') > -1) {
var sentObj = JSON.parse(localStorage.getItem(key));
nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key));
}
}
}
LocalStorageProvider.prototype.setItem = function (composedKey, object) {
if (composedKey) {
composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey);
localStorage.setItem(composedKey, object);
}
};
LocalStorageProvider.prototype.getItem = function (composedKey) {
if (composedKey) {
composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey);
return localStorage.getItem(composedKey ? composedKey : "");
}
return "";
};
LocalStorageProvider.prototype.getItemKey = function (composedStr) {
var item = "";
var _key = this.prefix + composedStr;
for (var key in localStorage) {
if (key.indexOf(_key) == 0) {
item = key;
break;
}
}
return item;
};
LocalStorageProvider.prototype.removeItem = function (composedKey) {
if (composedKey) {
composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey);
localStorage.removeItem(composedKey.toString());
}
};
LocalStorageProvider.prototype.clearItem = function () {
var me = this;
for (var key in localStorage) {
if (key.indexOf(me.prefix) > -1) {
me.removeItem(key);
}
}
};
//ๅไฝ๏ผๅญ่
LocalStorageProvider.prototype.onOutOfQuota = function () {
return JSON.stringify(localStorage).length;
};
return LocalStorageProvider;
})();
RongIMLib.LocalStorageProvider = LocalStorageProvider;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var UserDataProvider = (function () {
function UserDataProvider() {
this.opersistName = 'RongIMLib';
this.keyManager = 'RongUserDataKeyManager';
this._host = "";
this.prefix = "rong_";
this.oPersist = document.createElement("div");
this.oPersist.style.display = "none";
this.oPersist.style.behavior = "url('#default#userData')";
document.body.appendChild(this.oPersist);
this.oPersist.load(this.opersistName);
}
UserDataProvider.prototype.setItem = function (key, value) {
key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key);
this.oPersist.setAttribute(key, value);
var keyNames = this.getItem(this.keyManager);
keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key);
this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames);
this.oPersist.save(this.opersistName);
};
UserDataProvider.prototype.getItem = function (key) {
key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key);
return key ? this.oPersist.getAttribute(key) : key;
};
UserDataProvider.prototype.removeItem = function (key) {
key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key);
this.oPersist.removeAttribute(key);
this.oPersist.save(this.opersistName);
var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [];
for (var i = 0, len = keyNameArray.length; i < len; i++) {
if (keyNameArray[i] == key) {
keyNameArray.splice(i, 1);
}
}
this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(','));
this.oPersist.save(this.opersistName);
};
UserDataProvider.prototype.getItemKey = function (composedStr) {
var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this;
var _key = this.prefix + composedStr;
if (keyNameArray.length) {
for (var i = 0, len = keyNameArray.length; i < len; i++) {
if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) {
item = keyNameArray[i];
break;
}
}
}
return item;
};
UserDataProvider.prototype.clearItem = function () {
var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this;
keyNames && (keyNameArray = keyNames.split(','));
if (keyNameArray.length) {
for (var i = 0, len = keyNameArray.length; i < len; i++) {
keyNameArray[i] && me.removeItem(keyNameArray[i]);
}
me.removeItem(me.keyManager);
}
};
UserDataProvider.prototype.onOutOfQuota = function () {
return 10 * 1024 * 1024;
};
return UserDataProvider;
})();
RongIMLib.UserDataProvider = UserDataProvider;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var FeatureDectector = (function () {
function FeatureDectector(callback) {
this.script = document.createElement("script");
this.head = document.getElementsByTagName("head")[0];
if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) {
RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET;
if (!RongIMLib.RongIMClient.Protobuf) {
var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf;
var script = this.script;
script.src = url;
this.head.appendChild(script);
script.onload = script.onreadystatechange = function () {
var isLoaded = (!this.readState || this.readyState == 'loaded' || this.readyState == 'complete');
if (isLoaded) {
// ้ฒๆญข IE6ใ7 ไธๅถๅ่งฆๅไธคๆฌก loaded
script.onload = script.onreadystatechange = null;
if (callback) {
callback();
}
if (!callback) {
var token = RongIMLib.RongIMClient._memoryStore.token;
var connectCallback = RongIMLib.RongIMClient._memoryStore.callback;
token && RongIMLib.RongIMClient.connect(token, connectCallback);
}
}
};
}
}
else {
RongIMLib.Transportations._TransportType = "xhr-polling";
RongIMLib.RongIMClient.Protobuf = Polling;
}
}
return FeatureDectector;
})();
RongIMLib.FeatureDectector = FeatureDectector;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var FeaturePatcher = (function () {
function FeaturePatcher() {
}
FeaturePatcher.prototype.patchAll = function () {
this.patchJSON();
this.patchForEach();
};
FeaturePatcher.prototype.patchForEach = function () {
if (!Array.forEach) {
Array.forEach = function (arr, func) {
for (var i = 0; i < arr.length; i++) {
func.call(arr, arr[i], i, arr);
}
};
}
};
FeaturePatcher.prototype.patchJSON = function () {
if (!window["JSON"]) {
window["JSON"] = (function () {
function JSON() {
}
JSON.parse = function (sJSON) {
return eval('(' + sJSON + ')');
};
JSON.stringify = function (value) {
return this.str("", { "": value });
};
JSON.str = function (key, holder) {
var i, k, v, length, mind = "", partial, value = holder[key], me = this;
if (value && typeof value === "object" && typeof value.toJSON === "function") {
value = value.toJSON(key);
}
switch (typeof value) {
case "string":
return me.quote(value);
case "number":
return isFinite(value) ? String(value) : "null";
case "boolean":
case "null":
return String(value);
case "object":
if (!value) {
return "null";
}
partial = [];
if (Object.prototype.toString.apply(value) === "[object Array]") {
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = me.str(i, value) || "null";
}
v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]";
return v;
}
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = me.str(k, value);
if (v) {
partial.push(me.quote(k) + ":" + v);
}
}
}
v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}";
return v;
}
};
JSON.quote = function (string) {
var me = this;
me.rx_escapable.lastIndex = 0;
return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) {
var c = me.meta[a];
return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
};
JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g");
JSON.meta = {
"\b": "\\b",
" ": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
'"': '\\"',
"''": "\\''",
"\\": "\\\\"
};
return JSON;
})();
}
};
return FeaturePatcher;
})();
RongIMLib.FeaturePatcher = FeaturePatcher;
})(RongIMLib || (RongIMLib = {}));
var RongIMLib;
(function (RongIMLib) {
var PublicServiceMap = (function () {
function PublicServiceMap() {
this.publicServiceList = [];
}
PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) {
for (var i = 0, len = this.publicServiceList.length; i < len; i++) {
if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) {
return this.publicServiceList[i];
}
}
};
PublicServiceMap.prototype.add = function (publicServiceProfile) {
var isAdd = true, me = this;
for (var i = 0, len = this.publicServiceList.length; i < len; i++) {
if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) {
this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]);
isAdd = false;
break;
}
}
if (isAdd) {
this.publicServiceList.unshift(publicServiceProfile);
}
};
PublicServiceMap.prototype.replace = function (publicServiceProfile) {
var me = this;
for (var i = 0, len = this.publicServiceList.length; i < len; i++) {
if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) {
me.publicServiceList.splice(i, 1, publicServiceProfile);
break;
}
}
};
PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) {
var me = this;
for (var i = 0, len = this.publicServiceList.length; i < len; i++) {
if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) {
this.publicServiceList.splice(i, 1);
break;
}
}
};
return PublicServiceMap;
})();
RongIMLib.PublicServiceMap = PublicServiceMap;
/**
* ไผ่ฏๅทฅๅ
ท็ฑปใ
*/
var ConversationMap = (function () {
function ConversationMap() {
this.conversationList = [];
}
ConversationMap.prototype.get = function (conversavtionType, targetId) {
for (var i = 0, len = this.conversationList.length; i < len; i++) {
if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) {
return this.conversationList[i];
}
}
return null;
};
ConversationMap.prototype.add = function (conversation) {
var isAdd = true;
for (var i = 0, len = this.conversationList.length; i < len; i++) {
if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) {
this.conversationList.unshift(this.conversationList.splice(i, 1)[0]);
isAdd = false;
break;
}
}
if (isAdd) {
this.conversationList.unshift(conversation);
}
};
/**
* [replace ๆฟๆขไผ่ฏ]
* ไผ่ฏๆฐ็ปๅญๅจ็ๆ
ๅตไธ่ฐ็จaddๆนๆณไผๆฏๅฝๅไผ่ฏ่ขซๆฟๆขไธ่ฟๅๅฐ็ฌฌไธไธชไฝ็ฝฎ๏ผๅฏผ่ด็จๆทๆฌๅฐไธไบ่ฎพ็ฝฎๅคฑๆ๏ผๆไปฅๆไพreplaceๆนๆณ
*/
ConversationMap.prototype.replace = function (conversation) {
for (var i = 0, len = this.conversationList.length; i < len; i++) {
if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) {
this.conversationList.splice(i, 1, conversation);
break;
}
}
};
ConversationMap.prototype.remove = function (conversation) {
for (var i = 0, len = this.conversationList.length; i < len; i++) {
if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) {
this.conversationList.splice(i, 1);
break;
}
}
};
return ConversationMap;
})();
RongIMLib.ConversationMap = ConversationMap;
var CheckParam = (function () {
function CheckParam() {
}
CheckParam.getInstance = function () {
if (!CheckParam._instance) {
CheckParam._instance = new CheckParam();
}
return CheckParam._instance;
};
CheckParam.prototype.check = function (f, position, d, c) {
if (RongIMLib.RongIMClient._dataAccessProvider || d) {
for (var g = 0, e = c.length; g < e; g++) {
if (!new RegExp(this.getType(c[g])).test(f[g])) {
throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position);
}
}
}
else {
throw new Error("The parameter is incorrect or was not yet instantiated RongIMClient -> position:" + position);
}
};
CheckParam.prototype.getType = function (str) {
var temp = Object.prototype.toString.call(str).toLowerCase();
return temp.slice(8, temp.length - 1);
};
CheckParam.prototype.checkCookieDisable = function () {
document.cookie = "checkCookie=1";
var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false;
if (!arr) {
isDisable = true;
}
document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT";
return isDisable;
};
return CheckParam;
})();
RongIMLib.CheckParam = CheckParam;
var LimitableMap = (function () {
function LimitableMap(limit) {
this.map = {};
this.keys = [];
this.limit = limit || 10;
}
LimitableMap.prototype.set = function (key, value) {
if (this.map.hasOwnProperty(key)) {
if (this.keys.length === this.limit) {
var firstKey = this.keys.shift();
delete this.map[firstKey];
}
this.keys.push(key);
}
this.map[key] = value;
};
LimitableMap.prototype.get = function (key) {
return this.map[key] || 0;
};
LimitableMap.prototype.remove = function (key) {
delete this.map[key];
};
return LimitableMap;
})();
RongIMLib.LimitableMap = LimitableMap;
var RongAjax = (function () {
function RongAjax(options) {
var me = this;
me.xmlhttp = null;
me.options = options;
var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest();
if ("undefined" != typeof XMLHttpRequest && hasCORS) {
me.xmlhttp = new XMLHttpRequest();
}
else if ("undefined" != typeof XDomainRequest) {
me.xmlhttp = new XDomainRequest();
}
else {
me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
RongAjax.prototype.send = function (callback) {
var me = this;
me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1");
me.xmlhttp.onreadystatechange = function () {
if (me.xmlhttp.readyState == 4) {
if (me.options.type) {
callback();
}
else {
callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"')));
}
}
};
me.xmlhttp.open("POST", me.options.url, true);
me.xmlhttp.withCredentials = false;
if ("setRequestHeader" in me.xmlhttp) {
if (me.options.type) {
me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
}
else {
me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream");
me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token);
}
}
me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64);
};
return RongAjax;
})();
RongIMLib.RongAjax = RongAjax;
var RongUtil = (function () {
function RongUtil() {
}
RongUtil.noop = function () { };
RongUtil.isEmpty = function (obj) {
var empty = true;
for (var key in obj) {
empty = false;
break;
}
return empty;
};
RongUtil.isObject = function (obj) {
return Object.prototype.toString.call(obj) == '[object Object]';
};
RongUtil.isArray = function (array) {
return Object.prototype.toString.call(array) == '[object Array]';
};
RongUtil.isFunction = function (fun) {
return Object.prototype.toString.call(fun) == '[object Function]';
};
;
RongUtil.stringFormat = function (tmpl, vals) {
for (var i = 0, len = vals.length; i < len; i++) {
var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g");
tmpl = tmpl.replace(reg, val);
}
return tmpl;
};
RongUtil.forEach = function (obj, callback) {
callback = callback || RongUtil.noop;
var loopObj = function () {
for (var key in obj) {
callback(obj[key], key);
}
};
var loopArr = function () {
for (var i = 0, len = obj.length; i < len; i++) {
callback(obj[i], i);
}
};
if (RongUtil.isObject(obj)) {
loopObj();
}
if (RongUtil.isArray(obj)) {
loopArr();
}
};
RongUtil.extends = function (source, target, callback, force) {
RongUtil.forEach(source, function (val, key) {
var hasProto = (key in target);
if (force && hasProto) {
target[key] = val;
}
if (!hasProto) {
target[key] = val;
}
});
return target;
};
RongUtil.createXHR = function () {
var item = {
XMLHttpRequest: function () {
return new XMLHttpRequest();
},
XDomainRequest: function () {
return new XDomainRequest();
},
ActiveXObject: function () {
return new ActiveXObject('Microsoft.XMLHTTP');
}
};
var isXHR = (typeof XMLHttpRequest == 'function');
var isXDR = (typeof XDomainRequest == 'function');
var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject';
return item[key]();
};
RongUtil.request = function (opts) {
var url = opts.url;
var success = opts.success;
var error = opts.error;
var method = opts.method || 'GET';
var xhr = RongUtil.createXHR();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
success();
}
else {
error();
}
}
};
xhr.open(method, url, true);
xhr.send(null);
};
RongUtil.formatProtoclPath = function (config) {
var path = config.path;
var protocol = config.protocol;
var tmpl = config.tmpl || '{0}{1}';
var sub = config.sub;
var flag = '://';
var index = path.indexOf(flag);
var hasProtocol = (index > -1);
if (hasProtocol) {
index += flag.length;
path = path.substring(index);
}
if (sub) {
index = path.indexOf('/');
var hasPath = (index > -1);
if (hasPath) {
path = path.substr(0, index);
}
}
return RongUtil.stringFormat(tmpl, [protocol, path]);
};
;
RongUtil.supportLocalStorage = function () {
var support = false;
if (typeof localStorage == 'object') {
try {
var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL';
localStorage.setItem(key, value);
var localVal = localStorage.getItem(key);
if (localVal == value) {
support = true;
}
}
catch (err) {
console.log('localStorage is disabled.');
}
}
return support;
};
return RongUtil;
})();
RongIMLib.RongUtil = RongUtil;
})(RongIMLib || (RongIMLib = {}));
/*
่ฏดๆ: ่ฏทๅฟไฟฎๆน header.js ๅ footer.js
็จ้: ่ชๅจๆผๆฅๆด้ฒๆนๅผ
ๅฝไปค: grunt release ไธญ concat
*/
return RongIMLib;
}); |
function initialize(complete) {
// Configure Backbone to talk with Rails
Backbone.ajax = function() {
Backbone.$.ajaxSetup.call(Backbone.$, {
beforeSend: function(jqXHR){
var token = $("meta[name='csrf-token']").attr('content');
jqXHR.setRequestHeader('X-CSRF-Token', token);
}
});
return Backbone.$.ajax.apply(Backbone.$, arguments);
};
$(function() {
Backbone.history.start({
pushState: false,
root: '/',
silent: true
});
// RootView may use link or url helpers which
// depend on Backbone history being setup
// so need to wait to loadUrl() (which will)
// actually execute the route
<%= js_app_name %>.RootView.getInstance(document.body);
complete(function() {
Backbone.history.loadUrl();
});
});
}
initialize(function(next) {
// things to do when your application is loaded!
next();
}); |
const _ = require('lodash')
const { Todo } = require('../../models/todo')
const router = require('express').Router()
const { ObjectID } = require('mongodb')
const { authenticate } = require('../authenticate')
router.post('/todos', authenticate, (req, res) => {
let { text } = req.body
let _creator = req.user._id
let todo = new Todo({ text, _creator })
todo.save().then((todo) => {
res.send(todo)
}).catch((e) => {
res.status(400).send(e)
})
})
router.get('/todos', authenticate, (req, res) => {
Todo.find({
_creator: req.user._id
}).then((todos) => {
res.send({todos})
}).catch((e) => {
res.status(400).send(e)
})
})
router.get('/todos/:id', (req, res) => {
let { id } = req.params
if(!ObjectID.isValid(id)){
return res.status(400).send()
}
Todo.findById(id).then((todo) => {
if(!todo) {
return res.status(400).send()
}
res.send({todo})
}).catch((e) => {
res.status(400).send(e)
})
})
router.delete('/todos/:id', (req, res) => {
let { id } = req.params
if(!ObjectID.isValid(id)){
return res.status(400).send()
}
Todo.findByIdAndRemove(id).then((todo) => {
if(!todo){
return res.status(400).send()
}
res.send({todo})
}).catch((e) => {
res.status(400).send(e)
})
})
router.patch('/todos/:id', (req, res) => {
let { id } = req.params
let body = _.pick(req.body, ['text', 'completed'])
if (!ObjectID.isValid(id)) {
return res.status(404).send()
}
if(_.isBoolean(body.completed) && body.completed) {
body.completedAt = new Date().getTime()
} else {
body.completed = false
body.completedAt = null
}
Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then((todo) => {
if (!todo) {
return res.status(404).send()
}
res.send({todo})
}).catch((e) => {
res.status(400).send(e)
})
})
module.exports = { todos: router } |
define(function(require) {
'use strict';
var q = require('q');
var AppObj = require('js/app/obj');
var Display = require('js/display/obj');
var logger = AppObj.logger.get('root/js/apps/user/profile/controller');
AppObj.module('UserApp.Profile', function(Profile, AppObj, Backbone, Marionette, $, _) {
/**
* Gets the fb display mode string to use based on the client window size
* TODO: Duplicated in user/access and user/profile controllers - de-duplicate on next edit
* @param {String} ui_scale The UI scale as returned by `Marionette.get_ui_scale()`
* @return {String} The fb display mode to render the auth request in
*/
function get_fb_google_display_mode_from_ui_scale(ui_scale) {
switch(ui_scale) {
case 'mobile': return 'touch';
case 'tablet': return 'touch';
case 'smalldesk': return 'page';
case 'bigdesk': return 'page';
default:
logger.error('private.get_fb_google_display_mode_from_ui_scale -- unknown UI scale: ' + ui_scale);
return 'touch';
}
}
/**
* Returns the string to set the client browser location to, to request account connect from Facebook. Is the
* server API endpoint, which in turn generates and redirects to Facebook
*/
function get_fb_connect_url() {
return AppObj.config.apps.user.fb_connect_url + '?display=' +
get_fb_google_display_mode_from_ui_scale(Marionette.get_ui_scale());
}
/**
* Returns the string to set the client browser location to, to request account connect from Google. Is the
* server API endpoint, which in turn generates and redirects to Google
*/
function get_google_connect_url() {
return AppObj.config.apps.user.google_connect_url + '?display=' +
get_fb_google_display_mode_from_ui_scale(Marionette.get_ui_scale());
}
/**
* Returns the string to set the client browser location to, to request account connect from Twitter. Is the
* server API endpoint, which in turn generates and redirects to Twitter
*/
function get_twitter_connect_url() {
return AppObj.config.apps.user.twitter_connect_url;
}
/**
* Process form submission to change a user's local password
* @param {Object} form_data The submitted form data serialised as an object using syphon
* @param {Object} profile_view The profile layout view in which the profile component subviews are rendered
*/
function proc_change_password_submitted(form_data, profile_view) {
require('js/apps/user/entities');
// UserPasswordChange just for validation
var ucp = new AppObj.UserApp.Entities.UserChangePassword({
old_password: form_data.old_password,
new_password: form_data.new_password,
new_password_check: form_data.new_password_check
});
var val_errs = ucp.validate(ucp.attributes);
if(_.isEmpty(val_errs)) {
logger.debug('private.proc_change_password_submitted -- form validation passed: ' + JSON.stringify(form_data));
$.post(AppObj.config.apps.user.change_password_path, form_data, function(resp_data, textStatus, jqXhr) {
if(resp_data.status === 'success') {
logger.debug('private.proc_change_password_submitted - server API call response -- success');
AppObj.trigger('user:profile'); // cleaner than manually updating profile data and displaying flash message
}
else if(resp_data.status === 'failure') {
q(AppObj.request('common:entities:flashmessage'))
.then(function(flash_message_model) {
logger.debug('private.proc_change_password_submitted - server API call response -- connect failure: ' +
flash_message_model);
var CommonViews = require('js/common/views');
var msg_view = new CommonViews.FlashMessageView({ model: flash_message_model });
profile_view.region_message.show(msg_view);
AppObj.Display.tainer.scroll_to_top();
})
.fail(AppObj.handle_rejected_promise.bind(undefined,
'UserApp.Profile - private.proc_change_password_submitted'))
.done();
}
else {
logger.error('private.proc_change_password_submitted - server API call response -- unknown status: ' +
resp_data.status);
AppObj.trigger('user:profile'); // cleaner than manually updating profile data and displaying flash message
}
});
}
else {
logger.debug('private.proc_change_password_submitted -- form validation failed: ' + JSON.stringify(val_errs));
profile_view.trigger('change_password_form:show_val_errs', val_errs);
}
}
/**
* Process form submission to connect user to their separate email account
* @param {Object} form_data The submitted form data serialised as an object using syphon
* @param {Object} profile_view The profile layout view in which the profile component subviews are rendered
*/
function proc_connect_local_submitted(form_data, profile_view) {
require('js/apps/user/entities');
// UserLocalConnect just for validation (passport redirect mucks up Backbone model sync)
var ulc = new AppObj.UserApp.Entities.UserLocalConnect({
local_email: form_data.local_email.trim(),
local_email_check: form_data.local_email_check.trim(),
local_password: form_data.local_password,
local_password_check: form_data.local_password_check
});
var val_errs = ulc.validate(ulc.attributes);
if(_.isEmpty(val_errs)) {
logger.debug('private.proc_connect_local_submitted -- form validation passed: ' + JSON.stringify(form_data));
$.post(AppObj.config.apps.user.local_connect_path, form_data, function(resp_data, textStatus, jqXhr) {
if(resp_data.status === 'success') {
logger.debug('private.proc_connect_local_submitted - server API call response -- success');
AppObj.trigger('user:profile'); // cleaner than manually updating profile data and displaying flash message
}
else if(resp_data.status === 'failure') {
q(AppObj.request('common:entities:flashmessage'))
.then(function(flash_message_model) {
logger.debug('private.proc_local_signup - server API call response -- connect failure: ' +
flash_message_model);
var CommonViews = require('js/common/views');
var msg_view = new CommonViews.FlashMessageView({ model: flash_message_model });
profile_view.region_message.show(msg_view);
AppObj.Display.tainer.scroll_to_top();
})
.fail(AppObj.handle_rejected_promise.bind(undefined, 'UserApp.Profile - private.proc_connect_local_submitted'))
.done();
}
else {
logger.error('private.proc_connect_local_submitted - server API call response -- ' +
'unknown status: ' + resp_data.status);
AppObj.trigger('user:profile'); // cleaner than manually updating profile data and displaying flash message
}
});
}
else {
logger.debug('private.proc_connect_local_submitted -- form validation failed: ' + JSON.stringify(val_errs));
profile_view.trigger('connect_form:show_val_errs', val_errs);
}
}
/**
* Process an authorisation provider disconnect according to the parameters
* @param {[type]} confirm_model The ConfirmationPrompt model to display
* @param {[type]} disconnect_post_path The path to post to, to execute the disconnect
* @param {[type]} disconnect_callback Callback function to post
*/
function proc_disconnect(confirm_model, disconnect_post_path, disconnect_callback) {
logger.debug('private.proc_disconnect - post path: ' + disconnect_post_path);
require('js/common/entities');
q(AppObj.request('common:entities:flashmessage'))
.then(function(flash_message_model) {
var CommonViews = require('js/common/views');
var ProfileViews = require('js/apps/user/profile/views');
var profile_view = new ProfileViews.UserProfileLayout();
var header_view = new CommonViews.H1Header({ model: new AppObj.Base.Entities.TransientModel({
header_text: 'User profile'
})});
var msg_view = new CommonViews.FlashMessageView({ model: flash_message_model });
var confirm_view = new CommonViews.ConfirmationPrompt({ model: confirm_model });
// no profile control panel
confirm_view.on('confirm-clicked', function() {
$.post(disconnect_post_path, {}, disconnect_callback);
});
confirm_view.on('reject-clicked', function() {
AppObj.trigger('user:profile');
});
profile_view.on('render', function() {
profile_view.region_header.show(header_view);
profile_view.region_message.show(msg_view);
profile_view.region_profile_main.show(confirm_view);
});
Display.tainer.show_in('main', profile_view);
})
.fail(AppObj.handle_rejected_promise.bind(undefined, 'UserApp.Profile - private.proc_disconnect'))
.done();
}
Profile.controller = {
/**
* Display the user profile, allowing users to connect other providers and logout
* @param {String} query_string Used so the server can send a message code to trigger a message display
*/
show_user_profile: function show_user_profile(query_string) {
logger.trace('controller.show_user_profile -- query_string: ' + query_string);
require('js/apps/user/entities');
require('js/common/entities');
if(AppObj.is_logged_in()) {
var upd_promise = AppObj.request('userapp:entities:userprofiledata');
var upa_promise = AppObj.request('userapp:entities:userprofilecontrolpanel');
var msg_promise = AppObj.request('common:entities:flashmessage');
q.all([upd_promise, upa_promise, msg_promise])
.spread(function(up_data, up_admin, msg) {
var CommonViews = require('js/common/views');
var ProfileViews = require('js/apps/user/profile/views');
logger.debug('show_user_profile -- msg data: ' + JSON.stringify(msg));
logger.debug('show_user_profile -- up_data data: ' + JSON.stringify(up_data));
logger.debug('show_user_profile -- up_admin data: ' + JSON.stringify(up_admin));
up_admin.set('email_connected', up_data.is_email_connected());
up_admin.set('fb_connected', up_data.is_fb_connected());
up_admin.set('google_connected', up_data.is_google_connected());
up_admin.set('twitter_connected', up_data.is_twitter_connected());
var profile_view = new ProfileViews.UserProfileLayout();
var header_view = new CommonViews.H1Header({ model: new AppObj.Base.Entities.TransientModel({
header_text: 'User profile'
})});
var msg_view = new CommonViews.FlashMessageView({ model: msg });
var p_data_view = new ProfileViews.UserProfileData({ model: up_data });
var p_admin_view = new ProfileViews.UserProfileControlPanel({ model: up_admin });
p_admin_view.on('logout-clicked', function() { AppObj.trigger('user:profile:logout'); });
p_admin_view.on('deactivate-clicked', function() { AppObj.trigger('user:profile:deactivate'); });
p_admin_view.on('change-password-clicked', function() { AppObj.trigger('user:profile:change:password'); });
p_admin_view.on('local-connect-clicked', function() { AppObj.trigger('user:profile:connect:local'); });
p_admin_view.on('fb-connect-clicked', function() { AppObj.trigger('user:profile:connect:fb'); });
p_admin_view.on('google-connect-clicked', function() { AppObj.trigger('user:profile:connect:google'); });
p_admin_view.on('twitter-connect-clicked', function() { AppObj.trigger('user:profile:connect:twitter'); });
p_admin_view.on('local-disc-clicked', function() { AppObj.trigger('user:profile:disconnect:local'); });
p_admin_view.on('fb-disc-clicked', function() { AppObj.trigger('user:profile:disconnect:fb'); });
p_admin_view.on('google-disc-clicked', function() { AppObj.trigger('user:profile:disconnect:google'); });
p_admin_view.on('twitter-disc-clicked', function() { AppObj.trigger('user:profile:disconnect:twitter'); });
profile_view.on('render', function() {
profile_view.region_header.show(header_view);
profile_view.region_message.show(msg_view);
profile_view.region_profile_main.show(p_data_view);
profile_view.region_profile_control_panel.show(p_admin_view);
});
Display.tainer.show_in('main', profile_view);
})
.fail(AppObj.handle_rejected_promise.bind(undefined, 'UserApp.Profile.controller.show_user_profile'))
.done();
}
else {
AppObj.trigger('user:access', 'user:profile');
}
},
/**
* Log out logged in user after prompting for confirmation, redirect to home:show
*/
proc_logout: function proc_logout() {
logger.trace('controller.proc_logout');
require('js/common/entities');
q(AppObj.request('common:entities:flashmessage'))
.then(function(flash_message_model) {
var CommonViews = require('js/common/views');
var ProfileViews = require('js/apps/user/profile/views');
var profile_view = new ProfileViews.UserProfileLayout();
var header_view = new CommonViews.H1Header({ model: new AppObj.Base.Entities.TransientModel({
header_text: 'User profile'
})});
var msg_view = new CommonViews.FlashMessageView({ model: flash_message_model });
var confirm_view = new CommonViews.ConfirmationPrompt({ model: new AppObj.Common.Entities.ConfirmationPrompt({
header: 'Logout?',
detail: 'Are you sure you want to logout?',
confirm_text: 'Yes',
reject_text: 'No'
})});
// no profile control panel
confirm_view.on('confirm-clicked', function() {
$.get(AppObj.config.apps.user.logout_path, function(resp_data, textStatus, jqXhr) {
AppObj.trigger('home:show');
});
});
confirm_view.on('reject-clicked', function() {
AppObj.trigger('user:profile');
});
profile_view.on('render', function() {
profile_view.region_header.show(header_view);
profile_view.region_message.show(msg_view);
profile_view.region_profile_main.show(confirm_view);
});
Display.tainer.show_in('main', profile_view);
})
.fail(AppObj.handle_rejected_promise.bind(undefined, 'UserApp.Profile.controller.proc_logout'))
.done();
},
/**
* Delete (deactivate) logged in user after prompting for confirmation, redirect to home:show
*/
proc_deactivate: function proc_deactivate() {
logger.trace('controller.proc_deactivate');
require('js/common/entities');
q(AppObj.request('common:entities:flashmessage'))
.then(function(flash_message_model) {
var CommonViews = require('js/common/views');
var ProfileViews = require('js/apps/user/profile/views');
var profile_view = new ProfileViews.UserProfileLayout();
var header_view = new CommonViews.H1Header({ model: new AppObj.Base.Entities.TransientModel({
header_text: 'User profile'
})});
var msg_view = new CommonViews.FlashMessageView({ model: flash_message_model });
var confirm_view = new CommonViews.ConfirmationPrompt({ model: new AppObj.Common.Entities.ConfirmationPrompt({
header: 'Deactivate acount?',
detail: 'If you deactivate your account you will not be able to log in. Are you sure?',
confirm_text: 'Yes',
reject_text: 'No'
})});
// no profile control panel
confirm_view.on('confirm-clicked', function() {
$.get(AppObj.config.apps.user.deactivate_path, function(resp_data, textStatus, jqXhr) {
AppObj.trigger('home:show');
});
});
confirm_view.on('reject-clicked', function() {
AppObj.trigger('user:profile');
});
profile_view.on('render', function() {
profile_view.region_header.show(header_view);
profile_view.region_message.show(msg_view);
profile_view.region_profile_main.show(confirm_view);
});
Display.tainer.show_in('main', profile_view);
})
.fail(AppObj.handle_rejected_promise.bind(undefined, 'UserApp.Profile.controller.proc_deactivate'))
.done();
},
/**
* Allow users which have a local email and password set to change the password. Display an error if no local
* email or password is set.
*/
proc_change_password: function proc_change_password() {
logger.trace('controller.proc_change_password');
var CommonViews = require('js/common/views');
var ProfileViews = require('js/apps/user/profile/views');
var profile_view = new ProfileViews.UserProfileLayout();
var header_view = new CommonViews.H1Header({ model: new AppObj.Base.Entities.TransientModel({
header_text: 'Change password'
})});
var change_password_form_view = new ProfileViews.ChangePasswordForm({
model: new AppObj.UserApp.Entities.UserChangePassword()
});
change_password_form_view.on('profile-clicked', function() { AppObj.trigger('user:profile'); });
change_password_form_view.on('home-clicked', function() { AppObj.trigger('home:show'); });
change_password_form_view.on('change-password-submitted', function(form_data) {
proc_change_password_submitted(form_data, profile_view);
});
profile_view.on('change_password_form:show_val_errs', function(val_errs) {
change_password_form_view.show_val_errs.call(change_password_form_view, val_errs);
});
profile_view.on('render', function() {
profile_view.region_header.show(header_view);
profile_view.region_profile_main.show(change_password_form_view);
});
Display.tainer.show_in('main', profile_view);
},
/**
* Display form to connect user account to their separate email account
*/
proc_conn_local: function proc_conn_local() {
logger.trace('controller.proc_conn_local');
var CommonViews = require('js/common/views');
var ProfileViews = require('js/apps/user/profile/views');
var profile_view = new ProfileViews.UserProfileLayout();
var header_view = new CommonViews.H1Header({ model: new AppObj.Base.Entities.TransientModel({
header_text: 'Add email'
})});
var connect_form_view = new ProfileViews.LocalConnectForm({
model: new AppObj.UserApp.Entities.UserLocalConnect()
});
connect_form_view.on('profile-clicked', function() { AppObj.trigger('user:profile'); });
connect_form_view.on('local-connect-submitted', function(form_data) {
proc_connect_local_submitted(form_data, profile_view);
});
profile_view.on('connect_form:show_val_errs', function(val_errs) {
connect_form_view.show_val_errs.call(connect_form_view, val_errs);
});
profile_view.on('render', function() {
profile_view.region_header.show(header_view);
profile_view.region_profile_main.show(connect_form_view);
});
Display.tainer.show_in('main', profile_view);
},
/**
* Connect user account to fb account
*/
proc_conn_fb: function proc_conn_fb() {
window.location.href = get_fb_connect_url();
},
/**
* Connect user account to google account
*/
proc_conn_google: function proc_conn_google() {
window.location.href = get_google_connect_url();
},
/**
* Connect user account to twitter account
*/
proc_conn_twitter: function proc_conn_twitter() {
window.location.href = get_twitter_connect_url();
},
/**
* Disconnect email address from user account
*/
proc_disc_local: function proc_disc_local() {
logger.trace('controller.proc_disc_local');
require('js/common/entities');
var confirm_model = new AppObj.Common.Entities.ConfirmationPrompt({
header: 'Remove email address?',
detail: 'If you remove your email address you will not be able to login using your email and password. ' +
'Are you sure?',
confirm_text: 'Yes',
reject_text: 'No'
});
var disconnect_callback = function proc_disc_local_disconnect_callback(resp_data, textStatus, jqXhr) {
if(resp_data.status === 'success') {
logger.debug('private.proc_disc_local - server response -- success, re-rendering profile');
AppObj.trigger('user:profile');
}
else if(resp_data.status === 'failure') {
logger.debug('private.proc_disc_local - server response -- failure, re-rendering profile');
AppObj.trigger('user:profile');
}
else {
logger.error('private.proc_disc_loal - server response -- unknown status: ' + resp_data.status);
AppObj.trigger('user:profile');
}
};
proc_disconnect(confirm_model, AppObj.config.apps.user.local_disconnect_path, disconnect_callback);
},
/**
* Disconnect Facebook account from user account
*/
proc_disc_fb: function proc_disc_fb() {
logger.trace('controller.proc_disc_fb');
require('js/common/entities');
var confirm_model = new AppObj.Common.Entities.ConfirmationPrompt({
header: 'Disconnect Facebook?',
detail: 'If you disconnect your Facebook account you will not be able to use it to login. Are you sure?',
confirm_text: 'Yes',
reject_text: 'No'
});
var disconnect_callback = function proc_disc_fb_disconnect_callback(resp_data, textStatus, jqXhr) {
if(resp_data.status === 'success') {
logger.debug('private.proc_disc_fb - server response -- success, re-rendering profile');
AppObj.trigger('user:profile');
}
else if(resp_data.status === 'failure') {
logger.debug('private.proc_disc_fb - server response -- failure, re-rendering profile');
AppObj.trigger('user:profile');
}
else {
logger.error('private.proc_disc_fb - server response -- unknown status: ' + resp_data.status);
AppObj.trigger('user:profile');
}
};
proc_disconnect(confirm_model, AppObj.config.apps.user.fb_disconnect_path, disconnect_callback);
},
/**
* Disconnect Google account from user account
*/
proc_disc_google: function proc_disc_google() {
logger.trace('controller.proc_disc_google');
require('js/common/entities');
var confirm_model = new AppObj.Common.Entities.ConfirmationPrompt({
header: 'Disconnect Google?',
detail: 'If you disconnect your Google account you will not be able to use it to login. Are you sure?',
confirm_text: 'Yes',
reject_text: 'No'
});
var disconnect_callback = function proc_disc_google_disconnect_callback(resp_data, textStatus, jqXhr) {
if(resp_data.status === 'success') {
logger.debug('private.proc_disc_google - server response -- success, re-rendering profile');
AppObj.trigger('user:profile');
}
else if(resp_data.status === 'failure') {
logger.debug('private.proc_disc_google - server response -- failure, re-rendering profile');
AppObj.trigger('user:profile');
}
else {
logger.error('private.proc_disc_google - server response -- unknown status: ' + resp_data.status);
AppObj.trigger('user:profile');
}
};
proc_disconnect(confirm_model, AppObj.config.apps.user.google_disconnect_path, disconnect_callback);
},
/**
* Disconnect Twitter account from user account
*/
proc_disc_twitter: function proc_disc_twitter() {
logger.trace('controller.proc_disc_twitter');
require('js/common/entities');
var confirm_model = new AppObj.Common.Entities.ConfirmationPrompt({
header: 'Disconnect Twitter?',
detail: 'If you disconnect your Twitter account you will not be able to use it to login. Are you sure?',
confirm_text: 'Yes',
reject_text: 'No'
});
var disconnect_callback = function proc_disc_twitter_disconnect_callback(resp_data, textStatus, jqXhr) {
if(resp_data.status === 'success') {
logger.debug('private.proc_disc_twitter - server response -- success, re-rendering profile');
AppObj.trigger('user:profile');
}
else if(resp_data.status === 'failure') {
logger.debug('private.proc_disc_twitter - server response -- failure, re-rendering profile');
AppObj.trigger('user:profile');
}
else {
logger.error('private.proc_disc_twitter - server response -- unknown status: ' + resp_data.status);
AppObj.trigger('user:profile');
}
};
proc_disconnect(confirm_model, AppObj.config.apps.user.twitter_disconnect_path, disconnect_callback);
}
};
});
return AppObj.UserApp.Profile.controller;
});
|
module.exports = [
// html tags
{
name: 'empty html',
data: '<html></html>'
},
{
name: 'html with attribute',
data: '<html lang="en"></html>'
},
{
name: 'html with empty head and body',
data: '<html><head></head><body></body></html>'
},
{
name: 'html with empty head',
data: '<html><head></head></html>'
},
{
name: 'html with empty body',
data: '<html><body></body></html>'
},
{
name: 'unclosed html and head tags',
data: '<html><head>'
},
{
name: 'unclosed html and body tags',
data: '<html><body>'
},
{
name: 'unclosed html, head, and body tags',
data: '<html><head><body>'
},
// head and body tags
{
name: 'unclosed head',
data: '<head>'
},
{
name: 'empty head',
data: '<head></head>'
},
{
name: 'head with title',
data: '<head><title>Text</title></head>'
},
{
name: 'empty head and body',
data: '<head></head><body></body>'
},
{
name: 'unclosed head and body',
data: '<head><body>'
},
{
name: 'unclosed title',
data: '<title>'
},
{
name: 'empty title',
data: '<title></title>'
},
{
name: 'title with text',
data: '<title>text</title>'
},
{
name: 'title with text as tags',
data: '<title><b>text</b></title>'
},
{
name: 'unclosed body',
data: '<body>'
},
{
name: 'empty body',
data: '<body></body>'
},
{
name: 'capitalized body',
data: '<BODY></BODY>'
},
{
name: 'body with paragraph',
data: '<body><p>text</p></body>'
},
// common tags
{
name: 'empty div',
data: '<div></div>'
},
{
name: 'empty paragraph',
data: '<p></p>'
},
{
name: 'paragraph with text',
data: '<p>text</p>'
},
{
name: 'meta with attribute',
data: '<meta charset="utf-8">'
},
{
name: 'textarea with value',
data: '<textarea>value</textarea>'
},
{
name: 'multiple spans',
data: '<span>1</span><span>2</span>'
},
// void (self-closing) tags
{
name: 'void',
data: '<br>'
},
{
name: 'self-closing void',
data: '<hr/>'
},
{
name: 'input with attributes',
data: '<input type="text" value="value">'
},
{
name: 'image',
data: '<img src="https://httpbin.org/image/png" alt="Image">'
},
{
name: 'multiple void',
data: '<link /><meta/><hr><input type="radio" checked />'
},
// tag attributes
{
name: 'h1 with id attribute',
data: '<h1 id="heading"></h1>'
},
{
name: 'h2 with class attribute',
data: '<h2 class="heading"></h2>'
},
{
name: 'em with style attribute',
data: '<em style="color: white; z-index: 1; -webkit-appearance: none"></em>'
},
{
name: 'data attribute',
data: '<div data-attribute="value"></div>'
},
{
name: 'event attribute',
data: '<div onclick="alert();"></div>'
},
{
name: 'span with multiple attributes',
data: '<span id="button" class="big" style="border: 1px solid #000; -moz-appearance: button;" aria-label="Back" />'
},
{
name: 'hr with multiple attributes',
data: '<hr id="foo" class="bar baz" style="background: #fff; text-align: center;" data-foo="bar">'
},
// adjacent tags
{
name: 'sibling',
data: '<li>brother</li><li>sister</li>'
},
// nested tags
{
name: 'nested definition list',
data: '<dl><dt>foo</dt><dd>bar<span>baz</span></dd></dl>'
},
{
name: 'nested unordered list',
data: '<ul><li>foo<span>bar</span></li><li>baz</li></ul>'
},
// script tag
{
name: 'empty script',
data: '<script></script>'
},
{
name: 'script',
data: '<script>console.log(1 < 2);</script>'
},
{
name: 'script with json',
data: '<script type="application/json">{"foo":"bar"}</script>'
},
// noscript tag
{
name: 'empty noscript',
data: '<noscript></noscript>'
},
{
name: 'noscript with text',
data: '<noscript>JS is not enabled</noscript>'
},
{
name: 'noscript with p',
data: '<noscript><p>JS is disabled</p></noscript>',
get skip() {
// client parser renders noscript incorrectly in jsdom
// template renders noscript children as text instead of nodes
var isJSDOM = typeof window === 'object' && window.name === 'nodejs';
return isJSDOM;
}
},
// style tag
{
name: 'empty style',
data: '<style></style>'
},
{
name: 'style',
data: '<style>body > .foo { color: #f00; }</style>'
},
// html5 tags
{
name: 'audio',
data: '<audio controls="controls" preload="none" width="640">'
},
// html entities
{
name: 'non-breaking space',
data: ' '
},
{
name: 'en dash',
data: '–'
},
{
name: 'em dash',
data: '—'
},
// directive
{
name: 'directive',
data: '<!doctype html>'
},
{
name: 'directive with html',
data: '<!DOCTYPE html><html></html>'
},
// comment
{
name: 'comment',
data: '<!-- comment -->'
},
{
name: 'conditional comment',
data: '<!--[if lt IE 9]>Below IE 9<![endif]-->'
},
// text
{
name: 'empty string',
data: ''
},
{
name: 'text',
data: 'text'
},
{
name: 'space',
data: ' '
},
// custom tag
{
name: 'custom tag',
data: '<custom>'
},
{
name: 'custom tags',
data: '<foo><bar>'
},
// invalid
{
name: 'self-closing div',
data: '<div/>'
},
{
name: 'self-closing div and p',
data: '<div/><p/>'
},
// misc
{
name: 'unclosed tag',
data: '<div>'
},
{
name: 'unclosed tags',
data: '<p><span>'
},
{
name: 'closing tag',
data: '</div>'
}
];
|
import {applyMiddleware, combineReducers, compose, createStore} from "redux";
import promiseMiddleware from "redux-promise-middleware";
import {reducer as formReducer} from "redux-form";
export default function(middleware, todoListReducer, todoFormReducer) {
const reducer = combineReducers({list: todoListReducer, form: formReducer, todoForm: todoFormReducer});
const createStoreWithMiddleware = middleware(createStore);
const store = createStoreWithMiddleware(reducer);
return store;
};
|
/**
* Lo-Dash 2.3.0 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize underscore exports="node" -o ./underscore/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
/**
* Enables explicit method chaining on the wrapper object.
*
* @name chain
* @memberOf _
* @category Chaining
* @returns {*} Returns the wrapper object.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* // without explicit chaining
* _(characters).first();
* // => { 'name': 'barney', 'age': 36 }
*
* // with explicit chaining
* _(characters).chain()
* .first()
* .pick('age')
* .value()
* // => { 'age': 36 }
*/
function wrapperChain() {
this.__chain__ = true;
return this;
}
module.exports = wrapperChain;
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var AuthorSchema = Schema({
first_name: {type: String, required: true, max: 100},
family_name: {type: String, require: true, max: 100},
date_of_birth: {type: Date},
date_of_death: {type: Date},
});
AuthorSchema
.virtual('name')
.get(function() {
return this.family_name + ", " + this.first_name
});
AuthorSchema
.virtual('url')
.get(function() {
return '/catalog/author/' + this._id;
});
module.exports = mongoose.model('Author', AuthorSchema); |
var Component = new Brick.Component();
Component.requires = {
mod: [
{name: '{C#MODNAME}', files: ['io.js', 'app.js']}
]
};
Component.entryPoint = function(NS){
/* * * * * * * DEPRECATED * * * * * * */
var Y = Brick.YUI,
L = Y.Lang,
UID = Brick.env.user.id | 0,
ADDED = 'added',
SLICE = Array.prototype.slice;
var AppsCore = function(options){
var appsOptions = options && options.APPS ? options.APPS : null;
this._initApps(appsOptions);
};
AppsCore.prototype = {
_initApps: function(appsOptions){
this._appsState = new Y.State();
var ctor = this.constructor,
c = ctor;
while (c){
this.addApps(c.APPS);
c = c.superclass ? c.superclass.constructor : null;
}
if (appsOptions){
this.addApps(appsOptions);
}
},
appAdded: function(name){
return !!(this._appsState.get(name, ADDED));
},
addApp: function(name, config){
var state = this._appsState;
if (state.get(name, ADDED)){
return;
}
config = Y.merge({
name: name,
instance: null
}, config || {});
config[ADDED] = true;
state.data[name] = config;
},
addApps: function(apps){
if (!apps){
return;
}
apps = Y.AttributeCore.protectAttrs(apps);
var name;
for (name in apps){
if (!apps.hasOwnProperty(name)){
continue;
}
this.addApp(name, apps[name]);
}
},
getApp: function(name){
var state = this._appsState,
item = state.data[name];
return item ? item.instance : null;
},
initializeApps: function(callback, context){
var data = this._appsState.data,
arr = [];
var initApp = function(stack){
if (stack.length === 0){
return callback.call(context || this);
}
var app = stack.pop();
Brick.use(app.name, 'lib', function(err, ns){
if (err){
app.error = err;
return initApp(stack);
}
app.namespace = ns;
ns.initApp({
initCallback: function(err, appInstance){
if (err){
app.error = err;
return initApp(stack);
}
app.instance = appInstance;
initApp(stack);
}
});
});
};
for (var name in data){
if (!data.hasOwnProperty(name)){
continue;
}
var app = data[name];
if (app.instance){
continue;
}
arr[arr.length] = app;
}
initApp(arr);
}
};
NS.AppsCore = AppsCore;
var RequestCore = function(options){
var reqsOptions = options && options.REQS ? options.REQS : null;
this._initRequests(reqsOptions);
};
RequestCore.prototype = {
_initRequests: function(reqsOptions){
this._reqsState = new Y.State();
var ctor = this.constructor,
c = ctor;
while (c){
this.addRequests(c.REQS);
c = c.superclass ? c.superclass.constructor : null;
}
if (reqsOptions){
this.addRequests(reqsOptions);
}
},
requestAdded: function(name){
return !!(this._reqsState.get(name, ADDED));
},
addRequest: function(name, config){
var state = this._reqsState;
if (state.get(name, ADDED)){
return;
}
config = Y.merge({
args: [],
argsHandle: null,
attribute: false,
type: null,
typeClass: null,
attach: null,
requestDataHandle: null,
response: null,
onResponse: null,
cache: null
}, config || {});
if (Y.Lang.isString(config.type)){
var a = config.type.split(':');
config.type = a[0];
switch (config.type) {
case 'model':
case 'modelList':
case 'response':
if (!config.typeClass){
config.typeClass = a[1];
}
if (!this.attrAdded(name) && config.attribute){
this.addAttr(name, {});
}
break;
}
}
if (!config.type || !config.typeClass){
config.type = config.typeClass = null;
}
config[ADDED] = true;
state.data[name] = config;
},
addRequests: function(reqs){
if (!reqs){
return;
}
reqs = Y.AttributeCore.protectAttrs(reqs);
var name;
for (name in reqs){
if (!reqs.hasOwnProperty(name)){
continue;
}
this.addRequest(name, reqs[name]);
}
}
};
NS.RequestCore = RequestCore;
/**
* @deprecated
*/
NS.Application = Y.Base.create('application', Y.Base, [
NS.AppsCore,
NS.Navigator,
NS.RequestCore,
NS.CronCore,
NS.AJAX,
NS.Language
], {
initializer: function(){
this.publish('appResponses');
var ns = this.get('component');
ns.namespace.appInstance = this;
},
initCallbackFire: function(){
var initCallback = this.get('initCallback');
this.initializeApps(function(){
if (L.isFunction(initCallback)){
initCallback(null, this);
}
}, this);
},
_request: function(name){
if (!this.requestAdded(name)){
return;
}
var state = this._reqsState,
info = state.data[name],
funcArgs = SLICE.call(arguments),
funcArg,
defArgsOffset = 1,
aArgs = [],
args = info.args,
rData = {
'do': name
};
if (Y.Lang.isArray(args)){
defArgsOffset = args.length + 1;
if (Y.Lang.isFunction(info.argsHandle)){
args = info.argsHandle.apply(this, args);
}
for (var i = 0; i < args.length; i++){
funcArg = funcArgs[i + 1];
aArgs[aArgs.length] = funcArg;
if (funcArg && Y.Lang.isFunction(funcArg.toJSON)){
funcArg = funcArg.toJSON();
}
rData[args[i]] = funcArg;
}
}
if (Y.Lang.isFunction(info.requestDataHandle)){
rData = info.requestDataHandle.call(this, rData);
aArgs = [];
for (var i = 0; i < args.length; i++){
aArgs[i] = rData[args[i]];
}
}
var callback, context;
if (funcArgs[defArgsOffset]){
callback = funcArgs[defArgsOffset];
}
if (funcArgs[defArgsOffset + 1]){
context = funcArgs[defArgsOffset + 1];
}
var cacheResult;
if (Y.Lang.isFunction(info.cache)){
cacheResult = info.cache.apply(this, aArgs);
}
if (!cacheResult && info.attribute){
cacheResult = this.get(name);
}
if (cacheResult){
var ret = {};
ret[name] = cacheResult;
// TODO: develop - if attach not in cache
if (info.attach){
var req = info.attach;
if (Y.Lang.isString(req)){
req = req.split(',');
}
for (var i = 0; i < req.length; i++){
var actr = req[i];
if (this.requestAdded(actr) && state.get('actr', 'attribute')){
ret[actr] = this.get(actr);
}
}
}
return callback.apply(context, [null, ret]);
}
if (info.attach){
var req = info.attach;
if (Y.Lang.isString(req)){
req = req.split(',');
}
rData = [rData]
for (var i = 0, reqi, rinfo; i < req.length; i++){
reqi = req[i];
rinfo = state.data[reqi];
if (!rinfo){
continue;
}
if (rinfo.attribute && this.get(reqi)){
continue;
}
rData[rData.length] = {
'do': reqi
};
}
}
this._appRequest(rData, callback, context);
},
_appRequest: function(rData, callback, context){
if (this.get('isLoadAppStructure') && !this.get('appStructure')){
if (!Y.Lang.isArray(rData)){
rData = [rData];
}
rData.splice(0, 0, {do: 'appStructure'});
}
this.ajax(rData, this._onAppResponses, {
arguments: {callback: callback, context: context}
});
},
_onAppResponse: function(name, data, res){
if (!this.requestAdded(name)){
return;
}
var info = this._reqsState.data[name];
if (info.type && info.typeClass){
var di = data[name] || {}, typeClass;
switch (info.type) {
case 'response':
typeClass = this.get(info.typeClass) || NS.AppResponse;
di = Y.merge(di || {}, {
appInstance: this,
});
res[name] = new typeClass(di);
break;
case 'model':
typeClass = this.get(info.typeClass) || NS.AppModel;
di = Y.merge(di || {}, {
appInstance: this,
});
res[name] = new typeClass(di);
break;
case 'modelList':
typeClass = this.get(info.typeClass) || NS.AppModelList;
res[name] = new typeClass({
appInstance: this,
items: di.list || []
});
break;
}
} else {
res[name] = data[name];
if (Y.Lang.isFunction(info.response)){
res[name] = info.response.call(this, data[name]);
}
}
if (info.attribute){
this.set(name, res[name]);
}
var callback;
if (res[name] && Y.Lang.isFunction(info.onResponse)){
callback = info.onResponse.call(this, res[name], data[name]);
}
return callback;
},
_onAppResponses: function(err, res, details){
res = res || {};
if (res.userid !== UID){
window.location.reload(false);
return;
}
var tRes = {},
rData = res.data || {};
if (!Y.Lang.isArray(rData)){
rData = [rData];
}
var rCallbacks = [], i, data, name, cb;
for (i = 0; i < rData.length; i++){
data = rData[i];
for (name in data){
cb = this._onAppResponse(name, data, tRes);
if (Y.Lang.isFunction(cb)){
rCallbacks[rCallbacks.length] = cb;
}
}
}
var complete = function(){
this.fire('appResponses', {
error: err,
responses: rData,
result: tRes
});
if (Y.Lang.isFunction(details.callback)){
details.callback.apply(details.context, [err, tRes]);
}
};
var rCallbackFire = function(cbList){
if (cbList.length === 0){
return complete.call(this);
}
cbList.pop().call(this, function(err, result){
// TODO: implode errors
if (!err){
tRes = Y.merge(tRes, result || {});
}
return rCallbackFire.call(this, cbList);
}, this);
};
rCallbackFire.call(this, rCallbacks);
},
onAJAXError: function(err){
Brick.mod.widget.notice.show(err.msg);
},
}, {
ATTRS: {
initCallback: {value: null},
component: {value: null},
moduleName: {value: ''},
isLoadAppStructure: {value: false},
isAPI: {value: false}
}
});
NS.Application.build = function(component, ajaxes, px, extensions, sx){
extensions = extensions || [];
sx = sx || {};
sx.REQS = Y.merge({
appStructure: {
attribute: true,
response: function(d){
return new NS.AppStructure(d);
}
}
}, sx.REQS || {});
ajaxes = sx.REQS = Y.merge(ajaxes, sx.REQS || {});
var moduleName = component.moduleName,
ns = Brick.mod[moduleName],
appName = moduleName + 'App';
for (var n in ajaxes){
(function(){
var act = n;
px[act] = function(){
var args = SLICE.call(arguments);
args.splice(0, 0, act);
this._request.apply(this, args);
};
})();
}
sx.ATTRS = Y.merge(sx.ATTRS || {}, {
component: {value: component},
moduleName: {value: moduleName}
});
ns.App = Y.Base.create(appName, NS.Application, extensions, px, sx);
ns.initApp = function(options){
if (Y.Lang.isFunction(options)){
options = {
initCallback: options
}
}
options = Y.merge({
initCallback: function(){
}
}, options || {});
if (ns.appInstance){
return options.initCallback(null, ns.appInstance);
}
new ns.App(options);
};
ns.appInstance = null;
};
}; |
/*! jQuery UI - v1.11.2 - 2015-01-02
* http://jqueryui.com
* Includes: core.js, widget.js, position.js, autocomplete.js, menu.js
* Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
/*!
* jQuery UI Core 1.11.2
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/
// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};
$.extend( $.ui, {
version: "1.11.2",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
});
// plugins
$.fn.extend({
scrollParent: function( includeHidden ) {
var position = this.css( "position" ),
excludeStaticParent = position === "absolute",
overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
scrollParent = this.parents().filter( function() {
var parent = $( this );
if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
return false;
}
return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) );
}).eq( 0 );
return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent;
},
uniqueId: (function() {
var uuid = 0;
return function() {
return this.each(function() {
if ( !this.id ) {
this.id = "ui-id-" + ( ++uuid );
}
});
};
})(),
removeUniqueId: function() {
return this.each(function() {
if ( /^ui-id-\d+$/.test( this.id ) ) {
$( this ).removeAttr( "id" );
}
});
}
});
// selectors
function focusable( element, isTabIndexNotNaN ) {
var map, mapName, img,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap='#" + mapName + "']" )[ 0 ];
return !!img && visible( img );
}
return ( /input|select|textarea|button|object/.test( nodeName ) ?
!element.disabled :
"a" === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) &&
// the element and all of its ancestors must be visible
visible( element );
}
function visible( element ) {
return $.expr.filters.visible( element ) &&
!$( element ).parents().addBack().filter(function() {
return $.css( this, "visibility" ) === "hidden";
}).length;
}
$.extend( $.expr[ ":" ], {
data: $.expr.createPseudo ?
$.expr.createPseudo(function( dataName ) {
return function( elem ) {
return !!$.data( elem, dataName );
};
}) :
// support: jQuery <1.8
function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function( element ) {
return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
},
tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
isTabIndexNaN = isNaN( tabIndex );
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
}
});
// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
if ( border ) {
size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
}
});
return size;
}
$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}
return this.each(function() {
$( this ).css( type, reduce( this, size ) + "px" );
});
};
$.fn[ "outer" + name] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}
return this.each(function() {
$( this).css( type, reduce( this, size, true, margin ) + "px" );
});
};
});
}
// support: jQuery <1.8
if ( !$.fn.addBack ) {
$.fn.addBack = function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
};
}
// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
$.fn.removeData = (function( removeData ) {
return function( key ) {
if ( arguments.length ) {
return removeData.call( this, $.camelCase( key ) );
} else {
return removeData.call( this );
}
};
})( $.fn.removeData );
}
// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
$.fn.extend({
focus: (function( orig ) {
return function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$( elem ).focus();
if ( fn ) {
fn.call( elem );
}
}, delay );
}) :
orig.apply( this, arguments );
};
})( $.fn.focus ),
disableSelection: (function() {
var eventType = "onselectstart" in document.createElement( "div" ) ?
"selectstart" :
"mousedown";
return function() {
return this.bind( eventType + ".ui-disableSelection", function( event ) {
event.preventDefault();
});
};
})(),
enableSelection: function() {
return this.unbind( ".ui-disableSelection" );
},
zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}
if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
}
});
// $.ui.plugin is deprecated. Use $.widget() extensions instead.
$.ui.plugin = {
add: function( module, option, set ) {
var i,
proto = $.ui[ module ].prototype;
for ( i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args, allowDisconnected ) {
var i,
set = instance.plugins[ name ];
if ( !set ) {
return;
}
if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
return;
}
for ( i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
};
/*!
* jQuery UI Widget 1.11.2
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/jQuery.widget/
*/
var widget_uuid = 0,
widget_slice = Array.prototype.slice;
$.cleanData = (function( orig ) {
return function( elems ) {
var events, elem, i;
for ( i = 0; (elem = elems[i]) != null; i++ ) {
try {
// Only trigger remove when necessary to save time
events = $._data( elem, "events" );
if ( events && events.remove ) {
$( elem ).triggerHandler( "remove" );
}
// http://bugs.jquery.com/ticket/8235
} catch ( e ) {}
}
orig( elems );
};
})( $.cleanData );
$.widget = function( name, base, prototype ) {
var fullName, existingConstructor, constructor, basePrototype,
// proxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
proxiedPrototype = {},
namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( !$.isFunction( value ) ) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
});
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
return constructor;
};
$.widget.extend = function( target ) {
var input = widget_slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = widget_slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( options === "instance" ) {
returnValue = instance;
return false;
}
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} );
if ( instance._init ) {
instance._init();
}
} else {
$.data( this, fullName, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = widget_uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
});
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this._create();
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind( this.eventNamespace )
.removeData( this.widgetFullName )
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData( $.camelCase( this.widgetFullName ) );
this.widget()
.unbind( this.eventNamespace )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( this.eventNamespace );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( arguments.length === 1 ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( arguments.length === 1 ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetFullName + "-disabled", !!value );
// If the widget is becoming disabled, then nothing is interactive
if ( value ) {
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
}
return this;
},
enable: function() {
return this._setOptions({ disabled: false });
},
disable: function() {
return this._setOptions({ disabled: true });
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^([\w:-]*)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
delegateElement.delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_off: function( element, eventName ) {
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) +
this.eventNamespace;
element.unbind( eventName ).undelegate( eventName );
// Clear the stack to avoid memory leaks (#10056)
this.bindings = $( this.bindings.not( element ).get() );
this.focusable = $( this.focusable.not( element ).get() );
this.hoverable = $( this.hoverable.not( element ).get() );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
var widget = $.widget;
/*!
* jQuery UI Position 1.11.2
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/position/
*/
(function() {
$.ui = $.ui || {};
var cachedScrollbarWidth, supportsOffsetFractions,
max = Math.max,
abs = Math.abs,
round = Math.round,
rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[\+\-]\d+(\.[\d]+)?%?/,
rposition = /^\w+/,
rpercent = /%$/,
_position = $.fn.position;
function getOffsets( offsets, width, height ) {
return [
parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
];
}
function parseCss( element, property ) {
return parseInt( $.css( element, property ), 10 ) || 0;
}
function getDimensions( elem ) {
var raw = elem[0];
if ( raw.nodeType === 9 ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: 0, left: 0 }
};
}
if ( $.isWindow( raw ) ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
};
}
if ( raw.preventDefault ) {
return {
width: 0,
height: 0,
offset: { top: raw.pageY, left: raw.pageX }
};
}
return {
width: elem.outerWidth(),
height: elem.outerHeight(),
offset: elem.offset()
};
}
$.position = {
scrollbarWidth: function() {
if ( cachedScrollbarWidth !== undefined ) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $( "<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
innerDiv = div.children()[0];
$( "body" ).append( div );
w1 = innerDiv.offsetWidth;
div.css( "overflow", "scroll" );
w2 = innerDiv.offsetWidth;
if ( w1 === w2 ) {
w2 = div[0].clientWidth;
}
div.remove();
return (cachedScrollbarWidth = w1 - w2);
},
getScrollInfo: function( within ) {
var overflowX = within.isWindow || within.isDocument ? "" :
within.element.css( "overflow-x" ),
overflowY = within.isWindow || within.isDocument ? "" :
within.element.css( "overflow-y" ),
hasOverflowX = overflowX === "scroll" ||
( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
hasOverflowY = overflowY === "scroll" ||
( overflowY === "auto" && within.height < within.element[0].scrollHeight );
return {
width: hasOverflowY ? $.position.scrollbarWidth() : 0,
height: hasOverflowX ? $.position.scrollbarWidth() : 0
};
},
getWithinInfo: function( element ) {
var withinElement = $( element || window ),
isWindow = $.isWindow( withinElement[0] ),
isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9;
return {
element: withinElement,
isWindow: isWindow,
isDocument: isDocument,
offset: withinElement.offset() || { left: 0, top: 0 },
scrollLeft: withinElement.scrollLeft(),
scrollTop: withinElement.scrollTop(),
// support: jQuery 1.6.x
// jQuery 1.6 doesn't support .outerWidth/Height() on documents or windows
width: isWindow || isDocument ? withinElement.width() : withinElement.outerWidth(),
height: isWindow || isDocument ? withinElement.height() : withinElement.outerHeight()
};
}
};
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
target = $( options.of ),
within = $.position.getWithinInfo( options.within ),
scrollInfo = $.position.getScrollInfo( within ),
collision = ( options.collision || "flip" ).split( " " ),
offsets = {};
dimensions = getDimensions( target );
if ( target[0].preventDefault ) {
// force left top to allow flipping
options.at = "left top";
}
targetWidth = dimensions.width;
targetHeight = dimensions.height;
targetOffset = dimensions.offset;
// clone to reuse original targetOffset later
basePosition = $.extend( {}, targetOffset );
// force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[ this ] || "" ).split( " " ),
horizontalOffset,
verticalOffset;
if ( pos.length === 1) {
pos = rhorizontal.test( pos[ 0 ] ) ?
pos.concat( [ "center" ] ) :
rvertical.test( pos[ 0 ] ) ?
[ "center" ].concat( pos ) :
[ "center", "center" ];
}
pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
// calculate offsets
horizontalOffset = roffset.exec( pos[ 0 ] );
verticalOffset = roffset.exec( pos[ 1 ] );
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// reduce to just the positions without the offsets
options[ this ] = [
rposition.exec( pos[ 0 ] )[ 0 ],
rposition.exec( pos[ 1 ] )[ 0 ]
];
});
// normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
if ( options.at[ 0 ] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[ 0 ] === "center" ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[ 1 ] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[ 1 ] === "center" ) {
basePosition.top += targetHeight / 2;
}
atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each(function() {
var collisionPosition, using,
elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseCss( this, "marginLeft" ),
marginTop = parseCss( this, "marginTop" ),
collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
position = $.extend( {}, basePosition ),
myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
if ( options.my[ 0 ] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[ 0 ] === "center" ) {
position.left -= elemWidth / 2;
}
if ( options.my[ 1 ] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[ 1 ] === "center" ) {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
// if the browser doesn't support fractions, then round for consistent results
if ( !supportsOffsetFractions ) {
position.left = round( position.left );
position.top = round( position.top );
}
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[ i ] ] ) {
$.ui.position[ collision[ i ] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
my: options.my,
at: options.at,
within: within,
elem: elem
});
}
});
if ( options.using ) {
// adds feedback as second argument to using callback, if present
using = function( props ) {
var left = targetOffset.left - position.left,
right = left + targetWidth - elemWidth,
top = targetOffset.top - position.top,
bottom = top + targetHeight - elemHeight,
feedback = {
target: {
element: target,
left: targetOffset.left,
top: targetOffset.top,
width: targetWidth,
height: targetHeight
},
element: {
element: elem,
left: position.left,
top: position.top,
width: elemWidth,
height: elemHeight
},
horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
};
if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
feedback.horizontal = "center";
}
if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
feedback.vertical = "middle";
}
if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
feedback.important = "horizontal";
} else {
feedback.important = "vertical";
}
options.using.call( this, props, feedback );
};
}
elem.offset( $.extend( position, { using: using } ) );
});
};
$.ui.position = {
fit: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
outerWidth = within.width,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight;
// element is wider than within
if ( data.collisionWidth > outerWidth ) {
// element is initially over the left side of within
if ( overLeft > 0 && overRight <= 0 ) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
position.left += overLeft - newOverRight;
// element is initially over right side of within
} else if ( overRight > 0 && overLeft <= 0 ) {
position.left = withinOffset;
// element is initially over both left and right sides of within
} else {
if ( overLeft > overRight ) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// too far left -> align with left edge
} else if ( overLeft > 0 ) {
position.left += overLeft;
// too far right -> align with right edge
} else if ( overRight > 0 ) {
position.left -= overRight;
// adjust based on position and margin
} else {
position.left = max( position.left - collisionPosLeft, position.left );
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
outerHeight = data.within.height,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverBottom;
// element is taller than within
if ( data.collisionHeight > outerHeight ) {
// element is initially over the top of within
if ( overTop > 0 && overBottom <= 0 ) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
position.top += overTop - newOverBottom;
// element is initially over bottom of within
} else if ( overBottom > 0 && overTop <= 0 ) {
position.top = withinOffset;
// element is initially over both top and bottom of within
} else {
if ( overTop > overBottom ) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// too far up -> align with top
} else if ( overTop > 0 ) {
position.top += overTop;
// too far down -> align with bottom edge
} else if ( overBottom > 0 ) {
position.top -= overBottom;
// adjust based on position and margin
} else {
position.top = max( position.top - collisionPosTop, position.top );
}
}
},
flip: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.offset.left + within.scrollLeft,
outerWidth = within.width,
offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - offsetLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
data.at[ 0 ] === "right" ?
-data.targetWidth :
0,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if ( overLeft < 0 ) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
position.left += myOffset + atOffset + offset;
}
} else if ( overRight > 0 ) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
position.left += myOffset + atOffset + offset;
}
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.offset.top + within.scrollTop,
outerHeight = within.height,
offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - offsetTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
data.at[ 1 ] === "bottom" ?
-data.targetHeight :
0,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if ( overTop < 0 ) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
position.top += myOffset + atOffset + offset;
}
} else if ( overBottom > 0 ) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply( this, arguments );
$.ui.position.fit.left.apply( this, arguments );
},
top: function() {
$.ui.position.flip.top.apply( this, arguments );
$.ui.position.fit.top.apply( this, arguments );
}
}
};
// fraction support test
(function() {
var testElement, testElementParent, testElementStyle, offsetLeft, i,
body = document.getElementsByTagName( "body" )[ 0 ],
div = document.createElement( "div" );
//Create a "fake body" for testing based on method used in jQuery.support
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
};
if ( body ) {
$.extend( testElementStyle, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
}
for ( i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || document.documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
div.style.cssText = "position: absolute; left: 10.7432222px;";
offsetLeft = $( div ).offset().left;
supportsOffsetFractions = offsetLeft > 10 && offsetLeft < 11;
testElement.innerHTML = "";
testElementParent.removeChild( testElement );
})();
})();
var position = $.ui.position;
/*!
* jQuery UI Menu 1.11.2
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/menu/
*/
var menu = $.widget( "ui.menu", {
version: "1.11.2",
defaultElement: "<ul>",
delay: 300,
options: {
icons: {
submenu: "ui-icon-carat-1-e"
},
items: "> *",
menus: "ul",
position: {
my: "left-1 top",
at: "right top"
},
role: "menu",
// callbacks
blur: null,
focus: null,
select: null
},
_create: function() {
this.activeMenu = this.element;
// Flag used to prevent firing of the click handler
// as the event bubbles up through nested menus
this.mouseHandled = false;
this.element
.uniqueId()
.addClass( "ui-menu ui-widget ui-widget-content" )
.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length )
.attr({
role: this.options.role,
tabIndex: 0
});
if ( this.options.disabled ) {
this.element
.addClass( "ui-state-disabled" )
.attr( "aria-disabled", "true" );
}
this._on({
// Prevent focus from sticking to links inside menu after clicking
// them (focus should always stay on UL during navigation).
"mousedown .ui-menu-item": function( event ) {
event.preventDefault();
},
"click .ui-menu-item": function( event ) {
var target = $( event.target );
if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
this.select( event );
// Only set the mouseHandled flag if the event will bubble, see #9469.
if ( !event.isPropagationStopped() ) {
this.mouseHandled = true;
}
// Open submenu on click
if ( target.has( ".ui-menu" ).length ) {
this.expand( event );
} else if ( !this.element.is( ":focus" ) && $( this.document[ 0 ].activeElement ).closest( ".ui-menu" ).length ) {
// Redirect focus to the menu
this.element.trigger( "focus", [ true ] );
// If the active item is on the top level, let it stay active.
// Otherwise, blur the active item since it is no longer visible.
if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
clearTimeout( this.timer );
}
}
}
},
"mouseenter .ui-menu-item": function( event ) {
// Ignore mouse events while typeahead is active, see #10458.
// Prevents focusing the wrong item when typeahead causes a scroll while the mouse
// is over an item in the menu
if ( this.previousFilter ) {
return;
}
var target = $( event.currentTarget );
// Remove ui-state-active class from siblings of the newly focused menu item
// to avoid a jump caused by adjacent elements both having a class with a border
target.siblings( ".ui-state-active" ).removeClass( "ui-state-active" );
this.focus( event, target );
},
mouseleave: "collapseAll",
"mouseleave .ui-menu": "collapseAll",
focus: function( event, keepActiveItem ) {
// If there's already an active item, keep it active
// If not, activate the first item
var item = this.active || this.element.find( this.options.items ).eq( 0 );
if ( !keepActiveItem ) {
this.focus( event, item );
}
},
blur: function( event ) {
this._delay(function() {
if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
this.collapseAll( event );
}
});
},
keydown: "_keydown"
});
this.refresh();
// Clicks outside of a menu collapse any open menus
this._on( this.document, {
click: function( event ) {
if ( this._closeOnDocumentClick( event ) ) {
this.collapseAll( event );
}
// Reset the mouseHandled flag
this.mouseHandled = false;
}
});
},
_destroy: function() {
// Destroy (sub)menus
this.element
.removeAttr( "aria-activedescendant" )
.find( ".ui-menu" ).addBack()
.removeClass( "ui-menu ui-widget ui-widget-content ui-menu-icons ui-front" )
.removeAttr( "role" )
.removeAttr( "tabIndex" )
.removeAttr( "aria-labelledby" )
.removeAttr( "aria-expanded" )
.removeAttr( "aria-hidden" )
.removeAttr( "aria-disabled" )
.removeUniqueId()
.show();
// Destroy menu items
this.element.find( ".ui-menu-item" )
.removeClass( "ui-menu-item" )
.removeAttr( "role" )
.removeAttr( "aria-disabled" )
.removeUniqueId()
.removeClass( "ui-state-hover" )
.removeAttr( "tabIndex" )
.removeAttr( "role" )
.removeAttr( "aria-haspopup" )
.children().each( function() {
var elem = $( this );
if ( elem.data( "ui-menu-submenu-carat" ) ) {
elem.remove();
}
});
// Destroy menu dividers
this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" );
},
_keydown: function( event ) {
var match, prev, character, skip,
preventDefault = true;
switch ( event.keyCode ) {
case $.ui.keyCode.PAGE_UP:
this.previousPage( event );
break;
case $.ui.keyCode.PAGE_DOWN:
this.nextPage( event );
break;
case $.ui.keyCode.HOME:
this._move( "first", "first", event );
break;
case $.ui.keyCode.END:
this._move( "last", "last", event );
break;
case $.ui.keyCode.UP:
this.previous( event );
break;
case $.ui.keyCode.DOWN:
this.next( event );
break;
case $.ui.keyCode.LEFT:
this.collapse( event );
break;
case $.ui.keyCode.RIGHT:
if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
this.expand( event );
}
break;
case $.ui.keyCode.ENTER:
case $.ui.keyCode.SPACE:
this._activate( event );
break;
case $.ui.keyCode.ESCAPE:
this.collapse( event );
break;
default:
preventDefault = false;
prev = this.previousFilter || "";
character = String.fromCharCode( event.keyCode );
skip = false;
clearTimeout( this.filterTimer );
if ( character === prev ) {
skip = true;
} else {
character = prev + character;
}
match = this._filterMenuItems( character );
match = skip && match.index( this.active.next() ) !== -1 ?
this.active.nextAll( ".ui-menu-item" ) :
match;
// If no matches on the current filter, reset to the last character pressed
// to move down the menu to the first item that starts with that character
if ( !match.length ) {
character = String.fromCharCode( event.keyCode );
match = this._filterMenuItems( character );
}
if ( match.length ) {
this.focus( event, match );
this.previousFilter = character;
this.filterTimer = this._delay(function() {
delete this.previousFilter;
}, 1000 );
} else {
delete this.previousFilter;
}
}
if ( preventDefault ) {
event.preventDefault();
}
},
_activate: function( event ) {
if ( !this.active.is( ".ui-state-disabled" ) ) {
if ( this.active.is( "[aria-haspopup='true']" ) ) {
this.expand( event );
} else {
this.select( event );
}
}
},
refresh: function() {
var menus, items,
that = this,
icon = this.options.icons.submenu,
submenus = this.element.find( this.options.menus );
this.element.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length );
// Initialize nested menus
submenus.filter( ":not(.ui-menu)" )
.addClass( "ui-menu ui-widget ui-widget-content ui-front" )
.hide()
.attr({
role: this.options.role,
"aria-hidden": "true",
"aria-expanded": "false"
})
.each(function() {
var menu = $( this ),
item = menu.parent(),
submenuCarat = $( "<span>" )
.addClass( "ui-menu-icon ui-icon " + icon )
.data( "ui-menu-submenu-carat", true );
item
.attr( "aria-haspopup", "true" )
.prepend( submenuCarat );
menu.attr( "aria-labelledby", item.attr( "id" ) );
});
menus = submenus.add( this.element );
items = menus.find( this.options.items );
// Initialize menu-items containing spaces and/or dashes only as dividers
items.not( ".ui-menu-item" ).each(function() {
var item = $( this );
if ( that._isDivider( item ) ) {
item.addClass( "ui-widget-content ui-menu-divider" );
}
});
// Don't refresh list items that are already adapted
items.not( ".ui-menu-item, .ui-menu-divider" )
.addClass( "ui-menu-item" )
.uniqueId()
.attr({
tabIndex: -1,
role: this._itemRole()
});
// Add aria-disabled attribute to any disabled menu item
items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" );
// If the active item has been removed, blur the menu
if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
this.blur();
}
},
_itemRole: function() {
return {
menu: "menuitem",
listbox: "option"
}[ this.options.role ];
},
_setOption: function( key, value ) {
if ( key === "icons" ) {
this.element.find( ".ui-menu-icon" )
.removeClass( this.options.icons.submenu )
.addClass( value.submenu );
}
if ( key === "disabled" ) {
this.element
.toggleClass( "ui-state-disabled", !!value )
.attr( "aria-disabled", value );
}
this._super( key, value );
},
focus: function( event, item ) {
var nested, focused;
this.blur( event, event && event.type === "focus" );
this._scrollIntoView( item );
this.active = item.first();
focused = this.active.addClass( "ui-state-focus" ).removeClass( "ui-state-active" );
// Only update aria-activedescendant if there's a role
// otherwise we assume focus is managed elsewhere
if ( this.options.role ) {
this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
}
// Highlight active parent menu item, if any
this.active
.parent()
.closest( ".ui-menu-item" )
.addClass( "ui-state-active" );
if ( event && event.type === "keydown" ) {
this._close();
} else {
this.timer = this._delay(function() {
this._close();
}, this.delay );
}
nested = item.children( ".ui-menu" );
if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
this._startOpening(nested);
}
this.activeMenu = item.parent();
this._trigger( "focus", event, { item: item } );
},
_scrollIntoView: function( item ) {
var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
if ( this._hasScroll() ) {
borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
scroll = this.activeMenu.scrollTop();
elementHeight = this.activeMenu.height();
itemHeight = item.outerHeight();
if ( offset < 0 ) {
this.activeMenu.scrollTop( scroll + offset );
} else if ( offset + itemHeight > elementHeight ) {
this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
}
}
},
blur: function( event, fromFocus ) {
if ( !fromFocus ) {
clearTimeout( this.timer );
}
if ( !this.active ) {
return;
}
this.active.removeClass( "ui-state-focus" );
this.active = null;
this._trigger( "blur", event, { item: this.active } );
},
_startOpening: function( submenu ) {
clearTimeout( this.timer );
// Don't open if already open fixes a Firefox bug that caused a .5 pixel
// shift in the submenu position when mousing over the carat icon
if ( submenu.attr( "aria-hidden" ) !== "true" ) {
return;
}
this.timer = this._delay(function() {
this._close();
this._open( submenu );
}, this.delay );
},
_open: function( submenu ) {
var position = $.extend({
of: this.active
}, this.options.position );
clearTimeout( this.timer );
this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
.hide()
.attr( "aria-hidden", "true" );
submenu
.show()
.removeAttr( "aria-hidden" )
.attr( "aria-expanded", "true" )
.position( position );
},
collapseAll: function( event, all ) {
clearTimeout( this.timer );
this.timer = this._delay(function() {
// If we were passed an event, look for the submenu that contains the event
var currentMenu = all ? this.element :
$( event && event.target ).closest( this.element.find( ".ui-menu" ) );
// If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
if ( !currentMenu.length ) {
currentMenu = this.element;
}
this._close( currentMenu );
this.blur( event );
this.activeMenu = currentMenu;
}, this.delay );
},
// With no arguments, closes the currently active menu - if nothing is active
// it closes all menus. If passed an argument, it will search for menus BELOW
_close: function( startMenu ) {
if ( !startMenu ) {
startMenu = this.active ? this.active.parent() : this.element;
}
startMenu
.find( ".ui-menu" )
.hide()
.attr( "aria-hidden", "true" )
.attr( "aria-expanded", "false" )
.end()
.find( ".ui-state-active" ).not( ".ui-state-focus" )
.removeClass( "ui-state-active" );
},
_closeOnDocumentClick: function( event ) {
return !$( event.target ).closest( ".ui-menu" ).length;
},
_isDivider: function( item ) {
// Match hyphen, em dash, en dash
return !/[^\-\u2014\u2013\s]/.test( item.text() );
},
collapse: function( event ) {
var newItem = this.active &&
this.active.parent().closest( ".ui-menu-item", this.element );
if ( newItem && newItem.length ) {
this._close();
this.focus( event, newItem );
}
},
expand: function( event ) {
var newItem = this.active &&
this.active
.children( ".ui-menu " )
.find( this.options.items )
.first();
if ( newItem && newItem.length ) {
this._open( newItem.parent() );
// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
this._delay(function() {
this.focus( event, newItem );
});
}
},
next: function( event ) {
this._move( "next", "first", event );
},
previous: function( event ) {
this._move( "prev", "last", event );
},
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( direction, filter, event ) {
var next;
if ( this.active ) {
if ( direction === "first" || direction === "last" ) {
next = this.active
[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
.eq( -1 );
} else {
next = this.active
[ direction + "All" ]( ".ui-menu-item" )
.eq( 0 );
}
}
if ( !next || !next.length || !this.active ) {
next = this.activeMenu.find( this.options.items )[ filter ]();
}
this.focus( event, next );
},
nextPage: function( event ) {
var item, base, height;
if ( !this.active ) {
this.next( event );
return;
}
if ( this.isLastItem() ) {
return;
}
if ( this._hasScroll() ) {
base = this.active.offset().top;
height = this.element.height();
this.active.nextAll( ".ui-menu-item" ).each(function() {
item = $( this );
return item.offset().top - base - height < 0;
});
this.focus( event, item );
} else {
this.focus( event, this.activeMenu.find( this.options.items )
[ !this.active ? "first" : "last" ]() );
}
},
previousPage: function( event ) {
var item, base, height;
if ( !this.active ) {
this.next( event );
return;
}
if ( this.isFirstItem() ) {
return;
}
if ( this._hasScroll() ) {
base = this.active.offset().top;
height = this.element.height();
this.active.prevAll( ".ui-menu-item" ).each(function() {
item = $( this );
return item.offset().top - base + height > 0;
});
this.focus( event, item );
} else {
this.focus( event, this.activeMenu.find( this.options.items ).first() );
}
},
_hasScroll: function() {
return this.element.outerHeight() < this.element.prop( "scrollHeight" );
},
select: function( event ) {
// TODO: It should never be possible to not have an active item at this
// point, but the tests don't trigger mouseenter before click.
this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
var ui = { item: this.active };
if ( !this.active.has( ".ui-menu" ).length ) {
this.collapseAll( event, true );
}
this._trigger( "select", event, ui );
},
_filterMenuItems: function(character) {
var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ),
regex = new RegExp( "^" + escapedCharacter, "i" );
return this.activeMenu
.find( this.options.items )
// Only match on items, not dividers or other content (#10571)
.filter( ".ui-menu-item" )
.filter(function() {
return regex.test( $.trim( $( this ).text() ) );
});
}
});
/*!
* jQuery UI Autocomplete 1.11.2
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/autocomplete/
*/
$.widget( "ui.autocomplete", {
version: "1.11.2",
defaultElement: "<input>",
options: {
appendTo: null,
autoFocus: false,
delay: 300,
minLength: 1,
position: {
my: "left top",
at: "left bottom",
collision: "none"
},
source: null,
// callbacks
change: null,
close: null,
focus: null,
open: null,
response: null,
search: null,
select: null
},
requestIndex: 0,
pending: 0,
_create: function() {
// Some browsers only repeat keydown events, not keypress events,
// so we use the suppressKeyPress flag to determine if we've already
// handled the keydown event. #7269
// Unfortunately the code for & in keypress is the same as the up arrow,
// so we use the suppressKeyPressRepeat flag to avoid handling keypress
// events when we know the keydown event was used to modify the
// search term. #7799
var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
nodeName = this.element[ 0 ].nodeName.toLowerCase(),
isTextarea = nodeName === "textarea",
isInput = nodeName === "input";
this.isMultiLine =
// Textareas are always multi-line
isTextarea ? true :
// Inputs are always single-line, even if inside a contentEditable element
// IE also treats inputs as contentEditable
isInput ? false :
// All other element types are determined by whether or not they're contentEditable
this.element.prop( "isContentEditable" );
this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
this.isNewMenu = true;
this.element
.addClass( "ui-autocomplete-input" )
.attr( "autocomplete", "off" );
this._on( this.element, {
keydown: function( event ) {
if ( this.element.prop( "readOnly" ) ) {
suppressKeyPress = true;
suppressInput = true;
suppressKeyPressRepeat = true;
return;
}
suppressKeyPress = false;
suppressInput = false;
suppressKeyPressRepeat = false;
var keyCode = $.ui.keyCode;
switch ( event.keyCode ) {
case keyCode.PAGE_UP:
suppressKeyPress = true;
this._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
suppressKeyPress = true;
this._move( "nextPage", event );
break;
case keyCode.UP:
suppressKeyPress = true;
this._keyEvent( "previous", event );
break;
case keyCode.DOWN:
suppressKeyPress = true;
this._keyEvent( "next", event );
break;
case keyCode.ENTER:
// when menu is open and has focus
if ( this.menu.active ) {
// #6055 - Opera still allows the keypress to occur
// which causes forms to submit
suppressKeyPress = true;
event.preventDefault();
this.menu.select( event );
}
break;
case keyCode.TAB:
if ( this.menu.active ) {
this.menu.select( event );
}
break;
case keyCode.ESCAPE:
if ( this.menu.element.is( ":visible" ) ) {
if ( !this.isMultiLine ) {
this._value( this.term );
}
this.close( event );
// Different browsers have different default behavior for escape
// Single press can mean undo or clear
// Double press in IE means clear the whole form
event.preventDefault();
}
break;
default:
suppressKeyPressRepeat = true;
// search timeout should be triggered before the input value is changed
this._searchTimeout( event );
break;
}
},
keypress: function( event ) {
if ( suppressKeyPress ) {
suppressKeyPress = false;
if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
event.preventDefault();
}
return;
}
if ( suppressKeyPressRepeat ) {
return;
}
// replicate some key handlers to allow them to repeat in Firefox and Opera
var keyCode = $.ui.keyCode;
switch ( event.keyCode ) {
case keyCode.PAGE_UP:
this._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
this._move( "nextPage", event );
break;
case keyCode.UP:
this._keyEvent( "previous", event );
break;
case keyCode.DOWN:
this._keyEvent( "next", event );
break;
}
},
input: function( event ) {
if ( suppressInput ) {
suppressInput = false;
event.preventDefault();
return;
}
this._searchTimeout( event );
},
focus: function() {
this.selectedItem = null;
this.previous = this._value();
},
blur: function( event ) {
if ( this.cancelBlur ) {
delete this.cancelBlur;
return;
}
clearTimeout( this.searching );
this.close( event );
this._change( event );
}
});
this._initSource();
this.menu = $( "<ul>" )
.addClass( "ui-autocomplete ui-front" )
.appendTo( this._appendTo() )
.menu({
// disable ARIA support, the live region takes care of that
role: null
})
.hide()
.menu( "instance" );
this._on( this.menu.element, {
mousedown: function( event ) {
// prevent moving focus out of the text field
event.preventDefault();
// IE doesn't prevent moving focus even with event.preventDefault()
// so we set a flag to know when we should ignore the blur event
this.cancelBlur = true;
this._delay(function() {
delete this.cancelBlur;
});
// clicking on the scrollbar causes focus to shift to the body
// but we can't detect a mouseup or a click immediately afterward
// so we have to track the next mousedown and close the menu if
// the user clicks somewhere outside of the autocomplete
var menuElement = this.menu.element[ 0 ];
if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
this._delay(function() {
var that = this;
this.document.one( "mousedown", function( event ) {
if ( event.target !== that.element[ 0 ] &&
event.target !== menuElement &&
!$.contains( menuElement, event.target ) ) {
that.close();
}
});
});
}
},
menufocus: function( event, ui ) {
var label, item;
// support: Firefox
// Prevent accidental activation of menu items in Firefox (#7024 #9118)
if ( this.isNewMenu ) {
this.isNewMenu = false;
if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
this.menu.blur();
this.document.one( "mousemove", function() {
$( event.target ).trigger( event.originalEvent );
});
return;
}
}
item = ui.item.data( "ui-autocomplete-item" );
if ( false !== this._trigger( "focus", event, { item: item } ) ) {
// use value to match what will end up in the input, if it was a key event
if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
this._value( item.value );
}
}
// Announce the value in the liveRegion
label = ui.item.attr( "aria-label" ) || item.value;
if ( label && $.trim( label ).length ) {
this.liveRegion.children().hide();
$( "<div>" ).text( label ).appendTo( this.liveRegion );
}
},
menuselect: function( event, ui ) {
var item = ui.item.data( "ui-autocomplete-item" ),
previous = this.previous;
// only trigger when focus was lost (click on menu)
if ( this.element[ 0 ] !== this.document[ 0 ].activeElement ) {
this.element.focus();
this.previous = previous;
// #6109 - IE triggers two focus events and the second
// is asynchronous, so we need to reset the previous
// term synchronously and asynchronously :-(
this._delay(function() {
this.previous = previous;
this.selectedItem = item;
});
}
if ( false !== this._trigger( "select", event, { item: item } ) ) {
this._value( item.value );
}
// reset the term after the select event
// this allows custom select handling to work properly
this.term = this._value();
this.close( event );
this.selectedItem = item;
}
});
this.liveRegion = $( "<span>", {
role: "status",
"aria-live": "assertive",
"aria-relevant": "additions"
})
.addClass( "ui-helper-hidden-accessible" )
.appendTo( this.document[ 0 ].body );
// turning off autocomplete prevents the browser from remembering the
// value when navigating through history, so we re-enable autocomplete
// if the page is unloaded before the widget is destroyed. #7790
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( key, value ) {
this._super( key, value );
if ( key === "source" ) {
this._initSource();
}
if ( key === "appendTo" ) {
this.menu.element.appendTo( this._appendTo() );
}
if ( key === "disabled" && value && this.xhr ) {
this.xhr.abort();
}
},
_appendTo: function() {
var element = this.options.appendTo;
if ( element ) {
element = element.jquery || element.nodeType ?
$( element ) :
this.document.find( element ).eq( 0 );
}
if ( !element || !element[ 0 ] ) {
element = this.element.closest( ".ui-front" );
}
if ( !element.length ) {
element = this.document[ 0 ].body;
}
return element;
},
_initSource: function() {
var array, url,
that = this;
if ( $.isArray( this.options.source ) ) {
array = this.options.source;
this.source = function( request, response ) {
response( $.ui.autocomplete.filter( array, request.term ) );
};
} else if ( typeof this.options.source === "string" ) {
url = this.options.source;
this.source = function( request, response ) {
if ( that.xhr ) {
that.xhr.abort();
}
that.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
success: function( data ) {
response( data );
},
error: function() {
response([]);
}
});
};
} else {
this.source = this.options.source;
}
},
_searchTimeout: function( event ) {
clearTimeout( this.searching );
this.searching = this._delay(function() {
// Search if the value has changed, or if the user retypes the same value (see #7434)
var equalValues = this.term === this._value(),
menuVisible = this.menu.element.is( ":visible" ),
modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;
if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) {
this.selectedItem = null;
this.search( null, event );
}
}, this.options.delay );
},
search: function( value, event ) {
value = value != null ? value : this._value();
// always save the actual value, not the one passed as an argument
this.term = this._value();
if ( value.length < this.options.minLength ) {
return this.close( event );
}
if ( this._trigger( "search", event ) === false ) {
return;
}
return this._search( value );
},
_search: function( value ) {
this.pending++;
this.element.addClass( "ui-autocomplete-loading" );
this.cancelSearch = false;
this.source( { term: value }, this._response() );
},
_response: function() {
var index = ++this.requestIndex;
return $.proxy(function( content ) {
if ( index === this.requestIndex ) {
this.__response( content );
}
this.pending--;
if ( !this.pending ) {
this.element.removeClass( "ui-autocomplete-loading" );
}
}, this );
},
__response: function( content ) {
if ( content ) {
content = this._normalize( content );
}
this._trigger( "response", null, { content: content } );
if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
this._suggest( content );
this._trigger( "open" );
} else {
// use ._close() instead of .close() so we don't cancel future searches
this._close();
}
},
close: function( event ) {
this.cancelSearch = true;
this._close( event );
},
_close: function( event ) {
if ( this.menu.element.is( ":visible" ) ) {
this.menu.element.hide();
this.menu.blur();
this.isNewMenu = true;
this._trigger( "close", event );
}
},
_change: function( event ) {
if ( this.previous !== this._value() ) {
this._trigger( "change", event, { item: this.selectedItem } );
}
},
_normalize: function( items ) {
// assume all items have the right format when the first item is complete
if ( items.length && items[ 0 ].label && items[ 0 ].value ) {
return items;
}
return $.map( items, function( item ) {
if ( typeof item === "string" ) {
return {
label: item,
value: item
};
}
return $.extend( {}, item, {
label: item.label || item.value,
value: item.value || item.label
});
});
},
_suggest: function( items ) {
var ul = this.menu.element.empty();
this._renderMenu( ul, items );
this.isNewMenu = true;
this.menu.refresh();
// size and position menu
ul.show();
this._resizeMenu();
ul.position( $.extend({
of: this.element
}, this.options.position ) );
if ( this.options.autoFocus ) {
this.menu.next();
}
},
_resizeMenu: function() {
var ul = this.menu.element;
ul.outerWidth( Math.max(
// Firefox wraps long text (possibly a rounding bug)
// so we add 1px to avoid the wrapping (#7513)
ul.width( "" ).outerWidth() + 1,
this.element.outerWidth()
) );
},
_renderMenu: function( ul, items ) {
var that = this;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
},
_renderItemData: function( ul, item ) {
return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
},
_renderItem: function( ul, item ) {
return $( "<li>" ).text( item.label ).appendTo( ul );
},
_move: function( direction, event ) {
if ( !this.menu.element.is( ":visible" ) ) {
this.search( null, event );
return;
}
if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
this.menu.isLastItem() && /^next/.test( direction ) ) {
if ( !this.isMultiLine ) {
this._value( this.term );
}
this.menu.blur();
return;
}
this.menu[ direction ]( event );
},
widget: function() {
return this.menu.element;
},
_value: function() {
return this.valueMethod.apply( this.element, arguments );
},
_keyEvent: function( keyEvent, event ) {
if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
this._move( keyEvent, event );
// prevents moving cursor to beginning/end of the text field in some browsers
event.preventDefault();
}
}
});
$.extend( $.ui.autocomplete, {
escapeRegex: function( value ) {
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
},
filter: function( array, term ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" );
return $.grep( array, function( value ) {
return matcher.test( value.label || value.value || value );
});
}
});
// live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget( "ui.autocomplete", $.ui.autocomplete, {
options: {
messages: {
noResults: "No search results.",
results: function( amount ) {
return amount + ( amount > 1 ? " results are" : " result is" ) +
" available, use up and down arrow keys to navigate.";
}
}
},
__response: function( content ) {
var message;
this._superApply( arguments );
if ( this.options.disabled || this.cancelSearch ) {
return;
}
if ( content && content.length ) {
message = this.options.messages.results( content.length );
} else {
message = this.options.messages.noResults;
}
this.liveRegion.children().hide();
$( "<div>" ).text( message ).appendTo( this.liveRegion );
}
});
var autocomplete = $.ui.autocomplete;
})); |
var test = require('tape');
var HttpHash = require('../index.js');
test('httpHash is a function', function (assert) {
assert.equal(typeof HttpHash, 'function');
assert.end();
});
test('http hash inserts root', function (assert) {
// Arrange
function routeHandler() {}
var hash = HttpHash();
// Act
hash.set('/', routeHandler);
// Assert
assert.strictEqual(hash._hash.handler, routeHandler);
assert.end();
});
test('http hash inserts fixed route', function (assert) {
// Arrange
function routeHandler() {}
var hash = HttpHash();
// Act
hash.set('/test', routeHandler);
// Assert
assert.strictEqual(
hash._hash.staticPaths.test.handler,
routeHandler
);
assert.end();
});
test('http hash inserts variable route', function (assert) {
// Arrange
function routeHandler() {}
var hash = HttpHash();
// Act
hash.set('/:test', routeHandler);
// Assert
assert.strictEqual(
hash._hash.variablePaths.handler,
routeHandler
);
assert.end();
});
test('http hash retrieves root', function (assert) {
// Arrange
function routeHandler() {}
var hash = HttpHash();
hash.set('/', routeHandler);
var expectedParams = {};
// Act
var result = hash.get('/');
// Assert
assert.strictEqual(result.handler, routeHandler);
assert.strictEqual(result.src, '/');
assert.strictEqual(result.splat, null);
assert.deepEqual(result.params, expectedParams);
assert.end();
});
test('http hash retrieves fixed route', function (assert) {
// Arrange
function routeHandler() {}
var hash = HttpHash();
hash.set('/test', routeHandler);
var expectedParams = {};
// Act
var result = hash.get('/test');
// Assert
assert.strictEqual(result.handler, routeHandler);
assert.strictEqual(result.src, '/test');
assert.strictEqual(result.splat, null);
assert.deepEqual(result.params, expectedParams);
assert.end();
});
test('http hash retrieves variable route', function (assert) {
// Arrange
function routeHandler() {}
var hash = HttpHash();
hash.set('/:test', routeHandler);
var expectedParams = { test: 'hello' };
// Act
var result = hash.get('/hello');
// Assert
assert.strictEqual(result.handler, routeHandler);
assert.strictEqual(result.src, '/:test');
assert.strictEqual(result.splat, null);
assert.deepEqual(result.params, expectedParams);
assert.end();
});
test('http hash retrieves null root', function (assert) {
// Arrange
var hash = HttpHash();
// Act
var rootResult = hash.get('/');
var staticResult = hash.get('/a');
// Assert
assert.strictEqual(rootResult.handler, null);
assert.strictEqual(staticResult.handler, null);
assert.end();
});
test('http hash retrieves null static', function (assert) {
// Arrange
function routeHandler() {}
var hash = HttpHash();
hash.set('/a/b/c', routeHandler);
// Act
var rootResult = hash.get('/a/b/');
var staticResult = hash.get('/a/b/foo');
// Assert
assert.strictEqual(staticResult.handler, null);
assert.strictEqual(rootResult.handler, null);
assert.end();
});
test('http hash retrieves null variable', function (assert) {
// Arrange
function routeHandler() {}
var hash = HttpHash();
hash.set('/a/:b/c', routeHandler);
// Act
var rootResult = hash.get('/a/b/');
var staticResult = hash.get('/a/b/foo');
// Assert
assert.strictEqual(staticResult.handler, null);
assert.strictEqual(rootResult.handler, null);
assert.end();
});
test('conflicting root exception', function (assert) {
// Arrage
function routeHandler() {}
var hash = HttpHash();
hash.set('/', routeHandler);
// Act
var exception;
try {
hash.set('/', routeHandler);
} catch (e) {
exception = e;
}
// Assert
assert.ok(exception);
assert.strictEqual(exception.message, 'Route conflict');
assert.strictEqual(exception.attemptedPath, '/');
assert.strictEqual(exception.conflictPath, '/');
assert.end();
});
test('conflicting static route exception', function (assert) {
// Arrage
function routeHandler() {}
var hash = HttpHash();
hash.set('/test', routeHandler);
// Act
var exception;
try {
hash.set('/test', routeHandler);
} catch (e) {
exception = e;
}
// Assert
assert.ok(exception);
assert.strictEqual(exception.message, 'Route conflict');
assert.strictEqual(exception.attemptedPath, '/test');
assert.strictEqual(exception.conflictPath, '/test/');
assert.end();
});
test('conflicting variable route exception', function (assert) {
// Arrage
function routeHandler() {}
var hash = HttpHash();
hash.set('/:test', routeHandler);
// Act
var exception;
try {
hash.set('/:test', routeHandler);
} catch (e) {
exception = e;
}
// Assert
assert.ok(exception);
assert.strictEqual(exception.message, 'Route conflict');
assert.strictEqual(exception.message, 'Route conflict');
assert.strictEqual(exception.attemptedPath, '/:test');
assert.strictEqual(exception.conflictPath, '/:test/');
assert.end();
});
test('nesting routes', function (assert) {
// Arrange
var hash = HttpHash();
var firstRoutes = [
'/',
'/test',
'/:test'
];
var secondRoutes = [
'/',
'/var',
'/:var'
];
var conflicts = [];
for (var i = 0; i < firstRoutes.length; i++) {
for (var j = 0; j < secondRoutes.length; j++) {
try {
hash.set(firstRoutes[i] + secondRoutes[j], i + ',' + j);
} catch (e) {
conflicts.push(i + ',' + j);
}
}
}
// Act
var results = {};
for (var k = 0; k < firstRoutes.length; k++) {
for (var l = 0; l < secondRoutes.length; l++) {
results[k + ',' + l] = hash.get(firstRoutes[k] + secondRoutes[l]);
}
}
// Assert
for (var m = 0; m < firstRoutes.length; m++) {
for (var n = 0; n < secondRoutes.length; n++) {
var index = m + ',' + n;
if (conflicts.indexOf(index) >= 0) {
continue;
}
assert.strictEqual(results[index].handler, index);
}
}
// there should be 3 conflicts violation of variable name
assert.strictEqual(conflicts.length, 3);
assert.strictEqual(conflicts[0], '2,0');
assert.strictEqual(conflicts[1], '2,1');
assert.strictEqual(conflicts[2], '2,2');
assert.end();
});
test('deep route with splat test', function (assert) {
// Arrange
var hash = HttpHash();
function routeHandler() {}
hash.set('/a/:varA/b/:varB/c/*', routeHandler);
var expectedParams = {
varA: '123456',
varB: 'testing'
};
var expectedSplat = 'kersplat';
// Act
var result = hash.get('/a/123456///b///testing/c/kersplat');
// Assert
assert.strictEqual(result.src, "/a/:varA/b/:varB/c/*");
assert.strictEqual(result.handler, routeHandler);
assert.strictEqual(result.splat, expectedSplat);
assert.deepEqual(result.params, expectedParams);
assert.end();
});
test('splat in the middle causes splat error', function (assert) {
// Arrange
var hash = HttpHash();
// Act
var exception;
try {
hash.set('/a/*/b');
} catch (e) {
exception = e;
}
// Assert
assert.ok(exception);
assert.strictEqual(
exception.message,
'The splat * must be the last segment of the path'
);
assert.strictEqual(exception.pathname, '/a/*/b');
assert.end();
});
test('static routes work on splat nodes', function (assert) {
// Arrange
var hash = HttpHash();
function splatHandler() {}
function staticHandler() {}
hash.set('*', splatHandler);
hash.set('/static', staticHandler);
// Act
var splatResult = hash.get('/testing');
var staticResult = hash.get('/static');
// Assert
assert.strictEqual(splatResult.src, "*");
assert.strictEqual(splatResult.handler, splatHandler);
assert.strictEqual(splatResult.splat, 'testing');
assert.deepEqual(splatResult.params, {});
assert.strictEqual(staticResult.src, "/static");
assert.strictEqual(staticResult.handler, staticHandler);
assert.strictEqual(staticResult.splat, null);
assert.deepEqual(staticResult.params, {});
assert.end();
});
test('vairable routes do not work on splat nodes', function (assert) {
// Arrange
var hash = HttpHash();
function splatHandler() {}
hash.set('*', splatHandler);
function variableHandler() {}
// Act
var exception;
try {
hash.set('/:var', variableHandler);
} catch (e) {
exception = e;
}
// Assert
assert.ok(exception);
assert.strictEqual(exception.message, 'Route conflict');
assert.strictEqual(exception.attemptedPath, '/:var');
assert.strictEqual(exception.conflictPath, '/*');
assert.end();
});
test('splat routes do not work on variable nodes', function (assert) {
// Arrange
var hash = HttpHash();
function splatHandler() {}
hash.set('/:var', splatHandler);
function variableHandler() {}
// Act
var exception;
try {
hash.set('*', variableHandler);
} catch (e) {
exception = e;
}
// Assert
assert.ok(exception);
assert.strictEqual(exception.message, 'Route conflict');
assert.strictEqual(exception.attemptedPath, '*');
assert.strictEqual(exception.conflictPath, '/:var/');
assert.end();
});
test('does not conflict with prototype', function (assert) {
// Arrange
var hash = HttpHash();
function validHandler() {}
hash.set('/toString/valueOf', validHandler);
// Act
var toStringResult = hash.get('toString');
var valueOfResult = hash.get('valueOf');
var pathResult = hash.get('/toString/valueOf');
// Assert
assert.strictEqual(toStringResult.handler, null);
assert.strictEqual(valueOfResult.handler, null);
assert.strictEqual(pathResult.handler, validHandler);
assert.strictEqual(pathResult.src, '/toString/valueOf');
assert.end();
});
test('does not conflict with __proto__', function (assert) {
// Arrage
var hash = HttpHash();
function validHandler() {}
function validSubHandler() {}
hash.set('/__proto__', validHandler);
hash.set('/__proto__/sub', validSubHandler);
// Act
var validResult = hash.get('/__proto__');
var validSubResult = hash.get('/__proto__/sub');
var invalidResult = hash.get('/__proto__/__proto__');
// Assert
assert.strictEqual(validResult.handler, validHandler);
assert.strictEqual(validResult.src, '/__proto__');
assert.strictEqual(validSubResult.handler, validSubHandler);
assert.strictEqual(validSubResult.src, '/__proto__/sub');
assert.strictEqual(invalidResult.handler, null);
assert.end();
});
|
'use strict';
describe('copy-ast', function() {
var types = require('../lib/types');
var b = types.builders;
var copyAST = require('../lib/copy-ast');
var assert = require('assert');
it('copies things', function() {
var original = b.charSetUnion([b.charSet(['a', 'b']), b.charSet(['c', 'd'])]);
var copy = copyAST(original);
assert.notEqual(copy, original);
assert.deepEqual(copy, original);
});
it('copies using custom builders', function() {
var customBuilder = {
charSetUnion: function (members) {
return {members: members, type: 'CustomUnion'};
},
charSet: function (members) {
return {members: members, type: 'CustomCharSet'};
}
};
var original = b.charSetUnion([b.charSet(['a', 'b']), b.charSet(['c', 'd'])]);
var copy = copyAST(original, customBuilder);
assert.deepEqual(copy, {
members: [
{members: ['a', 'b'], type: 'CustomCharSet'},
{members: ['c', 'd'], type: 'CustomCharSet'}
],
type: 'CustomUnion'
});
});
it('throws errors if for some nonexistent type', function() {
assert.throws(
function() {
copyAST({type: 'NonExistentType'});
},
/registered builder/
);
});
it('throws if custom builder does not have the correct build Fn', function() {
assert.throws(
function() {
copyAST(b.charSet(['a','b']), {});
},
/custom builder/
);
});
it('throws if it gets an object without at "type" property', function() {
assert.throws(
function() {
copyAST({})
},
/not an AST node/
);
});
it('will not pass "undefined"', function() {
var log = [];
var customBuilder = {
charSet: function() {
log.push(Array.prototype.slice.call(arguments));
}
};
copyAST({type: 'CharSet', members:['a']}, customBuilder);
copyAST({type: 'CharSet', members:['a'], invert:false}, customBuilder);
assert.deepEqual(log, [
[['a']],
[['a'], false]
]);
});
});
|
beforeEach(function() {
this.addMatchers({
toBeAnInstanceOf: function(expectedClass) {
var instance = this.actual;
return instance instanceof expectedClass;
}
});
});
var fixtureBlock = function(){
return document.getElementById("jasmine_content");
};
var fixtureClear = function(){
var e = document.getElementById("jasmine_content");
if(e){
var childCount = e.childNodes.length;
for (var i = childCount -1; i >= 0; i--){
e.removeChild(e.childNodes[i]);
}
}
};
var buildTwilio = function(){
Twilio = {
// Throws an error unless overridden
require: function(lib){ undefined.apply(); }
};
};
var buildTwilioConnection = function(){
Twilio.ConnectionCallbacks = {};
Twilio.Connection = function(){};
Twilio.Connection.prototype = {
accept: function(fun){ Twilio.ConnectionCallbacks.accept = fun; },
cancel: function(fun){ Twilio.ConnectionCallbacks.cancel = fun; },
disconnect: function(fun){ Twilio.ConnectionCallbacks.disconnect = fun; },
error: function(fun){ Twilio.ConnectionCallbacks.error = fun; },
mute: function(){},
unmute: function(){},
sendDigits: function(){},
status: function(){return "pending";},
properties: {received: "params"}
};
};
var buildTwilioDevice = function(){
Twilio.DeviceCallbacks = {};
Twilio.Device = {
setup: function(token,params){ return Twilio.Device; },
ready: function(fun){ Twilio.DeviceCallbacks.ready = fun; },
offline: function(fun){ Twilio.DeviceCallbacks.offline = fun; },
incoming: function(fun){ Twilio.DeviceCallbacks.incoming = fun; },
cancel: function(fun){ Twilio.DeviceCallbacks.cancel = fun; },
connect: function(fun_or_params){ Twilio.DeviceCallbacks.connect = fun_or_params; return new Twilio.Connection(); },
disconnect: function(fun){ Twilio.DeviceCallbacks.disconnect = fun; },
presence: function(fun){ Twilio.DeviceCallbacks.presence = fun; },
error: function(fun){ Twilio.DeviceCallbacks.error = fun; },
instance: {
handlers: {
"error": [function(){}]
},
removeListener: function(name,handler){}
},
showPermissionsDialog: function(){
var e = document.createElement("div");
var attr = document.createAttribute("style");
attr.value = "position: fixed; z-index: 99999; top: 0px; left: 0px; width: 100%; height: auto; overflow: hidden; visibility: visible;";
e.setAttributeNode(attr);
e.innerHTML = '<div><object type="application/x-shockwave-flash" id="__connectionFlash__" style="visibility: visible;"></object><button>Close</button></div>';
fixtureBlock().appendChild(e);
}
};
};
var resetMocks = function(){
buildTwilio();
buildTwilioConnection();
buildTwilioDevice();
};
var resetClasses = function(){
com.jivatechnology.TwitTwilio.Device.resetInstance("TESTING");
com.jivatechnology.TwitTwilio.Connection.reset("TESTING");
};
|
'use strict';
var mockActionProvider = function(actionMap, doneAction) {
var self = {};
actionMap = actionMap || {};
doneAction = doneAction || function(){};
self.actionMap = function(_) {
if (!arguments.length) return actionMap;
actionMap = _;
return self;
};
self.watcher = function() {
var watcher = {};
watcher.hasActions = function(item) {
return !!actionMap[item];
};
watcher.update = function(item) {
return Promise.resolve(actionMap[item](item));
};
watcher.done = function() {
return Promise.resolve(doneAction());
};
return Promise.resolve(watcher);
};
return self;
};
module.exports = mockActionProvider;
|
app.controller('opnodesContent', ['$rootScope', '$scope', '$http', '$interval',
function($rootScope, $scope, $http, $interval) {
var getColumnDefs = function(rows) {
// columnDefs.push({ name: 'id', field: 'id', cellTemplate: '<div><input type="checkbox"></input></div>' });
};
$scope.onRefresh = function() {
$scope.isInProgress = true;
$http( { method: "GET",
url: '/backend/genericView.php',
params: {verb: "get", session: $rootScope.sessionToken, view: 'xen_host_get_all' } })
.then(function responseSuccess(response) {
if (response.data.exitCode === 0) {
$scope.viewRows = response.data.rows;
} else {
$scope.err = response.data.message;
}
$scope.isInProgress = false;
}, function loginError(response) {
$scope.isInProgress = false;
$scope.err = 'connection error';
});
};
$scope.onRefresh();
}]);
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var _1 = require("../");
var key_1 = require("./key");
/*
* GET key
* Get the value of a key
*/
function get(key, callback) {
if (!_1.isMasterNode()) {
_1.store.dispatch("get", callback, key);
}
else {
return _1.store[key];
}
}
exports.get = get;
/*
* SET key value [EX seconds] [PX milliseconds] [NX|XX]
* Set the string value of a key
*/
function set(key, value, callback) {
if (!_1.isMasterNode()) {
_1.store.dispatch("set", callback, key, value);
}
else {
_1.store[key] = value;
return "OK";
}
}
exports.set = set;
/*
* APPEND key value
* Append a value to a key
*/
function append() {
}
exports.append = append;
/*
* BITCOUNT key [start end]
* Count set bits in a string
*/
function bitcount() {
}
exports.bitcount = bitcount;
/*
* BITFIELD key [GET type offset] [SET type offset value] [INCRBY type offset increment] [OVERFLOW WRAP|SAT|FAIL]
* Perform arbitrary bitfield integer operations on strings
*/
function bitfield() {
}
exports.bitfield = bitfield;
/*
* BITOP operation destkey key [key ...]
* Perform bitwise operations between strings
*/
function bitop() {
}
exports.bitop = bitop;
/*
* BITPOS key bit [start] [end]
* Find first bit set or clear in a string
*/
function bitpos() {
}
exports.bitpos = bitpos;
/*
* DECR key
* Decrement the integer value of a key by one
*/
function decr(key, callback) {
if (!_1.isMasterNode()) {
_1.store.dispatch("decr", callback, key);
}
else {
if (!_1.store[key]) {
_1.store[key] = 0;
}
return (--_1.store[key]);
}
}
exports.decr = decr;
/*
* DECRBY key decrement
* Decrement the integer value of a key by the given number
*/
function decrby(key, value, callback) {
if (!_1.isMasterNode()) {
_1.store.dispatch("decrby", callback, key, value);
}
else {
if (!_1.store[key]) {
_1.store[key] = 0;
}
_1.store[key] -= value;
return _1.store[key];
}
}
exports.decrby = decrby;
/*
* GETBIT key offset
* Returns the bit value at offset in the string value stored at key
*/
function getbit() {
}
exports.getbit = getbit;
/*
* GETRANGE key start end
* Get a substring of the string stored at a key
*/
function getrange() {
}
exports.getrange = getrange;
/*
* GETSET key value
* Set the string value of a key and return its old value
*/
function getset() {
}
exports.getset = getset;
/*
* INCR key
* Increment the integer value of a key by one
*/
function incr(key, callback) {
if (!_1.isMasterNode()) {
_1.store.dispatch("incr", callback, key);
}
else {
if (!_1.store[key]) {
_1.store[key] = 0;
}
return ++_1.store[key];
}
}
exports.incr = incr;
/*
* INCRBY key increment
* Increment the integer value of a key by the given amount
*/
function incrby(key, value, callback) {
if (!_1.isMasterNode()) {
_1.store.dispatch("incrby", callback, key, value);
}
else {
if (!_1.store[key]) {
_1.store[key] = 0;
}
_1.store[key] += value;
return _1.store[key];
}
}
exports.incrby = incrby;
/*
* INCRBYFLOAT key increment
* Increment the float value of a key by the given amount
*/
function incrbyfloat() {
}
exports.incrbyfloat = incrbyfloat;
/*
* MGET key [key ...]
* Get the values of all the given keys
*/
function mget(keys, callback) {
if (!_1.isMasterNode()) {
_1.store.dispatch("mget", callback, keys);
}
else {
return keys.map(function (k) { return get(k, undefined); });
}
}
exports.mget = mget;
/*
* MSET key value [key value ...]
* Set multiple keys to multiple values
*/
function mset() {
}
exports.mset = mset;
/*
* MSETNX key value [key value ...]
* Set multiple keys to multiple values, only if none of the keys exist
*/
function msetnx() {
}
exports.msetnx = msetnx;
/*
* PSETEX key milliseconds value
* Set the value and expiration in milliseconds of a key
*/
function psetex() {
}
exports.psetex = psetex;
/*
* SETBIT key offset value
* Sets or clears the bit at offset in the string value stored at key
*/
function setbit() {
}
exports.setbit = setbit;
/*
* SETEX key seconds value
* Set the value and expiration of a key
*/
function setex(key, seconds, value, callback) {
if (!_1.isMasterNode()) {
_1.store.dispatch("setex", callback, key, seconds, value);
}
else {
set(key, value, undefined);
// enqueue to delete after timeout in seconds.
setTimeout(key_1.del, seconds * 1000, key);
return "OK";
}
}
exports.setex = setex;
/*
* SETNX key value
* Set the value of a key, only if the key does not exist
*/
function setnx() {
}
exports.setnx = setnx;
/*
* SETRANGE key offset value
* Overwrite part of a string at key starting at the specified offset
*/
function setrange() {
}
exports.setrange = setrange;
/*
* STRLEN key
* Get the length of the value stored in a key
*/
function strlen(key, callback) {
if (!_1.isMasterNode()) {
_1.store.dispatch("strlen", callback, key);
}
else {
return (_1.store[key] || "").length;
}
}
exports.strlen = strlen;
|
var vertShader =
"varying vec4 frontColor;" +
"attribute vec3 ps_Vertex;" +
"attribute vec3 ps_Normal;" +
"attribute vec4 ps_Color;" +
"uniform float ps_PointSize;" +
"uniform vec3 ps_Attenuation;" +
"uniform vec3 lightPos;" +
"uniform bool reflection;"+
"uniform mat4 ps_ModelViewMatrix;" +
"uniform mat4 ps_ProjectionMatrix;" +
"uniform mat4 ps_NormalMatrix;" +
"void PointLight(inout vec3 col, in vec3 ecPos, in vec3 vertNormal) {" +
" vec3 VP = lightPos - ecPos;" +
" VP = normalize( VP );" +
" float nDotVP = max( 0.0, dot( vertNormal, VP ));" +
" col += vec3(1.0, 1.0, 1.0) * nDotVP;" +
"}" +
"void main(void) {" +
" vec3 transNorm = vec3(ps_NormalMatrix * vec4(ps_Normal, 0.0));" +
" vec4 ecPos4 = ps_ModelViewMatrix * vec4(ps_Vertex, 1.0);" +
" vec3 ecPos = (vec3(ecPos4))/ecPos4.w;" +
" vec3 col = vec3(0.0, 0.0, 0.0);" +
" PointLight(col, ecPos, transNorm);" +
" frontColor = ps_Color * vec4(col, 1.0);" +
" if(reflection){" +
" float l = length(ps_Vertex - vec3(0.0, -20.0, 0.0))/20.0;" +
// magic number that super saturates to white
" float col = l * 5.0;" +
" frontColor += vec4(col, col, col, 1.0);" +
" }" +
" float dist = length( ecPos4 );" +
" float attn = ps_Attenuation[0] + " +
" (ps_Attenuation[1] * dist) + " +
" (ps_Attenuation[2] * dist * dist);" +
" gl_PointSize = ps_PointSize * sqrt(1.0/attn);" +
" gl_Position = ps_ProjectionMatrix * ecPos4;" +
"}";
var fragShader =
"#ifdef GL_ES\n" +
" precision highp float;\n" +
"#endif\n" +
"uniform vec4 uReflection;" +
"varying vec4 frontColor;" +
"void main(void){" +
" gl_FragColor = frontColor * uReflection;" +
"}";
|
/**
* @overview datejs
* @version 1.0.0-beta-2014-03-25
* @author Gregory Wild-Smith <gregory@wild-smith.com>
* @copyright 2014 Gregory Wild-Smith
* @license MIT
* @homepage https://github.com/abritinthebay/datejs
*/
/*
2014 Gregory Wild-Smith
@license MIT
@homepage https://github.com/abritinthebay/datejs
2014 Gregory Wild-Smith
@license MIT
@homepage https://github.com/abritinthebay/datejs
*/
Date.CultureStrings=Date.CultureStrings||{};
Date.CultureStrings["uk-UA"]={name:"uk-UA",englishName:"Ukrainian (Ukraine)",nativeName:"\u0443\u043a\u0440\u0430\u0457\u043d\u044c\u0441\u043a\u0430 (\u0423\u043a\u0440\u0430\u0457\u043d\u0430)",Sunday:"\u043d\u0435\u0434\u0456\u043b\u044f",Monday:"\u043f\u043e\u043d\u0435\u0434\u0456\u043b\u043e\u043a",Tuesday:"\u0432\u0456\u0432\u0442\u043e\u0440\u043e\u043a",Wednesday:"\u0441\u0435\u0440\u0435\u0434\u0430",Thursday:"\u0447\u0435\u0442\u0432\u0435\u0440",Friday:"\u043f'\u044f\u0442\u043d\u0438\u0446\u044f",
Saturday:"\u0441\u0443\u0431\u043e\u0442\u0430",Sun:"\u041d\u0434",Mon:"\u041f\u043d",Tue:"\u0412\u0442",Wed:"\u0421\u0440",Thu:"\u0427\u0442",Fri:"\u041f\u0442",Sat:"\u0421\u0431",Su:"\u041d\u0434",Mo:"\u041f\u043d",Tu:"\u0412\u0442",We:"\u0421\u0440",Th:"\u0427\u0442",Fr:"\u041f\u0442",Sa:"\u0421\u0431",S_Sun_Initial:"\u041d",M_Mon_Initial:"\u041f",T_Tue_Initial:"\u0412",W_Wed_Initial:"\u0421",T_Thu_Initial:"\u0427",F_Fri_Initial:"\u041f",S_Sat_Initial:"\u0421",January:"\u0421\u0456\u0447\u0435\u043d\u044c",
February:"\u041b\u044e\u0442\u0438\u0439",March:"\u0411\u0435\u0440\u0435\u0437\u0435\u043d\u044c",April:"\u041a\u0432\u0456\u0442\u0435\u043d\u044c",May:"\u0422\u0440\u0430\u0432\u0435\u043d\u044c",June:"\u0427\u0435\u0440\u0432\u0435\u043d\u044c",July:"\u041b\u0438\u043f\u0435\u043d\u044c",August:"\u0421\u0435\u0440\u043f\u0435\u043d\u044c",September:"\u0412\u0435\u0440\u0435\u0441\u0435\u043d\u044c",October:"\u0416\u043e\u0432\u0442\u0435\u043d\u044c",November:"\u041b\u0438\u0441\u0442\u043e\u043f\u0430\u0434",
December:"\u0413\u0440\u0443\u0434\u0435\u043d\u044c",Jan_Abbr:"\u0421\u0456\u0447",Feb_Abbr:"\u041b\u044e\u0442",Mar_Abbr:"\u0411\u0435\u0440",Apr_Abbr:"\u041a\u0432\u0456",May_Abbr:"\u0422\u0440\u0430",Jun_Abbr:"\u0427\u0435\u0440",Jul_Abbr:"\u041b\u0438\u043f",Aug_Abbr:"\u0421\u0435\u0440",Sep_Abbr:"\u0412\u0435\u0440",Oct_Abbr:"\u0416\u043e\u0432",Nov_Abbr:"\u041b\u0438\u0441",Dec_Abbr:"\u0413\u0440\u0443",AM:"",PM:"",firstDayOfWeek:1,twoDigitYearMax:2029,mdy:"dmy","M/d/yyyy":"dd.MM.yyyy","dddd, MMMM dd, yyyy":"d MMMM yyyy' \u0440.'",
"h:mm tt":"H:mm","h:mm:ss tt":"H:mm:ss","dddd, MMMM dd, yyyy h:mm:ss tt":"d MMMM yyyy' \u0440.' H:mm:ss","yyyy-MM-ddTHH:mm:ss":"yyyy-MM-ddTHH:mm:ss","yyyy-MM-dd HH:mm:ssZ":"yyyy-MM-dd HH:mm:ssZ","ddd, dd MMM yyyy HH:mm:ss":"ddd, dd MMM yyyy HH:mm:ss","MMMM dd":"d MMMM","MMMM, yyyy":"MMMM yyyy' \u0440.'","/jan(uary)?/":"\u0441\u0456\u0447(\u0435\u043d\u044c)?","/feb(ruary)?/":"\u043b\u044e\u0442(\u0438\u0439)?","/mar(ch)?/":"\u0431\u0435\u0440(\u0435\u0437\u0435\u043d\u044c)?","/apr(il)?/":"\u043a\u0432\u0456(\u0442\u0435\u043d\u044c)?",
"/may/":"\u0442\u0440\u0430(\u0432\u0435\u043d\u044c)?","/jun(e)?/":"\u0447\u0435\u0440(\u0432\u0435\u043d\u044c)?","/jul(y)?/":"\u043b\u0438\u043f(\u0435\u043d\u044c)?","/aug(ust)?/":"\u0441\u0435\u0440(\u043f\u0435\u043d\u044c)?","/sep(t(ember)?)?/":"\u0432\u0435\u0440(\u0435\u0441\u0435\u043d\u044c)?","/oct(ober)?/":"\u0436\u043e\u0432(\u0442\u0435\u043d\u044c)?","/nov(ember)?/":"\u043b\u0438\u0441(\u0442\u043e\u043f\u0430\u0434)?","/dec(ember)?/":"\u0433\u0440\u0443(\u0434\u0435\u043d\u044c)?",
"/^su(n(day)?)?/":"^\u043d\u0435\u0434\u0456\u043b\u044f","/^mo(n(day)?)?/":"^\u043f\u043e\u043d\u0435\u0434\u0456\u043b\u043e\u043a","/^tu(e(s(day)?)?)?/":"^\u0432\u0456\u0432\u0442\u043e\u0440\u043e\u043a","/^we(d(nesday)?)?/":"^\u0441\u0435\u0440\u0435\u0434\u0430","/^th(u(r(s(day)?)?)?)?/":"^\u0447\u0435\u0442\u0432\u0435\u0440","/^fr(i(day)?)?/":"^\u043f'\u044f\u0442\u043d\u0438\u0446\u044f","/^sa(t(urday)?)?/":"^\u0441\u0443\u0431\u043e\u0442\u0430","/^next/":"^next","/^last|past|prev(ious)?/":"^last|past|prev(ious)?",
"/^(\\+|aft(er)?|from|hence)/":"^(\\+|aft(er)?|from|hence)","/^(\\-|bef(ore)?|ago)/":"^(\\-|bef(ore)?|ago)","/^yes(terday)?/":"^yes(terday)?","/^t(od(ay)?)?/":"^t(od(ay)?)?","/^tom(orrow)?/":"^tom(orrow)?","/^n(ow)?/":"^n(ow)?","/^ms|milli(second)?s?/":"^ms|milli(second)?s?","/^sec(ond)?s?/":"^sec(ond)?s?","/^mn|min(ute)?s?/":"^mn|min(ute)?s?","/^h(our)?s?/":"^h(our)?s?","/^w(eek)?s?/":"^w(eek)?s?","/^m(onth)?s?/":"^m(onth)?s?","/^d(ay)?s?/":"^d(ay)?s?","/^y(ear)?s?/":"^y(ear)?s?","/^(a|p)/":"^(a|p)",
"/^(a\\.?m?\\.?|p\\.?m?\\.?)/":"^(a\\.?m?\\.?|p\\.?m?\\.?)","/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/":"^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)","/^\\s*(st|nd|rd|th)/":"^\\s*(st|nd|rd|th)","/^\\s*(\\:|a(?!u|p)|p)/":"^\\s*(\\:|a(?!u|p)|p)",LINT:"LINT",TOT:"TOT",CHAST:"CHAST",NZST:"NZST",NFT:"NFT",SBT:"SBT",AEST:"AEST",ACST:"ACST",JST:"JST",CWST:"CWST",CT:"CT",ICT:"ICT",MMT:"MMT",BIOT:"BST",NPT:"NPT",IST:"IST",
PKT:"PKT",AFT:"AFT",MSK:"MSK",IRST:"IRST",FET:"FET",EET:"EET",CET:"CET",UTC:"UTC",GMT:"GMT",CVT:"CVT",GST:"GST",BRT:"BRT",NST:"NST",AST:"AST",EST:"EST",CST:"CST",MST:"MST",PST:"PST",AKST:"AKST",MIT:"MIT",HST:"HST",SST:"SST",BIT:"BIT",CHADT:"CHADT",NZDT:"NZDT",AEDT:"AEDT",ACDT:"ACDT",AZST:"AZST",IRDT:"IRDT",EEST:"EEST",CEST:"CEST",BST:"BST",PMDT:"PMDT",ADT:"ADT",NDT:"NDT",EDT:"EDT",CDT:"CDT",MDT:"MDT",PDT:"PDT",AKDT:"AKDT",HADT:"HADT"};Date.CultureStrings.lang="uk-UA";
(function(){var f=Date,g=Date.CultureStrings?Date.CultureStrings.lang:null,c={},a=function(a,e){var b,h,f,m=e?e:g;if(Date.CultureStrings&&Date.CultureStrings[m]&&Date.CultureStrings[m][a])b=Date.CultureStrings[m][a];else switch(a){case "name":b="en-US";break;case "englishName":b="English (United States)";break;case "nativeName":b="English (United States)";break;case "twoDigitYearMax":b=2049;break;case "firstDayOfWeek":b=0;break;default:if(b=a,h=a.split("_"),f=h.length,1<f&&"/"!==a.charAt(0)&&(f=h[f-
1].toLowerCase(),"initial"===f||"abbr"===f))b=h[0]}"/"===a.charAt(0)&&(b=Date.CultureStrings&&Date.CultureStrings[m]&&Date.CultureStrings[m][a]?RegExp(Date.CultureStrings[m][a],"i"):RegExp(a.replace(RegExp("/","g"),""),"i"));c[a]=a;return b},b=function(a){a=Date.Config.i18n+a+".js";var e=document.getElementsByTagName("head")[0]||document.documentElement,b=document.createElement("script");b.src=a;var h={done:function(){}};b.onload=b.onreadystatechange=function(){this.readyState&&"loaded"!==this.readyState&&
"complete"!==this.readyState||(done=!0,h.done(),e.removeChild(b))};setTimeout(function(){e.insertBefore(b,e.firstChild)},0);return{done:function(a){h.done=function(){a&&a()}}}},e=function(){var e={name:a("name"),englishName:a("englishName"),nativeName:a("nativeName"),dayNames:[a("Sunday"),a("Monday"),a("Tuesday"),a("Wednesday"),a("Thursday"),a("Friday"),a("Saturday")],abbreviatedDayNames:[a("Sun"),a("Mon"),a("Tue"),a("Wed"),a("Thu"),a("Fri"),a("Sat")],shortestDayNames:[a("Su"),a("Mo"),a("Tu"),a("We"),
a("Th"),a("Fr"),a("Sa")],firstLetterDayNames:[a("S_Sun_Initial"),a("M_Mon_Initial"),a("T_Tues_Initial"),a("W_Wed_Initial"),a("T_Thu_Initial"),a("F_Fri_Initial"),a("S_Sat_Initial")],monthNames:[a("January"),a("February"),a("March"),a("April"),a("May"),a("June"),a("July"),a("August"),a("September"),a("October"),a("November"),a("December")],abbreviatedMonthNames:[a("Jan_Abbr"),a("Feb_Abbr"),a("Mar_Abbr"),a("Apr_Abbr"),a("May_Abbr"),a("Jun_Abbr"),a("Jul_Abbr"),a("Aug_Abbr"),a("Sep_Abbr"),a("Oct_Abbr"),
a("Nov_Abbr"),a("Dec_Abbr")],amDesignator:a("AM"),pmDesignator:a("PM"),firstDayOfWeek:a("firstDayOfWeek"),twoDigitYearMax:a("twoDigitYearMax"),dateElementOrder:a("mdy"),formatPatterns:{shortDate:a("M/d/yyyy"),longDate:a("dddd, MMMM dd, yyyy"),shortTime:a("h:mm tt"),longTime:a("h:mm:ss tt"),fullDateTime:a("dddd, MMMM dd, yyyy h:mm:ss tt"),sortableDateTime:a("yyyy-MM-ddTHH:mm:ss"),universalSortableDateTime:a("yyyy-MM-dd HH:mm:ssZ"),rfc1123:a("ddd, dd MMM yyyy HH:mm:ss"),monthDay:a("MMMM dd"),yearMonth:a("MMMM, yyyy")},
regexPatterns:{inTheMorning:a("/( in the )(morn(ing)?)\\b/"),thisMorning:a("/(this )(morn(ing)?)\\b/"),amThisMorning:a("/(\b\\d(am)? )(this )(morn(ing)?)/"),inTheEvening:a("/( in the )(even(ing)?)\\b/"),thisEvening:a("/(this )(even(ing)?)\\b/"),pmThisEvening:a("/(\b\\d(pm)? )(this )(even(ing)?)/"),jan:a("/jan(uary)?/"),feb:a("/feb(ruary)?/"),mar:a("/mar(ch)?/"),apr:a("/apr(il)?/"),may:a("/may/"),jun:a("/jun(e)?/"),jul:a("/jul(y)?/"),aug:a("/aug(ust)?/"),sep:a("/sep(t(ember)?)?/"),oct:a("/oct(ober)?/"),
nov:a("/nov(ember)?/"),dec:a("/dec(ember)?/"),sun:a("/^su(n(day)?)?/"),mon:a("/^mo(n(day)?)?/"),tue:a("/^tu(e(s(day)?)?)?/"),wed:a("/^we(d(nesday)?)?/"),thu:a("/^th(u(r(s(day)?)?)?)?/"),fri:a("/fr(i(day)?)?/"),sat:a("/^sa(t(urday)?)?/"),future:a("/^next/"),past:a("/last|past|prev(ious)?/"),add:a("/^(\\+|aft(er)?|from|hence)/"),subtract:a("/^(\\-|bef(ore)?|ago)/"),yesterday:a("/^yes(terday)?/"),today:a("/^t(od(ay)?)?/"),tomorrow:a("/^tom(orrow)?/"),now:a("/^n(ow)?/"),millisecond:a("/^ms|milli(second)?s?/"),
second:a("/^sec(ond)?s?/"),minute:a("/^mn|min(ute)?s?/"),hour:a("/^h(our)?s?/"),week:a("/^w(eek)?s?/"),month:a("/^m(onth)?s?/"),day:a("/^d(ay)?s?/"),year:a("/^y(ear)?s?/"),shortMeridian:a("/^(a|p)/"),longMeridian:a("/^(a\\.?m?\\.?|p\\.?m?\\.?)/"),timezone:a("/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/"),ordinalSuffix:a("/^\\s*(st|nd|rd|th)/"),timeContext:a("/^\\s*(\\:|a(?!u|p)|p)/")},timezones:[],abbreviatedTimeZoneDST:{},abbreviatedTimeZoneStandard:{}};e.abbreviatedTimeZoneDST[a("CHADT")]=
"+1345";e.abbreviatedTimeZoneDST[a("NZDT")]="+1300";e.abbreviatedTimeZoneDST[a("AEDT")]="+1100";e.abbreviatedTimeZoneDST[a("ACDT")]="+1030";e.abbreviatedTimeZoneDST[a("AZST")]="+0500";e.abbreviatedTimeZoneDST[a("IRDT")]="+0430";e.abbreviatedTimeZoneDST[a("EEST")]="+0300";e.abbreviatedTimeZoneDST[a("CEST")]="+0200";e.abbreviatedTimeZoneDST[a("BST")]="+0100";e.abbreviatedTimeZoneDST[a("PMDT")]="-0200";e.abbreviatedTimeZoneDST[a("ADT")]="-0300";e.abbreviatedTimeZoneDST[a("NDT")]="-0230";e.abbreviatedTimeZoneDST[a("EDT")]=
"-0400";e.abbreviatedTimeZoneDST[a("CDT")]="-0500";e.abbreviatedTimeZoneDST[a("MDT")]="-0600";e.abbreviatedTimeZoneDST[a("PDT")]="-0700";e.abbreviatedTimeZoneDST[a("AKDT")]="-0800";e.abbreviatedTimeZoneDST[a("HADT")]="-0900";e.abbreviatedTimeZoneStandard[a("LINT")]="+1400";e.abbreviatedTimeZoneStandard[a("TOT")]="+1300";e.abbreviatedTimeZoneStandard[a("CHAST")]="+1245";e.abbreviatedTimeZoneStandard[a("NZST")]="+1200";e.abbreviatedTimeZoneStandard[a("NFT")]="+1130";e.abbreviatedTimeZoneStandard[a("SBT")]=
"+1100";e.abbreviatedTimeZoneStandard[a("AEST")]="+1000";e.abbreviatedTimeZoneStandard[a("ACST")]="+0930";e.abbreviatedTimeZoneStandard[a("JST")]="+0900";e.abbreviatedTimeZoneStandard[a("CWST")]="+0845";e.abbreviatedTimeZoneStandard[a("CT")]="+0800";e.abbreviatedTimeZoneStandard[a("ICT")]="+0700";e.abbreviatedTimeZoneStandard[a("MMT")]="+0630";e.abbreviatedTimeZoneStandard[a("BST")]="+0600";e.abbreviatedTimeZoneStandard[a("NPT")]="+0545";e.abbreviatedTimeZoneStandard[a("IST")]="+0530";e.abbreviatedTimeZoneStandard[a("PKT")]=
"+0500";e.abbreviatedTimeZoneStandard[a("AFT")]="+0430";e.abbreviatedTimeZoneStandard[a("MSK")]="+0400";e.abbreviatedTimeZoneStandard[a("IRST")]="+0330";e.abbreviatedTimeZoneStandard[a("FET")]="+0300";e.abbreviatedTimeZoneStandard[a("EET")]="+0200";e.abbreviatedTimeZoneStandard[a("CET")]="+0100";e.abbreviatedTimeZoneStandard[a("GMT")]="+0000";e.abbreviatedTimeZoneStandard[a("UTC")]="+0000";e.abbreviatedTimeZoneStandard[a("CVT")]="-0100";e.abbreviatedTimeZoneStandard[a("GST")]="-0200";e.abbreviatedTimeZoneStandard[a("BRT")]=
"-0300";e.abbreviatedTimeZoneStandard[a("NST")]="-0330";e.abbreviatedTimeZoneStandard[a("AST")]="-0400";e.abbreviatedTimeZoneStandard[a("EST")]="-0500";e.abbreviatedTimeZoneStandard[a("CST")]="-0600";e.abbreviatedTimeZoneStandard[a("MST")]="-0700";e.abbreviatedTimeZoneStandard[a("PST")]="-0800";e.abbreviatedTimeZoneStandard[a("AKST")]="-0900";e.abbreviatedTimeZoneStandard[a("MIT")]="-0930";e.abbreviatedTimeZoneStandard[a("HST")]="-1000";e.abbreviatedTimeZoneStandard[a("SST")]="-1100";e.abbreviatedTimeZoneStandard[a("BIT")]=
"-1200";for(var d in e.abbreviatedTimeZoneStandard)e.abbreviatedTimeZoneStandard.hasOwnProperty(d)&&e.timezones.push({name:d,offset:e.abbreviatedTimeZoneStandard[d]});for(d in e.abbreviatedTimeZoneDST)e.abbreviatedTimeZoneDST.hasOwnProperty(d)&&e.timezones.push({name:d,offset:e.abbreviatedTimeZoneDST[d],dst:!0});return e};f.i18n={__:function(e,d){return a(e,d)},currentLanguage:function(){return g||"en-US"},setLanguage:function(a,d){if(d||"en-US"===a||Date.CultureStrings&&Date.CultureStrings[a])g=
a,Date.CultureStrings.lang=a,Date.CultureInfo=e();else if(!Date.CultureStrings||!Date.CultureStrings[a])if("undefined"!==typeof exports&&this.exports!==exports)try{require("../i18n/"+a+".js"),g=a,Date.CultureStrings.lang=a,Date.CultureInfo=e()}catch(c){throw Error("The DateJS IETF language tag '"+a+"' could not be loaded by Node. It likely does not exist.");}else Date.Config&&Date.Config.i18n?b(a).done(function(){g=a;Date.CultureStrings.lang=a;Date.CultureInfo=e()}):Date.console.error("The DateJS IETF language tag '"+
a+"' is not available and has not been loaded.")},getLoggedKeys:function(){return c},updateCultureInfo:function(){Date.CultureInfo=e()}};f.i18n.updateCultureInfo()})();
(function(){var f=Date,g=f.prototype,c=function(a,b){b||(b=2);return("000"+a).slice(-1*b)};f.console="undefined"!==typeof window&&"undefined"!==typeof window.console&&"undefined"!==typeof window.console.log?console:{log:function(){},error:function(){}};f.Config={};f.initOverloads=function(){f.now?f._now||(f._now=f.now):f._now=function(){return(new Date).getTime()};f.now=function(a){return a?f.present():f._now()};g.toISOString||(g.toISOString=function(){return this.getUTCFullYear()+"-"+c(this.getUTCMonth()+
1)+"-"+c(this.getUTCDate())+"T"+c(this.getUTCHours())+":"+c(this.getUTCMinutes())+":"+c(this.getUTCSeconds())+"."+String((this.getUTCMilliseconds()/1E3).toFixed(3)).slice(2,5)+"Z"});void 0===g._toString&&(g._toString=g.toString)};f.initOverloads();g.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this};g.setTimeToNow=function(){var a=new Date;this.setHours(a.getHours());this.setMinutes(a.getMinutes());this.setSeconds(a.getSeconds());this.setMilliseconds(a.getMilliseconds());
return this};f.today=function(){return(new Date).clearTime()};f.present=function(){return new Date};f.compare=function(a,b){if(isNaN(a)||isNaN(b))throw Error(a+" - "+b);if(a instanceof Date&&b instanceof Date)return a<b?-1:a>b?1:0;throw new TypeError(a+" - "+b);};f.equals=function(a,b){return 0===a.compareTo(b)};f.getDayName=function(a){return Date.CultureInfo.dayNames[a]};f.getDayNumberFromName=function(a){var b=Date.CultureInfo.dayNames,d=Date.CultureInfo.abbreviatedDayNames,c=Date.CultureInfo.shortestDayNames;
a=a.toLowerCase();for(var h=0;h<b.length;h++)if(b[h].toLowerCase()===a||d[h].toLowerCase()===a||c[h].toLowerCase()===a)return h;return-1};f.getMonthNumberFromName=function(a){var b=Date.CultureInfo.monthNames,d=Date.CultureInfo.abbreviatedMonthNames;a=a.toLowerCase();for(var c=0;c<b.length;c++)if(b[c].toLowerCase()===a||d[c].toLowerCase()===a)return c;return-1};f.getMonthName=function(a){return Date.CultureInfo.monthNames[a]};f.isLeapYear=function(a){return 0===a%4&&0!==a%100||0===a%400};f.getDaysInMonth=
function(a,b){!b&&f.validateMonth(a)&&(b=a,a=Date.today().getFullYear());return[31,f.isLeapYear(a)?29:28,31,30,31,30,31,31,30,31,30,31][b]};f.getTimezoneAbbreviation=function(a,b){var d,c=b?Date.CultureInfo.abbreviatedTimeZoneDST:Date.CultureInfo.abbreviatedTimeZoneStandard;for(d in c)if(c.hasOwnProperty(d)&&c[d]===a)return d;return null};f.getTimezoneOffset=function(a,b){var d,c=[],h=Date.CultureInfo.timezones;a||(a=(new Date).getTimezone());for(d=0;d<h.length;d++)h[d].name===a.toUpperCase()&&c.push(d);
if(!h[c[0]])return null;if(1!==c.length&&b)for(d=0;d<c.length;d++){if(h[c[d]].dst)return h[c[d]].offset}else return h[c[0]].offset};f.getQuarter=function(a){a=a||new Date;return[1,2,3,4][Math.floor(a.getMonth()/3)]};f.getDaysLeftInQuarter=function(a){a=a||new Date;var b=new Date(a);b.setMonth(b.getMonth()+3-b.getMonth()%3,0);return Math.floor((b-a)/864E5)};g.clone=function(){return new Date(this.getTime())};g.compareTo=function(a){return Date.compare(this,a)};g.equals=function(a){return Date.equals(this,
void 0!==a?a:new Date)};g.between=function(a,b){return this.getTime()>=a.getTime()&&this.getTime()<=b.getTime()};g.isAfter=function(a){return 1===this.compareTo(a||new Date)};g.isBefore=function(a){return-1===this.compareTo(a||new Date)};g.isToday=g.isSameDay=function(a){return this.clone().clearTime().equals((a||new Date).clone().clearTime())};g.addMilliseconds=function(a){if(!a)return this;this.setTime(this.getTime()+1*a);return this};g.addSeconds=function(a){return a?this.addMilliseconds(1E3*a):
this};g.addMinutes=function(a){return a?this.addMilliseconds(6E4*a):this};g.addHours=function(a){return a?this.addMilliseconds(36E5*a):this};g.addDays=function(a){if(!a)return this;this.setDate(this.getDate()+1*a);return this};g.addWeekdays=function(a){if(!a)return this;var b=this.getDay(),d=Math.ceil(Math.abs(a)/7);(0===b||6===b)&&0<a&&(this.next().monday(),this.addDays(-1));if(0>a){for(;0>a;)this.addDays(-1),b=this.getDay(),0!==b&&6!==b&&a++;return this}if(5<a||6-b<=a)a+=2*d;return this.addDays(a)};
g.addWeeks=function(a){return a?this.addDays(7*a):this};g.addMonths=function(a){if(!a)return this;var b=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+1*a);this.setDate(Math.min(b,f.getDaysInMonth(this.getFullYear(),this.getMonth())));return this};g.addQuarters=function(a){return a?this.addMonths(3*a):this};g.addYears=function(a){return a?this.addMonths(12*a):this};g.add=function(a){if("number"===typeof a)return this._orient=a,this;a.day&&0!==a.day-this.getDate()&&this.setDate(a.day);
a.milliseconds&&this.addMilliseconds(a.milliseconds);a.seconds&&this.addSeconds(a.seconds);a.minutes&&this.addMinutes(a.minutes);a.hours&&this.addHours(a.hours);a.weeks&&this.addWeeks(a.weeks);a.months&&this.addMonths(a.months);a.years&&this.addYears(a.years);a.days&&this.addDays(a.days);return this};g.getWeek=function(a){var b=new Date(this.valueOf());a?(b.addMinutes(b.getTimezoneOffset()),a=b.clone()):a=this;a=(a.getDay()+6)%7;b.setDate(b.getDate()-a+3);a=b.valueOf();b.setMonth(0,1);4!==b.getDay()&&
b.setMonth(0,1+(4-b.getDay()+7)%7);return 1+Math.ceil((a-b)/6048E5)};g.getISOWeek=function(){return c(this.getWeek(!0))};g.setWeek=function(a){return 0===a-this.getWeek()?1!==this.getDay()?this.moveToDayOfWeek(1,1<this.getDay()?-1:1):this:this.moveToDayOfWeek(1,1<this.getDay()?-1:1).addWeeks(a-this.getWeek())};g.setQuarter=function(a){a=Math.abs(3*(a-1)+1);return this.setMonth(a,1)};g.getQuarter=function(){return Date.getQuarter(this)};g.getDaysLeftInQuarter=function(){return Date.getDaysLeftInQuarter(this)};
var a=function(a,b,d,c){if("undefined"===typeof a)return!1;if("number"!==typeof a)throw new TypeError(a+" is not a Number.");return a<b||a>d?!1:!0};f.validateMillisecond=function(e){return a(e,0,999,"millisecond")};f.validateSecond=function(e){return a(e,0,59,"second")};f.validateMinute=function(e){return a(e,0,59,"minute")};f.validateHour=function(e){return a(e,0,23,"hour")};f.validateDay=function(e,b,d){return a(e,1,f.getDaysInMonth(b,d),"day")};f.validateWeek=function(e){return a(e,0,53,"week")};
f.validateMonth=function(e){return a(e,0,11,"month")};f.validateYear=function(e){return a(e,-271822,275760,"year")};g.set=function(a){f.validateMillisecond(a.millisecond)&&this.addMilliseconds(a.millisecond-this.getMilliseconds());f.validateSecond(a.second)&&this.addSeconds(a.second-this.getSeconds());f.validateMinute(a.minute)&&this.addMinutes(a.minute-this.getMinutes());f.validateHour(a.hour)&&this.addHours(a.hour-this.getHours());f.validateMonth(a.month)&&this.addMonths(a.month-this.getMonth());
f.validateYear(a.year)&&this.addYears(a.year-this.getFullYear());f.validateDay(a.day,this.getFullYear(),this.getMonth())&&this.addDays(a.day-this.getDate());a.timezone&&this.setTimezone(a.timezone);a.timezoneOffset&&this.setTimezoneOffset(a.timezoneOffset);a.week&&f.validateWeek(a.week)&&this.setWeek(a.week);return this};g.moveToFirstDayOfMonth=function(){return this.set({day:1})};g.moveToLastDayOfMonth=function(){return this.set({day:f.getDaysInMonth(this.getFullYear(),this.getMonth())})};g.moveToNthOccurrence=
function(a,b){if("Weekday"===a){if(0<b)this.moveToFirstDayOfMonth(),this.is().weekday()&&(b-=1);else if(0>b)this.moveToLastDayOfMonth(),this.is().weekday()&&(b+=1);else return this;return this.addWeekdays(b)}var d=0;if(0<b)d=b-1;else if(-1===b)return this.moveToLastDayOfMonth(),this.getDay()!==a&&this.moveToDayOfWeek(a,-1),this;return this.moveToFirstDayOfMonth().addDays(-1).moveToDayOfWeek(a,1).addWeeks(d)};g.moveToDayOfWeek=function(a,b){var d=(a-this.getDay()+7*(b||1))%7;return this.addDays(0===
d?d+7*(b||1):d)};g.moveToMonth=function(a,b){var d=(a-this.getMonth()+12*(b||1))%12;return this.addMonths(0===d?d+12*(b||1):d)};g.getOrdinate=function(){var a=this.getDate();return b(a)};g.getOrdinalNumber=function(){return Math.ceil((this.clone().clearTime()-new Date(this.getFullYear(),0,1))/864E5)+1};g.getTimezone=function(){return f.getTimezoneAbbreviation(this.getUTCOffset(),this.isDaylightSavingTime())};g.setTimezoneOffset=function(a){var b=this.getTimezoneOffset();return(a=-6*Number(a)/10)||
0===a?this.addMinutes(a-b):this};g.setTimezone=function(a){return this.setTimezoneOffset(f.getTimezoneOffset(a))};g.hasDaylightSavingTime=function(){return Date.today().set({month:0,day:1}).getTimezoneOffset()!==Date.today().set({month:6,day:1}).getTimezoneOffset()};g.isDaylightSavingTime=function(){return Date.today().set({month:0,day:1}).getTimezoneOffset()!==this.getTimezoneOffset()};g.getUTCOffset=function(a){a=-10*(a||this.getTimezoneOffset())/6;if(0>a)return a=(a-1E4).toString(),a.charAt(0)+
a.substr(2);a=(a+1E4).toString();return"+"+a.substr(1)};g.getElapsed=function(a){return(a||new Date)-this};var b=function(a){switch(1*a){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th"}};g.toString=function(a,f){var d=this;if(!f&&a&&1===a.length){var g,h=Date.CultureInfo.formatPatterns;d.t=d.toString;switch(a){case "d":return d.t(h.shortDate);case "D":return d.t(h.longDate);case "F":return d.t(h.fullDateTime);case "m":return d.t(h.monthDay);
case "r":case "R":return g=d.clone().addMinutes(d.getTimezoneOffset()),g.toString(h.rfc1123)+" GMT";case "s":return d.t(h.sortableDateTime);case "t":return d.t(h.shortTime);case "T":return d.t(h.longTime);case "u":return g=d.clone().addMinutes(d.getTimezoneOffset()),g.toString(h.universalSortableDateTime);case "y":return d.t(h.yearMonth)}}return a?a.replace(/((\\)?(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|S|q|Q|WW?W?W?)(?![^\[]*\]))/g,function(a){if("\\"===a.charAt(0))return a.replace("\\","");
d.h=d.getHours;switch(a){case "hh":return c(13>d.h()?0===d.h()?12:d.h():d.h()-12);case "h":return 13>d.h()?0===d.h()?12:d.h():d.h()-12;case "HH":return c(d.h());case "H":return d.h();case "mm":return c(d.getMinutes());case "m":return d.getMinutes();case "ss":return c(d.getSeconds());case "s":return d.getSeconds();case "yyyy":return c(d.getFullYear(),4);case "yy":return c(d.getFullYear());case "dddd":return Date.CultureInfo.dayNames[d.getDay()];case "ddd":return Date.CultureInfo.abbreviatedDayNames[d.getDay()];
case "dd":return c(d.getDate());case "d":return d.getDate();case "MMMM":return Date.CultureInfo.monthNames[d.getMonth()];case "MMM":return Date.CultureInfo.abbreviatedMonthNames[d.getMonth()];case "MM":return c(d.getMonth()+1);case "M":return d.getMonth()+1;case "t":return 12>d.h()?Date.CultureInfo.amDesignator.substring(0,1):Date.CultureInfo.pmDesignator.substring(0,1);case "tt":return 12>d.h()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator;case "S":return b(d.getDate());case "W":return d.getWeek();
case "WW":return d.getISOWeek();case "Q":return"Q"+d.getQuarter();case "q":return String(d.getQuarter());default:return a}}).replace(/\[|\]/g,""):this._toString()}})();
(function(){Date.Parsing={Exception:function(a){this.message="Parse error at '"+a.substring(0,10)+" ...'"}};var f=Date.Parsing,g=[0,31,59,90,120,151,181,212,243,273,304,334],c=[0,31,60,91,121,152,182,213,244,274,305,335];f.isLeapYear=function(a){return 0===a%4&&0!==a%100||0===a%400};f.processTimeObject=function(a){var b,e;b=new Date;e=f.isLeapYear(a.year)?c:g;a.hours=a.hours?a.hours:0;a.minutes=a.minutes?a.minutes:0;a.seconds=a.seconds?a.seconds:0;a.milliseconds=a.milliseconds?a.milliseconds:0;a.year||
(a.year=b.getFullYear());if(a.month||!a.week&&!a.dayOfYear)a.month=a.month?a.month:0,a.day=a.day?a.day:1,a.dayOfYear=e[a.month]+a.day;else for(a.dayOfYear||(a.weekDay=a.weekDay||0===a.weekDay?a.weekDay:1,b=new Date(a.year,0,4),b=0===b.getDay()?7:b.getDay(),a.dayOfYear=7*a.week+(0===a.weekDay?7:a.weekDay)-(b+3)),b=0;b<=e.length;b++)if(a.dayOfYear<e[b]||b===e.length){a.day=a.day?a.day:a.dayOfYear-e[b-1];break}else a.month=b;e=new Date(a.year,a.month,a.day,a.hours,a.minutes,a.seconds,a.milliseconds);
a.zone&&("Z"===a.zone.toUpperCase()||0===a.zone_hours&&0===a.zone_minutes?b=-e.getTimezoneOffset():(b=60*a.zone_hours+(a.zone_minutes?a.zone_minutes:0),"+"===a.zone_sign&&(b*=-1),b-=e.getTimezoneOffset()),e.setMinutes(e.getMinutes()+b));return e};f.ISO={regex:/^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-4])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?\s?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/,
parse:function(a){a=a.match(this.regex);if(!a||!a.length)return null;var b={year:a[1]?Number(a[1]):a[1],month:a[5]?Number(a[5])-1:a[5],day:a[7]?Number(a[7]):a[7],week:a[8]?Number(a[8]):a[8],weekDay:a[9]?7===Math.abs(Number(a[9]))?0:Math.abs(Number(a[9])):a[9],dayOfYear:a[10]?Number(a[10]):a[10],hours:a[15]?Number(a[15]):a[15],minutes:a[16]?Number(a[16].replace(":","")):a[16],seconds:a[19]?Math.floor(Number(a[19].replace(":","").replace(",","."))):a[19],milliseconds:a[20]?1E3*Number(a[20].replace(",",
".")):a[20],zone:a[21],zone_sign:a[22],zone_hours:a[23]&&"undefined"!==typeof a[23]?Number(a[23]):a[23],zone_minutes:a[24]&&"undefined"!==typeof a[23]?Number(a[24]):a[24]};a[18]&&((a[18]=60*Number(a[18].replace(",",".")),b.minutes)?b.seconds||(b.seconds=a[18]):b.minutes=a[18]);return b.year&&(b.year||b.month||b.day||b.week||b.dayOfYear)?f.processTimeObject(b):null}};f.Numeric={isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},regex:/\b([0-1]?[0-9])([0-3]?[0-9])([0-2]?[0-9]?[0-9][0-9])\b/i,
parse:function(a){var b,e={},c=Date.CultureInfo.dateElementOrder.split("");if(!this.isNumeric(a)||"+"===a[0]&&"-"===a[0])return null;if(5>a.length)return e.year=a,f.processTimeObject(e);a=a.match(this.regex);if(!a||!a.length)return null;for(b=0;b<c.length;b++)switch(c[b]){case "d":e.day=a[b+1];break;case "m":e.month=a[b+1]-1;break;case "y":e.year=a[b+1]}return f.processTimeObject(e)}};f.Normalizer={parse:function(a){var b=Date.CultureInfo.regexPatterns,e=Date.i18n.__;a=a.replace(b.jan.source,"January");
a=a.replace(b.feb,"February");a=a.replace(b.mar,"March");a=a.replace(b.apr,"April");a=a.replace(b.may,"May");a=a.replace(b.jun,"June");a=a.replace(b.jul,"July");a=a.replace(b.aug,"August");a=a.replace(b.sep,"September");a=a.replace(b.oct,"October");a=a.replace(b.nov,"November");a=a.replace(b.dec,"December");a=a.replace(b.tomorrow,Date.today().addDays(1).toString("d"));a=a.replace(b.yesterday,Date.today().addDays(-1).toString("d"));a=a.replace(/\bat\b/gi,"");a=a.replace(/\s{2,}/," ");a=a.replace(RegExp("(\\b\\d\\d?("+
e("AM")+"|"+e("PM")+")? )("+b.tomorrow.source.slice(1)+")","i"),function(a,b,e,d,c){return Date.today().addDays(1).toString("d")+" "+b});a=a.replace(RegExp("(("+b.past.source+")\\s("+b.mon.source+"))"),Date.today().last().monday().toString("d"));a=a.replace(RegExp("(("+b.past.source+")\\s("+b.tue.source+"))"),Date.today().last().tuesday().toString("d"));a=a.replace(RegExp("(("+b.past.source+")\\s("+b.wed.source+"))"),Date.today().last().wednesday().toString("d"));a=a.replace(RegExp("(("+b.past.source+
")\\s("+b.thu.source+"))"),Date.today().last().thursday().toString("d"));a=a.replace(RegExp("(("+b.past.source+")\\s("+b.fri.source+"))"),Date.today().last().friday().toString("d"));a=a.replace(RegExp("(("+b.past.source+")\\s("+b.sat.source+"))"),Date.today().last().saturday().toString("d"));a=a.replace(RegExp("(("+b.past.source+")\\s("+b.sun.source+"))"),Date.today().last().sunday().toString("d"));a=a.replace(b.amThisMorning,function(a,b){return b});a=a.replace(b.inTheMorning,"am");a=a.replace(b.thisMorning,
"9am");a=a.replace(b.amThisEvening,function(a,b){return b});a=a.replace(b.inTheEvening,"pm");a=a.replace(b.thisEvening,"7pm");try{var c=a.split(/([\s\-\.\,\/\x27]+)/);3===c.length&&f.Numeric.isNumeric(c[0])&&f.Numeric.isNumeric(c[2])&&4<=c[2].length&&"d"===Date.CultureInfo.dateElementOrder[0]&&(a="1/"+c[0]+"/"+c[2])}catch(d){}return a}}})();
(function(){for(var f=Date.Parsing,g=f.Operators={rtoken:function(a){return function(b){var d=b.match(a);if(d)return[d[0],b.substring(d[0].length)];throw new f.Exception(b);}},token:function(a){return function(a){return g.rtoken(RegExp("^s*"+a+"s*"))(a)}},stoken:function(a){return g.rtoken(RegExp("^"+a))},until:function(a){return function(b){for(var d=[],c=null;b.length;){try{c=a.call(this,b)}catch(h){d.push(c[0]);b=c[1];continue}break}return[d,b]}},many:function(a){return function(b){for(var d=[],
c=null;b.length;){try{c=a.call(this,b)}catch(h){break}d.push(c[0]);b=c[1]}return[d,b]}},optional:function(a){return function(b){var d=null;try{d=a.call(this,b)}catch(c){return[null,b]}return[d[0],d[1]]}},not:function(a){return function(b){try{a.call(this,b)}catch(d){return[null,b]}throw new f.Exception(b);}},ignore:function(a){return a?function(b){var d=null,d=a.call(this,b);return[null,d[1]]}:null},product:function(){for(var a=arguments[0],b=Array.prototype.slice.call(arguments,1),d=[],c=0;c<a.length;c++)d.push(g.each(a[c],
b));return d},cache:function(a){var b={},d=null;return function(c){try{d=b[c]=b[c]||a.call(this,c)}catch(h){d=b[c]=h}if(d instanceof f.Exception)throw d;return d}},any:function(){var a=arguments;return function(b){for(var d=null,c=0;c<a.length;c++)if(null!=a[c]){try{d=a[c].call(this,b)}catch(h){d=null}if(d)return d}throw new f.Exception(b);}},each:function(){var a=arguments;return function(b){for(var d=[],c=null,h=0;h<a.length;h++)if(null!=a[h]){try{c=a[h].call(this,b)}catch(g){throw new f.Exception(b);
}d.push(c[0]);b=c[1]}return[d,b]}},all:function(){var a=a;return a.each(a.optional(arguments))},sequence:function(a,b,d){b=b||g.rtoken(/^\s*/);d=d||null;return 1==a.length?a[0]:function(c){for(var h=null,g=null,m=[],n=0;n<a.length;n++){try{h=a[n].call(this,c)}catch(p){break}m.push(h[0]);try{g=b.call(this,h[1])}catch(s){g=null;break}c=g[1]}if(!h)throw new f.Exception(c);if(g)throw new f.Exception(g[1]);if(d)try{h=d.call(this,h[1])}catch(t){throw new f.Exception(h[1]);}return[m,h?h[1]:c]}},between:function(a,
b,d){d=d||a;var c=g.each(g.ignore(a),b,g.ignore(d));return function(a){a=c.call(this,a);return[[a[0][0],r[0][2]],a[1]]}},list:function(a,b,d){b=b||g.rtoken(/^\s*/);d=d||null;return a instanceof Array?g.each(g.product(a.slice(0,-1),g.ignore(b)),a.slice(-1),g.ignore(d)):g.each(g.many(g.each(a,g.ignore(b))),px,g.ignore(d))},set:function(a,b,d){b=b||g.rtoken(/^\s*/);d=d||null;return function(c){for(var h=null,k=h=null,m=null,n=[[],c],p=!1,s=0;s<a.length;s++){h=k=null;p=1==a.length;try{h=a[s].call(this,
c)}catch(t){continue}m=[[h[0]],h[1]];if(0<h[1].length&&!p)try{k=b.call(this,h[1])}catch(u){p=!0}else p=!0;p||0!==k[1].length||(p=!0);if(!p){h=[];for(p=0;p<a.length;p++)s!=p&&h.push(a[p]);h=g.set(h,b).call(this,k[1]);0<h[0].length&&(m[0]=m[0].concat(h[0]),m[1]=h[1])}m[1].length<n[1].length&&(n=m);if(0===n[1].length)break}if(0===n[0].length)return n;if(d){try{k=d.call(this,n[1])}catch(v){throw new f.Exception(n[1]);}n[1]=k[1]}return n}},forward:function(a,b){return function(d){return a[b].call(this,
d)}},replace:function(a,b){return function(d){d=a.call(this,d);return[b,d[1]]}},process:function(a,b){return function(d){d=a.call(this,d);return[b.call(this,d[0]),d[1]]}},min:function(a,b){return function(d){var c=b.call(this,d);if(c[0].length<a)throw new f.Exception(d);return c}}},c=function(a){return function(){var b=null,d=[],c;1<arguments.length?b=Array.prototype.slice.call(arguments):arguments[0]instanceof Array&&(b=arguments[0]);if(b){if(c=b.shift(),0<c.length)return b.unshift(c[void 0]),d.push(a.apply(null,
b)),b.shift(),d}else return a.apply(null,arguments)}},a="optional not ignore cache".split(/\s/),b=0;b<a.length;b++)g[a[b]]=c(g[a[b]]);c=function(a){return function(){return arguments[0]instanceof Array?a.apply(null,arguments[0]):a.apply(null,arguments)}};a="each any all".split(/\s/);for(b=0;b<a.length;b++)g[a[b]]=c(g[a[b]])})();
(function(){var f=Date,g=function(a){for(var b=[],c=0;c<a.length;c++)a[c]instanceof Array?b=b.concat(g(a[c])):a[c]&&b.push(a[c]);return b};f.Grammar={};f.Translator={hour:function(a){return function(){this.hour=Number(a)}},minute:function(a){return function(){this.minute=Number(a)}},second:function(a){return function(){this.second=Number(a)}},secondAndMillisecond:function(a){return function(){var b=a.match(/^([0-5][0-9])\.([0-9]{1,3})/);this.second=Number(b[1]);this.millisecond=Number(b[2])}},meridian:function(a){return function(){this.meridian=
a.slice(0,1).toLowerCase()}},timezone:function(a){return function(){var b=a.replace(/[^\d\+\-]/g,"");b.length?this.timezoneOffset=Number(b):this.timezone=a.toLowerCase()}},day:function(a){var b=a[0];return function(){this.day=Number(b.match(/\d+/)[0]);if(1>this.day)throw"invalid day";}},month:function(a){return function(){this.month=3===a.length?"jan feb mar apr may jun jul aug sep oct nov dec".indexOf(a)/4:Number(a)-1;if(0>this.month)throw"invalid month";}},year:function(a){return function(){var b=
Number(a);this.year=2<a.length?b:b+(b+2E3<Date.CultureInfo.twoDigitYearMax?2E3:1900)}},rday:function(a){return function(){switch(a){case "yesterday":this.days=-1;break;case "tomorrow":this.days=1;break;case "today":this.days=0;break;case "now":this.days=0,this.now=!0}}},finishExact:function(a){a=a instanceof Array?a:[a];for(var b=0;b<a.length;b++)a[b]&&a[b].call(this);a=new Date;!this.hour&&!this.minute||this.month||this.year||this.day||(this.day=a.getDate());this.year||(this.year=a.getFullYear());
this.month||0===this.month||(this.month=a.getMonth());this.day||(this.day=1);this.hour||(this.hour=0);this.minute||(this.minute=0);this.second||(this.second=0);this.millisecond||(this.millisecond=0);if(this.meridian&&(this.hour||0===this.hour)){if("a"==this.meridian&&11<this.hour&&Date.Config.strict24hr)throw"Invalid hour and meridian combination";if("p"==this.meridian&&12>this.hour&&Date.Config.strict24hr)throw"Invalid hour and meridian combination";"p"==this.meridian&&12>this.hour?this.hour+=12:
"a"==this.meridian&&12==this.hour&&(this.hour=0)}if(this.day>f.getDaysInMonth(this.year,this.month))throw new RangeError(this.day+" is not a valid value for days.");a=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);100>this.year&&a.setFullYear(this.year);this.timezone?a.set({timezone:this.timezone}):this.timezoneOffset&&a.set({timezoneOffset:this.timezoneOffset});return a},finish:function(a){a=a instanceof Array?g(a):[a];if(0===a.length)return null;for(var b=
0;b<a.length;b++)"function"==typeof a[b]&&a[b].call(this);a=f.today();if(!this.now||this.unit||this.operator)this.now&&(a=new Date);else return new Date;var b=!!(this.days&&null!==this.days||this.orient||this.operator),c,d,e;e="past"==this.orient||"subtract"==this.operator?-1:1;this.now||-1=="hour minute second".indexOf(this.unit)||a.setTimeToNow();this.month&&"week"==this.unit&&(this.value=this.month+1,delete this.month,delete this.day);!this.month&&0!==this.month||-1=="year day hour minute second".indexOf(this.unit)||
(this.value||(this.value=this.month+1),this.month=null,b=!0);b||!this.weekday||this.day||this.days||(c=Date[this.weekday](),this.day=c.getDate(),this.month||(this.month=c.getMonth()),this.year=c.getFullYear());b&&this.weekday&&"month"!=this.unit&&"week"!=this.unit&&(this.unit="day",c=f.getDayNumberFromName(this.weekday)-a.getDay(),d=7,this.days=c?(c+e*d)%d:e*d);this.month&&"day"==this.unit&&this.operator&&(this.value||(this.value=this.month+1),this.month=null);null!=this.value&&null!=this.month&&
null!=this.year&&(this.day=1*this.value);this.month&&!this.day&&this.value&&(a.set({day:1*this.value}),b||(this.day=1*this.value));this.month||!this.value||"month"!=this.unit||this.now||(this.month=this.value,b=!0);b&&(this.month||0===this.month)&&"year"!=this.unit&&(this.unit="month",c=this.month-a.getMonth(),d=12,this.months=c?(c+e*d)%d:e*d,this.month=null);this.unit||(this.unit="day");if(!this.value&&this.operator&&null!==this.operator&&this[this.unit+"s"]&&null!==this[this.unit+"s"])this[this.unit+
"s"]=this[this.unit+"s"]+("add"==this.operator?1:-1)+(this.value||0)*e;else if(null==this[this.unit+"s"]||null!=this.operator)this.value||(this.value=1),this[this.unit+"s"]=this.value*e;if(this.meridian&&(this.hour||0===this.hour)){if("a"==this.meridian&&11<this.hour&&Date.Config.strict24hr)throw"Invalid hour and meridian combination";if("p"==this.meridian&&12>this.hour&&Date.Config.strict24hr)throw"Invalid hour and meridian combination";"p"==this.meridian&&12>this.hour?this.hour+=12:"a"==this.meridian&&
12==this.hour&&(this.hour=0)}!this.weekday||"week"===this.unit||this.day||this.days||(c=Date[this.weekday](),this.day=c.getDate(),c.getMonth()!==a.getMonth()&&(this.month=c.getMonth()));!this.month&&0!==this.month||this.day||(this.day=1);if(!this.orient&&!this.operator&&"week"==this.unit&&this.value&&!this.day&&!this.month)return Date.today().setWeek(this.value);if("week"==this.unit&&this.weeks&&!this.day&&!this.month)return a=Date[this.weekday?this.weekday:"today"]().addWeeks(this.weeks),this.now&&
a.setTimeToNow(),a;b&&this.timezone&&this.day&&this.days&&(this.day=this.days);return b?a.add(this):a.set(this)}};var c=f.Parsing.Operators,a=f.Grammar,b=f.Translator,e;a.datePartDelimiter=c.rtoken(/^([\s\-\.\,\/\x27]+)/);a.timePartDelimiter=c.stoken(":");a.whiteSpace=c.rtoken(/^\s*/);a.generalDelimiter=c.rtoken(/^(([\s\,]|at|@|on)+)/);var q={};a.ctoken=function(a){var b=q[a];if(!b){for(var b=Date.CultureInfo.regexPatterns,d=a.split(/\s+/),e=[],f=0;f<d.length;f++)e.push(c.replace(c.rtoken(b[d[f]]),
d[f]));b=q[a]=c.any.apply(null,e)}return b};a.ctoken2=function(a){return c.rtoken(Date.CultureInfo.regexPatterns[a])};a.h=c.cache(c.process(c.rtoken(/^(0[0-9]|1[0-2]|[1-9])/),b.hour));a.hh=c.cache(c.process(c.rtoken(/^(0[0-9]|1[0-2])/),b.hour));a.H=c.cache(c.process(c.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/),b.hour));a.HH=c.cache(c.process(c.rtoken(/^([0-1][0-9]|2[0-3])/),b.hour));a.m=c.cache(c.process(c.rtoken(/^([0-5][0-9]|[0-9])/),b.minute));a.mm=c.cache(c.process(c.rtoken(/^[0-5][0-9]/),b.minute));
a.s=c.cache(c.process(c.rtoken(/^([0-5][0-9]|[0-9])/),b.second));a.ss=c.cache(c.process(c.rtoken(/^[0-5][0-9]/),b.second));a["ss.s"]=c.cache(c.process(c.rtoken(/^[0-5][0-9]\.[0-9]{1,3}/),b.secondAndMillisecond));a.hms=c.cache(c.sequence([a.H,a.m,a.s],a.timePartDelimiter));a.t=c.cache(c.process(a.ctoken2("shortMeridian"),b.meridian));a.tt=c.cache(c.process(a.ctoken2("longMeridian"),b.meridian));a.z=c.cache(c.process(c.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/),b.timezone));a.zz=c.cache(c.process(c.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/),
b.timezone));a.zzz=c.cache(c.process(a.ctoken2("timezone"),b.timezone));a.timeSuffix=c.each(c.ignore(a.whiteSpace),c.set([a.tt,a.zzz]));a.time=c.each(c.optional(c.ignore(c.stoken("T"))),a.hms,a.timeSuffix);a.d=c.cache(c.process(c.each(c.rtoken(/^([0-2]\d|3[0-1]|\d)/),c.optional(a.ctoken2("ordinalSuffix"))),b.day));a.dd=c.cache(c.process(c.each(c.rtoken(/^([0-2]\d|3[0-1])/),c.optional(a.ctoken2("ordinalSuffix"))),b.day));a.ddd=a.dddd=c.cache(c.process(a.ctoken("sun mon tue wed thu fri sat"),function(a){return function(){this.weekday=
a}}));a.M=c.cache(c.process(c.rtoken(/^(1[0-2]|0\d|\d)/),b.month));a.MM=c.cache(c.process(c.rtoken(/^(1[0-2]|0\d)/),b.month));a.MMM=a.MMMM=c.cache(c.process(a.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),b.month));a.y=c.cache(c.process(c.rtoken(/^(\d\d?)/),b.year));a.yy=c.cache(c.process(c.rtoken(/^(\d\d)/),b.year));a.yyy=c.cache(c.process(c.rtoken(/^(\d\d?\d?\d?)/),b.year));a.yyyy=c.cache(c.process(c.rtoken(/^(\d\d\d\d)/),b.year));e=function(){return c.each(c.any.apply(null,arguments),
c.not(a.ctoken2("timeContext")))};a.day=e(a.d,a.dd);a.month=e(a.M,a.MMM);a.year=e(a.yyyy,a.yy);a.orientation=c.process(a.ctoken("past future"),function(a){return function(){this.orient=a}});a.operator=c.process(a.ctoken("add subtract"),function(a){return function(){this.operator=a}});a.rday=c.process(a.ctoken("yesterday tomorrow today now"),b.rday);a.unit=c.process(a.ctoken("second minute hour day week month year"),function(a){return function(){this.unit=a}});a.value=c.process(c.rtoken(/^([-+]?\d+)?(st|nd|rd|th)?/),
function(a){return function(){this.value=a.replace(/\D/g,"")}});a.expression=c.set([a.rday,a.operator,a.value,a.unit,a.orientation,a.ddd,a.MMM]);e=function(){return c.set(arguments,a.datePartDelimiter)};a.mdy=e(a.ddd,a.month,a.day,a.year);a.ymd=e(a.ddd,a.year,a.month,a.day);a.dmy=e(a.ddd,a.day,a.month,a.year);a.date=function(b){return(a[Date.CultureInfo.dateElementOrder]||a.mdy).call(this,b)};a.format=c.process(c.many(c.any(c.process(c.rtoken(/^(dd?d?d?(?!e)|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),
function(b){if(a[b])return a[b];throw f.Parsing.Exception(b);}),c.process(c.rtoken(/^[^dMyhHmstz]+/),function(a){return c.ignore(c.stoken(a))}))),function(a){return c.process(c.each.apply(null,a),b.finishExact)});var d={},l=function(b){d[b]=d[b]||a.format(b)[0];return d[b]};a.allformats=function(a){var b=[];if(a instanceof Array)for(var c=0;c<a.length;c++)b.push(l(a[c]));else b.push(l(a));return b};a.formats=function(a){if(a instanceof Array){for(var b=[],d=0;d<a.length;d++)b.push(l(a[d]));return c.any.apply(null,
b)}return l(a)};a._formats=a.formats('"yyyy-MM-ddTHH:mm:ssZ";yyyy-MM-ddTHH:mm:ss.sz;yyyy-MM-ddTHH:mm:ssZ;yyyy-MM-ddTHH:mm:ssz;yyyy-MM-ddTHH:mm:ss;yyyy-MM-ddTHH:mmZ;yyyy-MM-ddTHH:mmz;yyyy-MM-ddTHH:mm;ddd, MMM dd, yyyy H:mm:ss tt;ddd MMM d yyyy HH:mm:ss zzz;MMddyyyy;ddMMyyyy;Mddyyyy;ddMyyyy;Mdyyyy;dMyyyy;yyyy;Mdyy;dMyy;d'.split(";"));a._start=c.process(c.set([a.date,a.time,a.expression],a.generalDelimiter,a.whiteSpace),b.finish);a.start=function(b){try{var c=a._formats.call({},b);if(0===c[1].length)return c}catch(d){}return a._start.call({},
b)};f._parse||(f._parse=f.parse);f.parse=function(a){var b,c,d=null;if(!a)return null;if(a instanceof Date)return a.clone();4<=a.length&&"0"!==a.charAt(0)&&"+"!==a.charAt(0)&&"-"!==a.charAt(0)&&(b=f.Parsing.ISO.parse(a)||f.Parsing.Numeric.parse(a));if(b instanceof Date&&!isNaN(b.getTime()))return b;a=(b=a.match(/\b(\d+)(?:st|nd|rd|th)\b/))&&2===b.length?a.replace(b[0],b[1]):a;a=f.Parsing.Normalizer.parse(a);try{d=f.Grammar.start.call({},a.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1"))}catch(e){return null}b=
0===d[1].length?d[0]:null;if(null!==b)return b;try{return(c=Date._parse(a))||0===c?new Date(c):null}catch(g){return null}};Date.getParseFunction=function(a){var b=Date.Grammar.allformats(a);return function(a){for(var c=null,d=0;d<b.length;d++){try{c=b[d].call({},a)}catch(e){continue}if(0===c[1].length)return c[0]}return null}};f.parseExact=function(a,b){return f.getParseFunction(b)(a)}})();
(function(){var f=Date,g=f.prototype,c=Number.prototype;g._orient=1;g._nth=null;g._is=!1;g._same=!1;g._isSecond=!1;c._dateElement="days";g.next=function(){this._move=!0;this._orient=1;return this};f.next=function(){return f.today().next()};g.last=g.prev=g.previous=function(){this._move=!0;this._orient=-1;return this};f.last=f.prev=f.previous=function(){return f.today().last()};g.is=function(){this._is=!0;return this};g.same=function(){this._same=!0;this._isSecond=!1;return this};g.today=function(){return this.same().day()};
g.weekday=function(){return this._nth?l("Weekday").call(this):this._move?this.addWeekdays(this._orient):this._is?(this._is=!1,!this.is().sat()&&!this.is().sun()):!1};g.weekend=function(){return this._is?(this._is=!1,this.is().sat()||this.is().sun()):!1};g.at=function(a){return"string"===typeof a?f.parse(this.toString("d")+" "+a):this.set(a)};c.fromNow=c.after=function(a){var b={};b[this._dateElement]=this;return(a?a.clone():new Date).add(b)};c.ago=c.before=function(a){var b={};b["s"!==this._dateElement[this._dateElement.length-
1]?this._dateElement+"s":this._dateElement]=-1*this;return(a?a.clone():new Date).add(b)};var a="sunday monday tuesday wednesday thursday friday saturday".split(/\s/),b="january february march april may june july august september october november december".split(/\s/),e="Millisecond Second Minute Hour Day Week Month Year Quarter Weekday".split(/\s/),q="Milliseconds Seconds Minutes Hours Date Week Month FullYear Quarter".split(/\s/),d="final first second third fourth fifth".split(/\s/);g.toObject=function(){for(var a=
{},b=0;b<e.length;b++)this["get"+q[b]]&&(a[e[b].toLowerCase()]=this["get"+q[b]]());return a};f.fromObject=function(a){a.week=null;return Date.today().set(a)};for(var l=function(a){return function(){if(this._is)return this._is=!1,this.getDay()===a;this._move&&(this._move=null);if(null!==this._nth){this._isSecond&&this.addSeconds(-1*this._orient);this._isSecond=!1;var b=this._nth;this._nth=null;var c=this.clone().moveToLastDayOfMonth();this.moveToNthOccurrence(a,b);if(this>c)throw new RangeError(f.getDayName(a)+
" does not occur "+b+" times in the month of "+f.getMonthName(c.getMonth())+" "+c.getFullYear()+".");return this}return this.moveToDayOfWeek(a,this._orient)}},h=function(a){return function(){var b=f.today(),c=a-b.getDay();0===a&&1===Date.CultureInfo.firstDayOfWeek&&0!==b.getDay()&&(c+=7);return b.addDays(c)}},k=0;k<a.length;k++)f[a[k].toUpperCase()]=f[a[k].toUpperCase().substring(0,3)]=k,f[a[k]]=f[a[k].substring(0,3)]=h(k),g[a[k]]=g[a[k].substring(0,3)]=l(k);a=function(a){return function(){return this._is?
(this._is=!1,this.getMonth()===a):this.moveToMonth(a,this._orient)}};h=function(a){return function(){return f.today().set({month:a,day:1})}};for(k=0;k<b.length;k++)f[b[k].toUpperCase()]=f[b[k].toUpperCase().substring(0,3)]=k,f[b[k]]=f[b[k].substring(0,3)]=h(k),g[b[k]]=g[b[k].substring(0,3)]=a(k);a=function(a){return function(b){if(this._isSecond)return this._isSecond=!1,this;if(this._same){this._same=this._is=!1;var c=this.toObject();b=(b||new Date).toObject();for(var d="",f=a.toLowerCase(),f="s"===
f[f.length-1]?f.substring(0,f.length-1):f,g=e.length-1;-1<g;g--){d=e[g].toLowerCase();if(c[d]!==b[d])return!1;if(f===d)break}return!0}"s"!==a.substring(a.length-1)&&(a+="s");this._move&&(this._move=null);return this["add"+a](this._orient)}};h=function(a){return function(){this._dateElement=a;return this}};for(k=0;k<e.length;k++)b=e[k].toLowerCase(),"weekday"!==b&&(g[b]=g[b+"s"]=a(e[k]),c[b]=c[b+"s"]=h(b+"s"));g._ss=a("Second");c=function(a){return function(b){if(this._same)return this._ss(b);if(b||
0===b)return this.moveToNthOccurrence(b,a);this._nth=a;return 2!==a||void 0!==b&&null!==b?this:(this._isSecond=!0,this.addSeconds(this._orient))}};for(b=0;b<d.length;b++)g[d[b]]=0===b?c(-1):c(b)})();
(function(){var f=Date,g=f.prototype,c=[],a=function(a,c){c||(c=2);return("000"+a).slice(-1*c)};f.normalizeFormat=function(a){return a};f.strftime=function(a,c){return(new Date(1E3*c)).$format(a)};f.strtotime=function(a){a=f.parse(a);a.addMinutes(-1*a.getTimezoneOffset());return Math.round(f.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate(),a.getUTCHours(),a.getUTCMinutes(),a.getUTCSeconds(),a.getUTCMilliseconds())/1E3)};g.$format=function(b){var e=this,g,d=function(a,b){c.push(a);return e.toString(a,
b)};return b?b.replace(/(%|\\)?.|%%/g,function(b){if("\\"===b.charAt(0)||"%%"===b.substring(0,2))return b.replace("\\","").replace("%%","%");switch(b){case "d":case "%d":return d("dd");case "D":case "%a":return d("ddd");case "j":case "%e":return d("d",!0);case "l":case "%A":return d("dddd");case "N":case "%u":return e.getDay()+1;case "S":return d("S");case "w":case "%w":return e.getDay();case "z":return e.getOrdinalNumber();case "%j":return a(e.getOrdinalNumber(),3);case "%U":b=e.clone().set({month:0,
day:1}).addDays(-1).moveToDayOfWeek(0);var h=e.clone().addDays(1).moveToDayOfWeek(0,-1);return h<b?"00":a((h.getOrdinalNumber()-b.getOrdinalNumber())/7+1);case "W":case "%V":return e.getISOWeek();case "%W":return a(e.getWeek());case "F":case "%B":return d("MMMM");case "m":case "%m":return d("MM");case "M":case "%b":case "%h":return d("MMM");case "n":return d("M");case "t":return f.getDaysInMonth(e.getFullYear(),e.getMonth());case "L":return f.isLeapYear(e.getFullYear())?1:0;case "o":case "%G":return e.setWeek(e.getISOWeek()).toString("yyyy");
case "%g":return e.$format("%G").slice(-2);case "Y":case "%Y":return d("yyyy");case "y":case "%y":return d("yy");case "a":case "%p":return d("tt").toLowerCase();case "A":return d("tt").toUpperCase();case "g":case "%I":return d("h");case "G":return d("H");case "h":return d("hh");case "H":case "%H":return d("HH");case "i":case "%M":return d("mm");case "s":case "%S":return d("ss");case "u":return a(e.getMilliseconds(),3);case "I":return e.isDaylightSavingTime()?1:0;case "O":return e.getUTCOffset();case "P":return g=
e.getUTCOffset(),g.substring(0,g.length-2)+":"+g.substring(g.length-2);case "e":case "T":case "%z":case "%Z":return e.getTimezone();case "Z":return-60*e.getTimezoneOffset();case "B":return b=new Date,Math.floor((3600*b.getHours()+60*b.getMinutes()+b.getSeconds()+60*(b.getTimezoneOffset()+60))/86.4);case "c":return e.toISOString().replace(/\"/g,"");case "U":return f.strtotime("now");case "%c":return d("d")+" "+d("t");case "%C":return Math.floor(e.getFullYear()/100+1);case "%D":return d("MM/dd/yy");
case "%n":return"\\n";case "%t":return"\\t";case "%r":return d("hh:mm tt");case "%R":return d("H:mm");case "%T":return d("H:mm:ss");case "%x":return d("d");case "%X":return d("t");default:return c.push(b),b}}):this._toString()};g.format||(g.format=g.$format)})();
var TimeSpan=function(f,g,c,a,b){for(var e="days hours minutes seconds milliseconds".split(/\s+/),q=function(a){return function(){return this[a]}},d=function(a){return function(b){this[a]=b;return this}},l=0;l<e.length;l++){var h=e[l],k=h.slice(0,1).toUpperCase()+h.slice(1);TimeSpan.prototype[h]=0;TimeSpan.prototype["get"+k]=q(h);TimeSpan.prototype["set"+k]=d(h)}4===arguments.length?(this.setDays(f),this.setHours(g),this.setMinutes(c),this.setSeconds(a)):5===arguments.length?(this.setDays(f),this.setHours(g),
this.setMinutes(c),this.setSeconds(a),this.setMilliseconds(b)):1===arguments.length&&"number"===typeof f&&(e=0>f?-1:1,this.setMilliseconds(Math.abs(f)),this.setDays(Math.floor(this.getMilliseconds()/864E5)*e),this.setMilliseconds(this.getMilliseconds()%864E5),this.setHours(Math.floor(this.getMilliseconds()/36E5)*e),this.setMilliseconds(this.getMilliseconds()%36E5),this.setMinutes(Math.floor(this.getMilliseconds()/6E4)*e),this.setMilliseconds(this.getMilliseconds()%6E4),this.setSeconds(Math.floor(this.getMilliseconds()/
1E3)*e),this.setMilliseconds(this.getMilliseconds()%1E3),this.setMilliseconds(this.getMilliseconds()*e));this.getTotalMilliseconds=function(){return 864E5*this.getDays()+36E5*this.getHours()+6E4*this.getMinutes()+1E3*this.getSeconds()};this.compareTo=function(a){var b=new Date(1970,1,1,this.getHours(),this.getMinutes(),this.getSeconds());a=null===a?new Date(1970,1,1,0,0,0):new Date(1970,1,1,a.getHours(),a.getMinutes(),a.getSeconds());return b<a?-1:b>a?1:0};this.equals=function(a){return 0===this.compareTo(a)};
this.add=function(a){return null===a?this:this.addSeconds(a.getTotalMilliseconds()/1E3)};this.subtract=function(a){return null===a?this:this.addSeconds(-a.getTotalMilliseconds()/1E3)};this.addDays=function(a){return new TimeSpan(this.getTotalMilliseconds()+864E5*a)};this.addHours=function(a){return new TimeSpan(this.getTotalMilliseconds()+36E5*a)};this.addMinutes=function(a){return new TimeSpan(this.getTotalMilliseconds()+6E4*a)};this.addSeconds=function(a){return new TimeSpan(this.getTotalMilliseconds()+
1E3*a)};this.addMilliseconds=function(a){return new TimeSpan(this.getTotalMilliseconds()+a)};this.get12HourHour=function(){return 12<this.getHours()?this.getHours()-12:0===this.getHours()?12:this.getHours()};this.getDesignator=function(){return 12>this.getHours()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator};this.toString=function(a){this._toString=function(){return null!==this.getDays()&&0<this.getDays()?this.getDays()+"."+this.getHours()+":"+this.p(this.getMinutes())+":"+this.p(this.getSeconds()):
this.getHours()+":"+this.p(this.getMinutes())+":"+this.p(this.getSeconds())};this.p=function(a){return 2>a.toString().length?"0"+a:a};var b=this;return a?a.replace(/dd?|HH?|hh?|mm?|ss?|tt?/g,function(a){switch(a){case "d":return b.getDays();case "dd":return b.p(b.getDays());case "H":return b.getHours();case "HH":return b.p(b.getHours());case "h":return b.get12HourHour();case "hh":return b.p(b.get12HourHour());case "m":return b.getMinutes();case "mm":return b.p(b.getMinutes());case "s":return b.getSeconds();
case "ss":return b.p(b.getSeconds());case "t":return(12>b.getHours()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator).substring(0,1);case "tt":return 12>b.getHours()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator}}):this._toString()};return this};Date.prototype.getTimeOfDay=function(){return new TimeSpan(0,this.getHours(),this.getMinutes(),this.getSeconds(),this.getMilliseconds())};
var TimePeriod=function(f,g,c,a,b,e,q){for(var d="years months days hours minutes seconds milliseconds".split(/\s+/),l=function(a){return function(){return this[a]}},h=function(a){return function(b){this[a]=b;return this}},k=0;k<d.length;k++){var m=d[k],n=m.slice(0,1).toUpperCase()+m.slice(1);TimePeriod.prototype[m]=0;TimePeriod.prototype["get"+n]=l(m);TimePeriod.prototype["set"+n]=h(m)}if(7===arguments.length)this.years=f,this.months=g,this.setDays(c),this.setHours(a),this.setMinutes(b),this.setSeconds(e),
this.setMilliseconds(q);else if(2===arguments.length&&arguments[0]instanceof Date&&arguments[1]instanceof Date){d=f.clone();l=g.clone();h=d.clone();k=d>l?-1:1;this.years=l.getFullYear()-d.getFullYear();h.addYears(this.years);1===k?h>l&&0!==this.years&&this.years--:h<l&&0!==this.years&&this.years++;d.addYears(this.years);if(1===k)for(;d<l&&d.clone().addMonths(1)<=l;)d.addMonths(1),this.months++;else for(;d>l&&d.clone().addDays(-d.getDaysInMonth())>l;)d.addMonths(-1),this.months--;d=l-d;0!==d&&(d=new TimeSpan(d),
this.setDays(d.getDays()),this.setHours(d.getHours()),this.setMinutes(d.getMinutes()),this.setSeconds(d.getSeconds()),this.setMilliseconds(d.getMilliseconds()))}return this};
|
/**
* Main bot logic that handles incoming messages and routes logic to helpers files
*
* @module helpers/logic
* @license MIT
*/
/** Dependencies */
const hourlyRatePicker = require('./hourlyRatePicker');
const categoryPicker = require('./categoryPicker');
const languagePicker = require('./languagePicker');
const adminPanel = require('./adminCommands');
const jobManager = require('./jobManager');
const keyboards = require('./keyboards');
const dbmanager = require('./dbmanager');
const profile = require('./profile');
const strings = require('./strings');
const check = require('./messageParser');
const bot = require('./telegramBot');
const botan = require('botanio')('e6ec3f07-db08-4a5a-9ef1-433dc34ed9ae');
/** Handle messages */
/**
* Fired when bot receives a message
*
* @param {Telegram:Message} msg - Message received by bot
*/
bot.on('message', (msg) => {
if (!msg) return;
else if (!msg.from.username) {
profile.sendAskForUsername(bot, msg);
return;
}
profile.textInputCheck(msg, (isTextInput, user) => {
if (user) {
if (user.ban_state) {
profile.sendBanMessage(bot, msg);
return;
}
profile.updateProfile(msg, user);
if (isTextInput) {
global.eventEmitter.emit(((msg.text === strings().cancel) ? 'cancel' : '') + isTextInput, { msg, user, bot });
} else if (check.replyMarkup(msg)) {
handleKeyboard(msg);
} else if (check.botCommandStart(msg)) {
keyboards.sendMainMenu(bot, msg.chat.id, false);
} else if (check.adminCommand(msg)) {
adminPanel.handleAdminCommand(msg, bot);
} else {
bot.sendMessage(-1001088665045, `@${user.username} sent strange message:\n\n\`${msg.text}\``, {parse_mode: 'Markdown'});
}
} else if (check.botCommandStart(msg)) {
profile.createProfile(bot, msg);
} else if (check.adminCommand(msg)) {
adminPanel.handleAdminCommand(msg, bot);
}
});
botan.track(msg, 'message');
});
/**
* Fired when user clicks button on inlline keyboard
*
* @param {Telegram:Message} msg - Message that gets passed from user and info about button clicked
*/
bot.on('callback_query', (msg) => {
if (!msg.from.username) {
profile.sendAskForUsername(msg);
return;
}
dbmanager.findUser({ id: msg.from.id })
.then((user) => {
if (user.ban_state) {
profile.sendBanMessage(msg);
return;
}
const options = msg.data.split(strings().inlineSeparator);
const inlineQuery = options[0];
global.eventEmitter.emit(inlineQuery, { bot, msg, user });
})
.catch(/** todo: handle error */);
});
bot.on('inline_query', (msg) => {
dbmanager.findUser({ id: msg.from.id })
.then((user) => {
if (!user) {
return
}
const results = [{
type: 'article',
id: `${getRandomInt(1000000000000000, 999999999999999999)}`,
title: strings().shareProfile,
input_message_content: {
message_text: user.getTextToShareProfile(),
},
}];
const opts = {
cache_time: 60,
is_personal: true,
};
bot.answerInlineQuery(msg.id, results, opts)
.catch(/** todo: handle error */);
})
.catch(/** todo: handle error */);
});
/**
* Handler for custom keyboard button clicks
*
* @param {Telegram:Message} msg - Message that is passed with click and keyboard option
*/
function handleKeyboard(msg) {
const text = msg.text;
const mainMenuOptions = strings().mainMenuOptions;
const clientOptions = strings().clientMenuOptions;
const freelanceMenuOptions = strings().freelanceMenuOptions;
if (text === mainMenuOptions.findJobs) {
keyboards.sendFreelanceMenu(bot, msg.chat.id);
} else if (text === mainMenuOptions.findContractors) {
keyboards.sendClientMenu(bot, msg.chat.id);
} else if (text === mainMenuOptions.help) {
keyboards.sendHelp(bot, msg.chat.id);
} else if (text === mainMenuOptions.chooseLanguage) {
languagePicker.sendInterfaceLanguagePicker(bot, msg.chat.id);
} else if (text === clientOptions.postNewJob) {
jobManager.startJobDraft(bot, msg);
} else if (text === clientOptions.myJobs) {
jobManager.sendAllJobs(bot, msg);
} else if (text === freelanceMenuOptions.editBio || text === freelanceMenuOptions.addBio) {
profile.askForBio(msg, bot);
} else if (text === freelanceMenuOptions.editCategories ||
text === freelanceMenuOptions.addCategories) {
categoryPicker.sendCategories(bot, msg.chat.id);
} else if (text === freelanceMenuOptions.editHourlyRate ||
text === freelanceMenuOptions.addHourlyRate) {
hourlyRatePicker.sendHourlyRate(bot, msg.chat.id);
} else if (text === freelanceMenuOptions.busy || text === freelanceMenuOptions.available) {
profile.toggleAvailability(bot, msg.chat.id);
} else if (text.indexOf('๐ท๐บ') > -1 || text.indexOf('๐บ๐ธ') > -1) {
/** todo: remove hardcoded flags ^^^ */
languagePicker.sendLanguagePicker(bot, msg.chat.id);
} else if (text === freelanceMenuOptions.back) {
keyboards.sendMainMenu(bot, msg.chat.id);
}
}
/** Helpers */
/**
* Get random int
*
* @param {Number} min
* @param {Number} max
* @return {Number} Random number
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * ((max - min) + 1)) + min;
}
|
/**
* Module dependencies
*/
var url = require('url')
var revalidator = require('revalidator')
var settings = require('../boot/settings')
var mailer = require('../boot/mailer').getMailer()
var User = require('../models/User')
var OneTimeToken = require('../models/OneTimeToken')
var PasswordsDisabledError = require('../errors/PasswordsDisabledError')
/**
* Account Recovery
*
* Recovery flow:
*
* 1. Accept user e-mail
* 2. Validate input as valid e-mail, display error if not
* 3. Verify user account exists with specified e-mail
* 4. If user account exists, issue token and send e-mail
* 5. Regardless of success/failure, direct user to emailSent view
*
* Password reset flow:
*
* 1. When user clicks on link, verify token exists and is for pw reset
* 2. Direct user to resetPassword view
* 3. Verify password fulfills password strength requirements
* 4. If error, re-display resetPassword view, but with error message
* 5. Update user object and revoke token
* 6. Send user an e-mail notifying them that their password was changed
* 7. Direct user to passwordReset view
*
* Default expiry time for tokens is 1 day
*/
function verifyPasswordsEnabled (req, res, next) {
if (!settings.providers.password) {
return next(new PasswordsDisabledError())
} else {
return next()
}
}
function verifyMailerConfigured (req, res, next) {
if (!mailer.transport) {
return next(new Error('Mailer not configured.'))
} else {
return next()
}
}
function verifyPasswordResetToken (req, res, next) {
if (!req.query.token) {
return res.render('recovery/resetPassword', {
error: 'Invalid reset code.'
})
}
OneTimeToken.peek(req.query.token, function (err, token) {
if (err) { return next(err) }
if (!token || token.use !== 'resetPassword') {
return res.render('recovery/resetPassword', {
error: 'Invalid reset code.'
})
}
req.passwordResetToken = token
next()
})
}
module.exports = function (server) {
server.get('/recovery',
verifyPasswordsEnabled,
verifyMailerConfigured,
function (req, res, next) {
res.render('recovery/start')
}
)
server.post('/recovery',
verifyPasswordsEnabled,
verifyMailerConfigured,
function (req, res, next) {
if (
!req.body.email ||
!revalidator.validate.formats.email.test(req.body.email)
) {
return res.render('recovery/start', {
error: 'Please enter a valid e-mail address.'
})
}
User.getByEmail(req.body.email, function (err, user) {
if (err) { return next(err) }
if (!user) { return res.render('recovery/emailSent') }
OneTimeToken.issue({
sub: user._id,
ttl: 3600 * 24, // 1 day
use: 'resetPassword'
}, function (err, token) {
if (err) { return next(err) }
var resetPasswordURL = url.parse(settings.issuer)
resetPasswordURL.pathname = 'resetPassword'
resetPasswordURL.query = { token: token._id }
mailer.sendMail('resetPassword', {
email: user.email,
resetPasswordURL: url.format(resetPasswordURL)
}, {
to: user.email,
subject: 'Reset your password'
}, function (err, responseStatus) {
if (err) { }
// TODO: REQUIRES REFACTOR TO MAIL QUEUE
res.render('recovery/emailSent')
})
})
})
}
)
server.get('/resetPassword',
verifyPasswordsEnabled,
verifyMailerConfigured,
verifyPasswordResetToken,
function (req, res, next) {
res.render('recovery/resetPassword')
}
)
server.post('/resetPassword',
verifyPasswordsEnabled,
verifyMailerConfigured,
verifyPasswordResetToken,
function (req, res, next) {
var uid = req.passwordResetToken.sub
if (req.body.password !== req.body.confirmPassword) {
return res.render('recovery/resetPassword', {
validationError: 'Passwords do not match.'
})
}
User.changePassword(uid, req.body.password, function (err, user) {
if (err && (
err.name === 'PasswordRequiredError' ||
err.name === 'InsecurePasswordError'
)) {
return res.render('recovery/resetPassword', {
validationError: err.message
})
}
if (err) { return next(err) }
OneTimeToken.revoke(req.passwordResetToken._id, function (err) {
if (err) { return next(err) }
var recoveryURL = url.parse(settings.issuer)
recoveryURL.pathname = 'recovery'
mailer.sendMail('passwordChanged', {
email: user.email,
recoveryURL: url.format(recoveryURL)
}, {
to: user.email,
subject: 'Your password has been changed'
}, function (err, responseStatus) {
if (err) { }
// TODO: REQUIRES REFACTOR TO MAIL QUEUE
res.render('recovery/passwordReset')
})
})
})
}
)
}
|
/**
*
* Controller Menu
*
*/
Ext.define('App.controller.cMenu', {
extend: 'Ext.app.Controller',
models: [
"App.model.menu.Root",
'App.model.menu.Item',
'App.model.menu.menus',
'App.model.menu.menusItem',
'App.model.menu.menuEditor'
],
stores: [
'App.store.Menu',
'App.store.menu.menus'
],
views: [
'App.view.security.UsersList',
'App.view.menu.Accordion',
'App.view.menu.Item',
'App.view.menu.menus',
'App.view.menu.vMenuEditor'
],
refs: [
{ref: 'mainPanel', selector: 'mainpanel'},
{ref: 'devmainPanel', selector: 'devmainpanel'},
{ref: 'mainMenus', selector: 'mainmenus'},
{ref: 'gridMenu', selector: 'vMenuEditor grid#gridMenu'},
{ ref: 'formMenu', selector: 'vMenuEditor form#formEditor'},
{ ref: 'toolRefresh', selector: 'mainmenu tool#refresh'}
],
init: function (application) {
var me = this;
me.control({
/**
* Render Main Menu
*
* @at region West
*/
"mainmenu": {
render: me.onPanelRender
},
/**
* Saat Refresh pada Main Menu
* @region West
* */
'mainmenu tool#refresh': { click: me.refresh_data_menu },
/**
* Generate Main Menu Item
*/
"mainmenuitem": {
/**
* Saat Select
*/
select: me.onTreepanelSelect,
/*Saat di click */
itemclick: me.onTreepanelItemClick
},
/**
* Edit Menu
*/
"vMenuEditor grid#gridMenu": {
selectionchange: me.selectMenuChange
},
/**
* Simpan Menu Form Edit
*/
'vMenuEditor form#formEditor toolbar #save': { click: me.onSave_FormMenu }
});
log('Menu');
},
refresh_data_menu: function (btn) {
// this.getMenuStore().removeAll(true);
// this.getMenuStore().load();
this.onPanelRender();
},
/**
* Saat Pemilihan Menu Pada Grid Menu Editor
* @param grid
* @param sels
*/
selectMenuChange: function (grid, sels) {
var me = this, rec = sels[0];
me.getFormMenu().down('[name=id]').setReadOnly(true);
me.getFormMenu().loadRecord(sels[0]);
},
/**
* Saat Simpan Form yang sudah diedit
* @param btn
*/
onSave_FormMenu: function (btn) {
var me = this, f = btn.up('form#formEditor'),
val = f.getValues(), rec = f.getRecord(),
m = Ext.ModelManager.getModel('App.model.menu.menuEditor');
log(m);
},
// onTreepanelItemClickMainMenus: function (treepanel, record, item, index, e, eOpts) {
// var tp = Ext.ComponentQuery.query('mainmenus')[0];
// log('treepanel component ', treepanel);
// log('record ', record);
// // log('item ', item);
// log('index ', index);
// log('Get Depth Record', record.get('depth'));
//
// var sm = treepanel.getSelectionModel();
// if (sm.hasSelection()) {
// selectedRoot = sm.getSelection()[0];
// }
// ;
//
// log('Selected Root : ', selectedRoot);
// var id = record.get('id');
//
// if (typeof id == 'undefined') return false;
// if (typeof selectedRoot == 'undefined') return false;
//
// log('Selected ID : ', selectedRoot.get('id'));
// log('Selected depth : ', selectedRoot.get('depth'));
// if (selectedRoot.get('depth') == '2') {
// log('im depth 2 bray');
// var parentId = selectedRoot.parentNode.get('index'),
// childId = selectedRoot.get('index');
// // return;
// }
//
//// log('Parent ID : ', selectedRoot.get('parentId'));
//// log('Parent Index : ', selectedRoot.parentNode.get('index'));
//
// // var item = Ext.ModelManager.getModel('App.model.menu.menusItem');
// var item = Ext.ModelManager.getModel('App.model.menu.menus');
// item.load(id, {success: function (items) {
// Ext.each(items.children(), function (a) {
// Ext.each(a.data.items, function (b, c) {
// var textC = b.get('text');
// var hasCreated = selectedRoot.findChild('id', b.get('id'));
// if (hasCreated == null) {
// var i = Ext.create('App.model.menu.menus', {
// text: b.get('text'),
// leaf: b.get('leaf') || true,
// iconCls: b.get('iconCls'),
// id: b.get('id'),
// className: b.get('className')
// });
// selectedRoot.appendChild(i);
// }
// ;
// })
// })
//
// }, failure: function (o) {
// msgError('Error Loading Menu ');
// }
// });
// tp.getView().refresh();
// selectedRoot.expand();
// },
/**
* Saat Render Panel Menu
* @param abstractcomponent
* @param options
*/
onPanelRender: function (abstractcomponent, options) {
var me = this;
me.getAppStoreMenuStore().load(function (records, op, success) {
var menuPanel = Ext.ComponentQuery.query('mainmenu')[0];
menuPanel.removeAll();
Ext.each(records, function (root) {
var menu = Ext.create('App.view.menu.Item', {
title: root.get('text'),
iconCls: root.get('iconCls')
});
Ext.each(root.items(), function (itens) {
Ext.each(itens.data.items, function (item) {
menu.getRootNode().appendChild({
// text: translations[item.get('text')],
text: item.get('text'),
text: translations[item.get('text')] || item.get('text'),
leaf: true,
iconCls: item.get('iconCls'),
id: item.get('id'),
className: item.get('className')
});
});
});
menuPanel.add(menu);
});
});
},
onTreepanelSelect: function (selModel, record, index, options) {
var mainPanel = this.getMainPanel();
if (!mainPanel){
mainPanel = this.getDevmainPanel();
}
var newTab = mainPanel.items.findBy(
function (tab) {
return tab.title === record.get('text');
});
if (!newTab) {
newTab = mainPanel.add({
xtype: record.raw.className,
closable: true,
iconCls: record.get('iconCls'),
title: record.get('text')
});
}
mainPanel.setActiveTab(newTab);
},
onTreepanelItemClick: function (view, record, item, index, event, options) {
// log('onTreepanelItemClick Exe');
this.onTreepanelSelect(view, record, index, options);
}
}); |
export default function() {
this.namespace = '/api';
}
export function testConfig() {
this.get('/foos');
this.get('/foos/:id');
this.get('/bars');
this.get('/bars/:id');
this.get('/bazs');
this.get('/bazs/:id');
this.get('/multis');
this.get('/multis/:id');
this.get('/foo-fixes');
this.get('/foo-fixes/:id');
this.get('/foo-bars');
this.get('/foo-bars/:id');
this.get('/foo-empties');
this.get('/foo-empties/:id');
this.get('/foo-cycles');
this.get('/foo-cycles/:id');
this.get('/foo-transforms');
this.get('/foo-transforms/:id');
this.get('/foo-fragment-holders');
this.get('/foo-fragment-holders/:id');
}
|
var co = require("co");
var config = require("../config")("local");
var dbWrap = require("../lib/dbWrap.js");
var chunks = dbWrap.getCollection(config.mongoUrl, "chunks");
module.exports.chunks = chunks;
module.exports.removeAllDocs = function(done){
co(function *(){
yield chunks.remove({});
})(done);
};
var app = require("../app.js");
module.exports.request = require("supertest").agent(app.listen());
module.exports.testUser = config.user; |
export function hello () {
console.log("Hello from a.js");
}; |
import angular from 'angular';
import {
characters
} from './characters';
export const charactersModule = 'characters';
angular
.module(charactersModule, [])
.component('characters', characters);
|
const { task, series, src, dest } = require('gulp');
const rev = require('gulp-rev');
const revReplace = require('gulp-rev-replace');
task('revision', () =>
src(['dist/**/app.js', 'dist/**/*.css'])
.pipe(rev())
.pipe(dest('dist'))
.pipe(rev.manifest())
.pipe(dest('dist'))
);
task('set-revisions', series('revision', () => {
const manifest = src('dist/rev-manifest.json');
return src('dist/index.html')
.pipe(revReplace({ manifest }))
.pipe(dest('dist'));
}));
|
angular.module('ifocus.status')
.factory('StatusService', ['$http', 'baseUrl', function ($http, baseUrl) {
return {
getSessionDistributionByDate: function (date) {
return $http.get(baseUrl + 'overview/distribution/' + date);
},
getOverviewStatusNumbers: function (date) {
return $http.get(baseUrl + 'overview/status/' + date);
},
//Add click distribution by date
getClickDistributionByDate: function (date) {
return $http.get(baseUrl + 'overview/status/clicks/' + date);
},
//Add throughput numbers
getThroughputNumbers: function (date) {
return $http.get(baseUrl + 'overview/status/thruput/' + date);
},
//Add status list
getStatusList: function (date) {
return $http.get(baseUrl + 'overview/status/list/' + date);
},
getRefererSearchEngines: function () {
return $http.get(baseUrl + 'overview/sessions/sources/se');
},
getCountriesDistribution: function () {
return $http.get(baseUrl + 'overview/sessions/sources/countries');
},
getFrequentCategories: function () {
return $http.get(baseUrl + 'overview/sessions/frequent/categories');
},
getFrequentPages: function () {
return $http.get(baseUrl + "overview/sessions/frequent/pages");
},
getFrequentPagesByCategory: function (category) {
return $http.get(baseUrl + "overview/sessions/frequent/" + category);
},
getMainLandingCategories: function () {
return $http.get(baseUrl + 'overview/sessions/landings/categories');
},
getMainDropOffCategories: function () {
return $http.get(baseUrl + 'overview/sessions/dropoff/categories');
}
};
}]); |
const assert = require('assert'),
underTest = require("../10/10"),
[bots, values, outputs, Bot, Value] = [underTest.bots, underTest.values, underTest.outputs, underTest.Bot, underTest.Value];
describe('10', () => {
describe('define 3 bots and 2 values', function() {
new Bot('bot 0 gives low to bot 1 and high to bot 1');
new Bot('bot 1 gives low to bot 2 and high to bot 2');
new Bot('bot 2 gives low to output 0 and high to output 1');
new Value('value 1 goes to bot 0').push();
new Value('value 2 goes to bot 0').push();
it('outputs should be [1,2]', () => {
assert.deepEqual([1,2], outputs);
});
});
}); |
// COPYRIGHT ยฉ 2017 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/4.4/esri/copyright.txt for details.
define({title:"Mijn locatie zoeken"}); |
<html>
<script language='javascript'>
/*
includes/reloadParent.js
YeAPF 0.8.58-13 built on 2017-05-30 11:50 (-3 DST)
Copyright (C) 2004-2017 Esteban Daniel Dortta - dortta@yahoo.com
2012-08-14 11:43:36 (-3 DST)
*/
function recarregar()
{
var id=new String('#campo(id)');
var rnd=Math.random()*1000;
var s=new String(window.opener.location);
rnd=Math.round(rnd);
var p=s.search('rnd=');
if (p>0)
s=s.slice(0,p-1);
p=s.search('#');
if (p>0)
s=s.slice(0,p);
s=s+'&rnd='+rnd;
s=s+'#'+id;
window.opener.location.replace(s);
window.close();
}
</script>
<body onLoad='recarregar()'>
</body>
</html>
|
'use strict';
var Container = function () {
this._dockerContainer = null;
};
Container.prototype = {
init: function (container) {
this._dockerContainer = container;
},
start: function (opts, done) {
this._dockerContainer.start(opts, done);
},
kill: function (done) {
this._dockerContainer.kill(done);
},
remove: function (done) {
this._dockerContainer.remove(done);
},
restart: function (done) {
this._dockerContainer.restart(done);
},
getStream: function (done) {
this._getStreamInternal({stream: true, stdin: true, stdout: true, stderr: true, tty: false}, done);
},
getReadStream: function (done) {
this._getStreamInternal({stream: true, stdout: true, stderr: true, tty: false}, done);
},
demuxStream: function (stream, stdout, stderr) {
this._dockerContainer.modem.demuxStream(stream, stdout, stderr);
},
_getStreamInternal: function (opts, done) {
this._dockerContainer.attach(opts, done);
},
wait: function (done) {
this._dockerContainer.wait(done);
},
inspect: function (done) {
this._dockerContainer.inspect(done);
},
logs: function (opts, done) {
this._dockerContainer.logs(opts, done);
}
};
module.exports = Container; |
var TILE_SIZE = 32;
var SCREEN_WIDTH = 320;
var SCREEN_HEIGHT = 240;
// http://stackoverflow.com/a/9071606/2038264
function choose(choices) {
var index = Math.floor(Math.random() * choices.length);
return choices[index];
}
|
var conf = require('../app.json');
exports.getDocumentation = function(req, res, next){
res.header('Location', conf.documentation.url);
res.send(308, 'Redirecting to the Roomies API Documentation');
return next();
};
exports.getConf = function(req, res, next){
res.send(conf);
return next();
};
exports.methodNotAllowed = function(req, res, next) {
res.send(405, {error: true, message: 'Method not allowed.'});
return next();
};
exports.redirectToRootAPI = function (app) {
return function(req, res, next){
res.header('Location', app.url + '/api');
res.send(302, 'Redirection to /api');
return next();
};
};
exports.apiMethodsList = function(req, res, next) {
res.json([
'GET /',
'GET /api',
'GET /api/docs',
'GET /api/roomies',
'POST /api/roomies',
'DELETE /api/roomies',
'GET /api/roomies/:uuid',
'PUT /api/roomies/:uuid',
'DELETE /api/roomies/:uuid'
]);
return next();
};
exports.authenticate = function(req, res, next) {
var credentials;
try {
credentials = req.headers.authorization.split(':');
} catch (e) {
return res.send(400, {error: true, message: 'Error parsing credentials, recevied "' + req.headers.authorization + '"'});
}
var username = credentials[0];
var password = credentials[1];
if(!username) {
return res.send(400, {error: true, message: 'Error parsing credentials : username missing'});
}
if(!password) {
return res.send(400, {error: true, message: 'Error parsing credentials : password missing'});
}
req.models.Roomy
.find({
where: {username: username},
include: [req.models.Collocation]
})
.on('success', function(roomy) {
if(!roomy) {
return res.send(404, {error: true, message: 'Roomy not found'});
}
if(!roomy.checkPassword(password)) {
return res.send(400, {error: true, message: 'Wrong credentials'});
}
// Success
return res.send(200, {error: false, message: roomy});
});
};
|
/* flash_team_update.js
* ---------------------------------
*
*/
function updateJSONFormField() {
$('#flash_team_json').val(JSON.stringify(flashTeamsJSON));
};
$('.edit_flash_team').submit(function(e) {
e.preventDefault();
var valuesToSubmit = $(this).serialize();
$.ajax({
type: 'POST',
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
})
.success(function(json){
console.log("submit succeded");
});
return false; // prevents normal behaviour
});
$("#flashTeamSaveBtn").click(function() {
updateJSONFormField();
$('.edit_flash_team').submit();
}); |
const querystring = require('querystring');
module.exports = function(getRequest, apiKey) {
return {
/**
* Returns the ABI/Interface of a given contract
* @param {string} address - Contract address
* @example
* api.contract
* .getabi('0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359')
* .at('0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359')
* .memberId('0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359')
* .then(console.log)
* @returns {Promise.<object>}
*/
getabi(address) {
const module = 'contract';
const action = 'getabi';
var query = querystring.stringify({
module, action, address, apiKey
});
return getRequest(query);
}
};
};
|
module.exports = Explicit;
var DONE = false;
function Explicit() {}
Explicit.prototype.asyncStart = function($happn, opts, optionalOpts, callback) {
if (typeof callback === 'undefined') callback = optionalOpts;
setTimeout(function() {
DONE = true;
callback(null);
}, 200);
};
Explicit.prototype.asyncStartFails = function(callback) {
callback(new Error('erm'));
};
Explicit.prototype.methodName1 = function(opts, blob, callback) {
if (typeof blob === 'function') callback = blob;
callback(null, { yip: 'eee' });
};
if (global.TESTING_16) return; // When 'requiring' the module above,
var should = require('chai').should();
var mesh;
var anotherMesh;
var Mesh = require('../../..');
describe(
require('../../__fixtures/utils/test_helper')
.create()
.testName(__filename, 3),
function() {
this.timeout(120000);
before(function(done) {
global.TESTING_16 = true; //.............
mesh = this.mesh = new Mesh();
mesh.initialize(
{
util: {
// logLevel: 'error'
},
happn: {
port: 8001
},
modules: {
expliCit: {
path: __filename
}
},
components: {
explicit: {
moduleName: 'expliCit',
startMethod: 'asyncStart',
schema: {
exclusive: true,
methods: {
asyncStart: {
type: 'async',
parameters: [
{ name: 'opts', required: true, value: { op: 'tions' } },
{ name: 'optionalOpts', required: false },
{ type: 'callback', required: true }
],
callback: {
parameters: [{ type: 'error' }]
}
},
methodName1: {
// alias: 'm1',
parameters: [
{ name: 'opts', required: true, value: { op: 'tions' } },
{ name: 'blob', required: false },
{ type: 'callback', required: true }
]
}
}
}
}
}
},
function(err) {
if (err) return done(err);
mesh.start(function(err) {
if (err) {
//eslint-disable-next-line
console.log(err.stack);
return done(err);
}
return done();
});
}
);
});
after(function(done) {
delete global.TESTING_16; //.............
mesh.stop({ reconnect: false }, function(e) {
if (e) return done(e);
anotherMesh.stop({ reconnect: false }, done);
});
});
it('has called and finished the component async start method', function(done) {
DONE.should.eql(true);
done();
});
it('has called back with error into the mesh start callback because the component start failed', function(done) {
anotherMesh = new Mesh();
anotherMesh.initialize(
{
util: {
logger: {}
},
happn: {
port: 8002
},
modules: {
expliCit: {
path: __filename
}
},
components: {
explicit: {
moduleName: 'expliCit',
startMethod: 'asyncStartFails',
schema: {
methods: {
asyncStartFails: {
type: 'async',
parameters: [{ type: 'callback', required: true }],
callback: {
parameters: [{ type: 'error' }]
}
}
}
}
}
}
},
function(err) {
if (err) return done(err);
anotherMesh.start(function(err) {
should.exist(err);
done();
});
}
);
});
xit('validates methods', function(done) {
this.mesh.api.exchange.explicit.methodName1({ op: 'tions3' }, function(err, res) {
res.should.be.an.instanceof(Error);
done();
});
});
}
);
|
import React, { Component } from 'react';
import './WordList.css';
/**
* WordList is to display the list of unique words that are
* being used in the application.
*/
class WordList extends Component {
/**
* Render the word object
*/
renderWordObject(i) {
const toggleText = i.inReadingList === 1 ? 'hide': 'show';
return (
<div key={i.id} className='WordItem'>
<span>{i.arabicScript}</span>
<div>
<button className='word-button' onClick={e => this.props.toggleVisibility(i)}>{toggleText}</button>
<button className='word-button' onClick={e => this.props.removeWord(i.id)}>remove</button>
</div>
</div>
);
}
/**
* Render method to display the list of vocabulary words
*/
render() {
// Create list of words sorted by id
let words = this.props.words.sort((a, b) => {
return a.id - b.id;
}).map(word => this.renderWordObject(word));
return (
<div className='word-list' style={{fontSize: this.props.fontSize + 'px'}}>
{words}
</div>
);
}
}
export default WordList;
|
'use strict';
// app.js ์๋ฒ ์ดํ๋ฆฌ์ผ์ด์
์์ ES6 ๋ฌธ๋ฒ์ ์ฌ์ฉํ๊ธฐ์ํ ํธ์ถํ์ผ
require('babel-register');
require('./app.js'); |
var gulp = require('gulp');
var gsplit = require('../index');
var del = require('del');
gulp.task('clean', function(cb) {
del(['tmp'], cb);
});
gulp.task('compress', ['clean'], function() {
gulp.src('file.txt')
.pipe(gsplit({
prefix: 'resource_',
ext: 'txt',
count: 3
}))
.pipe(gulp.dest('tmp'));
});
gulp.task('default', ['compress']); |
var qs = require('querystring');
exports.requestToken = {
request: {
method: 'POST',
url: 'https://api.twitter.com/oauth/request_token',
},
oauth: {
consumerKey: 'GDdmIQH6jhtmLUypg82g',
consumerSecret: 'MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98',
nonce: 'QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk',
signatureMethod: 'HMAC-SHA1',
timestamp: '1272323042',
version: '1.0',
callback: 'http://localhost:3005/the_dance/process_callback?service_provider_id=11'
},
expected: {
basestring: 'POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252Flocalhost%253A3005%252Fthe_dance%252Fprocess_callback%253Fservice_provider_id%253D11%26oauth_consumer_key%3DGDdmIQH6jhtmLUypg82g%26oauth_nonce%3DQP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1272323042%26oauth_version%3D1.0',
signature: '8wUi7m5HFQy76nowoCThusfgB+Q='
}
};
exports.accessToken = {
request: {
method: 'POST',
url: 'https://api.twitter.com/oauth/access_token',
},
oauth: {
consumerKey: 'GDdmIQH6jhtmLUypg82g',
consumerSecret: 'MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98',
token: '8ldIZyxQeVrFZXFOZH5tAwj6vzJYuLQpl0WUEYtWc',
tokenSecret: 'x6qpRnlEmW9JbQn4PQVVeVG8ZLPEx6A0TOebgwcuA',
nonce: '9zWH6qe0qG7Lc1telCn7FhUbLyVdjEaL3MO5uHxn8',
signatureMethod: 'HMAC-SHA1',
timestamp: '1272323047',
version: '1.0',
verifier: 'pDNg57prOHapMbhv25RNf75lVRd6JDsni1AJJIDYoTY'
},
expected: {
basestring: 'POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Faccess_token&oauth_consumer_key%3DGDdmIQH6jhtmLUypg82g%26oauth_nonce%3D9zWH6qe0qG7Lc1telCn7FhUbLyVdjEaL3MO5uHxn8%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1272323047%26oauth_token%3D8ldIZyxQeVrFZXFOZH5tAwj6vzJYuLQpl0WUEYtWc%26oauth_verifier%3DpDNg57prOHapMbhv25RNf75lVRd6JDsni1AJJIDYoTY%26oauth_version%3D1.0',
signature: 'PUw/dHA4fnlJYM6RhXk5IU/0fCc='
}
};
exports.statusUpdate = {
request: {
method: 'POST',
url: 'http://api.twitter.com/1/statuses/update.json',
body: qs.stringify({ status: 'setting up my twitter ็งใฎใใใใใ่จญๅฎใใ' }),
},
oauth: {
consumerKey: 'GDdmIQH6jhtmLUypg82g',
consumerSecret: 'MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98',
token: '819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw',
tokenSecret: 'J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA',
nonce: 'oElnnMTQIZvqvlfXM56aBLAf5noGD0AQR3Fmi7Q6Y',
signatureMethod: 'HMAC-SHA1',
timestamp: '1272325550',
version: '1.0',
},
expected: {
basestring: 'POST&http%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&oauth_consumer_key%3DGDdmIQH6jhtmLUypg82g%26oauth_nonce%3DoElnnMTQIZvqvlfXM56aBLAf5noGD0AQR3Fmi7Q6Y%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1272325550%26oauth_token%3D819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw%26oauth_version%3D1.0%26status%3Dsetting%2520up%2520my%2520twitter%2520%25E7%25A7%2581%25E3%2581%25AE%25E3%2581%2595%25E3%2581%2588%25E3%2581%259A%25E3%2582%258A%25E3%2582%2592%25E8%25A8%25AD%25E5%25AE%259A%25E3%2581%2599%25E3%2582%258B',
signature: 'yOahq5m0YjDDjfjxHaXEsW9D+X0='
}
};
|
const Customer = require('./customer')
class Order {
constructor(customerName) {
this._customer = Customer.getNamed(customerName)
}
getCustomerName() {
return this._customer.getName()
}
}
module.exports = Order
|
import joinUri from "join-uri"
const baseUrl = "http://daynhauhoc.com/"
export const postIdToUrl = (id) => joinUri(baseUrl, "t", id.toString())
|
'use strict';
const namespace = require('hapi-namespace');
module.exports = namespace('/api',
[
{
method: 'GET',
path: '/health',
handler: function (request, reply) {
reply('Alive!');
}
},
]
);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.