language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript
|
class McDatepicker {
constructor(overlay, ngZone, viewContainerRef, scrollStrategy, dateAdapter, dir, document) {
this.overlay = overlay;
this.ngZone = ngZone;
this.viewContainerRef = viewContainerRef;
this.dateAdapter = dateAdapter;
this.dir = dir;
this.document = document;
this._hasBackdrop = false;
this._opened = false;
/** The view that the calendar should start in. */
this.startView = McCalendarView.Month;
/**
* Emits selected year in multiyear view.
* This doesn't imply a change on the selected date.
*/
this.yearSelected = new EventEmitter();
/**
* Emits selected month in year view.
* This doesn't imply a change on the selected date.
*/
this.monthSelected = new EventEmitter();
this.backdropClass = 'cdk-overlay-transparent-backdrop';
/** Emits when the datepicker has been opened. */
this.openedStream = new EventEmitter();
/** Emits when the datepicker has been closed. */
this.closedStream = new EventEmitter();
/** The id for the datepicker calendar. */
this.id = `mc-datepicker-${datepickerUid++}`;
this.stateChanges = new Subject();
/** Emits when the datepicker is disabled. */
this.disabledChange = new Subject();
/** Emits new selected date when selected date changes. */
this.selectedChanged = new Subject();
this.validSelected = null;
/** The element that was focused before the datepicker was opened. */
this.focusedElementBeforeOpen = null;
/** Subscription to value changes in the associated input element. */
this.inputSubscription = Subscription.EMPTY;
this.closeSubscription = Subscription.EMPTY;
if (!this.dateAdapter) {
throw createMissingDateImplError('DateAdapter');
}
this.scrollStrategy = scrollStrategy;
}
get hasBackdrop() {
return this._hasBackdrop;
}
set hasBackdrop(value) {
this._hasBackdrop = coerceBooleanProperty(value);
}
/** The date to open the calendar to initially. */
get startAt() {
// If an explicit startAt is set we start there, otherwise we start at whatever the currently
// selected value is.
return this._startAt || (this.datepickerInput ? this.datepickerInput.value : null);
}
set startAt(value) {
this._startAt = this.getValidDateOrNull(this.dateAdapter.deserialize(value));
}
/** Whether the datepicker pop-up should be disabled. */
get disabled() {
return this._disabled === undefined && this.datepickerInput ? this.datepickerInput.disabled : this._disabled;
}
set disabled(value) {
const newValue = coerceBooleanProperty(value);
if (newValue !== this._disabled) {
this._disabled = newValue;
this.disabledChange.next(newValue);
}
}
/** Whether the calendar is open. */
get opened() {
return this._opened;
}
set opened(value) {
coerceBooleanProperty(value) ? this.open() : this.close();
}
/** The currently selected date. */
get selected() {
return this.validSelected;
}
set selected(value) {
this.validSelected = value;
}
/** The minimum selectable date. */
get minDate() {
return this.datepickerInput && this.datepickerInput.min;
}
/** The maximum selectable date. */
get maxDate() {
return this.datepickerInput && this.datepickerInput.max;
}
get dateFilter() {
return this.datepickerInput && this.datepickerInput.dateFilter;
}
get value() {
return this.selected;
}
ngOnDestroy() {
this.close();
this.inputSubscription.unsubscribe();
this.closeSubscription.unsubscribe();
this.disabledChange.complete();
this.destroyOverlay();
}
/** Selects the given date */
select(date) {
const oldValue = this.selected;
this.selected = date;
if (!this.dateAdapter.sameDate(oldValue, this.selected)) {
this.selectedChanged.next(date);
}
}
/** Emits the selected year in multiyear view */
selectYear(normalizedYear) {
this.yearSelected.emit(normalizedYear);
}
/** Emits selected month in year view */
selectMonth(normalizedMonth) {
this.monthSelected.emit(normalizedMonth);
}
/**
* Register an input with this datepicker.
* @param input The datepicker input to register with this datepicker.
*/
registerInput(input) {
if (this.datepickerInput) {
throw Error('A McDatepicker can only be associated with a single input.');
}
this.datepickerInput = input;
this.inputSubscription = this.datepickerInput.valueChange
.subscribe((value) => {
var _a;
this.selected = value;
if (this.popupComponentRef) {
(_a = this.popupComponentRef.instance.calendar.monthView) === null || _a === void 0 ? void 0 : _a.init();
this.popupComponentRef.instance.calendar.activeDate = value;
}
});
}
/** Open the calendar. */
open() {
if (this._opened || this.disabled) {
return;
}
if (!this.datepickerInput) {
throw Error('Attempted to open an McDatepicker with no associated input.');
}
if (this.document) {
this.focusedElementBeforeOpen = this.document.activeElement;
}
this.openAsPopup();
this._opened = true;
this.openedStream.emit();
}
/** Close the calendar. */
close(restoreFocus = true) {
if (!this._opened) {
return;
}
if (this.popupComponentRef) {
const instance = this.popupComponentRef.instance;
instance.startExitAnimation();
instance.animationDone
.pipe(take(1))
.subscribe(() => this.destroyOverlay());
}
if (restoreFocus) {
this.focusedElementBeforeOpen.focus();
}
this._opened = false;
this.closedStream.emit();
this.focusedElementBeforeOpen = null;
}
toggle() {
if (this.datepickerInput.isReadOnly) {
return;
}
this._opened ? this.close() : this.open();
}
/** Destroys the current overlay. */
destroyOverlay() {
if (this.popupRef) {
this.popupRef.dispose();
this.popupRef = this.popupComponentRef = null;
}
}
/** Open the calendar as a popup. */
openAsPopup() {
if (!this.calendarPortal) {
this.calendarPortal = new ComponentPortal(McDatepickerContent, this.viewContainerRef);
}
if (!this.popupRef) {
this.createPopup();
}
if (!this.popupRef.hasAttached()) {
this.popupComponentRef = this.popupRef.attach(this.calendarPortal);
this.popupComponentRef.instance.datepicker = this;
// Update the position once the calendar has rendered.
this.ngZone.onStable.asObservable()
.pipe(take(1))
.subscribe(() => this.popupRef.updatePosition());
}
}
/** Create the popup. */
createPopup() {
const overlayConfig = new OverlayConfig({
positionStrategy: this.createPopupPositionStrategy(),
hasBackdrop: this.hasBackdrop,
backdropClass: this.backdropClass,
direction: this.dir,
scrollStrategy: this.scrollStrategy(),
panelClass: 'mc-datepicker__popup'
});
this.popupRef = this.overlay.create(overlayConfig);
this.closeSubscription = this.closingActions()
.subscribe(() => this.close(this.restoreFocus()));
}
restoreFocus() {
return this.document.activeElement === this.document.body;
}
closingActions() {
return merge(this.popupRef.backdropClick(), this.popupRef.outsidePointerEvents(), this.popupRef.detachments());
}
/** Create the popup PositionStrategy. */
createPopupPositionStrategy() {
return this.overlay.position()
.flexibleConnectedTo(this.datepickerInput.elementRef)
.withTransformOriginOn('.mc-datepicker__content')
.withFlexibleDimensions(false)
.withViewportMargin(8)
.withLockedPosition()
.withPositions([
{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top'
},
{
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'bottom'
},
{
originX: 'end',
originY: 'bottom',
overlayX: 'end',
overlayY: 'top'
},
{
originX: 'end',
originY: 'top',
overlayX: 'end',
overlayY: 'bottom'
}
]);
}
/**
* @param obj The object to check.
* @returns The given object if it is both a date instance and valid, otherwise null.
*/
getValidDateOrNull(obj) {
return (this.dateAdapter.isDateInstance(obj) && this.dateAdapter.isValid(obj)) ? obj : null;
}
}
|
JavaScript
|
class Register extends Component {
constructor(props) {
super(props);
this.state = {
firstName: "",
lastName: "",
email: "",
password: "",
confirmPassword: "",
errors: {},
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleGoogleLogin = this.handleGoogleLogin.bind(this);
}
componentDidMount() {
if (this.props.auth.isAuthenticated) {
this.props.history.push("/dashboard");
}
}
componentWillUnmount() {
this.props.clearErrors();
}
handleInputChange(event) {
const target = event.target;
const name = target.name;
const value = target.value;
this.setState({
[name]: value,
});
}
handleSubmit(event) {
event.preventDefault();
const newUser = {
firstName: this.state.firstName,
lastName: this.state.lastName,
email: this.state.email,
password: this.state.password,
confirmPassword: this.state.confirmPassword,
};
this.props.registerUser(newUser).then(() => {
if (this.props.auth.register_status === "succeeded") {
this.props.history.push("/login");
}
});
}
handleGoogleLogin(response) {
if (response.error === undefined) {
this.props.authenticateWithGoogle(response.tokenId).then(() => {
if (this.props.auth.login_status === "succeeded") {
this.props.history.push("/dashboard");
}
});
}
}
render() {
const errors = this.props.auth ? this.props.auth.errors : {};
return (
<div className="row">
<div className="col-md-6 mx-auto">
<div className="card card--login-and-register-modal-adjustment">
<div className="card-body">
<h1 className="card-title pb-4">Create an account</h1>
<form onSubmit={this.handleSubmit}>
<InputFormGroup
htmlFor="firstName"
label="First name"
name="firstName"
type="text"
error={errors.firstName}
value={this.state.fistName}
onChange={this.handleInputChange}
/>
<InputFormGroup
htmlFor="lastName"
label="Last name"
name="lastName"
type="text"
error={errors.lastName}
value={this.state.lastName}
onChange={this.handleInputChange}
/>
<InputFormGroup
htmlFor="email"
label="Email address"
name="email"
type="email"
error={errors.email}
value={this.state.email}
onChange={this.handleInputChange}
/>
<InputFormGroup
htmlFor="password"
label="Password"
name="password"
type="password"
error={errors.password}
value={this.state.password}
onChange={this.handleInputChange}
info="Use 8 or more characters with at least one uppercase letter, one lowercase letter, one number, and one symbol"
hideInfoOnError={true}
/>
<InputFormGroup
htmlFor="confirmPassword"
label="Confirm password"
name="confirmPassword"
type="password"
error={errors.confirmPassword}
value={this.state.confirmPassword}
onChange={this.handleInputChange}
/>
<button
type="submit"
className="btn btn-primary float-right mt-3 mb-3"
>
Sign up with email
</button>
</form>
<div className="clear">
<div className="row">
<div className="col">
<hr></hr>
</div>
<div className="col-auto">Or</div>
<div className="col">
<hr></hr>
</div>
</div>
<GoogleLogin
clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID}
render={(renderProps) => (
<button
onClick={renderProps.onClick}
className="btn btn-secondary btn-block mt-3 mb-3"
>
<i className="fab fa-google mr-2"></i> Continue with
Google
</button>
)}
buttonText="Sign up with Google"
onSuccess={this.handleGoogleLogin}
onFailure={this.handleGoogleLogin}
/>
<h2 className="sign-up-prompt pt-2">
Already have an account?{" "}
<Link
to="/login"
className="a--default-style-removed text-decoraction-none"
>
Sign in
</Link>
</h2>
</div>
</div>
</div>
</div>
</div>
);
}
}
|
JavaScript
|
class ListSelect extends React.Component {
/**
* object_list: [ {str:'display string',sort:'var by which to sort', id:'id of object',other_keys...}]
* Props should send api_url (url to get objects from)
* @param props : object_list, handleSelect (function)
*/
constructor(props) {
super(props);
console.log(props)
this.reverse = props.reverse;
let temp_list = [...props.object_list];
temp_list = ListSelect.sortList(temp_list);
if (this.reverse) {
temp_list.reverse()
}
if (props.default) {
temp_list = ListSelect.setDefault(props.default, temp_list, props.id_key);
}
this.state = {
object_list: props.object_list,
temp_list: temp_list,
selected_option: 0
};
this.options = React.createRef();
this.filterList = this.filterList.bind(this);
this.handleSelect = this.handleSelect.bind(this);
// set the first value if there is one...
// sort object list into alphabetical and then if there is a default, find it in the list via id and set it as the first item...
}
/**
* Check the length, compare each item's id (we expect and id and an str), return true
* @param arr1
* @param arr2
*/
static test_array_equal(arr1, arr2, id_key) {
if (arr1.length !== arr2.length)
return false;
for (var i = arr1.length; i--;) {
if (arr1[i][id_key] !== arr2[i][id_key])
return false;
}
return true;
}
componentDidMount() {
//select the first item if there is one.
this.state.temp_list[0] ? this.props.handleSelect(this.state.temp_list[0]) : this.props.handleSelect(null)
}
/**
* Parent updates with new list of objects
* @param props : object_list
*/
UNSAFE_componentWillReceiveProps(props) {
//pre process the props (make sure they go through sorting and adding default (as in the constructor)
let data = props.object_list;
if (props.select_object) {
let index = ListSelect.getIndex(props.select_object, this.state.temp_list);
if (index !== this.state.selected_option) {
this.handleSelect(index);
}
}
if ("object_list" in props && !ListSelect.test_array_equal(data, this.state.object_list)) {
let temp_list = ListSelect.sortList([...data]);
if (this.reverse) {
temp_list.reverse();
}
this.setState({
object_list: data,
temp_list: temp_list,
});
temp_list[0] ? this.props.handleSelect(temp_list[0]) : this.props.handleSelect(null);
}
}
static getIndex(object, list, id_key) {
let index = 0;
for (var i = 1; i < list.length; i += 1) {
if (list[i][id_key] === object[id_key]) {
index = i
}
}
return index
}
/**
* If there is a default set it
*/
static setDefault(object, list, id_key) {
// find and remove it from the current list
let id_pop = ListSelect.getIndex(object, list, id_key);
list.unshift(object);
list.splice(id_pop + 1, 1);
return list;
// set it as the first element in the list
}
/**
* Function to sort alphabetically an array of objects by some specific key.
*
* @param {String} property Key of the object to sort.
*/
static dynamicSort(property) {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a, b) {
let c = +a[property];
let d = +b[property];
if (c && d) {
return sortOrder === -1 ? c < d ? 1 : -1 : d < c ? 1 : -1;
}
return sortOrder === -1 ? b[property] > a[property] ? 1 : -1 : a[property] > b[property] ? 1 : -1;
}
}
/**
* sort the list into alphabetical by the str attribute
*/
static sortList(list) {
list.sort(ListSelect.dynamicSort(list));
return list;
}
/**
* Filter the object list from the filter input
* send the first item in the list as the selected item.
* if there is nothing send null
* @param event
*/
filterList(event) {
console.log(event)
console.log(this.props)
let all_data = this.state.object_list.filter(function (item) {
return item[this.props.str_key].toLowerCase().search(
event.target.value.toLowerCase()) !== -1;
});
console.log("here1")
all_data = ListSelect.sortList(all_data);
console.log("here2")
if (this.reverse) {
all_data.reverse();
}
this.setState({temp_list: all_data});
console.log("here3")
if (all_data[0]) {
this.props.handleSelect(all_data[0]);
this.setState({
selected_option: 0
})
} else {
this.props.handleSelect(null);
}
console.log("here4")
}
handleSelect(index) {
this.setState({
selected_option: index
});
this.props.handleSelect(this.state.temp_list[index]);
}
/**
* Render the list witall_datah an on click to send the id to the parent,
* and the filter event.
* @return {*}
*/
render() {
let lang = languages[document.documentElement.lang];
if (!this.state.temp_list) return <div style={{display: 'inline-block'}}>N/A</div>;
let select =
<select value={this.state.selected_option} ref={this.options}
onChange={(event) => this.handleSelect(event.target.value)}>
{
this.state.temp_list.map((item, index) => <option value={index}
key={item[this.props.id_key]}> {item[this.props.str_key]}</option>)
}
</select>;
let filter = <input type="text" placeholder={lang.filter}
onChange={this.filterList}/>;
if (this.props.filter === undefined || this.props.filter === true) {
return (
<div className={'ListSelect'}>
{filter}
{select}
</div>
)
} else {
return (
<div className={'ListSelect'}>
{select}
</div>
)
}
}
}
|
JavaScript
|
class BucketDeployment extends core_1.Construct {
/**
* @stability stable
*/
constructor(scope, id, props) {
var _d, _e;
super(scope, id);
if (props.distributionPaths) {
if (!props.distribution) {
throw new Error('Distribution must be specified if distribution paths are specified');
}
if (!cdk.Token.isUnresolved(props.distributionPaths)) {
if (!props.distributionPaths.every(distributionPath => cdk.Token.isUnresolved(distributionPath) || distributionPath.startsWith('/'))) {
throw new Error('Distribution paths must start with "/"');
}
}
}
if (props.useEfs && !props.vpc) {
throw new Error('Vpc must be specified if useEfs is set');
}
const accessPointPath = '/lambda';
let accessPoint;
if (props.useEfs && props.vpc) {
const accessMode = '0777';
const fileSystem = this.getOrCreateEfsFileSystem(scope, {
vpc: props.vpc,
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
accessPoint = fileSystem.addAccessPoint('AccessPoint', {
path: accessPointPath,
createAcl: {
ownerUid: '1001',
ownerGid: '1001',
permissions: accessMode,
},
posixUser: {
uid: '1001',
gid: '1001',
},
});
accessPoint.node.addDependency(fileSystem.mountTargetsAvailable);
}
// Making VPC dependent on BucketDeployment so that CFN stack deletion is smooth.
// Refer comments on https://github.com/aws/aws-cdk/pull/15220 for more details.
if (props.vpc) {
this.node.addDependency(props.vpc);
}
const mountPath = `/mnt${accessPointPath}`;
const handler = new lambda.SingletonFunction(this, 'CustomResourceHandler', {
uuid: this.renderSingletonUuid(props.memoryLimit, props.vpc),
code: lambda.Code.fromAsset(path.join(__dirname, 'lambda')),
layers: [new lambda_layer_awscli_1.AwsCliLayer(this, 'AwsCliLayer')],
runtime: lambda.Runtime.PYTHON_3_7,
environment: props.useEfs ? {
MOUNT_PATH: mountPath,
} : undefined,
handler: 'index.handler',
lambdaPurpose: 'Custom::CDKBucketDeployment',
timeout: cdk.Duration.minutes(15),
role: props.role,
memorySize: props.memoryLimit,
vpc: props.vpc,
vpcSubnets: props.vpcSubnets,
filesystem: accessPoint ? lambda.FileSystem.fromEfsAccessPoint(accessPoint, mountPath) : undefined,
});
const handlerRole = handler.role;
if (!handlerRole) {
throw new Error('lambda.SingletonFunction should have created a Role');
}
const sources = props.sources.map((source) => source.bind(this, { handlerRole }));
props.destinationBucket.grantReadWrite(handler);
if (props.distribution) {
handler.addToRolePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['cloudfront:GetInvalidation', 'cloudfront:CreateInvalidation'],
resources: ['*'],
}));
}
new cdk.CustomResource(this, 'CustomResource', {
serviceToken: handler.functionArn,
resourceType: 'Custom::CDKBucketDeployment',
properties: {
SourceBucketNames: sources.map(source => source.bucket.bucketName),
SourceObjectKeys: sources.map(source => source.zipObjectKey),
DestinationBucketName: props.destinationBucket.bucketName,
DestinationBucketKeyPrefix: props.destinationKeyPrefix,
RetainOnDelete: props.retainOnDelete,
Prune: (_d = props.prune) !== null && _d !== void 0 ? _d : true,
Exclude: props.exclude,
Include: props.include,
UserMetadata: props.metadata ? mapUserMetadata(props.metadata) : undefined,
SystemMetadata: mapSystemMetadata(props),
DistributionId: (_e = props.distribution) === null || _e === void 0 ? void 0 : _e.distributionId,
DistributionPaths: props.distributionPaths,
},
});
}
renderSingletonUuid(memoryLimit, vpc) {
let uuid = '8693BB64-9689-44B6-9AAF-B0CC9EB8756C';
// if user specify a custom memory limit, define another singleton handler
// with this configuration. otherwise, it won't be possible to use multiple
// configurations since we have a singleton.
if (memoryLimit) {
if (cdk.Token.isUnresolved(memoryLimit)) {
throw new Error('Can\'t use tokens when specifying "memoryLimit" since we use it to identify the singleton custom resource handler');
}
uuid += `-${memoryLimit.toString()}MiB`;
}
// if user specify to use VPC, define another singleton handler
// with this configuration. otherwise, it won't be possible to use multiple
// configurations since we have a singleton.
// A VPC is a must if EFS storage is used and that's why we are only using VPC in uuid.
if (vpc) {
uuid += `-${vpc.node.addr}`;
}
return uuid;
}
/**
* Function to get/create a stack singleton instance of EFS FileSystem per vpc.
*
* @param scope Construct
* @param fileSystemProps EFS FileSystemProps
*/
getOrCreateEfsFileSystem(scope, fileSystemProps) {
var _d;
const stack = cdk.Stack.of(scope);
const uuid = `BucketDeploymentEFS-VPC-${fileSystemProps.vpc.node.addr}`;
return (_d = stack.node.tryFindChild(uuid)) !== null && _d !== void 0 ? _d : new efs.FileSystem(scope, uuid, fileSystemProps);
}
}
|
JavaScript
|
class CacheControl {
constructor(
/**
* The raw cache control setting.
*/
value) {
this.value = value;
}
/**
* Sets 'must-revalidate'.
*
* @stability stable
*/
static mustRevalidate() { return new CacheControl('must-revalidate'); }
/**
* Sets 'no-cache'.
*
* @stability stable
*/
static noCache() { return new CacheControl('no-cache'); }
/**
* Sets 'no-transform'.
*
* @stability stable
*/
static noTransform() { return new CacheControl('no-transform'); }
/**
* Sets 'public'.
*
* @stability stable
*/
static setPublic() { return new CacheControl('public'); }
/**
* Sets 'private'.
*
* @stability stable
*/
static setPrivate() { return new CacheControl('private'); }
/**
* Sets 'proxy-revalidate'.
*
* @stability stable
*/
static proxyRevalidate() { return new CacheControl('proxy-revalidate'); }
/**
* Sets 'max-age=<duration-in-seconds>'.
*
* @stability stable
*/
static maxAge(t) { return new CacheControl(`max-age=${t.toSeconds()}`); }
/**
* Sets 's-maxage=<duration-in-seconds>'.
*
* @stability stable
*/
static sMaxAge(t) { return new CacheControl(`s-maxage=${t.toSeconds()}`); }
/**
* Constructs a custom cache control key from the literal value.
*
* @stability stable
*/
static fromString(s) { return new CacheControl(s); }
}
|
JavaScript
|
class Expires {
constructor(
/**
* The raw expiration date expression.
*/
value) {
this.value = value;
}
/**
* (deprecated) Expire at the specified date.
*
* @param d date to expire at.
* @deprecated
*/
static atDate(d) { return new Expires(d.toUTCString()); }
/**
* (deprecated) Expire at the specified timestamp.
*
* @param t timestamp in unix milliseconds.
* @deprecated
*/
static atTimestamp(t) { return Expires.atDate(new Date(t)); }
/**
* (deprecated) Expire once the specified duration has passed since deployment time.
*
* @param t the duration to wait before expiring.
* @deprecated
*/
static after(t) { return Expires.atDate(new Date(Date.now() + t.toMilliseconds())); }
/**
* (deprecated) Create an expiration date from a raw date string.
*
* @deprecated
*/
static fromString(s) { return new Expires(s); }
}
|
JavaScript
|
class LoadingNotice extends React.Component {
render() {
var {preferred, datasets, features, basicFeatures} = this.props;
if (!preferred || !datasets || !features || !basicFeatures) {
let {colId, controls, title, width} = this.props,
wizardProps = {
colId,
controls,
title,
loading: true,
loadingCohort: true,
width
};
return <WizardCard {...wizardProps}/>;
}
return <VariableSelect {...this.props}/>;
}
}
|
JavaScript
|
class ShaderBuilder {
constructor() {
/**
* Uniforms; these will be declared in the header (should include the type).
* @type {Array<string>}
* @private
*/
this.uniforms = [];
/**
* Attributes; these will be declared in the header (should include the type).
* @type {Array<string>}
* @private
*/
this.attributes = [];
/**
* Varyings with a name, a type and an expression.
* @type {Array<VaryingDescription>}
* @private
*/
this.varyings = [];
/**
* @type {string}
* @private
*/
this.sizeExpression = 'vec2(1.0)';
/**
* @type {string}
* @private
*/
this.offsetExpression = 'vec2(0.0)';
/**
* @type {string}
* @private
*/
this.colorExpression = 'vec4(1.0)';
/**
* @type {string}
* @private
*/
this.texCoordExpression = 'vec4(0.0, 0.0, 1.0, 1.0)';
/**
* @type {string}
* @private
*/
this.discardExpression = 'false';
/**
* @type {boolean}
* @private
*/
this.rotateWithView = false;
}
/**
* Adds a uniform accessible in both fragment and vertex shaders.
* The given name should include a type, such as `sampler2D u_texture`.
* @param {string} name Uniform name
* @return {ShaderBuilder} the builder object
*/
addUniform(name) {
this.uniforms.push(name);
return this;
}
/**
* Adds an attribute accessible in the vertex shader, read from the geometry buffer.
* The given name should include a type, such as `vec2 a_position`.
* @param {string} name Attribute name
* @return {ShaderBuilder} the builder object
*/
addAttribute(name) {
this.attributes.push(name);
return this;
}
/**
* Adds a varying defined in the vertex shader and accessible from the fragment shader.
* The type and expression of the varying have to be specified separately.
* @param {string} name Varying name
* @param {'float'|'vec2'|'vec3'|'vec4'} type Type
* @param {string} expression Expression used to assign a value to the varying.
* @return {ShaderBuilder} the builder object
*/
addVarying(name, type, expression) {
this.varyings.push({
name: name,
type: type,
expression: expression
});
return this;
}
/**
* Sets an expression to compute the size of the shape.
* This expression can use all the uniforms and attributes available
* in the vertex shader, and should evaluate to a `vec2` value.
* @param {string} expression Size expression
* @return {ShaderBuilder} the builder object
*/
setSizeExpression(expression) {
this.sizeExpression = expression;
return this;
}
/**
* Sets an expression to compute the offset of the symbol from the point center.
* This expression can use all the uniforms and attributes available
* in the vertex shader, and should evaluate to a `vec2` value.
* Note: will only be used for point geometry shaders.
* @param {string} expression Offset expression
* @return {ShaderBuilder} the builder object
*/
setSymbolOffsetExpression(expression) {
this.offsetExpression = expression;
return this;
}
/**
* Sets an expression to compute the color of the shape.
* This expression can use all the uniforms, varyings and attributes available
* in the fragment shader, and should evaluate to a `vec4` value.
* @param {string} expression Color expression
* @return {ShaderBuilder} the builder object
*/
setColorExpression(expression) {
this.colorExpression = expression;
return this;
}
/**
* Sets an expression to compute the texture coordinates of the vertices.
* This expression can use all the uniforms and attributes available
* in the vertex shader, and should evaluate to a `vec4` value.
* @param {string} expression Texture coordinate expression
* @return {ShaderBuilder} the builder object
*/
setTextureCoordinateExpression(expression) {
this.texCoordExpression = expression;
return this;
}
/**
* Sets an expression to determine whether a fragment (pixel) should be discarded,
* i.e. not drawn at all.
* This expression can use all the uniforms, varyings and attributes available
* in the fragment shader, and should evaluate to a `bool` value (it will be
* used in an `if` statement)
* @param {string} expression Fragment discard expression
* @return {ShaderBuilder} the builder object
*/
setFragmentDiscardExpression(expression) {
this.discardExpression = expression;
return this;
}
/**
* Sets whether the symbols should rotate with the view or stay aligned with the map.
* Note: will only be used for point geometry shaders.
* @param {boolean} rotateWithView Rotate with view
* @return {ShaderBuilder} the builder object
*/
setSymbolRotateWithView(rotateWithView) {
this.rotateWithView = rotateWithView;
return this;
}
/**
* @returns {string} Previously set size expression
*/
getSizeExpression() {
return this.sizeExpression;
}
/**
* @returns {string} Previously set symbol offset expression
*/
getOffsetExpression() {
return this.offsetExpression;
}
/**
* @returns {string} Previously set color expression
*/
getColorExpression() {
return this.colorExpression;
}
/**
* @returns {string} Previously set texture coordinate expression
*/
getTextureCoordinateExpression() {
return this.texCoordExpression;
}
/**
* @returns {string} Previously set fragment discard expression
*/
getFragmentDiscardExpression() {
return this.discardExpression;
}
/**
* Generates a symbol vertex shader from the builder parameters,
* intended to be used on point geometries.
*
* Three uniforms are hardcoded in all shaders: `u_projectionMatrix`, `u_offsetScaleMatrix`,
* `u_offsetRotateMatrix`, `u_time`.
*
* The following attributes are hardcoded and expected to be present in the vertex buffers:
* `vec2 a_position`, `float a_index` (being the index of the vertex in the quad, 0 to 3).
*
* The following varyings are hardcoded and gives the coordinate of the pixel both in the quad and on the texture:
* `vec2 v_quadCoord`, `vec2 v_texCoord`
*
* @returns {string} The full shader as a string.
*/
getSymbolVertexShader() {
const offsetMatrix = this.rotateWithView ?
'u_offsetScaleMatrix * u_offsetRotateMatrix' :
'u_offsetScaleMatrix';
return `precision mediump float;
uniform mat4 u_projectionMatrix;
uniform mat4 u_offsetScaleMatrix;
uniform mat4 u_offsetRotateMatrix;
uniform float u_time;
${this.uniforms.map(function(uniform) {
return 'uniform ' + uniform + ';';
}).join('\n')}
attribute vec2 a_position;
attribute float a_index;
${this.attributes.map(function(attribute) {
return 'attribute ' + attribute + ';';
}).join('\n')}
varying vec2 v_texCoord;
varying vec2 v_quadCoord;
${this.varyings.map(function(varying) {
return 'varying ' + varying.type + ' ' + varying.name + ';';
}).join('\n')}
void main(void) {
mat4 offsetMatrix = ${offsetMatrix};
vec2 size = ${this.sizeExpression};
vec2 offset = ${this.offsetExpression};
float offsetX = a_index == 0.0 || a_index == 3.0 ? offset.x - size.x / 2.0 : offset.x + size.x / 2.0;
float offsetY = a_index == 0.0 || a_index == 1.0 ? offset.y - size.y / 2.0 : offset.y + size.y / 2.0;
vec4 offsets = offsetMatrix * vec4(offsetX, offsetY, 0.0, 0.0);
gl_Position = u_projectionMatrix * vec4(a_position, 0.0, 1.0) + offsets;
vec4 texCoord = ${this.texCoordExpression};
float u = a_index == 0.0 || a_index == 3.0 ? texCoord.s : texCoord.q;
float v = a_index == 2.0 || a_index == 3.0 ? texCoord.t : texCoord.p;
v_texCoord = vec2(u, v);
u = a_index == 0.0 || a_index == 3.0 ? 0.0 : 1.0;
v = a_index == 2.0 || a_index == 3.0 ? 0.0 : 1.0;
v_quadCoord = vec2(u, v);
${this.varyings.map(function(varying) {
return ' ' + varying.name + ' = ' + varying.expression + ';';
}).join('\n')}
}`;
}
/**
* Generates a symbol fragment shader from the builder parameters,
* intended to be used on point geometries.
*
* Expects the following varyings to be transmitted by the vertex shader:
* `vec2 v_quadCoord`, `vec2 v_texCoord`
*
* @returns {string} The full shader as a string.
*/
getSymbolFragmentShader() {
return `precision mediump float;
uniform float u_time;
${this.uniforms.map(function(uniform) {
return 'uniform ' + uniform + ';';
}).join('\n')}
varying vec2 v_texCoord;
varying vec2 v_quadCoord;
${this.varyings.map(function(varying) {
return 'varying ' + varying.type + ' ' + varying.name + ';';
}).join('\n')}
void main(void) {
if (${this.discardExpression}) { discard; }
gl_FragColor = ${this.colorExpression};
gl_FragColor.rgb *= gl_FragColor.a;
}`;
}
}
|
JavaScript
|
class Entity { // eslint-disable-line no-unused-vars
/**
* Entity constructor
* @constructor
* @param {number} x x position
* @param {number} y y position
* @param {number} width object width
* @param {number} height object height
* @param {number} imageID image ID for rendering (if has not, -1)
*/
constructor(x, y, width, height, imageID = -1) {
/**
* Entity x position
* @type {number}
*/
this.x = x;
/**
* Entity y position
* @type {number}
*/
this.y = y;
/**
* Entity width
* @type {number}
*/
this.width = width;
/**
* Entity height
* @type {number}
*/
this.height = height;
/**
* Entity image id
* @protected
* @type {number}
*/
this.imageID = imageID;
/**
* X direction of entity
* @type {number}
*/
this.directionX = 0;
/**
* Y direction of entity
* @type {number}
*/
this.directionY = 0;
}
/**
* Set stage
* @param {Stage} stage Stage information
*/
setStage(stage) {
/**
* Stage information
* @type {Stage}
*/
this.stage = stage;
}
/**
* Set collider
* @param {Collider} collider collider
*/
setCollider(collider) {
/**
* Entity collider
* @type {Collider}
*/
this.collider = collider;
// initialize
collider.setEntity(this);
collider.init();
}
/**
* Set material
* @param {Material} material Material information
*/
setMaterial(material) {
/**
* Material inofrmation
* @type {Material}
*/
this.material = material;
}
/**
* Initialize entity
* @interface
*/
init() {}
/**
* Update entty
* @interface
* @param {number} dt - delta time
*/
update(dt) {}
/**
* Render entity
* @interface
* @param {Context} ctx - canvas context
* @param {number} [shiftX = 0] shift x position
* @param {number} [shiftY = 0] shift y position
*/
render(ctx, shiftX = 0, shiftY = 0) {}
}
|
JavaScript
|
class PhotoGrid extends React.Component {
constructor(props) {
super(props);
this.state = {
isToken: false,
photos: [],
albums: [],
addToAlbum: '',
selectedPhotos: []
};
}
handleSelectAlbum = (id) => {
fetch('/photos/' + id)
.then(d => d.json())
.then(d =>
this.setState({
photos: d,
selectedPhotos: []
})
);
}
handleDeleteImg = (id) => {
if (localStorage.key('token')) {
const data = new FormData();
data.append("id", id);
fetch('/api/photos/delete', {
method: 'POST',
body: data,
headers: {
'token': localStorage.getItem('token')
}
})
document.getElementById(id).remove();
} else {
alert('You must be logined')
}
}
handlePhotoSelect = (selectedPhoto) => {
if (selectedPhoto.checked) {
this.setState(prevState => {
return { selectedPhotos: [...prevState.selectedPhotos, selectedPhoto.id] };
});
} else {
this.setState(prevState => {
return { selectedPhotos: prevState.selectedPhotos.filter(id => id !== selectedPhoto.id) };
});
}
}
handleAddToAlbum = (id) => {
this.setState({
addToAlbum: id
});
}
handleAddPhotoToAlbum = () => {
if (localStorage.key('token')) {
const data = new FormData();
data.append("albumId", this.state.addToAlbum);
data.append("imgIds", JSON.stringify(this.state.selectedPhotos));
fetch('/api/album/addPhotos',
{
method: 'post',
body: data,
headers: {
'token': localStorage.getItem('token')
}
})
.then(d => d.json())
.then(d =>
this.setState(prevState => ({
selectedPhotos: [],
addToAlbum: '',
photos: prevState.photos.map(e => Object.assign({}, e))
}))
);
} else {
alert('You must be logined')
}
}
componentDidMount() {
const urlImg = '/photos';
const urlSelect = '/album/list';
fetch(urlImg)
.then(d => d.json())
.then(d =>
this.setState({
photos: d
})
);
fetch(urlSelect)
.then(d => d.json())
.then(d =>
this.setState({
albums: d
})
);
if (localStorage.getItem('token')) {
this.setState({
isToken: true
})
}
}
handleLogOut = (id) => {
localStorage.removeItem('token');
document.querySelector('.logout').remove();
}
render() {
const { photos, selectedPhotos, addToAlbum, albums, isToken } = this.state;
return (
<div>
{isToken ? <button className='btn btn-primary logout' onClick={this.handleLogOut}>Log Out</button> : null}
Filter: <Select data={albums} onChange={this.handleSelectAlbum} />
{selectedPhotos.length ?
<span>Add selected photo to:
<Select data={albums} onChange={this.handleAddToAlbum} />
</span> : ''
}
{addToAlbum && selectedPhotos.length ? <button className='btn btn-primary' onClick={this.handleAddPhotoToAlbum}>Send</button> : ''}
<div className="photos-container">
{photos.map(item =>
<Photo
key={item._id}
image={item}
onSelect={this.handlePhotoSelect}
deleteItem={this.handleDeleteImg}
/>)}
</div>
</div>
);
}
}
|
JavaScript
|
class MapMarker extends Component {
static propTypes = {
children: PropTypes.any,
lat: PropTypes.number.isRequired,
lng: PropTypes.number.isRequired,
};
render() {
return (
<div className="map-marker" {...this.props}>
{this.props.children}
</div>
);
}
}
|
JavaScript
|
class Moostaka {
/**
* Instantiate the SPA
*
* @param {Object} opts - a dictionary of options. Supported keys are:
* {string} defaultRoute - the default route. defaults to '/'
* {string} viewLocation - a url fragment for locating page
* templates. defaults to '/views'
*/
constructor(opts) {
this.routes = [];
// define the defaults
this.defaultRoute = '/';
this.viewLocation = '/views';
// redirect to default route if none defined
if(location.pathname === '') {
history.pushState('data', this.defaultRoute, this.defaultRoute);
}
// override the defaults
if(opts) {
this.defaultRoute = typeof opts.defaultRoute !== 'undefined' ? opts.defaultRoute : this.defaultRoute;
this.viewLocation = typeof opts.viewLocation !== 'undefined' ? opts.viewLocation : this.viewLocation;
}
let self = this;
// hook up events
document.addEventListener('click', (event) => {
if(event.target.matches('a[href], a[href] *')) {
// walk up the tree until we find the href
let element = event.target;
while(element instanceof HTMLElement) {
if(element.href) {
if(element.href.startsWith(location.host) || element.href.startsWith(location.protocol + '//' + location.host)) {
// staying in application
event.preventDefault();
let url = element.href.replace('http://', '').replace('https://', '').replace(location.host, '');
let text = document.title;
if(element.title instanceof String && element.title != "") {
text = element.title;
} else if(event.target.title instanceof String && event.target.title != "") {
text = event.target.title;
}
history.pushState({}, text, element.href);
self.navigate(url);
} // else do nothing so browser does the default thing ie browse to new location
return;
} else {
element = element.parentElement;
}
}
} // else not a link; ignore
}, false);
// pop state
window.onpopstate = (e) => {
self.navigate(location.pathname);
};
}
/**
* handle navigation events routing to a "route" if one is defined which
* matches the specified pathname
*
* @param {string} pathname the uri to change to
*/
navigate(pathname) {
if(this.onnavigate) {
this.onnavigate(pathname);
}
// if no path, go to default
if(!pathname || pathname === '/') {
pathname = this.defaultRoute;
}
let hashParts = pathname.split('/');
let params = {};
for(let i = 0, len = this.routes.length; i < len; i++) {
if(typeof this.routes[i].pattern === 'string') {
let routeParts = this.routes[i].pattern.split('/');
let thisRouteMatch = true;
// if segment count is not equal the pattern will not match
if(routeParts.length !== hashParts.length) {
thisRouteMatch = false;
} else {
for(let x = 0; x < routeParts.length; x++) {
// A wildcard is found, lets break and return what we have already
if(routeParts[x] === '*') {
break;
}
// if not optional params we check it
if(routeParts[x].substring(0, 1) !== ':') {
if(lowerCase(routeParts[x]) !== lowerCase(hashParts[x])) {
thisRouteMatch = false;
}
} else {
// this is an optional param that the user will want
let partName = routeParts[x].substring(1);
params[partName] = hashParts[x];
}
}
}
// if route is matched
if(thisRouteMatch === true) {
return this.routes[i].handler(params);
}
} else {
if(pathname.substring(1).match(this.routes[i].pattern)) {
return this.routes[i].handler({'hash': pathname.substring(1).split('/')});
}
}
}
// no routes were matched. try defaultRoute if that is not the route being attempted
if(this.defaultRoute != pathname) {
history.pushState('data', 'home', this.defaultRoute);
this.navigate(this.defaultRoute);
} // else we should perhaps implement an error route?
}
/**
* Render a template into a specified HTMLElement node
*
* @param {HTMLElement|string} an element node or a string specifiying an
* HTMLElement node e.g. '#content' for <div id="content"></div>
* @param {string} view - the name of an .mst file in the views location
* to use as a template
* @param {?object} params - additional parameters for the Mustache template
* renderer
* @param {?object} options - a dictionary of options. supported keys:
* {array<string>} tags - a list of delimiters for Mustache to use
* {bool} append - if true then new content to the element's contents
* otherwise replace the contents of element with the render
* output. Default: false
* @param {?function} callback - a callback function to invoke once the
* template has been rendered into place
*/
render(element, view, params, options, callback) {
let destination = null;
if(element instanceof HTMLElement) {
destination = element;
} else {
destination = document.querySelector(element);
}
if(!params) {
params = {};
}
if(!options) {
options = {};
}
if(typeof options.tags === 'undefined') {
Mustache.tags = [ '{{', '}}' ];
} else {
Mustache.tags = options.tags;
}
if(typeof options.append === 'undefined') {
options.append = false;
}
let url = this.viewLocation + '/' + view.replace('.mst', '') + '.mst';
fetch(url).then((response) => {
return response.text();
}).then(template => {
if(options.append === true) {
destination.innerHTML += Mustache.render(template, params);
} else {
while(destination.firstChild) {
destination.removeChild(destination.firstChild);
}
destination.innerHTML = Mustache.render(template, params);
}
if(callback instanceof Function) {
callback();
}
});
}
/**
* Render a template and the as rendered template to the callback as a
* string parameter
*
* @param {string} view - the name of an .mst file in the views location
* to use as a template
* @param {?object} params - additional parameters for the Mustache template
* renderer
* @param {?object} options - a dictionary of options. supported keys:
* {array<string>} tags - a list of delimiters for Mustache to use
* {bool} markdown - if true and window.markdownit exists call
* window.markdownit.render() on the template data before
* rendering content with Mustache.
* @param {function} callback - a callback function to invoke once the
* template has been rendered. The string value of the rendered
* template will be passed to the function as its first and only
* paramter
*/
getHtml(view, params, options, callback) {
if(!(callback instanceof Function)) {
throw new TypeError("callback is not a function");
}
if(!params) {
params = {};
}
if(!options) {
options = {};
}
if(typeof options.tags === 'undefined') {
Mustache.tags = [ '{{', '}}' ];
} else {
Mustache.tags = options.tags;
}
if(typeof options.markdown === 'undefined') {
options.markdown = false;
}
let url = this.viewLocation + '/' + view.replace('.mst', '') + '.mst';
fetch(url).then(response => {
return response.text();
}).then(template => {
if(window.markdownit && options.markdown === true) {
let md = window.markdownit();
callback(Mustache.render(md.render(template), params));
} else {
callback(Mustache.render(template, params));
}
});
}
/**
* Add a route to the SPA
*
* @param {string} pattern - a pattern string that if matched to the URI
* will cause the specified handler to be invoked
* @param {function} handler - a callback function to invoke when the user
* navigates to this route.
*/
route(pattern, handler) {
// should check if pattern is already routed and if so
// throw error or overwrite?
this.routes.push({pattern: pattern, handler: handler});
}
/**
* clear all routes currently configured useful if transitioning between
* authenticated and unauthenticated states
*/
flush() {
this.routes = [];
}
}
|
JavaScript
|
class LoadedProject {
/**
* Constructs a LoadedProject from the project loaded from disk or created and the path to the .digiblocks file
* where it should be saved/loaded form on disk.
*
* @param {Project} project Project loaded from disk
* @param {String} loadPath Path to the cache directory where the .drop file has been extracted
* @param {String} projectPath Path to the .drop archive file
* @param {BaseProjectManager} projectManager Project manager that is currently being used
* @param {String} [fileType=digiblocks] digiblocks or drop
*/
constructor(project, loadPath, projectPath, projectManager, fileType = 'digiblocks') {
this.loadedProject = project;
this.loadPath = loadPath;
this.projectPath = projectPath;
this.projectManager = projectManager;
this.fileType = fileType;
this.readOnly = false;
}
/**
* Helper to get the path to the blocks file (.xml) that contains all of the blocks the user has placed
* @return {string} The path to the blocks file (.xml)
*/
getBlocksPath() {
return path.join(this.loadPath, `${this.loadedProject.name}.xml`);
}
/**
* Helper to get the path to the project file (.digiblocks) this file contains JSON to describe the project and its
* metadata
* @return {string} The path to the project file (.digiblocks)
*/
getProjectPath() {
return path.join(this.loadPath, `${this.loadedProject.name}.digiblocks`);
}
/**
* Helper to get the name of the project
* @return {string} The name of the project
*/
getName() {
return this.loadedProject.name;
}
/**
* Get the string representing the type of the project ex. 'wink'
* @return {string} The type of the loaded project
*/
getType() {
return this.loadedProject.type;
}
/**
* Get any metadata on the current project
* @return {*} An object containing metadata for the currently loaded project
*/
getMetaData() {
return this.loadedProject.meta;
}
/**
* Get the inner project directory that contains the generated source code, and user added assets
* @return {string} The path to the project directory
*/
getProjectDir() {
return path.join(this.loadPath, this.getName());
}
/**
* Get a file from the inner project directory. The inner directory contains the actual files for the project.
*
* @param {string} file Path to the file in the project dir
* @return {string} The path to the given file
*/
getFileInProjectDir(file) {
return path.join(this.getProjectDir(), file);
}
getProjectManager() {
return this.projectManager;
}
/**
* Pass through files to the project manager to save them to disk
* @param files List of file data to save
* @param files.path Path to the location in the cache dir this will be saved to
* @param files.data Data for the file (this inherently limits files to < 2GB)
*/
save(files) {
if(this.readOnly){
return;
}
this.getProjectManager().saveProject(this, files);
}
/**
* .digiblocks was deprecated in 2.0.0 all projects are now archived .drop
* @return {boolean} true if a legacy flat project
*/
isLegacy() {
return this.fileType === DIGIBLOCKS_PROJECT;
}
/**
* Get the path to the source output file for this loaded project
* @param extension
*/
getSourceFile(extension) {
return this.getFileInProjectDir(`${this.getName()}.${extension}`);
}
setReadOnly(readOnly){
this.readOnly = readOnly;
}
}
|
JavaScript
|
class ConfigEntry extends EngineEntryForWorldInfo {
/**
* @param {WorldInfoEntry} worldInfo
*/
constructor(worldInfo) {
super(worldInfo);
}
static get forType() { return "Config"; }
get targetSources() { return tuple(); }
/**
* Prevents State-Engine from producing these as entries.
*
* @returns {Iterable<StateEngineEntry>}
*/
static produceEntries() {
return [];
}
/**
* Hard disables this entry in State-Engine, just in case it finds its way into the
* system somehow.
*
* @returns {boolean}
*/
associator() {
// Never associates, period.
return false;
}
}
|
JavaScript
|
class State {
constructor(/** @type {PlainObject} */ defaults) {
if (defaults) {
applyStateChanges(this, defaults);
}
}
/**
* Return a new copy of this state that includes the indicated changes,
* invoking any registered `onChange` handlers that depend on the changed
* state members.
*
* There is no need to invoke this method yourself.
* [ReactiveMixin](ReactiveMixin) will take care of doing that when you invoke
* [internal.setState]](ReactiveMixin[internal.setState]).
*
* @param {object} changes - the changes to apply to the state
* @returns {object} - the new `state`, and a `changed` flag indicating
* whether there were any substantive changes
*/
copyWithChanges(changes) {
// Create a new state object that holds a copy of the old state. If we pass
// the current state to the State constructor, we'll trigger the application
// of its change handlers, which will ultimately realize the state is
// already as refined as possible, and so do work for nothing. So we create
// a new empty State, merge in the old state, then run the change handlers
// with the requested changes.
const state = Object.assign(new State(), this);
// If the changes include new change callbacks, apply those too.
if (changes[changeCallbacksKey]) {
// Also copy over the set of change callbacks.
state[changeCallbacksKey] = changes[changeCallbacksKey];
}
const changed = applyStateChanges(state, changes);
return { state, changed };
}
/**
* Ask the `State` object to invoke the specified `callback` when any of the
* state members listed in the `dependencies` array change.
*
* The `callback` should be a function that accepts:
*
* * A `state` parameter indicating the current state.
* * A `changed` parameter. This will be a set of flags that indicate which
* specified state members have changed since the last time the callback was
* run. If the handler doesn't care about which specific members have
* changed, this parameter can be omitted.
*
* The callback should return `null` if it finds the current state acceptable.
* If the callback wants to make changes to the state, it returns an object
* representing the changes that should be applied to the state. The callback
* does *not* need to check to see whether the changes actually need to be
* applied to the state; the `State` object itself will avoid applying
* unnecessary changes.
*
* The common place to invoke `onChange` is when an element's `defaultState`
* is being constructed.
* @param {string[]|string} dependencies - the name(s) of the state fields
* that should trigger the callback if they are changed
* @param {function} callback - the function to run when any of the
* dependencies changes
*/
onChange(dependencies, callback) {
if (!this[changeCallbacksKey]) {
this[changeCallbacksKey] = {};
}
const array = dependencies instanceof Array ? dependencies : [dependencies];
// Register the callback for each dependent state field.
array.forEach(dependency => {
/** @type {any} */
const changeCallbacks = this[changeCallbacksKey];
if (!changeCallbacks[dependency]) {
changeCallbacks[dependency] = [];
}
changeCallbacks[dependency].push(callback);
});
}
}
|
JavaScript
|
class OhCommunityTopics extends HTMLElement {
constructor() {
super();
if (!this.style.display || this.style.display.length == 0)
this.style.display = "block";
}
static get observedAttributes() {
return ['url', 'cachetime'];
}
connectedCallback() {
this.loading = this.getAttribute("loading") || "Loading... ";
this.error = this.getAttribute("error") || "Failed to fetch! ";
this.limit = this.hasAttribute("limit") ? parseInt(this.getAttribute("limit")) : null;
this.topics = this.hasAttribute("topics") ? this.getAttribute("topics") : null;
this.order = this.hasAttribute("order") ? this.getAttribute("order") : "created";
this.attributeChangedCallback();
this.initdone = true;
this.checkCacheAndLoad();
}
set contenturl(val) {
while (this.firstChild) { this.firstChild.remove(); }
this.innerHTML = this.loading;
this.checkCacheAndLoad(val);
}
get contenturl() {
if (!this.topics) return null;
if (this.order)
return this.url + "/" + this.topics + ".json?order=" + this.order;
else
return this.url + "/" + this.topics + ".json";
}
attributeChangedCallback(name, oldValue, newValue) {
this.cachetime = this.cachetime = (this.hasAttribute("cachetime") ? parseInt(this.getAttribute("cachetime")) : null) || 1440; // One day in minutes
this.url = this.hasAttribute("url") ? this.getAttribute("url") : "https://cors-anywhere.herokuapp.com/https://community.openhab.org";
if (this.initdone) this.checkCacheAndLoad();
}
checkCacheAndLoad() {
if (!this.contenturl) {
while (this.firstChild) { this.firstChild.remove(); }
this.innerHTML = "No url given!";
return;
}
var cacheTimestamp = parseInt(localStorage.getItem("timestamp_" + this.contenturl)) || 0;
this.title = `Caching for ${this.cachetime / 60} hours. Last refresh: ${new Date(cacheTimestamp).toLocaleString()}`;
var cachedData = null;
if (cacheTimestamp > 0 && (cacheTimestamp + this.cachetime * 60 * 1000 > Date.now())) {
cachedData = localStorage.getItem(this.contenturl);
}
if (cachedData) {
while (this.firstChild) { this.firstChild.remove(); }
this.innerHTML = cachedData;
} else {
this.reload();
}
}
reload() {
if (!this.contenturl) {
while (this.firstChild) { this.firstChild.remove(); }
this.innerHTML = "No url given!";
return;
}
localStorage.removeItem("timestamp_" + this.contenturl);
while (this.firstChild) { this.firstChild.remove(); }
this.innerHTML = this.loading;
this.load();
}
load() {
const url = this.contenturl;
fetchWithTimeout(url)
.then(response => response.json())
.then(jsonData => {
var d = "<ul>";
var counter = 0;
for (var topic of jsonData.topic_list.topics) {
const date = new Date(topic.created_at).toLocaleDateString();
d += "<li><a target='_blank' href='https://community.openhab.org/t/" + topic.slug + "/" + topic.id + "'>" + topic.title + "</a> <small>" + date + "</small></li>"
if (this.limit > 0 && this.limit <= counter) break;
++counter;
};
return d + "</ul>";
})
.then(html => {
localStorage.setItem(url, html);
localStorage.setItem("timestamp_" + url, Date.now());
this.title = `Caching for ${this.cachetime / 60} hours. Last refresh: ${new Date(Date.now()).toLocaleString()}`;
while (this.firstChild) { this.firstChild.remove(); }
this.innerHTML = html;
}).catch(e => {
while (this.firstChild) { this.firstChild.remove(); }
this.innerHTML = this.error + e;
throw e;
})
}
}
|
JavaScript
|
class NgAnyNameExcept extends NgClass{
/**
* @since 0.0.1
* @method NgAnyNameExcept#constructor
*
*/
constructor(nameClass) {
super(NgAnyNameExcept);
this.className = 'NgAnyNameExcept';
this.nameClass = nameClass;
}
/**
* @since 0.0.1
* @method NgAnyNameExcept#contains
* @description
* Contains pattern
* @param nameClass
* @param qName
*/
contains(nameClass, qName) {
return !this.contains(nameClass.nameClass, qName);
}
}
|
JavaScript
|
class NavbarB extends Component {
state = {
darkmode: false
};
logout = () => {
localStorage.removeItem("userId");
};
mode = () => {
this.setState({ darkmode: !this.state.darkmode });
this.props.flipMode();
};
render() {
const { darkmode } = this.state;
return (
<div className={"navbarb " + (darkmode ? "dark" : "light")}>
<div className="nav">
<div className="left">
<Link exact to="/">
<RedHome />
</Link>
<Link exact to="/">
LiveSafe
</Link>
</div>
<div className="center">
{/* <form>
<input type="text" placeholder="Enter a location" />
<button>
<WhiteSearch />
</button>
</form> */}
<div id="geocoder" className="geocoder" />
</div>
<div className="right notauth">
<NavLink exact to="/login" activeClassName="activeA">
Sign up or Login
</NavLink>
<NavLink exact to="/landing" activeClassName="activeA">
Product
</NavLink>
<NavLink exact to="/about" activeClassName="activeA">
About
</NavLink>
<NavLink exact to="/pricing" activeClassName="activeA">
Pricing
</NavLink>
{/*
<span onClick={this.mode}>
<button className="icons">
{darkmode ? <MoonDarkA /> : <MoonLightA />}
</button>
</span> */}
</div>
</div>
</div>
);
}
}
|
JavaScript
|
class LrndesignAvatar extends SimpleColors {
//styles function
static get styles() {
return [
...super.styles,
css`
:host {
display: block;
margin: 0;
padding: 0;
}
:host([hidden]) {
display: none;
}
paper-avatar {
border-radius: var(--lrndesign-avatar-border-radius, 50%);
max-height: var(--lrndesign-avatar-width, 40px);
--paper-avatar-width: var(--lrndesign-avatar-width, 40px);
--paper-avatar-color: var(
--simple-colors-default-theme-accent-8,
#444
);
--paper-avatar-text-color: var(
--simple-colors-default-theme-grey-1,
#fff
);
}
:host([invert]) paper-avatar {
--paper-avatar-color: var(--simple-colors-default-theme-grey-1, #fff);
--paper-avatar-text-color: var(
--simple-colors-default-theme-accent-8,
#444
);
}
`,
];
}
// render function
render() {
return html` <paper-avatar
accent-color="${this.accentColor}"
?allow-grey="${this.allowGrey}"
?dark="${this.dark}"
.label="${this.label || ""}"
.icon="${this.icon || ""}"
.src="${this.src || ""}"
?two-chars="${this.twoChars}"
?jdenticon="${this.jdenticon}"
></paper-avatar>`;
}
// haxProperty definition
static get haxProperties() {
return {
canScale: false,
canPosition: false,
canEditSource: true,
gizmo: {
title: "Avatar",
description:
"Visualize a user account either with an image, icon, initials, or as abstract art.",
icon: "image:collections",
color: "yellow",
groups: ["Media", "Image"],
handles: [
{
type: "image",
source: "image",
},
],
meta: {
author: "ELMS:LN",
},
},
settings: {
configure: [
{
property: "accentColor",
title: "Accent Color",
description: "Pick an accent color.",
inputMethod: "colorpicker",
},
{
property: "dark",
title: "Dark",
description: "Use dark text (and light background) for avatar.",
inputMethod: "boolean",
},
{
property: "icon",
title: "Icon",
description: "Optional: Pick an icon for avatar.",
inputMethod: "iconpicker",
},
{
property: "src",
title: "Image Source",
description: "Optional: Upload an image for avatar.",
inputMethod: "haxupload",
},
{
property: "label",
title: "Two-character initials",
description: "Label used to create initials or unique Jdenticon.",
inputMethod: "textfield",
},
{
property: "twoChars",
title: "Two-character initials",
description:
"When no Jdenticon, image, or icon, use two-character for initials.",
inputMethod: "boolean",
},
{
property: "jdenticon",
title: "Jdenticon",
description: "Optional: Unique icon design based on label.",
inputMethod: "boolean",
},
],
advanced: [
{
property: "allowGrey",
title: "Allow Grey",
description:
"Allows grey if set. Otherwise a color will be assigned",
inputMethod: "boolean",
},
],
},
};
}
// properties available to the custom element for data binding
static get properties() {
return {
...super.properties,
/**
* allow grey instead of accent color, default selects a color
*/
allowGrey: {
type: Boolean,
attribute: "allow-grey",
},
/**
* optional simple-icon
*/
icon: {
type: String,
},
/**
* invert colors
*/
invert: {
type: Boolean,
attribute: "invert",
reflect: true,
},
/**
* text to use for avatar
*/
label: {
type: String,
},
/**
* link to an image, optional
*/
src: {
type: String,
},
/**
* Mode for presenting 1st two letters
*/
twoChars: {
type: Boolean,
attribute: "two-chars",
},
/**
* "Deprecated": Color class work to apply
*/
color: {
type: String,
},
/**
* Form abstract art from hash of label
*/
jdenticon: {
type: Boolean,
},
};
}
/**
* Store the tag name to make it easier to obtain directly.
* @notice function name must be here for tooling to operate correctly
*/
static get tag() {
return "lrndesign-avatar";
}
// life cycle
constructor() {
super();
this.allowGrey = false;
this.dark = false;
this.twoChars = false;
this.jdenticon = false;
this.label = "|";
}
_getAccentColor() {
// legacy API bridge
if (
this.colors &&
!this.allowGrey &&
(!this.accentColor || this.accentColor === "grey")
) {
let color = (this.color || "").replace("-text", "");
if (color && this.colors[color]) {
this.accentColor = color;
} else {
let str = this.label || this.icon,
char =
str && str.charCodeAt(0)
? str.charCodeAt(0)
: Math.floor(Math.random() * 16),
colors = Object.keys(this.colors);
color = colors[(char % 16) + 1];
this.accentColor =
colors[(char % 16) + 1] ||
colors[Math.floor(Math.random() * this.colors.length)];
}
}
}
updated(changedProperties) {
if (super.updated) {
super.updated(changedProperties);
}
changedProperties.forEach((oldValue, propName) => {
if (propName == "color" || propName == "label" || propName == "icon") {
this._getAccentColor();
}
});
}
}
|
JavaScript
|
class Login extends Component {
constructor(props) {
super(props);
this.state = {
showPassword: false,
registration: false
};
this.displayPassword = this.displayPassword.bind(this);
}
componentDidMount() {
this.props.getRegOptions();
}
handleSubmit(data) {
const credentials = this.prepareData(data);
this.props.getLogged(credentials);
}
prepareData(data) {
const authData = {};
authData.username = data.username;
authData.password = data.password;
authData['remember-me'] = data.rememberMe ? "on" : "off";
return Object.keys(authData).map(key => {
return encodeURIComponent(key) + '=' + encodeURIComponent(authData[key]);
}).join('&');
}
displayPassword() {
this.setState({showPassword: !this.state.showPassword});
}
renderFooter() {
const {regOptions} = this.props;
if (!regOptions || !regOptions.allowed) return null;
return (
<div className="text-center text-secondary">
<small>Don't have an account?
<a href="#" onClick={() => this.setState({registration: true})}>
Sign Up
</a>
</small>
</div>);
}
render() {
const { security, savedCredentials} = this.props;
if (security.logged && security.url)
window.location.assign(security.url);
const { registration} = this.state;
if (registration) return <RegistrationContainer/>;
const {isLoggingIn, errorLoggingIn} = security;
return (
<div className="container-fluid">
<LogoMini/>
<div className="row mt-1">
<div className="col-1 col-sm-2 col-md-3 col-lg-4"></div>
<div className="col-10 col-sm-8 col-md-6 col-lg-4">
<div className="card bg-transparent">
<div className="card-header pt-1 pb-1">
<small>
<div className="text-secondary text-center">Authentication</div>
</small>
</div>
<div className="card-body">
{
isLoggingIn &&
<div className="text-center text-info mt-n2 mb-2">
<span>Authentication...
<div className="spinner-grow spinner-grow-sm text-info" role="checking"/>
</span>
</div>
}
{
errorLoggingIn &&
<div className="alert alert-danger p-1" role="alert">
<Failure message={errorLoggingIn.message}/>
</div>
}
<LoginForm
onSubmit = {data=>this.handleSubmit(data)}
initialValues={savedCredentials ?
{
username: savedCredentials.email,
password: savedCredentials.password,
rememberMe: false}
: null
}
disabled = {isLoggingIn}
showPassword = {this.state.showPassword}
displayPassword = {this.displayPassword}
/>
</div>
<div className="form-group text-center mt-n2 mb-2">
<a href="#" className="badge badge-secondary" onClick={() => {
this.props.resetForm();
this.props.clearRegisteredCredentials();
}}>Reset</a>
</div>
<div className="card-footer pt-0 pb-0">
{this.renderFooter()}
<div className="d-flex justify-content-center">
<small><a href="#">Forgot your password?</a></small>
</div>
</div>
</div>
</div>
<div className="col-1 col-sm-2 col-md-3 col-lg-4"/>
</div>
</div>
);
}
}
|
JavaScript
|
class AlertController {
/**
* @constructor
* @param {AlertControllerOptions} [opts] - Controller configuration parameters
*/
constructor (opts = {}) {
const { initState, preferencesStore } = opts
const state = {
...defaultState,
...initState,
unconnectedAccountAlertShownOrigins: {},
}
this.store = new ObservableStore(state)
this.selectedAddress = preferencesStore.getState().selectedAddress
preferencesStore.subscribe(({ selectedAddress }) => {
const currentState = this.store.getState()
if (currentState.unconnectedAccountAlertShownOrigins && this.selectedAddress !== selectedAddress) {
this.selectedAddress = selectedAddress
this.store.updateState({ unconnectedAccountAlertShownOrigins: {} })
}
})
}
setAlertEnabledness (alertId, enabledness) {
let { alertEnabledness } = this.store.getState()
alertEnabledness = { ...alertEnabledness }
alertEnabledness[alertId] = enabledness
this.store.updateState({ alertEnabledness })
}
/**
* Sets the "switch to connected" alert as shown for the given origin
* @param {string} origin - The origin the alert has been shown for
*/
setUnconnectedAccountAlertShown (origin) {
let { unconnectedAccountAlertShownOrigins } = this.store.getState()
unconnectedAccountAlertShownOrigins = { ...unconnectedAccountAlertShownOrigins }
unconnectedAccountAlertShownOrigins[origin] = true
this.store.updateState({ unconnectedAccountAlertShownOrigins })
}
}
|
JavaScript
|
class SelectFieldExampleSimple extends Component {
state = {
value: 1,
};
handleChange = (event, index, value) => this.setState({value});
render() {
return (
<div>
<SelectField
floatingLabelText="Frequency"
value={this.state.value}
onChange={this.handleChange}
>
<MenuItem value={1} primaryText="Never" />
<MenuItem value={2} primaryText="Every Night" />
<MenuItem value={3} primaryText="Weeknights" />
<MenuItem value={4} primaryText="Weekends" />
<MenuItem value={5} primaryText="Weekly" />
</SelectField>
<br />
<SelectField floatingLabelText="Frequency" value={1} disabled={true}>
<MenuItem value={1} primaryText="Disabled" />
<MenuItem value={2} primaryText="Every Night" />
</SelectField>
<br />
<SelectField
floatingLabelText="Frequency"
value={this.state.value}
onChange={this.handleChange}
style={styles.customWidth}
>
<MenuItem value={1} primaryText="Custom width" />
<MenuItem value={2} primaryText="Every Night" />
<MenuItem value={3} primaryText="Weeknights" />
<MenuItem value={4} primaryText="Weekends" />
<MenuItem value={5} primaryText="Weekly" />
</SelectField>
<br />
<SelectField
floatingLabelText="Frequency"
value={this.state.value}
onChange={this.handleChange}
autoWidth={true}
>
<MenuItem value={1} primaryText="Auto width" />
<MenuItem value={2} primaryText="Every Night" />
<MenuItem value={3} primaryText="Weeknights" />
<MenuItem value={4} primaryText="Weekends" />
<MenuItem value={5} primaryText="Weekly" />
</SelectField>
</div>
);
}
}
|
JavaScript
|
class RequestTournamentData {
JSONRequest(sv, op, sid) {
var url = 'http://test.rdb.ringen-nrw.de/index.php';
var Reqs = {
sv: sv,
op: op,
sid: sid,
};
//Shows data of upcoming matches
$.getJSON(url, Reqs, function (data) {
var dataString = JSON.stringify(data);
var result = JSON.parse(dataString);
var d = new Date(result.tnmList[matchIndex].startDate);
var dayName = days[d.getDay()];
matchAmount = result.tnmList.length;
$('.matchName').html(result.tnmList[matchIndex].name);
$('.matchDescription').html(result.tnmList[matchIndex].description);
$('.day').html(dayName + ":");
$('.matchDateTime, .matchDateSlider').html(result.tnmList[matchIndex].startDate);
//Updates Progress status
if (result.tnmList[matchIndex].startDate < CurDate) {
$('.matchProgress').html('FINISHED');
} else if (result.tnmList[matchIndex].startDate == CurDate) {
$('.matchProgress').html('IN PROGRESS');
} else {
$('.matchProgress').html('NOT STARTED');
}
})
}
}
|
JavaScript
|
class RequestParticipantData {
JSONRequest(sv, op, sid) {
var url = 'http://test.rdb.ringen-nrw.de/index.php';
var Reqs = {
sv: sv,
op: op,
sid: sid,
tnmid: matchIndex
};
//Shows data of upcoming matches
$.getJSON(url, Reqs, function (data) {
var dataString = JSON.stringify(data);
var result = JSON.parse(dataString);
console.log(result);
});
}
}
|
JavaScript
|
class Transition {
/**
* Creates a new instance of the Transition class. By defaily, this is an internal transition.
* @param source The source vertex of the transition.
* @internal
* @hidden
*/
constructor(source) {
this.source = source;
/**
* The optional guard condition that can restrict the transision being traversed based on trigger event type.
* @internal
* @hidden
*/
this.typeGuard = () => true;
/**
* The optional guard condition that can restrict the transition being traversed based on user logic.
* @internal
* @hidden
*/
this.userGuard = () => true;
/**
* The user defined actions that will be called on transition traversal.
* @internal
* @hidden
*/
this.actions = [];
this.target = source;
this.execute = internalTransition;
this.source.outgoing.push(this);
}
/**
* Adds an event type constraint to the transition; it will only be traversed if a trigger event of this type is evaluated.
* @param eventType The type of trigger event that will cause this transition to be traversed.
* @return Returns the transitions thereby allowing a fluent style transition construction.
*/
on(eventType) {
this.typeGuard = (trigger) => trigger.constructor === eventType;
return this;
}
/**
* Adds an guard condition to the transition; it will only be traversed if the guard condition evaluates true for a given trigger event.
* @param guard A boolean predicate callback that takes the trigger event as a parameter.
* @return Returns the transitions thereby allowing a fluent style transition construction.
* @remarks It is recommended that this is used in conjunction with the on method, which will first test the type of the trigger event.
*/
when(guard) {
this.userGuard = guard;
return this;
}
/**
* Specifies a target vertex of the transition and the semantics of the transition.
* @param target The target vertex of the transition.
* @param kind The kind of transition, defining the precise semantics of how the transition will impact the active state configuration.
* @return Returns the transitions thereby allowing a fluent style transition construction.
*/
to(target, kind = _1.TransitionKind.External) {
this.target = target;
if (kind === _1.TransitionKind.External) {
this.execute = externalTransition(this.source, this.target);
}
else {
this.execute = localTransition;
}
return this;
}
/**
* Adds user-defined behaviour to the transition that will be called after the source vertex has been exited and before the target vertex is entered.
* @param actions The action, or actions to call with the trigger event as a parameter.
* @return Returns the transitions thereby allowing a fluent style transition construction.
*/
effect(...actions) {
this.actions.push(...actions);
return this;
}
/**
* Tests the trigger event against both the event type constraint and guard condition if specified.
* @param trigger The trigger event.
* @returns Returns true if the trigger event was of the event type and the guard condition passed if specified.
* @internal
* @hidden
*/
evaluate(trigger) {
return this.typeGuard(trigger) && this.userGuard(trigger);
}
/**
* Traverses a transition.
* @param transaction The current transaction being executed.
* @param deepHistory True if deep history semantics are in play.
* @param trigger The trigger event.
* @internal
* @hidden
*/
traverse(transaction, deepHistory, trigger) {
var transition = this;
// initilise the composite with the initial transition
const transitions = [transition];
// For junction pseudo states, we must follow the transitions prior to traversing them
while (transition.target instanceof _1.PseudoState && (transition.target.kind & _1.PseudoStateKind.Junction) && (transition = transition.target.getTransition(trigger))) {
transitions.push(transition);
}
// execute the transition strategy for each transition in composite
transitions.forEach(t => t.execute(transaction, deepHistory, trigger, t));
}
}
|
JavaScript
|
class Main
{
constructor ()
{
//this.keyboard = new Keyboard();
this.sceneRenderer = new SceneRenderer();
this.sceneRenderer.CreateScene();
this.start = false;
this.loader = new THREE.TextureLoader();
this.player1 = new Player("Player 1");
this.player2 = new Player("Player 2");
/*Resetable Variables */
this.currentPlayersTurn = this.player1;
$(".playerTurn").html(this.currentPlayersTurn.name);
this.turnEnd = false;
this.ballsStopped = true;
this.ballInHole = false;
this.playerShot = false;
this.WhiteBallInHole = false;
this.gameDone = false;
this.balls = new Array();
//this.balls[0] is main ball
this.SpawnBall(0,-20,"BallCue.jpg",0);
this.mouse = new Mouse(this.balls[0],this.sceneRenderer.camera);
document.addEventListener("onshoot",(e)=> {this.OnShoot(e);});
this.sceneRenderer.AddObject(this.mouse.line);
this.SpawnAllBalls();
/*Light */
var light = new THREE.AmbientLight( 0xffffff,0.5);
//light.castShadow = true;
light.position.set( 0, 1, 1 );
this.sceneRenderer.AddObject(light);
var light = new THREE.PointLight(0x40ff00);
light.castShadow = true;
light.position.set( 0, 0, 5 );//.normalize();//?
this.sceneRenderer.AddObject(light);
var light = new THREE.SpotLight(0xffffff,0.25);
light.castShadow = true;
light.position.set( 0, 60, 80);//.normalize();//?
light.shadow.camera.near = 1;
light.shadow.camera.far = 225;
// var test = new THREE.CameraHelper( light.shadow.camera )
//this.sceneRenderer.AddObject(test);
this.sceneRenderer.AddObject(light);
//SkyDome
var skyGeo = new THREE.SphereGeometry(1000, 25, 25);
var material = new THREE.MeshBasicMaterial();
material.map = this.loader.load("assets/textures/skydome02.jpg");
var sky = new THREE.Mesh(skyGeo, material);
var rot = (90 * Math.PI) /180;
sky.rotateX(rot);
sky.position.set(0,0,200);
sky.material.side = THREE.BackSide;
this.sceneRenderer.AddObject(sky);
/*field*/
this.fieldObjects = new Array();
var geometry = new THREE.BoxGeometry(2,60,2);
var material = new THREE.MeshLambertMaterial();
material.map = this.loader.load("assets/textures/wood.jpg");
var box = new THREE.Mesh(geometry,material);
box.position.set(20,0,0);
box.receiveShadow = true;
box.castShadow = true;
this.sceneRenderer.AddObject(box);
this.fieldObjects.push(box);
var geometry = new THREE.BoxGeometry(2,60,2);
var box = new THREE.Mesh(geometry,material);
box.position.set(-20,0,0);
box.receiveShadow = true;
box.castShadow = true;
this.sceneRenderer.AddObject(box);
this.fieldObjects.push(box);
var geometry = new THREE.BoxGeometry(40,2,2);
var box = new THREE.Mesh(geometry,material);
box.position.set(0,-30,0);
box.receiveShadow = true;
box.castShadow = true;
this.sceneRenderer.AddObject(box);
this.fieldObjects.push(box);
var geometry = new THREE.BoxGeometry(40,2,2);
var box = new THREE.Mesh(geometry,material);
box.position.set(0,30,0);
box.receiveShadow = true;
box.castShadow = true;
this.sceneRenderer.AddObject(box);
this.fieldObjects.push(box);
//floor
var floorHeight = 20;
var geometry = new THREE.PlaneGeometry(250,250);
var plane = new THREE.Mesh(geometry,material);
plane.position.set(0,0,-floorHeight);
plane.receiveShadow = true;
plane.castShadow = true;
this.sceneRenderer.AddObject(plane);
this.fieldObjects.push(plane);
//feets
var geometry = new THREE.BoxGeometry(2,2,floorHeight);
var box = new THREE.Mesh(geometry,material);
box.position.set(20,30,-(floorHeight/2));
box.receiveShadow = true;
box.castShadow = true;
this.sceneRenderer.AddObject(box);
this.fieldObjects.push(box);
var geometry = new THREE.BoxGeometry(2,2,floorHeight);
var box = new THREE.Mesh(geometry,material);
box.position.set(-20,30,-(floorHeight/2));
box.receiveShadow = true;
box.castShadow = true;
this.sceneRenderer.AddObject(box);
this.fieldObjects.push(box);
var geometry = new THREE.BoxGeometry(2,2,floorHeight);
var box = new THREE.Mesh(geometry,material);
box.position.set(20,-30,-(floorHeight/2));
box.receiveShadow = true;
box.castShadow = true;
this.sceneRenderer.AddObject(box);
this.fieldObjects.push(box);
var geometry = new THREE.BoxGeometry(2,2,floorHeight);
var box = new THREE.Mesh(geometry,material);
box.position.set(-20,-30,-(floorHeight/2));
box.receiveShadow = true;
box.castShadow = true;
this.sceneRenderer.AddObject(box);
this.fieldObjects.push(box);
//pool floor
var geometry = new THREE.BoxGeometry(40,60,1);
var material = new THREE.MeshLambertMaterial();
material.map = this.loader.load("assets/textures/test.jpg");
var box = new THREE.Mesh(geometry,material);
box.position.set(0,0,-1);
box.receiveShadow = true;
box.castShadow = true;
this.sceneRenderer.AddObject(box);
this.fieldObjects.push(box);
//Holes
this.holeBalls = Array();
this.SpawnHoleBall(18,28);
this.SpawnHoleBall(-18,-28);
this.SpawnHoleBall(18,-28);
this.SpawnHoleBall(-18,28);
this.SpawnHoleBall(18,0);
this.SpawnHoleBall(-18,0);
document.addEventListener("onballinhole",(e)=> {this.OnBallInHole(e);});
//Both
this.allObjects = this.balls.concat(this.fieldObjects);
//this.allObjects.splice(this.mouse.mainBall);
//Events
document.addEventListener("onrenderupdate",(e)=> {this.OnRenderUpdate(e);});
document.addEventListener("oncollisionupdate",(e)=> {this.OnCollisionUpdate(e);});
$(".start").click("onStartClick",(e)=> {this.OnStartClick(e);});
this.sceneRenderer.Render();
var peopleTalking = document.createElement('audio');
peopleTalking.appendChild(audioSources.peopleTalking);
peopleTalking.volume = 0.3;
peopleTalking.loop = true;
peopleTalking.play();
}
OnBallInHole(e)
{
if(e.detail.ballNr == 0)
{
e.detail.position.set(0,-20,-20);
e.detail.velocity.set(0,0,0);
this.WhiteBallInHole = true;
this.turnEnd = true;
return;
}
if(e.detail.ballNr == 8)
{
if(this.HaveAllBallIn())
{
// console.log("Won");
$(".playerTurn").html(this.currentPlayersTurn.name + " Won :D ! PARTY! Refresh!");
}
else
{
// console.log("Lost");
$(".playerTurn").html(this.currentPlayersTurn.name + " Lost :( Go cry in corner Refresh!");
}
this.gameDone = true;
this.Reset();
}
if(this.player1.ballSet == false || this.player2.ballSet == false )
{
if (e.detail.ballNr < 8)
{
this.player1.firstHalf = true;
}
else if(e.detail.ballNr > 8)
{
this.player2.firstHalf = true;
}
this.player1.ballSet = true;
this.player2.ballSet = true;
}
if(e.detail.ballNr > 8 && this.currentPlayersTurn.firstHalf
|| e.detail.ballNr < 8 && !this.currentPlayersTurn.firstHalf)
{
this.turnEnd = true;
}
this.RemoveBall(e.detail);
this.sceneRenderer.RemoveObject(e.detail);
if(this.balls.length == 1)
{
console.log("win");
}
this.ballInHole = true;
}
OnRenderUpdate(e)
{
if(this.start == true && !this.gameDone)
{
for (var i = 0; i < this.balls.length; i++)
{
this.balls[i].OnUpdate(e);
}
this.CameraControl();
$(".speed").html("Power:" + this.mouse.power);
if(this.ballsStopped)
{
if(this.playerShot)
{
if(this.ballInHole == false)
{
this.turnEnd = true;
}
this.playerShot = false;
}
if((this.turnEnd))
{
if (this.currentPlayersTurn == this.player1)
this.currentPlayersTurn = this.player2;
else
this.currentPlayersTurn = this.player1;
this.turnEnd = false;
}
if(this.WhiteBallInHole)
{
this.balls[0].position.set(0,-20,0);
this.WhiteBallInHole = false;
}
}
var text = "Turn: " + this.currentPlayersTurn.name;
if(this.currentPlayersTurn.ballSet == true)
{
if (this.currentPlayersTurn.firstHalf == false)
{
text = text + "\nShoot half balls";
}
else
{
text = text + "\nShoot whole balls";
}
}
else
{
text = text + "\nNo side picked";
}
$(".playerTurn").html(text);
}
if(keyboard.GetKey('b'))
{
this.start = false;
$(".start").show();
}
if(keyboard.GetKey('r'))
{
this.Reset();
}
}
OnCollisionUpdate(e)
{
if(this.start == true)
{
this.ballsStopped = true;
for (var i = 0; i < this.balls.length; i++)
{
this.balls[i].CollisionUpdate(this.balls,this.fieldObjects);
if(this.balls[i].velocity.x != 0 || this.balls[i].velocity.y !=0 || this.balls[i].velocity.z != 0)
{
this.ballsStopped = false;
}
}
for(var i = 0; i < this.holeBalls.length; i++)
{
this.holeBalls[i].CollisionUpdate(this.balls);
}
if(this.ballsStopped == true)
{
this.sceneRenderer.RemoveObject(this.mouse.line);
this.mouse.OnMouseRayUpdate(this.allObjects , this.sceneRenderer.camera);
this.sceneRenderer.AddObject(this.mouse.line);
}
}
}
OnShoot(e)
{
this.ballInHole = false;
this.playerShot = true;
this.ballsStopped = false;
}
CameraControl()
{
if(keyboard.GetKey('q') == true)
{
this.sceneRenderer.RotateLeftRight(50*DeltaTime);
}
if(keyboard.GetKey('e') == true)
{
this.sceneRenderer.RotateLeftRight(-50*DeltaTime);
}
if(keyboard.GetKey('a') == true)
{
this.sceneRenderer.camera.translateX(-25 * DeltaTime);
//this.sceneRenderer.camera.rotateZ(-10 * DeltaTime);
// this.Translate(-this.speed * DeltaTime,0,0);
}
if(keyboard.GetKey('d') == true)
{
this.sceneRenderer.camera.translateX(25 * DeltaTime);
//this.sceneRenderer.camera.rotateZ(10 * DeltaTime);
//this.Translate(this.speed * DeltaTime,0,0);
}
if(keyboard.GetKey('s') == true)
{
this.sceneRenderer.ForwardBackward(25 * DeltaTime);
}
if(keyboard.GetKey('w') == true)
{
this.sceneRenderer.ForwardBackward(-25 * DeltaTime);
}
// console.log(this.sceneRenderer.camera.position);
}
Reset()
{
this.currentPlayersTurn = this.player1;
$(".playerTurn").html(this.currentPlayersTurn.name);
this.turnEnd = false;
this.ballsStopped = true;
this.ballInHole = false;
this.playerShot = false;
this.WhiteBallInHole = false;
this.gameDone = false;
this.RemoveAllBalls();
this.SpawnBall(0,-20,"BallCue.jpg",0);
this.mouse.mainBall = this.balls[0];
this.SpawnAllBalls();
this.allObjects = this.balls.concat(this.fieldObjects);
this.start = false;
$(".start").show();
this.canShoot = false;
}
SpawnAllBalls()
{
var ballCount = 1;
for(var i = 0; i < 5; i++)
{
var x = -4 + i * 2;
var y = 4;
this.SpawnBall(x,y,"Ball"+ballCount +".jpg",ballCount);
ballCount ++;
}
for(var i = 0; i < 4; i++)
{
var x = -3 + i * 2;
var y = 2;
this.SpawnBall(x,y,"Ball"+ballCount +".jpg",ballCount);
ballCount ++;
}
for(var i = 0; i < 3; i++)
{
var x = -2 + i * 2;
var y = 0;
this.SpawnBall(x,y,"Ball"+ballCount +".jpg",ballCount);
ballCount ++;
}
for(var i = 0; i < 2; i++)
{
var x = -1 + i * 2;
var y = -2;
this.SpawnBall(x,y,"Ball"+ballCount +".jpg",ballCount);
ballCount ++;
}
var x = 0;
var y = -4;
this.SpawnBall(x,y,"Ball"+ballCount +".jpg",ballCount);
}
RemoveAllBalls()
{
for(var i = 0; i < this.balls.length; i++)
{
this.sceneRenderer.RemoveObject(this.balls[i]);
}
this.balls = new Array();
}
SpawnBall(x,y,textureName,ballNr)
{
var geometry = new THREE.SphereGeometry(1,12,12);//THREE.BoxGeometry(1,2,1);
var material = new THREE.MeshPhongMaterial();
//var color = (0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
material.map = this.loader.load("assets/textures/" + textureName);
var ball = new Ball(geometry,material);
var ballPosZ = 0;
ball.position.set(x,y, ballPosZ);
ball.ballNr = ballNr;
ball.receiveShadow = true;
ball.castShadow = true;
this.sceneRenderer.AddObject(ball);
this.balls.push(ball);
}
SpawnHoleBall(x,y)
{
var geometry = new THREE.SphereGeometry(2,12,12);
var material = new THREE.MeshLambertMaterial();
material.color.setHex("0x000000");
var holeBall = new HoleBall(geometry,material);
holeBall.position.set(x,y,-1);
// holeBall.addEventListener()
this.sceneRenderer.AddObject(holeBall);
this.holeBalls.push(holeBall);
}
HaveAllBallIn()
{
for(var i = 0; i < this.balls.length; i ++)
{
if(this.balls[i].ballNr < 8 && this.currentPlayersTurn.firstHalf
|| this.balls[i].ballNr > 8 && !this.currentPlayersTurn.firstHalf)
{
return false;
}
}
return true;
}
RemoveBall(ball)
{
for(var i = 0; i < this.balls.length; i++)
{
if(this.balls[i] == ball)
{
this.balls.splice(i,1);
break;
}
}
}
OnStartClick(e)
{
this.start = true;
$(".start").hide();
this.mouse.Init();
}
}
|
JavaScript
|
class DataBuffer {
/**
* Construct buffer.
*/
constructor(options = {}) {
// Link to first buffer item
this._firstBufferItem = null;
this._lastBufferItem = null;
this._listeners = new Map();
//If option passed don't save buffer
if (options.hasOwnProperty('disableStoring'))
this._disableStoring = options.disableStoring;
else
this._disableStoring = false;
}
/**
* Push packet to buffer. Methdo will notify all buffer listeners
* implementing "onPush" callback.
*
* @param packet
* Bufferable data packet
* @param options
*/
push(packet) {
//if option was set when starting then don't store data
if (!this._disableStoring) {
let bufferItem = new BufferItem(packet);
if (this._firstBufferItem == null)
this._firstBufferItem = bufferItem;
if (this._lastBufferItem == null) {
this._lastBufferItem = bufferItem;
} else {
this._lastBufferItem.setNext(bufferItem);
this._lastBufferItem = bufferItem;
}
}
// Notify listeners which extends onPush callback
this._listeners.forEach((listener, listenerKey) => {
if (listener.hasOwnProperty('onPush'))
listener.onPush(packet);
});
}
/**
* Fetch next packet from buffer.
*
* @return packet
* Data packet or null if buffer is empty.
*/
fetch() {
let bufferItem = this._firstBufferItem;
let packet = bufferItem != null ? bufferItem.getPacket() : null;
let nextBufferItem = bufferItem != null ? bufferItem.getNext() : null;
if (nextBufferItem != null)
this._firstBufferItem = nextBufferItem;
else
this._firstBufferItem = this._lastBufferItem = null;
return packet;
}
/**
* Method to check if buffer has data available.
*
* @return boolean hasData
*/
hasData() {
return this._firstBufferItem == null ? false : true;
}
/**
* Register event listener for data buffer.
*
* @param name
* Listener key name to be used when unregistering listener.
* @param callback
* Listener callback
*/
registerListener(name, listener) {
this._listeners.set(name, listener);
}
/**
* Unregister listener.
*
* @param name
*/
unregisterListener(name) {
if (this._listeners.has(name))
return this._listeners.delete(name)
}
}
|
JavaScript
|
class AdRequestCriticalPath extends Audit {
/**
* @return {LH.Audit.Meta}
* @override
*/
static get meta() {
// @ts-ignore - TODO: add AsyncCallStacks to enum.
return {
id,
title,
failureTitle,
description,
requiredArtifacts: ['devtoolsLogs', 'traces', 'AsyncCallStacks'],
};
}
/**
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts, context) {
const trace = artifacts.traces[Audit.DEFAULT_PASS];
const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS];
const networkRecords = await NetworkRecords.request(devtoolsLog, context);
const criticalRequests = getAdCriticalGraph(
networkRecords, trace.traceEvents);
const REQUEST_TYPES = ['Script', 'XHR', 'Fetch', 'EventStream', 'Document'];
const blockingRequests = Array.from(criticalRequests)
.filter((r) => REQUEST_TYPES.includes(r.resourceType))
.filter((r) => r.mimeType != 'text/css');
if (!blockingRequests.length) {
return auditNotApplicable(NOT_APPLICABLE.NO_ADS);
}
const pageStartTime = getPageStartTime(networkRecords);
let tableView = blockingRequests.map((req) => ({
url: trimUrl(req.url),
abbreviatedUrl: getAbbreviatedUrl(req.url),
type: req.resourceType,
startTime: (req.startTime - pageStartTime) * 1000,
endTime: (req.endTime - pageStartTime) * 1000,
duration: (req.endTime - req.startTime) * 1000,
})).filter((r) => r.duration > 30 && r.startTime > 0);
tableView = computeSummaries(tableView);
const depth = computeDepth(tableView);
const failed = depth > 3;
const serialPluralEnding = depth != 1 ? 's' : '';
const totalPluralEnding = tableView.length != 1 ? 's' : '';
return {
rawValue: depth,
score: failed ? 0 : 1,
displayValue: util.format(
displayValue,
depth,
serialPluralEnding,
tableView.length,
totalPluralEnding
),
details: AdRequestCriticalPath.makeTableDetails(HEADINGS, tableView),
};
}
}
|
JavaScript
|
class SignToPersonalSignSubprovider extends Subprovider {
constructor(opts) {
super(opts)
this.stripPrefix = opts.stripPrefix
}
handleRequest(payload, next, end) {
if (payload.method === 'eth_sign') {
let [addr, data] = payload.params
if (this.stripPrefix) data = stripPrefix(data)
payload.method = 'personal_sign'
payload.params = [data, addr, '']
}
next()
}
}
|
JavaScript
|
class Skinner {
constructor() {
this.components = null;
}
getComponent(name) {
if (this.components === null) {
throw new Error(
"Attempted to get a component before a skin has been loaded."+
" This is probably because either:"+
" a) Your app has not called sdk.loadSkin(), or"+
" b) A component has called getComponent at the root level",
);
}
let comp = this.components[name];
// XXX: Temporarily also try 'views.' as we're currently
// leaving the 'views.' off views.
if (!comp) {
comp = this.components['views.'+name];
}
if (!comp) {
throw new Error("No such component: "+name);
}
// components have to be functions.
const validType = typeof comp === 'function';
if (!validType) {
throw new Error(`Not a valid component: ${name}.`);
}
return comp;
}
load(skinObject) {
if (this.components !== null) {
throw new Error(
"Attempted to load a skin while a skin is already loaded"+
"If you want to change the active skin, call resetSkin first"
);
}
this.components = {};
var compKeys = Object.keys(skinObject.components);
for (var i = 0; i < compKeys.length; ++i) {
var comp = skinObject.components[compKeys[i]];
this.addComponent(compKeys[i], comp);
}
}
addComponent(name, comp) {
var slot = name;
if (comp.replaces !== undefined) {
if (comp.replaces.indexOf('.') > -1) {
slot = comp.replaces;
} else {
slot = name.substr(0, name.lastIndexOf('.') + 1) + comp.replaces.split('.').pop();
}
}
this.components[slot] = comp;
}
reset() {
this.components = null;
}
}
|
JavaScript
|
class WrappedAead {
/**
* @param {!PrimitiveSet.PrimitiveSet} aeadSet
*/
// The constructor should be @private, but it is not supported by Closure
// (see https://github.com/google/closure-compiler/issues/2761).
constructor(aeadSet) {
/** @private @const {!PrimitiveSet.PrimitiveSet} */
this.aeadSet_ = aeadSet;
}
/**
* @param {!PrimitiveSet.PrimitiveSet} aeadSet
*
* @return {!Aead}
*/
static newAead(aeadSet) {
if (!aeadSet) {
throw new SecurityException('Primitive set has to be non-null.');
}
if (!aeadSet.getPrimary()) {
throw new SecurityException('Primary has to be non-null.');
}
return new WrappedAead(aeadSet);
}
/**
* @override
*/
async encrypt(plaintext, opt_associatedData) {
if (!plaintext) {
throw new SecurityException('Plaintext has to be non-null.');
}
const primitive = this.aeadSet_.getPrimary().getPrimitive();
const encryptedText =
await primitive.encrypt(plaintext, opt_associatedData);
const keyId = this.aeadSet_.getPrimary().getIdentifier();
const ciphertext = new Uint8Array(keyId.length + encryptedText.length);
ciphertext.set(keyId, 0);
ciphertext.set(encryptedText, keyId.length);
return ciphertext;
}
/**
* @override
*/
async decrypt(ciphertext, opt_associatedData) {
if (!ciphertext) {
throw new SecurityException('Ciphertext has to be non-null.');
}
if (ciphertext.length > CryptoFormat.NON_RAW_PREFIX_SIZE) {
const keyId = ciphertext.subarray(0, CryptoFormat.NON_RAW_PREFIX_SIZE);
const entries = await this.aeadSet_.getPrimitives(keyId);
const rawCiphertext = ciphertext.subarray(
CryptoFormat.NON_RAW_PREFIX_SIZE, ciphertext.length);
let /** @type {!Uint8Array} */ decryptedText;
try {
decryptedText = await this.tryDecryption_(
entries, rawCiphertext, opt_associatedData);
} catch (e) {
}
if (decryptedText) {
return decryptedText;
}
}
const entries = await this.aeadSet_.getRawPrimitives();
const decryptedText =
await this.tryDecryption_(entries, ciphertext, opt_associatedData);
return decryptedText;
}
/**
* Tries to decrypt the ciphertext using each entry in entriesArray and
* returns the ciphertext decrypted by first primitive which succeed. It
* throws an exception if no entry succeeds.
*
* @private
* @param {!Array<!PrimitiveSet.Entry>} entriesArray
* @param {!Uint8Array} ciphertext
* @param {?Uint8Array=} opt_associatedData
*
* @return {!Promise<!Uint8Array>}
*/
async tryDecryption_(entriesArray, ciphertext, opt_associatedData) {
const entriesArrayLength = entriesArray.length;
for (let i = 0; i < entriesArrayLength; i++) {
if (entriesArray[i].getKeyStatus() != PbKeyStatusType.ENABLED) {
continue;
}
const primitive = entriesArray[i].getPrimitive();
let decryptionResult;
try {
decryptionResult =
await primitive.decrypt(ciphertext, opt_associatedData);
} catch (e) {
continue;
}
return decryptionResult;
}
throw new SecurityException('Decryption failed for the given ciphertext.');
}
}
|
JavaScript
|
class TinyMCEActionRegistrar {
constructor() {
this.actions = {};
}
/**
* Register a new action for a menu item, and trigger callback
*
* @param {String} menu Name of top level menu item
* @param {Object} action Menu action option
*/
addAction(menu, action) {
this.actions[menu] = this.getActions(menu).concat([action]);
}
/**
* Get list of actions for this menu
*
* @param {String} menu
* @return {Array}
*/
getActions(menu) {
return this.actions[menu] || [];
}
}
|
JavaScript
|
class MyCircle extends CGFobject {
constructor(scene, nVertices) {
super(scene);
this.nVertices = nVertices;
this.initBuffers();
}
/**
* Initialize vertices, normals, texture coordinates and indices of the circle
*/
initBuffers() {
this.vertices = [ ];
this.normals = [ ];
this.texCoords = [ ];
this.indices = [ ];
var dangle = (Math.PI * 2)/this.nVertices, angle = 0;
var x, y;
for (var i = 0; i < this.nVertices; i++) {
x = Math.cos(angle);
y = Math.sin(angle);
// Front
this.vertices.push(x, y, 0);
this.normals.push(0, 0, 1);
this.texCoords.push(0.5 + x / 2, 1 - (0.5 + y / 2));
this.indices.push(i * 2, ((i + 1) * 2) % (this.nVertices * 2), this.nVertices * 2);
// Back
this.vertices.push(x, y, 0);
this.normals.push(0, 0, -1);
this.texCoords.push(1 - (0.5 + x / 2), 1 - (0.5 + y / 2));
this.indices.push(((i + 1) * 2 + 1) % (this.nVertices * 2), i * 2 + 1, this.nVertices * 2 + 1);
angle += dangle;
}
this.vertices.push(0, 0, 0); this.vertices.push(0, 0, 0);
this.normals.push(0, 0, 1); this.normals.push(0, 0, -1);
this.texCoords.push(0.5, 0.5); this.texCoords.push(0.5, 0.5);
this.primitiveType = this.scene.gl.TRIANGLES;
this.initGLBuffers();
}
setFillMode() {
this.primitiveType=this.scene.gl.TRIANGLES;
}
setLineMode() {
this.primitiveType=this.scene.gl.LINES;
};
}
|
JavaScript
|
class PackSpritesheetLoader {
static async use(resource, next) {
if (
!resource.data ||
resource.type !== LoaderResource.TYPE.JSON ||
!isPackJson(resource.data)
) {
next()
return
}
const loadOptions = {
crossOrigin: resource.crossOrigin,
parentResource: resource,
}
// Load each sprite sheet as a resource
try {
await Promise.all(
Object.keys(resource.data).map(async key => {
return new Promise((resolve, reject) => {
const metaSheet = resource.data[key]
const pixiSheet = packToPixi(metaSheet, key)
this.add(`${key}_image`, key, loadOptions, res => {
if (res.error) {
reject(res.error)
return
}
const spritesheet = new Spritesheet(
res.texture.baseTexture,
pixiSheet,
resource.url
)
spritesheet.parse(() => {
resource.spritesheet = spritesheet
resource.textures = spritesheet.textures
resolve()
})
})
})
})
)
} catch (error) {
next(error)
}
next()
}
}
|
JavaScript
|
class Node extends EventEmitter {
constructor(nodeType, dbPath, port, protocolClass, initPeerUrls, debug, noserver) {
// if (new.target === Node) {
// throw new TypeError("Cannot construct Node instances directly.");
// }
super();
// some necessary info
this.uuid = uuidv1();
this.nodeType = nodeType;
this.initPeerUrls = initPeerUrls;
if (true) {
if (fs.existsSync(dbPath) && fs.statSync(dbPath).isDirectory()) {
console.log('Using existing LevelDB directory.');
} else {
console.log('A new LevelDB directory will be created.');
}
}
// initialize the database (Level DB)
this.db = levelup(leveldb(dbPath));
// create underlying litenode
this.litenode = new LiteNode(this.uuid, { port, debug, noserver });
// instantiate the protocol manager
this.protocol = new protocolClass(this);
this.protocol.on('ready', () => {
// connect to initial peers
this.initPeerUrls.forEach(url => this.litenode.createConnection(url));
this.emit('ready');
});
}
/**
* @param {string|Array<string>} nodeTypes pass `*` for matching all types
*/
peers(nodeTypes = '*') {
if (typeof nodeTypes === 'string' && nodeTypes !== '*') {
nodeTypes = [nodeTypes];
}
let peers = this.litenode ? Object.values(this.litenode.peers) : [];
return peers.filter(peer => nodeTypes === '*' || nodeTypes.includes(peer.nodeType));
}
/**
* Do the cleanup.
*/
close() {
this.removeAllListeners();
this.protocol.close();
this.litenode.close();
this.db.close();
}
}
|
JavaScript
|
class ThinLiteProtocol extends P2PProtocol {
static get ver() {
return VERSION;
}
constructor(node) {
super(node, { nodeTypes: AUTO_CONN_NODE_TYPES });
this.invHandler = this.invHandler.bind(this);
this.headersHandler = this.headersHandler.bind(this);
this.dataHandler = this.dataHandler.bind(this);
this.peerConnectHandler = this.peerConnectHandler.bind(this);
this.litestore = new LiteProtocolStore(node.db);
// a blockchain manager
this.blockchain = new Blockchain(this.litestore);
// wait for blockchain initializing itself
this.blockchain.on('ready', () => this.init());
// or upon error
this.blockchain.on('error', err => {
console.error(err);
process.exit(1);
});
}
init() {
// register message/connection handlers
this.litenode.on(`message/${messageTypes.inv}`, this.invHandler);
this.litenode.on(`message/${messageTypes.headers}`, this.headersHandler);
this.litenode.on(`message/${messageTypes.data}`, this.dataHandler);
this.litenode.on('peerconnect', this.peerConnectHandler);
this.handshake = new HandshakeManager(this);
if (this.litenode.debug && "node" === 'node') {
// create and run rest server
let debugPort = this.litenode.debugPort;
createRestServer(this).listen(debugPort);
console.log(`Debugging RESTful API server listening on port ${debugPort}.`);
}
// protocol handling setup is ready now
this.emit('ready');
}
/**
* If the given litemessage id is in LevelDB's litemessage index.
*/
async hasLitemsg(litemsgId) {
return await this.litestore.hasLitemsg(litemsgId);
}
async invHandler({ messageType, ...payload }, peer) {
try {
messageValidators[messageType](payload);
// Note the "blocks" here either is a single block just
// mined by peer, or is a sub blockchain, which, in
// other words, means those blocks are consecutive.
// This is just due to how the protocol is designed.
let { blocks } = payload;
let blocksToGet = [];
// Filter out blocks already have (blocks off main branch
// still as being haven). Also note that those blocks haven
// by the current node, if any, must always certainly reside
// at the beginning of received `inv`'s blockchain. Again,
// this is just due to how the protocol is designed.
for (let blockId of blocks) {
if (!(await this.blockchain.hasBlock(blockId, false))) {
blocksToGet.push(blockId);
}
}
if (blocksToGet.length) {
peer.sendJson(
getHeaders({ blocks: blocksToGet })
);
}
} catch (err) {
console.warn(err);
}
}
async headersHandler({ messageType, ...payload }, peer) {
try {
messageValidators[messageType](payload);
// `blocks` is only header (don't have body)
let { blocks } = payload;
// filter out invalid blocks (headers)
blocks = blocks.filter(block => verifyHeader(block));
blocks.sort((a, b) => a.height - b.height);
let headBlockId = this.blockchain.getHeadBlockIdSync();
if (blocks.length && blocks[blocks.length - 1].height > this.blockchain.getCurHeightSync()) {
if (blocks.length === 1) {
let block = blocks[0];
if (block.prevBlock === headBlockId) {
this.blockchain.append(block);
} else {
let blockLocators = this.blockchain.getLocatorsSync();
peer.sendJson(getBlocks({ blockLocators }));
}
} else {
// Note that `prevBlockId` and `prevBlock` down below refer to same block.
// Later, they will be used for traversing backward along the blockchain.
let prevBlockId = blocks[0].prevBlock;
let prevBlock = prevBlockId ?
(await this.blockchain.getBlock(prevBlockId)) :
undefined;
if (verifyHeaderChain(blocks, prevBlock)) {
// For efficiency, node doesn't fetch blocks on forked branch which it already
// has. The `litemsg_${litemsg_id}` of these mentioned blocks might be records
// on the main branch (before appending). So here, suppose the previous
// block of appended blocks is not on main branch, we need to extend from
// the appended blocks backwards to until a block which is on the main
// branch, or until the genesis block (of the forked branch), whichever reaches
// first. And then rewrite all `litemsg_${litemsg_id}` records so that all
// litemessages are correctly indexed after switching to another branch.
let extendedBlocks = [];
while (prevBlockId && !this.blockchain.onMainBranchSync(prevBlockId)
&& headBlockId === this.blockchain.getHeadBlockIdSync()) {
extendedBlocks.unshift(prevBlock);
prevBlockId = prevBlock.prevBlock;
prevBlock = prevBlockId ?
(await this.blockchain.getBlock(prevBlockId)) :
undefined;
}
if (headBlockId === this.blockchain.getHeadBlockIdSync()) {
// switch the blockchain to another branch,
// for efficiency, don't await it finishing
// (no await here)
this.blockchain.appendAt([...extendedBlocks, ...blocks]);
}
}
}
}
} catch (err) {
console.warn(err);
}
}
peerConnectHandler(peer) {
if (peer.nodeType === 'full' && this.node.peers('full').length === 1) {
// wait for 30 seconds to retrieve blocks
// because of concorrent resolving (it takes
// time to construct connections with peers)
setTimeout(() => {
let blockLocators = this.blockchain.getLocatorsSync();
peer.sendJson(getBlocks({ blockLocators }));
}, 20000);
}
// TODO
// peer._resolver = new InventoryResolver(peer, this);
}
async dataHandler({ messageType, ...payload }, peer) {
try {
messageValidators[messageType](payload);
let { blocks } = payload;
// filter out invalid blocks and those that aren't on main branch
blocks = blocks.filter(block => verifyBlock(block)
&& this.blockchain.onMainBranchSync(block.hash));
for (let block of blocks) {
// index body (litemessages) of the block
this.blockchain.updateBlock(block);
}
} catch (err) {
console.warn(err);
}
}
close() {
this.handshake.close();
super.close();
}
}
|
JavaScript
|
class P2PProtocol extends EventEmitter {
/**
* @param {*} node full node, thin node, or...
* @param {*} options
* nodeTypes nodeTypes node types to which a node will try to establish connection
* automatically. For instance, you want to maintain connected
* `full` nodes at least with a specific number, but you don't
* care how many `thin` nodes are connected. So you should only
* give `full` here, instead of both.
* minPeerNum the minimal number of peers of type specified by `nodeTypes`
*/
constructor(node, { nodeTypes = [], minPeerNum = 8 } = {}) {
super();
// if (new.target === P2PProtocol) {
// throw new TypeError("Cannot construct P2PProtocol instances directly.");
// }
this.persistPeerUrls = this.persistPeerUrls.bind(this);
this.fetchPeersHandler = this.fetchPeersHandler.bind(this);
this.returnPeersHandler = this.returnPeersHandler.bind(this);
this.node = node;
this.litenode = node.litenode;
this.intervalTimers = [];
this.store = new P2PProtocolStore(node.db);
this.nodeTypes = nodeTypes;
this.minPeerNum = minPeerNum;
// register message handlers
this.litenode.on(`message/${messageTypes['fetchPeers']}`, this.fetchPeersHandler);
this.litenode.on(`message/${messageTypes['returnPeers']}`, this.returnPeersHandler);
if (nodeTypes.length) {
this.connectToLastConnectedPeers();
// periodically fetch more peers of given node types
this.intervalTimers.push(
setInterval(() => {
if (this.node.peers(nodeTypes).length < minPeerNum) {
this.litenode.broadcastJson(fetchPeers({ nodeTypes }));
}
}, 10000)
);
// periodically persist peer urls
this.intervalTimers.push(
setInterval(this.persistPeerUrls, 120000)
);
}
}
async connectToLastConnectedPeers() {
try {
let initUrls = this.node.initPeerUrls;
if (true) {
// initial peer urls can be hostnames, so perform dns queries first
var addresses = await Promise.all(
initUrls.map(url => lookup(new URL(url).hostname, { family: 4 }))
);
}
initUrls = initUrls.map((url, i) => {
url = new URL(url);
if (addresses) {
url.hostname = addresses[i].address
}
return url.toString().replace(/\/$/, '');
});
(await this.store.readCurPeerUrls())
.filter(url => !initUrls.includes(url))
.forEach(url => this.litenode.createConnection(url));
} catch (err) {
console.error(err);
process.exit(1);
}
}
async persistPeerUrls() {
try {
let peerUrls = this.node.peers(this.nodeTypes)
.map(peer => peer.url);
await this.store.writeCurPeerUrls(peerUrls);
} catch (err) {
console.error(err);
}
}
fetchPeersHandler({ messageType, ...payload }, peer) {
try {
// validate the received message
messageValidators[messageType](payload);
let { nodeTypes, limit } = payload;
let connectedPeerUrls = this.node.peers(nodeTypes)
.map(peer => peer.url);
if (connectedPeerUrls.includes(peer.url)) {
connectedPeerUrls.splice(connectedPeerUrls.indexOf(peer.url), 1);
}
let peerUrls = pickItems(connectedPeerUrls, limit);
let resMsg = returnPeers({ nodeTypes, peerUrls });
peer.sendJson(resMsg);
} catch (err) {
console.warn(err);
}
}
returnPeersHandler({ messageType, ...payload }, peer) {
try {
// validate the received message
messageValidators[messageType](payload);
let { nodeTypes, peerUrls } = payload;
let connectedPeerUrls = this.node.peers(nodeTypes)
.map(peer => peer.url);
peerUrls.filter(url => !connectedPeerUrls.includes(url))
.forEach(url => this.litenode.createConnection(url));
} catch (err) {
console.warn(err);
}
}
close() {
this.removeAllListeners();
this.intervalTimers.forEach(t => clearInterval(t));
}
}
|
JavaScript
|
class Blockchain extends EventEmitter {
constructor(store) {
super();
this.store = store;
this.db = store.db;
this.genKey = store.constructor.genKey;
// an array of block ids (in hex encoding)
this.blockchain = null;
this._ready = false;
this.init();
}
get ready() {
return this._ready;
}
async init() {
try {
let height = await this.getCurHeight() + 1;
let numOfChunks = Math.floor(height / chunkSize);
let numOfBlocks = height % chunkSize;
let chunks = await Promise.all(
Array.from(Array(numOfChunks).keys()) // generate a number sequence
.map(num => this._getChunk(num))
);
// flatten chunks
chunks = [].concat.apply([], chunks);
let blocks = [];
let prevBlockId = null;
for (let i = 0; i < numOfBlocks; i++) {
let block = await (
i === 0 ? this.getHeadBlock() : this.getBlock(prevBlockId)
);
prevBlockId = block.prevBlock;
blocks.unshift(block.hash);
}
this.blockchain = [...chunks, ...blocks];
this._ready = true;
this.emit('ready');
} catch (err) {
this.emit('error', err);
}
}
/**
* Inside a chunk, the order is from elder blocks to newer blocks.
* Note that if you're trying to get a non-existent chunk, an error
* will be thrown.
*/
async _getChunk(serialNum) {
let buf = await this.db.get(this.genKey(`chunk_${serialNum}`));
let chunk = [];
// just be cautious
if (buf.length !== chunkSize * 32) { process.exit(1); }
for (let i = 0; i < buf.length; i += 32) {
chunk.push(buf.slice(i, i + 32).toString('hex'));
}
return chunk;
}
/**
* Append next block on top of current head block on the blockchain.
*/
async append(block) {
const prevHead = this.getHeadBlockIdSync();
const ops = [];
this.blockchain.push(block.hash);
let height = this.getCurHeightSync();
if ((height + 1) % chunkSize === 0) {
const serialNum = Math.floor((height + 1) / chunkSize) - 1;
const buf = Buffer.from(this.blockchain.slice(height + 1 - chunkSize).join(''), 'hex');
ops.push({ type: 'put', key: this.genKey(`chunk_${serialNum}`), value: buf });
}
return this.store.appendBlock(block, ops)
.then(() => this.emit('push', block, prevHead));
}
/**
* Append a branch on a specific location on the blockchain, and the
* new branch will be the main blockchain branch.
*
* TODO update chunk index
*/
async appendAt(blocks) {
// some cautious checks
if (!blocks.length) { return; }
if (blocks[blocks.length - 1].height <= this.getCurHeightSync()) {
throw new Error('Trying to append a invalid subchain, abort.');
}
let prevHead = this.getHeadBlockIdSync();
let at = blocks[0].height;
let blockIds = blocks.map(block => block.hash);
let offBlockIds = this.blockchain.splice(at, Number.MAX_SAFE_INTEGER, ...blockIds);
let chunkAt = Math.floor(at / chunkSize);
let ops = [];
for (let i = chunkAt * chunkSize; i + chunkSize < this.blockchain.length; i += chunkSize) {
let buf = Buffer.from(this.blockchain.slice(i, i + chunkSize).join(''), 'hex');
ops.push({ type: 'put', key: this.genKey(`chunk_${i / chunkSize}`), value: buf });
}
// append the new branch
await this.store.appendBlocksAt(blocks, ops);
// following removes stale litemessage indices
let offBlocks = await Promise.all(
offBlockIds.map(id => this.getBlock(id))
);
let offLitemsgs = [];
for (let block of offBlocks) {
if (block.litemsgs) {
offLitemsgs.push(...block.litemsgs);
}
}
await Promise.all(
offLitemsgs.map(async ({ hash }) => {
let blockId = await this.store.readLitemsg(hash);
if (!this.onMainBranchSync(blockId)) {
return this.store.removeLitemsg(hash);
}
})
);
this.emit('switch', blocks, prevHead);
// resolve nothing when success
// reject with error when error
}
/**
* Same as always, always pass valid block here.
* And note that you can update block only if that
* block currently is on the main branch.
*
* If you are trying to update a non-existent block
* or that block is not on the main branch, nothing
* will happen.
*/
async updateBlock(block) {
if (this.onMainBranchSync(block.hash)) {
await this.store.writeBlock(block);
}
this.emit('update', block, this.getHeadBlockIdSync());
// resolve nothing when success
// reject with error when error
}
/**
* Return the head block, or `undefined` when there's no
* block on the blockchain.
*/
async getHeadBlock() {
let blockId = await this.store.readHeadBlock();
return this.getBlock(blockId);
}
/**
* Synchronously get current head block's id. If there is no block
* yet, `undefined` will be returned.
*/
getHeadBlockIdSync() {
let length = this.blockchain.length;
return length ? this.blockchain[length - 1] : undefined;
}
getBlockIdAtSync(height) {
let curHeight = this.getCurHeightSync();
if (height < 0 || height > curHeight) {
throw new Error('Invalid height given.');
}
return this.blockchain[height];
}
/**
* Note that height is 0-based (first block's height is 0).
* If there's no block yet, `-1` will returned.
*/
async getCurHeight() {
let block = await this.getHeadBlock();
return block ? block.height : -1;
}
/**
* Note that height is 0-based (first block's height is 0).
* If there's no block yet, `-1` will returned.
*/
getCurHeightSync() {
return this.blockchain.length - 1;
}
/**
* Get a list of block locator hashes, which is used in the
* `getBlocks` message that typically exists in blockchain
* protocol.
*/
getLocatorsSync() {
let locators = [];
let height = this.getCurHeightSync();
let pow = 0;
if (height === -1) { return []; }
while (true) {
let i = Math.max(height + 1 - Math.pow(2, pow), 0);
locators.push(this.getBlockIdAtSync(i));
if (i === 0) { break; }
pow += 1;
}
return locators;
}
/**
* Get forked branch based on locators (an array of block hashes) peer provides.
* Return an array of block ids (from elder blocks to latest ones).
*/
getForkedBranchSync(locators) {
if (this.blockchain.length < locators.length) {
return [];
}
let height = this.getCurHeightSync();
if (height === -1) { return []; }
let i = height;
for (; i >= 0; i--) {
let blockId = this.blockchain[i];
if (locators.includes(blockId)) {
break;
}
}
if (i === height) { return []; }
return this.blockchain.slice(i + 1);
}
/**
* @param {*} height note that height is 0-based index
*/
async getBlockAt(height) {
// just to be cautious
if (height >= this.blockchain.length) {
throw new Error('Invalid block height.');
}
let blockId = this.blockchain[height];
return this.getBlock(blockId);
}
/**
* Get all blocks on the blockchain main branch.
* At this point there is no pagination yet, so this
* operation is very expensive.
*/
async getBlocks(reverse = true) {
let blocks = await Promise.all(
this.blockchain.map(this.getBlock, this)
);
if (reverse) { blocks.reverse(); }
return blocks;
}
/**
* This method is a helper to help scroll along the
* blockchain (pagination) from newer blocks to older
* ones.
*
* It gets a sub blockchain with specified length ending
* at the given block id (exclusive).
*
* Both parameters are optional. If you don't pass
* `until` (or you pass a nonexistent block id), it
* will return until the head block (inclusive in this
* case).
*
* @param {*} until the last block id (exclusive)
* @param {*} len length of the blockchain
*/
async getSubBlockchain(until, len = 100) {
let i = this.blockchain.indexOf(until);
let hashes = i < 0 ? this.blockchain.slice(-len) :
this.blockchain.slice(Math.max(0, i - len), i);
return Promise.all( hashes.map(this.getBlock, this) );
}
/**
* Return the whole block specified by the given block id.
* If block doesn't exist, `undefined` will be returned.
*/
async getBlock(blockId) {
return this.store.readBlock(blockId);
}
/**
* If the given block is not on the main blockchain, the confirmation
* count will always be 0.
*/
getConfirmationCntSync(blockId) {
if (!this.onMainBranchSync(blockId)) { return null; }
return this.getCurHeightSync() - this.blockchain.indexOf(blockId);
}
/**
* Determine whether the given block is on the main blockchain branch.
* The difference from the func `hasBlock` is that this is a synchronous
* operation.
*/
onMainBranchSync(blockId) {
return this.blockchain.includes(blockId);
}
/**
* By default, return true only if the given block is on the main blockchain
* branch. If you want it to return true even if the block is off main branch,
* set the `onMainBranch` to false.
*/
async hasBlock(blockId, onMainBranch = true) {
if (onMainBranch) {
return this.blockchain.includes(blockId);
}
return await this.getBlock(blockId) !== undefined;
}
/**
* @param {*} litemsgId
* @param {*} untilHeight exclusive (optional)
*/
async litemsgOnMainBranch(litemsgId, untilHeight = Number.MAX_SAFE_INTEGER) {
let blockId = await this.store.readLitemsg(litemsgId);
if (!blockId || !this.onMainBranchSync(blockId)) { return false; }
let block = await this.getBlock(blockId);
if (block.height >= untilHeight) {
return false;
} else {
return true;
}
}
}
|
JavaScript
|
class LiteProtocol extends P2PProtocol {
static get ver() {
return VERSION;
}
constructor(node) {
super(node, { nodeTypes: AUTO_CONN_NODE_TYPES });
this.getBlocksHandler = this.getBlocksHandler.bind(this);
this.invHandler = this.invHandler.bind(this);
this.getDataHandler = this.getDataHandler.bind(this);
this.getHeadersHandler = this.getHeadersHandler.bind(this);
this.dataHandler = this.dataHandler.bind(this);
this.locateLitemsgsHandler = this.locateLitemsgsHandler.bind(this);
this.getPendingMsgsHandler = this.getPendingMsgsHandler.bind(this);
this.peerConnectHandler = this.peerConnectHandler.bind(this);
this.litestore = new LiteProtocolStore(node.db);
// a blockchain manager
this.blockchain = new Blockchain(this.litestore);
this.miner = new Miner();
// map litemessage id to litemessage itself (pending litemessages)
this.litemsgPool = {};
// wait for blockchain initializing itself
this.blockchain.on('ready', () => this.init());
this.blockchain.on('error', err => {
console.error(err);
process.exit(1);
});
}
init() {
// register message/connection handlers
this.litenode.on(`message/${messageTypes.getBlocks}`, this.getBlocksHandler);
this.litenode.on(`message/${messageTypes.inv}`, this.invHandler);
this.litenode.on(`message/${messageTypes.getData}`, this.getDataHandler);
this.litenode.on(`message/${messageTypes.getHeaders}`, this.getHeadersHandler);
this.litenode.on(`message/${messageTypes.data}`, this.dataHandler);
this.litenode.on(`message/${messageTypes.locateLitemsgs}`, this.locateLitemsgsHandler);
this.litenode.on(`message/${messageTypes.getPendingMsgs}`, this.getPendingMsgsHandler);
this.litenode.on('peerconnect', this.peerConnectHandler);
// instantiate a handshake manager so that
// our node can connect to other nodes : P
this.handshake = new HandshakeManager(this);
// this node supports inventory resolution : P
this.invResolvHandler = new InvResolveHandler(this);
if (this.litenode.debug) {
// create and run rest server
let debugPort = this.litenode.daemonPort + 1;
createRestServer(this).listen(debugPort);
console.log(`Debugging RESTful API server listening on port ${debugPort}.`);
}
// some schedule tasks (interval timers)
this.timers = [];
// schedule mining
this.timers.push(
setInterval(async () => {
if (!this.miner.mining && Object.entries(this.litemsgPool).length) {
this.mineNextBlock();
}
}, 1000)
);
// schedule getting pending messages
this.timers.push(
setInterval(() => {
if (Object.entries(this.litemsgPool).length > 0) { return; }
try {
pickItems(this.node.peers('full'), 8)
.forEach(peer => peer.sendJson(getPendingMsgs()))
} catch (err) { console.warn(err); }
}, 30000)
);
// protocol handling setup is ready now
this.emit('ready');
}
async getNextBlock() {
let time = getCurTimestamp();
let litemsgs = pickItems(Object.values(this.litemsgPool), BLOCK_LIMIT);
let merkleRoot = calcMerkleRoot(litemsgs.map(m => m.hash));
let {
height = -1, hash: prevBlock = undefined
} = await this.blockchain.getHeadBlock() || {};
height += 1;
return createBlock(VERSION, time, height, prevBlock, merkleRoot, BITS, undefined, litemsgs);
}
async mineNextBlock() {
let block = await this.getNextBlock();
block = await this.miner.mine(block);
let headBlockId = this.blockchain.getHeadBlockIdSync();
if (!headBlockId || block.prevBlock === headBlockId) {
let now = getCurTimestamp();
let timeTaken = Math.round((now - block.time) / 1000);
console.log(`Successfully mined a new block (${timeTaken} s): ${block.hash}.`);
// append the mined block to blockchain
this.blockchain.append(block);
// remove from pending message pool
for (let litemsg of block.litemsgs) {
delete this.litemsgPool[litemsg.hash];
}
// broadcast to peers
this.litenode.broadcastJson(inv({ blocks: [block.hash] }));
}
}
/**
* After receiving blocks from a peer and verifying them, call this
* func to remove litemessages (if any) which exist in these blocks
* before appending them to the blockchain.
*
* @param {*} blocks blocks (already verified) received from a peer
*/
cleanPoolAndRestartMining(blocks) {
for (let block of blocks) {
for (let litemsg of block.litemsgs) {
delete this.litemsgPool[litemsg.hash];
}
}
if (Object.entries(this.litemsgPool).length) {
this.mineNextBlock();
}
}
inLitemsgPool(litemsgId) {
return !!this.litemsgPool[litemsgId];
}
/**
* Check for repeated litemessages. If any,
* this method will return true.
*
* It accepts a optional `untilHeight`.
*/
async checkChainForRepeatedLitemsgs(blocks, untilHeight) {
for (let block of blocks) {
for (let litemsg of block.litemsgs) {
if (await this.blockchain.litemsgOnMainBranch(litemsg.hash, untilHeight)) {
return true;
}
}
}
return false;
}
/**
* If the given litemessage id is in LevelDB's litemessage index
* (only opn main branch), or it's in the pending pool, the return
* value will be `true`.
*/
async hasLitemsg(litemsgId) {
return (await this.blockchain.litemsgOnMainBranch(litemsgId))
|| this.inLitemsgPool(litemsgId);
}
async getBlocksHandler({ messageType, ...payload }, peer) {
try {
messageValidators[messageType](payload);
let { blockLocators } = payload;
let forkedBranch = this.blockchain.getForkedBranchSync(blockLocators);
if (forkedBranch.length) {
// send response based on received locators
peer.sendJson(inv({ blocks: forkedBranch }));
}
} catch (err) {
console.warn(err);
}
}
async invHandler({ messageType, ...payload }, peer) {
try {
messageValidators[messageType](payload);
// Note the "blocks" here either is a single block just
// mined by peer, or is a sub blockchain, which, in
// other words, means those blocks are consecutive.
// This is just due to how the protocol is designed.
let { blocks, litemsgs } = payload;
let blocksToGet = [];
let litemsgsToGet = [];
// Filter out blocks already have (blocks off main branch
// still as being haven). Also note that those blocks haven
// by the current node, if any, must always certainly reside
// at the beginning of received `inv`'s blockchain. Again,
// this is just due to how the protocol is designed.
for (let blockId of blocks) {
if (!(await this.blockchain.hasBlock(blockId, false))) {
blocksToGet.push(blockId);
}
}
// filter out litemessages already have
for (let litemsgId of litemsgs) {
if (!(await this.hasLitemsg(litemsgId))) {
litemsgsToGet.push(litemsgId);
}
}
if (blocksToGet.length || litemsgsToGet.length) {
peer._resolver.resolve({
blocks: blocksToGet,
litemsgs: litemsgsToGet
});
}
} catch (err) {
console.warn(err);
}
}
async getDataHandler({ messageType, ...payload }, peer) {
try {
messageValidators[messageType](payload);
let { blocks, litemsgs } = payload;
let respBlocks = null;
let respLitemsgs = [];
// give blocks no matter which branch they are on
respBlocks = await Promise.all(
blocks.map(blockId => this.blockchain.getBlock(blockId))
);
respBlocks = respBlocks.filter(block => typeof block !== 'undefined');
for (let litemsgId of litemsgs) {
// note only return litemessages from pool for `getData`
let litemsg = this.litemsgPool[litemsgId];
if (litemsg) { respLitemsgs.push(litemsg); }
}
if (respBlocks.length || respLitemsgs.length) {
// send response
peer.sendJson(
data({ blocks: respBlocks, litemsgs: respLitemsgs })
);
}
} catch (err) {
console.warn(err);
}
}
async getHeadersHandler({ messageType, ...payload }, peer) {
try {
messageValidators[messageType](payload);
let { blocks } = payload;
// give blocks no matter which branch they are on
let respBlocks = (await Promise.all(
blocks.map(blockId =>
this.blockchain.getBlock(blockId))
))
.filter(block => typeof block !== 'undefined');
// strip off block bodies
for (let block of respBlocks) {
delete block['litemsgs'];
}
if (respBlocks.length) {
// send response
peer.sendJson(
headers({ blocks: respBlocks })
);
}
} catch (err) {
console.warn(err);
}
}
/**
* TODO sync pool and restart mining?
*/
async dataHandler({ messageType, ...payload }, peer) {
try {
messageValidators[messageType](payload);
let { blocks, litemsgs } = payload;
let relayBlocks = []; // always 0 or 1 element
let relayLitemsgs = [];
// filter out invalid blocks and litemessages
blocks = blocks.filter(block => verifyBlock(block));
blocks.sort((a, b) => a.height - b.height);
litemsgs = litemsgs.filter(litemsg => verifyLitemsg(litemsg));
let headBlockId = this.blockchain.getHeadBlockIdSync();
if (blocks.length && blocks[blocks.length - 1].height > this.blockchain.getCurHeightSync()) {
if (blocks.length === 1) {
let block = blocks[0];
if (block.prevBlock === headBlockId) {
if (!(await this.checkChainForRepeatedLitemsgs(blocks))) {
this.cleanPoolAndRestartMining(blocks);
this.blockchain.append(block);
relayBlocks.push(block);
}
} else {
let blockLocators = this.blockchain.getLocatorsSync();
peer.sendJson(getBlocks({ blockLocators }));
}
} else {
// Note that `prevBlockId` and `prevBlock` down below refer to same block.
// Later, they will be used for traversing backward along the blockchain.
let prevBlockId = blocks[0].prevBlock;
let prevBlock = prevBlockId ?
(await this.blockchain.getBlock(prevBlockId)) :
undefined;
if (verifySubchain(blocks, prevBlock)) {
// For efficiency, node doesn't fetch blocks on forked branch which it already
// has. The `litemsg_${litemsg_id}` of these mentioned blocks might be records
// on the main branch (before appending). So here, suppose the previous
// block of appended blocks is not on main branch, we need to extend from
// the appended blocks backwards to until a block which is on the main
// branch, or until the genesis block (of the forked branch), whichever reaches
// first. And then rewrite all `litemsg_${litemsg_id}` records so that all
// litemessages are correctly indexed after switching to another branch.
let extendedBlocks = [];
while (prevBlockId && !this.blockchain.onMainBranchSync(prevBlockId)
&& headBlockId === this.blockchain.getHeadBlockIdSync()) {
extendedBlocks.unshift(prevBlock);
prevBlockId = prevBlock.prevBlock;
prevBlock = prevBlockId ?
(await this.blockchain.getBlock(prevBlockId)) :
undefined;
}
let chainToSwitch = [...extendedBlocks, ...blocks];
if (!(await this.checkChainForRepeatedLitemsgs(chainToSwitch, chainToSwitch[0].height))) {
if (headBlockId === this.blockchain.getHeadBlockIdSync()) {
this.cleanPoolAndRestartMining(blocks);
// switch the blockchain to another branch,
// for efficiency, don't await it finishing
// (no await here)
this.blockchain.appendAt(chainToSwitch);
}
}
}
}
}
// process received litemessages
for (let litemsg of litemsgs) {
if (await this.hasLitemsg(litemsg.hash)) { continue; }
relayLitemsgs.push(litemsg.hash);
this.litemsgPool[litemsg.hash] = litemsg;
}
if (relayBlocks.length || relayLitemsgs.length) {
// relay (broadcast) data messaage
this.litenode.broadcastJson(
inv({ blocks: relayBlocks, litemsgs: relayLitemsgs }),
[peer.uuid]
);
}
} catch (err) {
console.warn(err);
}
}
async locateLitemsgsHandler({ messageType, ...payload }, peer) {
try {
messageValidators[messageType](payload);
let { litemsgs } = payload;
let lookup = await Promise.all(
litemsgs.map(id => this.litestore.readLitemsg(id))
);
let blocks = await Promise.all(
[...new Set(lookup)]
.filter(id => id)
.map(id => this.blockchain.getBlock(id))
);
if (litemsgs.length) {
// send response
peer.sendJson(
litemsgLocators({ litemsgs, blocks, lookup })
);
}
} catch (err) {
console.warn(err);
}
}
getPendingMsgsHandler({ messageType, ...payload }, peer) {
try {
messageValidators[messageType](payload);
let litemsgs = Object.keys(this.litemsgPool);
if (litemsgs.length) {
// send response
peer.sendJson(inv({ litemsgs }));
}
} catch (err) {
console.warn(err);
}
}
peerConnectHandler(peer) {
if (peer.nodeType === 'full' && this.node.peers('full').length === 1) {
// wait for 30 seconds to retrieve blocks
// because of concorrent resolving (it takes
// time to construct connections with peers)
setTimeout(() => {
let blockLocators = this.blockchain.getLocatorsSync();
peer.sendJson(getBlocks({ blockLocators }));
}, 60000);
}
peer._resolver = new InventoryResolver(peer, this);
}
close() {
for (let timer of this.timers) {
clearInterval(timer);
}
if (this.handshake) { this.handshake.close(); }
super.close();
}
}
|
JavaScript
|
class LiteNode extends EventEmitter {
constructor(uuid, { port = 1113, debug = false, noserver = false } = {}) {
super();
this.socketConnectHandler = this.socketConnectHandler.bind(this);
this.socketMessageHandler = this.socketMessageHandler.bind(this);
this.socketCloseHandler = this.socketCloseHandler.bind(this);
this.uuid = uuid;
this.daemonPort = noserver ? undefined : port;
this.debugPort = port + 1;
this.noserver = noserver;
// node's uuid => peer
this.peers = {};
// remote socket addresses (str) => peers
this.socketsToPeers = {};
// used for debugging (view all protocol messages since start)
this.debug = debug;
this.messageLogs = [];
// create the underlyng websocket server
this.wss = noserver ? new WSClient() : new WSServer(port);
if (!noserver) {
// when bound to an network interface
this.wss.on('listening', (port) => {
console.log(`${uuid}: Start listening on port ${port}.`);
if (debug) { console.log('Debug mode is enabled.'); }
});
}
// when new connection established
this.wss.on('connection', this.socketConnectHandler);
}
/**
* Create a proxy to intercept the `send` function call,
* mainly for debugging / logging.
*/
createSocketProxy(socket, remoteUuid) {
if (!this.debug) { return socket; }
const messageLogs = this.messageLogs;
const handler = {
get: (socket, propName) => {
if (propName !== 'send') { return socket[propName]; }
// return the wrapper function as a proxy
return function (data, options, callback) {
messageLogs.push({
peer: remoteUuid,
dir: 'outbound',
msg: JSON.parse(data),
time: getCurTimestamp('s')
});
return socket.send(data, options, callback);
};
}
};
// create socket proxy and return
return new Proxy(socket, handler);
}
/**
* Note that you cannot have more than one socket to a single URL.
* And also note that error could be thrown if url is invalid.
* Failure of connection will only cause some log (won't crash
* the application).
*
* Right now, there's no way to get notified when it fail to connect
* (such as because of timeout) except for a log mentioned before.
*/
createConnection(url) {
return this.wss.createConnection(url);
}
/**
* @param {string} msg
* @param {Array<string>} exUuids
*/
broadcast(msg, exUuids = []) {
let peers = Object.keys(this.peers)
.filter(uuid => !exUuids.includes(uuid))
.map(uuid => this.peers[uuid]);
for (let peer of peers) {
try {
peer.send(msg);
} catch (err) {
console.error(err);
}
}
}
/**
* @param {Object} jsonObj
* @param {Array<string>} exUuids
*/
broadcastJson(jsonObj, exUuids) {
this.broadcast(JSON.stringify(jsonObj), exUuids);
}
socketConnectHandler(socket, incoming) {
let socketAddress = getSocketAddress(socket);
if (incoming) {
console.log(`Accepted socket connection from ${socketAddress}.`);
} else {
console.log(`Established socket connection to ${socketAddress}.`);
}
socket.on('close', (code, reason) =>
this.socketCloseHandler(code, reason, socket));
// notify listeners
this.emit('socketconnect', socket, incoming);
}
socketMessageHandler(msg, peer) {
let msgObj = null;
try { msgObj = JSON.parse(msg); } catch (e) {}
if (msgObj && msgObj['messageType']) {
if (this.debug) {
// note that only logs valid procotol messages
this.messageLogs.push({
peer: peer.uuid,
dir: 'inbound',
msg: msgObj,
time: getCurTimestamp('s')
});
}
this.emit(`message/${msgObj['messageType']}`, msgObj, peer);
}
}
socketCloseHandler(code, reason, socket) {
let socketAddress = getSocketAddress(socket);
let peer = this.socketsToPeers[socketAddress]
if (peer) {
delete this.peers[peer.uuid];
delete this.socketsToPeers[socketAddress]
console.log(`Disconnected from ${peer.uuid}@${socketAddress}.`);
// notify listeners
this.emit('peerdisconnect', peer);
}
console.log(`Closed socket connection with ${socketAddress} (${code || 'N/A'} | ${reason || 'N/A'}).`);
}
/**
* Add new peer to peer collection of this node. The protocol
* implmementation should call this after a protocol-specific
* handshake completes (this class is protocol agnostic).
*/
addNewPeer(peer) {
let { uuid, socket, incoming, nodeType } = peer;
let socketAddress = getSocketAddress(socket);
if (this.peers.hasOwnProperty(uuid)) {
console.warn(`Established connection with a connected peer (${uuid}@${socketAddress});\n`
+ `so, going to disconnect from it.`);
socket.close(undefined, 'DOUBLE_CONNECT');
return;
}
peer.socket = socket = this.createSocketProxy(socket, uuid);
this.peers[uuid] = peer;
this.socketsToPeers[socketAddress] = peer;
socket.on( true ? 'message' : undefined, (message) =>
this.socketMessageHandler(message, peer));
if (incoming) {
console.log(`Accepted connection from ${peer.uuid}@${socketAddress} (${nodeType}).`);
} else {
console.log(`Established connection to ${peer.uuid}@${socketAddress} (${nodeType}).`);
}
// notify listeners
this.emit('peerconnect', peer);
}
/**
* Get some useful information about this node.
*/
getInfo() {
let network = this.wss.getInfo();
if (network.sockets) {
for (let socketInfo of network.sockets) {
let peer = this.socketsToPeers[socketInfo.remoteSocketAddr];
socketInfo.remoteUuid = peer.uuid;
socketInfo.remoteDaemonPort = peer.daemonPort;
}
}
return {
uuid: this.uuid,
daemonPort: this.daemonPort,
network,
};
}
/**
* Close this node (both server and outgoing socket connections will
* be closed)
*/
close() {
this.removeAllListeners();
this.wss.close();
}
}
|
JavaScript
|
class WSClient extends EventEmitter {
constructor() {
super();
this.connectionHandler = this.connectionHandler.bind(this);
// map remote socket addresses (ip:port) to sockets
this.servers = {};
// set up heartbeats
if (true) {
this.timer = setInterval(this.genHeartbeat(), 60000);
}
}
/**
* Note that you cannot have more than one socket to a single URL.
* And also note that error could be thrown if url is invalid.
* Failure of connection will only cause some logs (won't crash
* the application).
*
* Right now, there's no way to get notified when it fails to connect
* (such as because of timeout) except for a log mentioned before.
*/
createConnection(url) {
let socketAddress = null;
let remoteDaemonPort = null;
try {
({ host: socketAddress, port: remoteDaemonPort } = new URL(url));
if (!socketAddress || !remoteDaemonPort.match(/^\d+$/)) { throw new Error(); }
} catch (err) {
throw new Error(`Wrong url (${url}) to connect.`);
}
let prevSocket = this.servers[socketAddress];
if (prevSocket && this.socketAlive(prevSocket)) {
console.warn(`Tried to connect to same url (${url}) twice. Operation aborted.`);
return;
}
let socket = new WebSocket(url, { handshakeTimeout: 10000 });
socket.on('error', (err) =>
console.log(`Unable to establish connection to ${url}. Details:\n${err}.`));
socket.on( true ? 'open' : undefined, () => {
let prevSocket = this.servers[socketAddress];
if (prevSocket && this.socketAlive(prevSocket)) {
// TODO investigate memory leak
socket.on('close', () => socket.removeAllListeners());
socket.close(undefined, 'DOUBLE_CONNECT');
return;
}
socket.removeAllListeners('error');
this.connectionHandler(socket, false);
this.servers[socketAddress] = socket;
});
}
genHeartbeat() {
let noop = () => {};
return () => {
for (let socket of Object.values(this.servers)) {
if (this.socketAbnormal(socket)) {
socket.terminate();
}
// set socket `alive` to false, later pong response
// from client will recover `alive` from false to true
socket.alive = false;
socket.ping(noop);
}
}
}
/**
* @param {*} socket the underlaying socket
* @param {boolean} incoming whether the connection is incoming
*/
connectionHandler(socket, incoming) {
let socketAddress = getSocketAddress(socket);
socket.alive = true;
socket.on('message', () => socket.alive = true);
socket.on('pong', () => socket.alive = true);
socket.on('close', () => {
socket.alive = false;
socket.removeAllListeners();
if (socket === this.servers[socketAddress]) {
delete this.servers[socketAddress];
}
});
socket.on('error', err => {
console.log(err);
socket.terminate();
});
// notify subscribers
this.emit('connection', socket, incoming);
}
socketAbnormal(socket) {
return !socket.alive && getReadyState(socket) === WebSocket.OPEN;
}
socketAlive(socket) {
return getReadyState(socket) === WebSocket.OPEN;
}
/**
* Get some useful information about the network.
*/
getInfo() {
let sockets = [];
for (let socket of Object.values(this.servers)) {
sockets.push({
dir: 'outbound',
...getSocketInfo(socket)
});
}
return {
sockets
};
}
/**
* Close this node (both server and outgoing socket connections will
* be closed)
*/
close() {
this.removeAllListeners();
clearInterval(this.timer);
}
}
|
JavaScript
|
class WSServer extends EventEmitter {
constructor(port) {
super();
this.connectionHandler = this.connectionHandler.bind(this);
// map remote socket addresses (ip:port) to sockets
this.servers = {};
this.port = port;
// create underlaying server and listen
this.wss = new WebSocket.Server({ port });
// when bound to an network interface
this.wss.on('listening', () => this.emit('listening', port));
// when receiving incoming connection
this.wss.on('connection', (socket, req) => {
this.connectionHandler(socket, true);
});
// when websocket server has error (don't crash it)
this.wss.on('error', console.log);
// set up heartbeats
this.timer = setInterval(this.genHeartbeat(), 60000);
}
/**
* Note that you cannot have more than one socket to a single URL.
* And also note that error could be thrown if url is invalid.
* Failure of connection will only cause some logs (won't crash
* the application).
*
* Right now, there's no way to get notified when it fails to connect
* (such as because of timeout) except for a log mentioned before.
*/
createConnection(url) {
let socketAddress = null;
let remoteDaemonPort = null;
try {
({ host: socketAddress, port: remoteDaemonPort } = new URL(url));
if (!socketAddress || !remoteDaemonPort.match(/^\d+$/)) { throw new Error(); }
} catch (err) {
throw new Error(`Wrong url (${url}) to connect.`);
}
let prevSocket = this.servers[socketAddress];
if (prevSocket && this.socketAlive(prevSocket)) {
console.warn(`Tried to connect to same url (${url}) twice. Operation aborted.`);
return;
}
let socket = new WebSocket(url, { handshakeTimeout: 10000 });
socket.on('error', (err) =>
console.log(`Unable to establish connection to ${url}. Details:\n${err}.`));
socket.on('open', () => {
let prevSocket = this.servers[socketAddress];
if (prevSocket && this.socketAlive(prevSocket)) {
// TODO investigate memory leak
socket.on('close', () => socket.removeAllListeners());
socket.close(undefined, 'DOUBLE_CONNECT');
return;
}
socket.removeAllListeners('error');
this.connectionHandler(socket, false);
this.servers[socketAddress] = socket;
});
}
genHeartbeat() {
let noop = () => {};
return () => {
for (let socket of [...this.wss.clients, ...Object.values(this.servers)]) {
if (this.socketAbnormal(socket)) {
socket.terminate();
}
// set socket `alive` to false, later pong response
// from client will recover `alive` from false to true
socket.alive = false;
socket.ping(noop);
}
}
}
/**
* @param {*} socket the underlaying socket
* @param {boolean} incoming whether the connection is incoming
*/
connectionHandler(socket, incoming) {
let socketAddress = getSocketAddress(socket);
socket.alive = true;
socket.on('message', () => socket.alive = true);
socket.on('pong', () => socket.alive = true);
socket.on('close', () => {
socket.alive = false;
socket.removeAllListeners();
if (socket === this.servers[socketAddress]) {
delete this.servers[socketAddress];
}
});
socket.on('error', err => {
console.log(err);
socket.terminate();
});
// notify subscribers
this.emit('connection', socket, incoming);
}
socketAbnormal(socket) {
return !socket.alive && socket.readyState === WebSocket.OPEN;
}
socketAlive(socket) {
return socket.readyState === WebSocket.OPEN;
}
/**
* Get some useful information about the network.
*/
getInfo() {
let sockets = [];
for (let socket of this.wss.clients) {
sockets.push({
dir: 'inbound',
...getSocketInfo(socket)
});
}
for (let socket of Object.values(this.servers)) {
sockets.push({
dir: 'outbound',
...getSocketInfo(socket)
});
}
return {
port: this.port,
sockets
};
}
/**
* Close this node (both server and outgoing socket connections will
* be closed)
*/
close() {
this.removeAllListeners();
clearInterval(this.timer);
this.wss.close();
}
}
|
JavaScript
|
class FullNode extends Node {
constructor(dbPath, { protocolClass = LiteProtocol, initPeerUrls = [], port, debug } = {}) {
super(NODE_TYPE, dbPath, port, protocolClass, initPeerUrls, debug);
this.timer = setInterval(() => {
console.log(`Right now, there are ${this.peers().length} connected peers (full & thin).`);
// TODO this.debugInfo();
}, 20000);
}
static get nodeType() {
return NODE_TYPE;
}
close() {
clearInterval(this.timer);
super.close();
}
// TODO
debugInfo() {
console.log('<<<<< debug start >>>>>');
let peerUrls = this.peers().map(peer => peer.url);
console.log(peerUrls);
console.log('<<<<<< debug end >>>>>>');
}
}
|
JavaScript
|
class Miner {
/**
* Use `mine` down below; it has easier interface.
*
* Start mining. If at the point you call this function,
* a mining is going on, that mining will be canceled
* automatically (right now doesn't support concurrent
* mining).
*
* Note that if the mining is canceled, it won't trigger
* `resolve` or `reject` of the returned promise.
*/
calc(content, bits) {
if (this.mining) { this.cancel(); }
this.mining = mine(content, bits);
return this.mining
.then(nonce => {
this.mining = null;
return nonce;
})
.catch(err => {
this.mining = null;
throw err;
});
}
/**
* Note that it won't change the orginal block, but return a new
* successfully mined block.
*
* @param {*} block
*/
mine(block) {
const { ver, time, height, prevBlock, merkleRoot, bits, litemsgs } = block;
const content = `${ver}${time}${height}${prevBlock}${merkleRoot}${bits}`;
return this.calc(content, bits)
.then(nonce =>
createBlock(ver, time, height, prevBlock, merkleRoot, bits, nonce, litemsgs));
}
cancel() {
if (this.mining) {
this.mining.cancel();
this.mining = null;
}
}
}
|
JavaScript
|
class InvResolveHandler {
constructor(liteprotocol) {
this.getDataPartialHandler = this.getDataPartialHandler.bind(this);
this.litenode = liteprotocol.litenode;
this.blockchain = liteprotocol.blockchain;
this.litenode.on(`message/${messageTypes.getDataPartial}`, this.getDataPartialHandler);
}
async getDataPartialHandler({ messageType, ...payload }, peer) {
try {
messageValidators[messageType](payload);
let { merkleDigest, blocks: blockIds } = payload;
let blocks = await Promise.all(
blockIds.map(id => this.blockchain.getBlock(id))
);
if (blocks.some(block => !block)) {
peer.sendJson(
partialNotFound({
merkleDigest,
blocks: blockIds
})
); // end of sendJson
} else {
peer.sendJson(
dataPartial({
merkleDigest,
blocks
})
); // end of sendJson
} // end of else
} catch (err) {
console.warn(err);
}
}
}
|
JavaScript
|
class BlockInventory {
/**
* @param {*} blocks block ids
* @param {*} slices number of slices
*/
constructor(blocks, slices) {
// chain's merkle digest
this.merkleDigest = calcMerkleRoot(blocks);
// chunk digest (sub merkle) => chunk data
this.chunks = {};
// the timestamp when resolving given blocks
this.timestamp = null;
for (let blockIds of sliceItems(blocks, slices)) {
let digest = calcMerkleRoot(blockIds);
this.chunks[digest] = {
// merkle root digest
digest,
// the block ids
ids: blockIds,
// the actual block data
blocks: undefined,
// the timestamp when resolving each chunk
timestamp: undefined
};
}
}
* [Symbol.iterator]() {
for (let chunk of Object.values(this.chunks)) {
yield chunk;
}
}
getBlocks() {
let blockArrays = Object.values(this.chunks).map(chunk => chunk.blocks);
let blocks = [];
for (let array of blockArrays) {
blocks.push(...array);
}
return blocks;
}
/**
* Whether this block inventory is resolved (a boolean).
*/
resolved() {
for (let chunk of this) {
if (!chunk.blocks) { return false; }
}
return true;
}
}
|
JavaScript
|
class InventoryResolver {
/**
* @param {*} socket the peer whose inventory needs to resolve
* @param {*} liteprotocol the protocol implementation itself
* @param {*} options
* `slices` number of slices
* `blockThreshold` the length threshold for sub blockchain. When
* sub blockchain's length is less than this
* threshold, the resolving will fall back
* to original approach (only by communicating one
* peer), which is via the `getData` message type.
* By default, this is undefined - always using
* parallel resolving.
*/
constructor(peer, liteprotocol, { slices = 10, blockThreshold = 1000 } = {}) {
this.peerDisconnectHandler = this.peerDisconnectHandler.bind(this);
this.dataPartialHandler = this.dataPartialHandler.bind(this);
this.partialNotFoundHandler = this.partialNotFoundHandler.bind(this);
this.peer = peer;
this.node = liteprotocol.node;
this.litenode = liteprotocol.litenode;
this.blockchain = liteprotocol.blockchain;
this.slices = slices;
this.blockThreshold = blockThreshold;
// merkle digest => block inventory to resolve
this.blockInventories = {};
this.litenode.on(`message/${messageTypes.dataPartial}`, this.dataPartialHandler);
this.litenode.on(`message/${messageTypes.partialNotFound}`, this.partialNotFoundHandler);
this.litenode.on('peerdisconnect', this.peerDisconnectHandler);
this.timer = setInterval(() => {
let now = getCurTimestamp();
for (let blockInv of Object.values(this.blockInventories)) {
// filter to get those timeout chunks
let chunks = [...blockInv].filter(chunk =>
!chunk.blocks && now - chunk.timestamp >= RESOLV_TIMEOUT);
if (chunks.some(chunk => chunk.peer.uuid === this.peer.uuid)) {
// abort resolving
delete this.blockInventories[ blockInv.merkleDigest ];
continue;
}
for (let chunk of chunks) {
this._resolveChunk(chunk, this.peer, blockInv);
}
} // end of loop
}, 30000);
}
/**
* Resolve the chunk (a slice of block inventory) by using
* the given peer. You should also pass the block inventory
* to which the chunk belongs.
*/
_resolveChunk(chunk, peer, blockInv) {
peer.sendJson(
getDataPartial({
merkleDigest: blockInv.merkleDigest,
blocks: chunk.ids
})
);
chunk.timestamp = getCurTimestamp();
chunk.peer = peer;
}
_resolveBlocks(blocks) {
if (blocks.length < this.blockThreshold) {
this.peer.sendJson(getData({ blocks }));
}
let blockInv = new BlockInventory(blocks, this.slices);
let chunks = [...blockInv];
let peers = this.node.peers('full');
if (this.blockInventories[ blockInv.merkleDigest ]) {
return;
}
// using round robin across peers
for (let i = 0; i < chunks.length; i++) {
// make sure request the last (latest) chunk
// from the peer which is the owner of the
// inventory to be resolved here (because
// other peers might not have the latest
// blocks of the chunk just mined)
let peer = i + 1 === chunks.length ?
this.peer : peers[i % peers.length];
this._resolveChunk(chunks[i], peer, blockInv);
} // end of loop
this.blockInventories[ blockInv.merkleDigest ] = blockInv;
}
_resolveLitemsgs(litemsgs) {
this.peer.sendJson(getData({ litemsgs }));
}
/**
* Note you don't have to provide the exact raw `inv` message
* here, but just an `inv`-like object. An `inv`-like object
* is any object which has either `blocks` or `litemsgs`
* properties, or both to resolve.
*
* @param {*} inv an `inv`-like object here
*/
resolve({ blocks = [], litemsgs = [] }) {
if (blocks.length) {
this._resolveBlocks(blocks);
}
if (litemsgs.length) {
this._resolveLitemsgs(litemsgs);
}
}
async dataPartialHandler({ messageType, ...payload }, peer) {
try {
messageValidators[messageType](payload);
let { merkleDigest, blocks } = payload;
let blockInv = this.blockInventories[merkleDigest];
if (!blockInv) { /* not interested in the resolved blocks */ return; }
// Here we just verify the resolved blocks separately,
// the reason is explained in the doc on this resolver
// class.
blocks = blocks.filter(block => verifyBlock(block));
let blockIds = blocks.map(block => block.hash);
let chunk = blockInv.chunks[calcMerkleRoot(blockIds)];
if (!chunk || chunk.blocks) { return; }
// save block data to inventory
chunk.blocks = blocks;
if (blockInv.resolved()) {
this.litenode.emit(
`message/${messageTypes.data}`,
data({ blocks: blockInv.getBlocks() }),
this.peer
);
delete this.blockInventories[merkleDigest];
}
} catch (err) {
console.warn(err);
}
}
async partialNotFoundHandler({ messageType, ...payload }, peer) {
// TODO
}
peerDisconnectHandler(peer) {
if (peer.uuid !== this.peer.uuid) { return; }
clearInterval(this.timer);
this.litenode.removeListener(`message/${messageTypes.dataPartial}`, this.dataPartialHandler);
this.litenode.removeListener(`message/${messageTypes.partialNotFound}`, this.partialNotFoundHandler);
this.litenode.removeListener('peerdisconnect', this.peerDisconnectHandler);
}
}
|
JavaScript
|
class GameController {
/**
* @param {Object} gameControllerConfig
* @param {String} gameControllerConfig.containerId DOM ID to mount this app
* @param {Phaser} gameControllerConfig.Phaser Phaser package
* @constructor
*/
constructor(gameControllerConfig) {
this.DEBUG = gameControllerConfig.debug;
// Phaser pre-initialization config
window.PhaserGlobal = {
disableAudio: true,
disableWebAudio: true,
hideBanner: !this.DEBUG
};
/**
* @public {Object} codeOrgAPI - API with externally-callable methods for
* starting an attempt, issuing commands, etc.
*/
this.codeOrgAPI = new CodeOrgAPI(this);
var Phaser = gameControllerConfig.Phaser;
/**
* Main Phaser game instance.
* @property {Phaser.Game}
*/
this.game = new Phaser.Game({
forceSetTimeOut: gameControllerConfig.forceSetTimeOut,
width: GAME_WIDTH,
height: GAME_HEIGHT,
renderer: Phaser.AUTO,
parent: gameControllerConfig.containerId,
state: "earlyLoad",
// TODO(bjordan): remove now that using canvas
preserveDrawingBuffer: false // enables saving .png screengrabs
});
this.specialLevelType = null;
this.queue = new CommandQueue(this);
this.OnCompleteCallback = null;
this.assetRoot = gameControllerConfig.assetRoot;
this.audioPlayer = gameControllerConfig.audioPlayer;
this.afterAssetsLoaded = gameControllerConfig.afterAssetsLoaded;
this.assetLoader = new AssetLoader(this);
this.earlyLoadAssetPacks = gameControllerConfig.earlyLoadAssetPacks || [];
this.earlyLoadNiceToHaveAssetPacks = gameControllerConfig.earlyLoadNiceToHaveAssetPacks || [];
this.resettableTimers = [];
this.timeouts = [];
this.timeout = 0;
this.initializeCommandRecord();
this.score = 0;
this.useScore = false;
this.scoreText = null;
this.onScoreUpdate = gameControllerConfig.onScoreUpdate;
this.events = [];
// Phaser "slow motion" modifier we originally tuned animations using
this.assumedSlowMotion = 1.5;
this.initialSlowMotion = gameControllerConfig.customSlowMotion || this.assumedSlowMotion;
this.tweenTimeScale = 1.5 / this.initialSlowMotion;
this.playerDelayFactor = 1.0;
this.dayNightCycle = null;
this.player = null;
this.agent = null;
this.timerSprite = null;
this.game.state.add("earlyLoad", {
preload: () => {
// don't let state change stomp essential asset downloads in progress
this.game.load.resetLocked = true;
this.assetLoader.loadPacks(this.earlyLoadAssetPacks);
},
create: () => {
// optionally load some more assets if we complete early load before level load
this.assetLoader.loadPacks(this.earlyLoadNiceToHaveAssetPacks);
this.game.load.start();
}
});
this.game.state.add("levelRunner", {
preload: this.preload.bind(this),
create: this.create.bind(this),
update: this.update.bind(this),
render: this.render.bind(this)
});
}
/**
* Is this one of those level types in which the player is controlled by arrow
* keys rather than by blocks?
*
* @return {boolean}
*/
getIsDirectPlayerControl() {
return this.levelData.isEventLevel || this.levelData.isAgentLevel;
}
/**
* @param {Object} levelConfig
*/
loadLevel(levelConfig) {
this.levelData = Object.assign(levelConfig);
this.levelEntity = new LevelEntity(this);
this.levelModel = new LevelModel(this.levelData, this);
this.levelView = new LevelView(this);
this.specialLevelType = levelConfig.specialLevelType;
this.dayNightCycle = Number.parseInt(levelConfig.dayNightCycle);
this.timeout = levelConfig.levelVerificationTimeout;
if (levelConfig.useScore !== undefined) {
this.useScore = levelConfig.useScore;
}
this.timeoutResult = levelConfig.timeoutResult;
this.onDayCallback = levelConfig.onDayCallback;
this.onNightCallback = levelConfig.onNightCallback;
if (!Number.isNaN(this.dayNightCycle) && this.dayNightCycle > 1000) {
this.setDayNightCycle(this.dayNightCycle, "day");
}
this.game.state.start("levelRunner");
}
reset() {
this.dayNightCycle = null;
this.queue.reset();
this.levelEntity.reset();
this.levelModel.reset();
this.levelView.reset(this.levelModel);
this.levelEntity.loadData(this.levelData);
this.player = this.levelModel.player;
this.agent = this.levelModel.agent;
this.resettableTimers.forEach((timer) => {
timer.stop(true);
});
this.timeouts.forEach((timeout) => {
clearTimeout(timeout);
});
if (this.timerSprite) {
this.timerSprite.kill();
}
this.timerSprite = null;
this.timeouts = [];
this.resettableTimers.length = 0;
this.events.length = 0;
this.score = 0;
if (this.useScore) {
this.updateScore();
}
if (!this.getIsDirectPlayerControl()) {
this.events.push(event => {
if (event.eventType === EventType.WhenUsed && event.targetType === "sheep") {
this.codeOrgAPI.drop(null, "wool", event.targetIdentifier);
}
if (event.eventType === EventType.WhenTouched && event.targetType === "creeper") {
this.codeOrgAPI.flashEntity(null, event.targetIdentifier);
this.codeOrgAPI.explodeEntity(null, event.targetIdentifier);
}
});
}
this.initializeCommandRecord();
}
preload() {
this.game.load.resetLocked = true;
this.game.time.advancedTiming = this.DEBUG;
this.game.stage.disableVisibilityChange = true;
this.assetLoader.loadPacks(this.levelData.assetPacks.beforeLoad);
}
create() {
this.levelView.create(this.levelModel);
this.game.time.slowMotion = this.initialSlowMotion;
this.addCheatKeys();
this.assetLoader.loadPacks(this.levelData.assetPacks.afterLoad);
this.game.load.image("timer", `${this.assetRoot}images/placeholderTimer.png`);
this.game.load.onLoadComplete.addOnce(() => {
if (this.afterAssetsLoaded) {
this.afterAssetsLoaded();
}
});
this.levelEntity.loadData(this.levelData);
this.game.load.start();
}
run(onErrorCallback, apiObject) {
/* Execute user/designer's code */
try {
new Function('api', `'use strict'; ${this.levelData.script}`)(apiObject);
} catch (err) {
onErrorCallback(err);
}
// dispatch when spawn event at run
this.events.forEach(e => e({ eventType: EventType.WhenRun, targetIdentifier: undefined }));
for (let value of this.levelEntity.entityMap) {
var entity = value[1];
this.events.forEach(e => e({ eventType: EventType.WhenSpawned, targetType: entity.type, targetIdentifier: entity.identifier }));
entity.queue.begin();
}
// set timeout for timeout
const isNumber = !Number.isNaN(this.timeout);
if (isNumber && this.timeout > 0) {
this.timerSprite = this.game.add.sprite(-50, 390, "timer");
var tween = this.levelView.addResettableTween(this.timerSprite).to({
x: -450, alpha: 0.5
}, this.timeout, Phaser.Easing.Linear.None);
tween.onComplete.add(() => {
this.endLevel(this.timeoutResult(this.levelModel));
});
tween.start();
}
}
followingPlayer() {
return !!this.levelData.gridDimensions && !this.checkMinecartLevelEndAnimation();
}
update() {
this.queue.tick();
this.levelEntity.tick();
if (this.levelModel.usePlayer) {
this.player.updateMovement();
}
if (this.levelModel.usingAgent) {
this.agent.updateMovement();
}
this.levelView.update();
// Check for completion every frame for "event" levels. For procedural
// levels, only check completion after the player has run all commands.
if (this.getIsDirectPlayerControl() || this.player.queue.state > 1) {
this.checkSolution();
}
}
addCheatKeys() {
if (!this.levelModel.usePlayer) {
return;
}
const keysToMovementState = {
[Phaser.Keyboard.W]: FacingDirection.North,
[Phaser.Keyboard.D]: FacingDirection.East,
[Phaser.Keyboard.S]: FacingDirection.South,
[Phaser.Keyboard.A]: FacingDirection.West,
[Phaser.Keyboard.SPACEBAR]: -2,
[Phaser.Keyboard.BACKSPACE]: -3
};
const editableElementSelected = function () {
const editableHtmlTags = ["INPUT", "TEXTAREA"];
return document.activeElement !== null &&
editableHtmlTags.includes(document.activeElement.tagName);
};
Object.keys(keysToMovementState).forEach((key) => {
const movementState = keysToMovementState[key];
this.game.input.keyboard.addKey(key).onDown.add(() => {
if (editableElementSelected()) {
return;
}
this.player.movementState = movementState;
this.player.updateMovement();
});
this.game.input.keyboard.addKey(key).onUp.add(() => {
if (editableElementSelected()) {
return;
}
if (this.player.movementState === movementState) {
this.player.movementState = -1;
}
this.player.updateMovement();
});
this.game.input.keyboard.removeKeyCapture(key);
});
}
handleEndState(result) {
// report back to the code.org side the pass/fail result
// then clear the callback so we dont keep calling it
if (this.OnCompleteCallback) {
this.OnCompleteCallback(result, this.levelModel);
this.OnCompleteCallback = null;
}
}
render() {
if (this.DEBUG) {
this.game.debug.text(this.game.time.fps || "--", 2, 14, "#00ff00");
}
this.levelView.render();
}
scaleFromOriginal() {
var [newWidth, newHeight] = this.levelData.gridDimensions || [10, 10];
var [originalWidth, originalHeight] = [10, 10];
return [newWidth / originalWidth, newHeight / originalHeight];
}
getScreenshot() {
return this.game.canvas.toDataURL("image/png");
}
// command record
initializeCommandRecord() {
let commandList = ["moveAway", "moveToward", "moveForward", "turn", "turnRandom", "explode", "wait", "flash", "drop", "spawn", "destroy", "playSound", "attack", "addScore"];
this.commandRecord = new Map;
this.repeatCommandRecord = new Map;
this.isRepeat = false;
for (let i = 0; i < commandList.length; i++) {
this.commandRecord.set(commandList[i], new Map);
this.commandRecord.get(commandList[i]).set("count", 0);
this.repeatCommandRecord.set(commandList[i], new Map);
this.repeatCommandRecord.get(commandList[i]).set("count", 0);
}
}
startPushRepeatCommand() {
this.isRepeat = true;
}
endPushRepeatCommand() {
this.isRepeat = false;
}
addCommandRecord(commandName, targetType, repeat) {
var commandRecord = repeat ? this.repeatCommandRecord : this.commandRecord;
// correct command name
if (commandRecord.has(commandName)) {
// update count for command map
let commandMap = commandRecord.get(commandName);
commandMap.set("count", commandMap.get("count") + 1);
// command map has target
if (commandMap.has(targetType)) {
// increment count
commandMap.set(targetType, commandMap.get(targetType) + 1);
} else {
commandMap.set(targetType, 1);
}
if (this.DEBUG) {
const msgHeader = repeat ? "Repeat " : "" + "Command :";
console.log(msgHeader + commandName + " executed in mob type : " + targetType + " updated count : " + commandMap.get(targetType));
}
}
}
getCommandCount(commandName, targetType, repeat) {
var commandRecord = repeat ? this.repeatCommandRecord : this.commandRecord;
// command record has command name and target
if (commandRecord.has(commandName)) {
let commandMap = commandRecord.get(commandName);
// doesn't have target so returns global count for command
if (targetType === undefined) {
return commandMap.get("count");
// type specific count
} else if (commandMap.has(targetType)) {
return commandMap.get(targetType);
// doesn't have a target
} else {
return 0;
}
} else {
return 0;
}
}
// command processors
getEntity(target) {
if (target === undefined) {
target = "Player";
}
let entity = this.levelEntity.entityMap.get(target);
if (entity === undefined) {
console.log("Debug GetEntity: there is no entity : " + target + "\n");
}
return entity;
}
getEntities(type) {
return this.levelEntity.getEntitiesOfType(type);
}
isType(target) {
return typeof (target) === "string" && (target !== "Player" && target !== "PlayerAgent");
}
printErrorMsg(msg) {
if (this.DEBUG) {
this.game.debug.text(msg);
}
}
/**
* @param {any} commandQueueItem
* @param {any} moveAwayFrom (entity identifier)
*
* @memberOf GameController
*/
moveAway(commandQueueItem, moveAwayFrom) {
var target = commandQueueItem.target;
// apply to all entities
if (target === undefined) {
var entities = this.levelEntity.entityMap;
for (let value of entities) {
let entity = value[1];
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.moveAway(callbackCommand, moveAwayFrom); }, entity.identifier);
entity.addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
} else {
let targetIsType = this.isType(target);
let moveAwayFromIsType = this.isType(moveAwayFrom);
if (target === moveAwayFrom) {
this.printErrorMsg("Debug MoveAway: Can't move away entity from itself\n");
commandQueueItem.succeeded();
return;
}
// move away entity from entity
if (!targetIsType && !moveAwayFromIsType) {
let entity = this.getEntity(target);
let moveAwayFromEntity = this.getEntity(moveAwayFrom);
if (entity === moveAwayFromEntity) {
commandQueueItem.succeeded();
return;
}
entity.moveAway(commandQueueItem, moveAwayFromEntity);
} else if (targetIsType && !moveAwayFromIsType) {
// move away type from entity
let targetEntities = this.getEntities(target);
let moveAwayFromEntity = this.getEntity(moveAwayFrom);
if (moveAwayFromEntity !== undefined) {
for (let i = 0; i < targetEntities.length; i++) {
// not move if it's same entity
if (targetEntities[i].identifier === moveAwayFromEntity.identifier) {
continue;
}
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.moveAway(callbackCommand, moveAwayFrom); }, targetEntities[i].identifier);
targetEntities[i].addCommand(callbackCommand, commandQueueItem.repeat);
}
}
commandQueueItem.succeeded();
} else if (!targetIsType && moveAwayFromIsType) {
// move away entity from type
let entity = this.getEntity(target);
let moveAwayFromEntities = this.getEntities(moveAwayFrom);
if (moveAwayFromEntities.length > 0) {
let closestTarget = [Number.MAX_VALUE, -1];
for (let i = 0; i < moveAwayFromEntities.length; i++) {
if (entity.identifier === moveAwayFromEntities[i].identifier) {
continue;
}
let distance = entity.getDistance(moveAwayFromEntities[i]);
if (distance < closestTarget[0]) {
closestTarget = [distance, i];
}
}
if (closestTarget[1] !== -1) {
entity.moveAway(commandQueueItem, moveAwayFromEntities[closestTarget[1]]);
}
} else {
commandQueueItem.succeeded();
}
} else {
// move away type from type
let entities = this.getEntities(target);
let moveAwayFromEntities = this.getEntities(moveAwayFrom);
if (moveAwayFromEntities.length > 0 && entities.length > 0) {
for (let i = 0; i < entities.length; i++) {
let entity = entities[i];
let closestTarget = [Number.MAX_VALUE, -1];
for (let j = 0; j < moveAwayFromEntities.length; j++) {
// not move if it's same entity
if (moveAwayFromEntities[i].identifier === entity.identifier) {
continue;
}
let distance = entity.getDistance(moveAwayFromEntities[j]);
if (distance < closestTarget[0]) {
closestTarget = [distance, j];
}
}
if (closestTarget !== -1) {
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.moveAway(callbackCommand, moveAwayFromEntities[closestTarget[1]].identifier); }, entity.identifier);
entity.addCommand(callbackCommand, commandQueueItem.repeat);
} else {
commandQueueItem.succeeded();
}
}
commandQueueItem.succeeded();
}
}
}
}
/**
* @param {any} commandQueueItem
* @param {any} moveTowardTo (entity identifier)
*
* @memberOf GameController
*/
moveToward(commandQueueItem, moveTowardTo) {
var target = commandQueueItem.target;
// apply to all entities
if (target === undefined) {
let entities = this.levelEntity.entityMap;
for (let value of entities) {
let entity = value[1];
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.moveToward(callbackCommand, moveTowardTo); }, entity.identifier);
entity.addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
} else {
let targetIsType = this.isType(target);
let moveTowardToIsType = this.isType(moveTowardTo);
if (target === moveTowardTo) {
commandQueueItem.succeeded();
return;
}
// move toward entity to entity
if (!targetIsType && !moveTowardToIsType) {
let entity = this.getEntity(target);
let moveTowardToEntity = this.getEntity(moveTowardTo);
entity.moveToward(commandQueueItem, moveTowardToEntity);
} else if (targetIsType && !moveTowardToIsType) {
// move toward type to entity
let targetEntities = this.getEntities(target);
let moveTowardToEntity = this.getEntity(moveTowardTo);
if (moveTowardToEntity !== undefined) {
for (let i = 0; i < targetEntities.length; i++) {
// not move if it's same entity
if (targetEntities[i].identifier === moveTowardToEntity.identifier) {
continue;
}
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.moveToward(callbackCommand, moveTowardTo); }, targetEntities[i].identifier);
targetEntities[i].addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
}
} else if (!targetIsType && moveTowardToIsType) {
// move toward entity to type
let entity = this.getEntity(target);
let moveTowardToEntities = this.getEntities(moveTowardTo);
if (moveTowardToEntities.length > 0) {
let closestTarget = [Number.MAX_VALUE, -1];
for (let i = 0; i < moveTowardToEntities.length; i++) {
// not move if it's same entity
if (moveTowardToEntities[i].identifier === entity.identifier) {
continue;
}
let distance = entity.getDistance(moveTowardToEntities[i]);
if (distance < closestTarget[0]) {
closestTarget = [distance, i];
}
}
// there is valid target
if (closestTarget[1] !== -1) {
entity.moveToward(commandQueueItem, moveTowardToEntities[closestTarget[1]]);
} else {
commandQueueItem.succeeded();
}
} else {
commandQueueItem.succeeded();
}
} else {
// move toward type to type
let entities = this.getEntities(target);
let moveTowardToEntities = this.getEntities(moveTowardTo);
if (moveTowardToEntities.length > 0 && entities.length > 0) {
for (let i = 0; i < entities.length; i++) {
let entity = entities[i];
let closestTarget = [Number.MAX_VALUE, -1];
for (let j = 0; j < moveTowardToEntities.length; j++) {
// not move if it's same entity
if (moveTowardToEntities[i].identifier === entity.identifier) {
continue;
}
let distance = entity.getDistance(moveTowardToEntities[j]);
if (distance < closestTarget[0]) {
closestTarget = [distance, j];
}
}
if (closestTarget[1] !== -1) {
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.moveToward(callbackCommand, moveTowardToEntities[closestTarget[1]].identifier); }, entity.identifier);
entity.addCommand(callbackCommand, commandQueueItem.repeat);
}
}
commandQueueItem.succeeded();
}
}
}
}
positionEquivalence(lhs, rhs) {
return (lhs[0] === rhs[0] && lhs[1] === rhs[1]);
}
/**
* Run a command. If no `commandQueueItem.target` is provided, the command
* will be applied to all targets.
*
* @param commandQueueItem
* @param command
* @param commandArgs
*/
execute(commandQueueItem, command, ...commandArgs) {
let target = commandQueueItem.target;
if (!this.isType(target)) {
if (target === undefined) {
// Apply to all entities.
let entities = this.levelEntity.entityMap;
for (let value of entities) {
let entity = value[1];
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.execute(callbackCommand, command, ...commandArgs); }, entity.identifier);
entity.addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
} else {
// Apply to the given target.
let entity = this.getEntity(target);
entity[command](commandQueueItem, ...commandArgs);
}
} else {
// Apply to all targets of the given type.
let entities = this.getEntities(target);
for (let i = 0; i < entities.length; i++) {
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.execute(callbackCommand, command, ...commandArgs); }, entities[i].identifier);
entities[i].addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
}
}
moveForward(commandQueueItem) {
this.execute(commandQueueItem, "moveForward");
}
moveBackward(commandQueueItem) {
this.execute(commandQueueItem, "moveBackward");
}
moveDirection(commandQueueItem, direction) {
let player = this.levelModel.player;
let shouldRide = this.levelModel.shouldRide(direction);
if (shouldRide) {
player.handleGetOnRails(direction);
commandQueueItem.succeeded();
} else {
this.execute(commandQueueItem, "moveDirection", direction);
}
}
turn(commandQueueItem, direction) {
this.execute(commandQueueItem, "turn", direction);
}
turnRandom(commandQueueItem) {
this.execute(commandQueueItem, "turnRandom");
}
flashEntity(commandQueueItem) {
let target = commandQueueItem.target;
if (!this.isType(target)) {
// apply to all entities
if (target === undefined) {
let entities = this.levelEntity.entityMap;
for (let value of entities) {
let entity = value[1];
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.flashEntity(callbackCommand); }, entity.identifier);
entity.addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
} else {
let entity = this.getEntity(target);
let delay = this.levelView.flashSpriteToWhite(entity.sprite);
this.addCommandRecord("flash", entity.type, commandQueueItem.repeat);
this.delayBy(delay, () => {
commandQueueItem.succeeded();
});
}
} else {
let entities = this.getEntities(target);
for (let i = 0; i < entities.length; i++) {
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.flashEntity(callbackCommand); }, entities[i].identifier);
entities[i].addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
}
}
explodeEntity(commandQueueItem) {
let target = commandQueueItem.target;
if (!this.isType(target)) {
// apply to all entities
if (target === undefined) {
let entities = this.levelEntity.entityMap;
for (let value of entities) {
let entity = value[1];
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.explodeEntity(callbackCommand); }, entity.identifier);
entity.addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
} else {
let targetEntity = this.getEntity(target);
this.levelView.playExplosionCloudAnimation(targetEntity.position);
this.addCommandRecord("explode", targetEntity.type, commandQueueItem.repeat);
this.levelView.audioPlayer.play("explode");
let entities = this.levelEntity.entityMap;
for (let value of entities) {
let entity = value[1];
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
if (i === 0 && j === 0) {
continue;
}
let position = [targetEntity.position[0] + i, targetEntity.position[1] + j];
this.destroyBlockWithoutPlayerInteraction(position);
if (entity.position[0] === targetEntity.position[0] + i && entity.position[1] === targetEntity.position[1] + j) {
entity.blowUp(commandQueueItem, targetEntity.position);
}
}
}
}
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.destroyEntity(callbackCommand, targetEntity.identifier); }, targetEntity.identifier);
targetEntity.queue.startPushHighPriorityCommands();
targetEntity.addCommand(callbackCommand, commandQueueItem.repeat);
targetEntity.queue.endPushHighPriorityCommands();
}
commandQueueItem.succeeded();
this.updateFowPlane();
this.updateShadingPlane();
} else {
let entities = this.getEntities(target);
for (let i = 0; i < entities.length; i++) {
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.explodeEntity(callbackCommand); }, entities[i].identifier);
entities[i].addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
}
}
wait(commandQueueItem, time) {
let target = commandQueueItem.target;
if (!this.isType(target)) {
let entity = this.getEntity(target);
this.addCommandRecord("wait", entity.type, commandQueueItem.repeat);
setTimeout(() => { commandQueueItem.succeeded(); }, time * 1000 / this.tweenTimeScale);
} else {
let entities = this.getEntities(target);
for (let i = 0; i < entities.length; i++) {
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.wait(callbackCommand, time); }, entities[i].identifier);
entities[i].addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
}
}
spawnEntity(commandQueueItem, type, spawnDirection) {
this.addCommandRecord("spawn", type, commandQueueItem.repeat);
let spawnedEntity = this.levelEntity.spawnEntity(type, spawnDirection);
if (spawnedEntity !== null) {
this.events.forEach(e => e({ eventType: EventType.WhenSpawned, targetType: type, targetIdentifier: spawnedEntity.identifier }));
}
commandQueueItem.succeeded();
}
spawnEntityAt(commandQueueItem, type, x, y, facing) {
let spawnedEntity = this.levelEntity.spawnEntityAt(type, x, y, facing);
if (spawnedEntity !== null) {
this.events.forEach(e => e({ eventType: EventType.WhenSpawned, targetType: type, targetIdentifier: spawnedEntity.identifier }));
}
commandQueueItem.succeeded();
}
destroyEntity(commandQueueItem, target) {
if (!this.isType(target)) {
// apply to all entities
if (target === undefined) {
let entities = this.levelEntity.entityMap;
for (let value of entities) {
let entity = value[1];
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.destroyEntity(callbackCommand, entity.identifier); }, entity.identifier);
entity.addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
} else {
this.addCommandRecord("destroy", this.type, commandQueueItem.repeat);
let entity = this.getEntity(target);
if (entity !== undefined) {
entity.healthPoint = 1;
entity.takeDamage(commandQueueItem);
} else {
commandQueueItem.succeeded();
}
}
} else {
let entities = this.getEntities(target);
for (let i = 0; i < entities.length; i++) {
let entity = entities[i];
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.destroyEntity(callbackCommand, entity.identifier); }, entity.identifier);
entity.addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
}
}
drop(commandQueueItem, itemType) {
let target = commandQueueItem.target;
if (!this.isType(target)) {
// apply to all entities
if (target === undefined) {
let entities = this.levelEntity.entityMap;
for (let value of entities) {
let entity = value[1];
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.drop(callbackCommand, itemType); }, entity.identifier);
entity.addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
} else {
let entity = this.getEntity(target);
entity.drop(commandQueueItem, itemType);
}
} else {
let entities = this.getEntities(target);
for (let i = 0; i < entities.length; i++) {
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.drop(callbackCommand, itemType); }, entities[i].identifier);
entities[i].addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
}
}
attack(commandQueueItem) {
let target = commandQueueItem.target;
if (!this.isType(target)) {
// apply to all entities
if (target === undefined) {
let entities = this.levelEntity.entityMap;
for (let value of entities) {
let entity = value[1];
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.attack(callbackCommand); }, entity.identifier);
entity.addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
} else {
let entity = this.getEntity(target);
if (entity.identifier === "Player") {
this.codeOrgAPI.destroyBlock(() => { }, entity.identifier);
commandQueueItem.succeeded();
} else {
entity.attack(commandQueueItem);
}
}
} else {
let entities = this.getEntities(target);
for (let i = 0; i < entities.length; i++) {
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.attack(callbackCommand); }, entities[i].identifier);
entities[i].addCommand(callbackCommand, commandQueueItem.repeat);
}
commandQueueItem.succeeded();
}
}
playSound(commandQueueItem, sound) {
this.addCommandRecord("playSound", undefined, commandQueueItem.repeat);
this.levelView.audioPlayer.play(sound);
commandQueueItem.succeeded();
}
use(commandQueueItem) {
let player = this.levelModel.player;
let frontPosition = this.levelModel.getMoveForwardPosition(player);
let frontEntity = this.levelEntity.getEntityAt(frontPosition);
let frontBlock = this.levelModel.actionPlane.getBlockAt(frontPosition);
const isFrontBlockDoor = !!frontBlock && frontBlock.blockType === "door";
if (player.movementState == -3) {
//player.movementState = -1;
this.destroyBlock(commandQueueItem);
return;
}
if (frontEntity !== null && frontEntity !== this.agent) {
// push use command to execute general use behavior of the entity before executing the event
this.levelView.setSelectionIndicatorPosition(frontPosition[0], frontPosition[1]);
this.levelView.onAnimationEnd(this.levelView.playPlayerAnimation("punch", player.position, player.facing, false), () => {
frontEntity.queue.startPushHighPriorityCommands();
let useCommand = new CallbackCommand(this, () => { }, () => { frontEntity.use(useCommand, player); }, frontEntity.identifier);
const isFriendlyEntity = this.levelEntity.isFriendlyEntity(frontEntity.type);
// push frienly entity 1 block
if (!isFriendlyEntity) {
const pushDirection = player.facing;
let moveAwayCommand = new CallbackCommand(this, () => { }, () => { frontEntity.pushBack(moveAwayCommand, pushDirection, 150); }, frontEntity.identifier);
frontEntity.addCommand(moveAwayCommand);
}
frontEntity.addCommand(useCommand);
frontEntity.queue.endPushHighPriorityCommands();
this.levelView.playPlayerAnimation("idle", player.position, player.facing, false);
if (this.getIsDirectPlayerControl()) {
this.delayPlayerMoveBy(0, 0, () => {
commandQueueItem.succeeded();
});
} else {
commandQueueItem.waitForOtherQueue = true;
}
setTimeout(() => { this.levelView.setSelectionIndicatorPosition(player.position[0], player.position[1]); }, 0);
});
} else if (isFrontBlockDoor) {
this.levelView.setSelectionIndicatorPosition(frontPosition[0], frontPosition[1]);
this.levelView.onAnimationEnd(this.levelView.playPlayerAnimation("punch", player.position, player.facing, false), () => {
this.audioPlayer.play("doorOpen");
// if it's not walable, then open otherwise, close
const canOpen = !frontBlock.isWalkable;
this.levelView.playDoorAnimation(frontPosition, canOpen, () => {
frontBlock.isWalkable = !frontBlock.isWalkable;
this.levelView.playIdleAnimation(player.position, player.facing, player.isOnBlock);
this.levelView.setSelectionIndicatorPosition(player.position[0], player.position[1]);
commandQueueItem.succeeded();
});
});
} else if (frontBlock && frontBlock.isRail) {
this.levelView.playTrack(frontPosition, player.facing, true, player, null);
commandQueueItem.succeeded();
} else {
this.placeBlockForward(commandQueueItem, player.selectedItem);
}
}
destroyBlock(commandQueueItem) {
let player = this.getEntity(commandQueueItem.target);
// if there is a destroyable block in front of the player
if (this.levelModel.canDestroyBlockForward(player)) {
let block = this.levelModel.actionPlane.getBlockAt(this.levelModel.getMoveForwardPosition(player));
if (block !== null) {
let destroyPosition = this.levelModel.getMoveForwardPosition(player);
let blockType = block.blockType;
if (block.isDestroyable) {
switch (blockType) {
case "logAcacia":
case "treeAcacia":
blockType = "planksAcacia";
break;
case "logBirch":
case "treeBirch":
blockType = "planksBirch";
break;
case "logJungle":
case "treeJungle":
blockType = "planksJungle";
break;
case "logOak":
case "treeOak":
blockType = "planksOak";
break;
case "logSpruce":
case "treeSpruce":
blockType = "planksSpruce";
break;
}
this.levelView.playDestroyBlockAnimation(player.position, player.facing, destroyPosition, blockType, player, () => {
commandQueueItem.succeeded();
});
} else if (block.isUsable) {
switch (blockType) {
case "sheep":
// TODO: What to do with already sheered sheep?
this.levelView.playShearSheepAnimation(player.position, player.facing, destroyPosition, blockType, () => {
commandQueueItem.succeeded();
});
break;
default:
commandQueueItem.succeeded();
}
} else {
commandQueueItem.succeeded();
}
}
// if there is a entity in front of the player
} else {
this.levelView.playPunchDestroyAirAnimation(player.position, player.facing, this.levelModel.getMoveForwardPosition(player), () => {
this.levelView.setSelectionIndicatorPosition(player.position[0], player.position[1]);
this.levelView.playIdleAnimation(player.position, player.facing, player.isOnBlock, player);
this.delayPlayerMoveBy(0, 0, () => {
commandQueueItem.succeeded();
});
}, player);
}
}
destroyBlockWithoutPlayerInteraction(position) {
if (!this.levelModel.inBounds(position)) {
return;
}
let block = this.levelModel.actionPlane.getBlockAt(position);
if (block !== null && block !== undefined) {
let destroyPosition = position;
let blockType = block.blockType;
if (block.isDestroyable) {
switch (blockType) {
case "logAcacia":
case "treeAcacia":
blockType = "planksAcacia";
break;
case "logBirch":
case "treeBirch":
blockType = "planksBirch";
break;
case "logJungle":
case "treeJungle":
blockType = "planksJungle";
break;
case "logOak":
case "treeOak":
blockType = "planksOak";
break;
case "logSpruce":
case "treeSpruce":
case "logSpruceSnowy":
case "treeSpruceSnowy":
blockType = "planksSpruce";
break;
}
this.levelView.destroyBlockWithoutPlayerInteraction(destroyPosition);
this.levelView.playExplosionAnimation(this.levelModel.player.position, this.levelModel.player.facing, position, blockType, () => { }, false);
this.levelView.createMiniBlock(destroyPosition[0], destroyPosition[1], blockType);
this.updateFowPlane();
this.updateShadingPlane();
} else if (block.isUsable) {
switch (blockType) {
case "sheep":
// TODO: What to do with already sheered sheep?
this.levelView.playShearAnimation(this.levelModel.player.position, this.levelModel.player.facing, position, blockType, () => { });
break;
}
}
}
// clear the block in level model (block info in 2d grid)
this.levelModel.destroyBlock(position);
}
checkTntAnimation() {
return this.specialLevelType === "freeplay";
}
checkMinecartLevelEndAnimation() {
return this.specialLevelType === "minecart";
}
checkHouseBuiltEndAnimation() {
return this.specialLevelType === "houseBuild";
}
checkAgentSpawn() {
return this.specialLevelType === "agentSpawn";
}
placeBlock(commandQueueItem, blockType) {
const player = this.getEntity(commandQueueItem.target);
const position = player.position;
let blockAtPosition = this.levelModel.actionPlane.getBlockAt(position);
let blockTypeAtPosition = blockAtPosition.blockType;
if (this.levelModel.canPlaceBlock(player, blockAtPosition)) {
if (blockTypeAtPosition !== "") {
this.levelModel.destroyBlock(position);
}
if (blockType !== "cropWheat" || this.levelModel.groundPlane.getBlockAt(player.position).blockType === "farmlandWet") {
this.levelModel.player.updateHidingBlock(player.position);
if (this.checkMinecartLevelEndAnimation() && blockType === "rail") {
// Special 'minecart' level places a mix of regular and powered tracks, depending on location.
if (player.position[1] < 7) {
blockType = "railsUnpoweredVertical";
} else {
blockType = "rails";
}
}
this.levelView.playPlaceBlockAnimation(player.position, player.facing, blockType, blockTypeAtPosition, player, () => {
const entity = convertNameToEntity(blockType, position.x, position.y);
if (entity) {
this.levelEntity.spawnEntityAt(...entity);
} else {
this.levelModel.placeBlock(blockType, player);
this.updateFowPlane();
this.updateShadingPlane();
}
this.delayBy(200, () => {
this.levelView.playIdleAnimation(player.position, player.facing, false, player);
});
this.delayPlayerMoveBy(200, 400, () => {
commandQueueItem.succeeded();
});
});
} else {
let signalBinding = this.levelView.playPlayerAnimation("jumpUp", player.position, player.facing, false, player).onLoop.add(() => {
this.levelView.playIdleAnimation(player.position, player.facing, false, player);
signalBinding.detach();
this.delayBy(800, () => commandQueueItem.succeeded());
}, this);
}
} else {
commandQueueItem.succeeded();
}
}
setPlayerActionDelayByQueueLength() {
if (!this.levelModel.usePlayer) {
return;
}
let START_SPEED_UP = 10;
let END_SPEED_UP = 20;
let queueLength = this.levelModel.player.queue.getLength();
let speedUpRangeMax = END_SPEED_UP - START_SPEED_UP;
let speedUpAmount = Math.min(Math.max(queueLength - START_SPEED_UP, 0), speedUpRangeMax);
this.playerDelayFactor = 1 - (speedUpAmount / speedUpRangeMax);
}
delayBy(ms, completionHandler) {
let timer = this.game.time.create(true);
timer.add(this.originalMsToScaled(ms), completionHandler, this);
timer.start();
this.resettableTimers.push(timer);
}
delayPlayerMoveBy(minMs, maxMs, completionHandler) {
this.delayBy(Math.max(minMs, maxMs * this.playerDelayFactor), completionHandler);
}
originalMsToScaled(ms) {
let realMs = ms / this.assumedSlowMotion;
return realMs * this.game.time.slowMotion;
}
originalFpsToScaled(fps) {
let realFps = fps * this.assumedSlowMotion;
return realFps / this.game.time.slowMotion;
}
placeBlockForward(commandQueueItem, blockType) {
this.placeBlockDirection(commandQueueItem, blockType, 0);
}
placeBlockDirection(commandQueueItem, blockType, direction) {
let player = this.getEntity(commandQueueItem.target);
let position,
placementPlane,
soundEffect = () => { };
if (!this.levelModel.canPlaceBlockDirection(blockType, player, direction)) {
this.levelView.playPunchAirAnimation(player.position, player.facing, player.position, () => {
this.levelView.playIdleAnimation(player.position, player.facing, false, player);
commandQueueItem.succeeded();
}, player);
return;
}
position = this.levelModel.getMoveDirectionPosition(player, direction);
placementPlane = this.levelModel.getPlaneToPlaceOn(position, player, blockType);
if (this.levelModel.isBlockOfTypeOnPlane(position, "lava", placementPlane)) {
soundEffect = () => this.levelView.audioPlayer.play("fizz");
}
this.levelView.playPlaceBlockInFrontAnimation(player, player.position, player.facing, position, () => {
this.levelModel.placeBlockDirection(blockType, placementPlane, player, direction);
this.levelView.refreshGroundGroup();
this.updateFowPlane();
this.updateShadingPlane();
soundEffect();
this.delayBy(200, () => {
this.levelView.playIdleAnimation(player.position, player.facing, false, player);
});
this.delayPlayerMoveBy(200, 400, () => {
commandQueueItem.succeeded();
});
});
}
checkSolution() {
if (!this.attemptRunning || this.resultReported) {
return;
}
// check the final state to see if its solved
if (this.levelModel.isSolved()) {
const player = this.levelModel.player;
if (this.checkHouseBuiltEndAnimation()) {
this.resultReported = true;
var houseBottomRight = this.levelModel.getHouseBottomRight();
var inFrontOfDoor = new Position(houseBottomRight.x - 1, houseBottomRight.y + 2);
var bedPosition = new Position(houseBottomRight.x, houseBottomRight.y);
var doorPosition = new Position(houseBottomRight.x - 1, houseBottomRight.y + 1);
this.levelModel.moveTo(inFrontOfDoor);
this.levelView.playSuccessHouseBuiltAnimation(
player.position,
player.facing,
player.isOnBlock,
this.levelModel.houseGroundToFloorBlocks(houseBottomRight),
[bedPosition, doorPosition],
() => {
this.endLevel(true);
},
() => {
this.levelModel.destroyBlock(bedPosition);
this.levelModel.destroyBlock(doorPosition);
this.updateFowPlane();
this.updateShadingPlane();
}
);
} else if (this.checkMinecartLevelEndAnimation()) {
this.resultReported = true;
this.levelView.playMinecartAnimation(player.isOnBlock, () => {
this.handleEndState(true);
});
} else if (this.checkAgentSpawn()) {
this.resultReported = true;
const levelEndAnimation = this.levelView.playLevelEndAnimation(player.position, player.facing, player.isOnBlock);
levelEndAnimation.onComplete.add(() => {
this.levelModel.spawnAgent(null, new Position(3, 4), 2); // This will spawn the Agent at [3, 4], facing South.
this.levelView.agent = this.agent;
this.levelView.resetEntity(this.agent);
this.updateFowPlane();
this.updateShadingPlane();
this.delayBy(200, () => {
this.endLevel(true);
});
});
} else if (this.checkTntAnimation()) {
this.resultReported = true;
this.levelView.scaleShowWholeWorld(() => {});
var tnt = this.levelModel.getTnt();
var wasOnBlock = player.isOnBlock;
this.levelView.playDestroyTntAnimation(player.position, player.facing, player.isOnBlock, this.levelModel.getTnt(), this.levelModel.shadingPlane,
() => {
for (let i in tnt) {
if (tnt[i].x === this.levelModel.player.position.x && tnt[i].y === this.levelModel.player.position.y) {
this.levelModel.player.isOnBlock = false;
}
var surroundingBlocks = this.levelModel.getAllBorderingPositionNotOfType(tnt[i], "tnt");
this.levelModel.destroyBlock(tnt[i]);
for (let b = 1; b < surroundingBlocks.length; ++b) {
if (surroundingBlocks[b][0]) {
this.destroyBlockWithoutPlayerInteraction(surroundingBlocks[b][1]);
}
}
}
if (!player.isOnBlock && wasOnBlock) {
this.levelView.playPlayerJumpDownVerticalAnimation(player.facing, player.position);
}
this.updateFowPlane();
this.updateShadingPlane();
this.delayBy(200, () => {
this.levelView.playSuccessAnimation(player.position, player.facing, player.isOnBlock, () => {
this.endLevel(true);
});
});
});
} else {
this.endLevel(true);
}
} else if (this.levelModel.isFailed() || !(this.getIsDirectPlayerControl() || this.levelData.isAquaticLevel)) {
// For "Events" levels, check the final state to see if it's failed.
// Procedural levels only call `checkSolution` after all code has run, so
// fail if we didn't pass the success condition.
this.endLevel(false);
}
}
endLevel(result) {
if (!this.levelModel.usePlayer) {
if (result) {
this.levelView.audioPlayer.play("success");
} else {
this.levelView.audioPlayer.play("failure");
}
this.resultReported = true;
this.handleEndState(result);
return;
}
if (result) {
let player = this.levelModel.player;
let callbackCommand = new CallbackCommand(this, () => { }, () => {
this.levelView.playSuccessAnimation(player.position, player.facing, player.isOnBlock, () => { this.handleEndState(true); });
}, player.identifier);
player.queue.startPushHighPriorityCommands();
player.addCommand(callbackCommand, this.isRepeat);
player.queue.endPushHighPriorityCommands();
} else {
let player = this.levelModel.player;
let callbackCommand = new CallbackCommand(this, () => { }, () => { this.destroyEntity(callbackCommand, player.identifier); }, player.identifier);
player.queue.startPushHighPriorityCommands();
player.addCommand(callbackCommand, this.isRepeat);
player.queue.endPushHighPriorityCommands();
}
}
addScore(commandQueueItem, score) {
this.addCommandRecord("addScore", undefined, commandQueueItem.repeat);
if (this.useScore) {
this.score += score;
this.updateScore();
}
commandQueueItem.succeeded();
}
updateScore() {
if (this.onScoreUpdate) {
this.onScoreUpdate(this.score);
}
}
isPathAhead(blockType) {
return this.player.isOnBlock ? true : this.levelModel.isForwardBlockOfType(blockType);
}
addCommand(commandQueueItem) {
// there is a target, push command to the specific target
if (commandQueueItem.target !== undefined) {
let target = this.getEntity(commandQueueItem.target);
target.addCommand(commandQueueItem, this.isRepeat);
} else {
this.queue.addCommand(commandQueueItem, this.isRepeat);
this.queue.begin();
}
}
addGlobalCommand(commandQueueItem) {
let entity = this.levelEntity.entityMap.get(commandQueueItem.target);
if (entity !== undefined) {
entity.addCommand(commandQueueItem, this.isRepeat);
} else {
this.queue.addCommand(commandQueueItem, this.isRepeat);
this.queue.begin();
}
}
startDay(commandQueueItem) {
if (this.levelModel.isDaytime) {
if (commandQueueItem !== undefined && commandQueueItem !== null) {
commandQueueItem.succeeded();
}
if (this.DEBUG) {
this.game.debug.text("Impossible to start day since it's already day time\n");
}
} else {
if (this.onDayCallback !== undefined) {
this.onDayCallback();
}
this.levelModel.isDaytime = true;
this.levelModel.clearFow();
this.levelView.updateFowGroup(this.levelModel.fowPlane);
this.events.forEach(e => e({ eventType: EventType.WhenDayGlobal }));
let entities = this.levelEntity.entityMap;
for (let value of entities) {
let entity = value[1];
this.events.forEach(e => e({ eventType: EventType.WhenDay, targetIdentifier: entity.identifier, targetType: entity.type }));
}
let zombieList = this.levelEntity.getEntitiesOfType("zombie");
for (let i = 0; i < zombieList.length; i++) {
zombieList[i].setBurn(true);
}
if (commandQueueItem !== undefined && commandQueueItem !== null) {
commandQueueItem.succeeded();
}
}
}
startNight(commandQueueItem) {
if (!this.levelModel.isDaytime) {
if (commandQueueItem !== undefined && commandQueueItem !== null) {
commandQueueItem.succeeded();
}
if (this.DEBUG) {
this.game.debug.text("Impossible to start night since it's already night time\n");
}
} else {
if (this.onNightCallback !== undefined) {
this.onNightCallback();
}
this.levelModel.isDaytime = false;
this.levelModel.computeFowPlane();
this.levelView.updateFowGroup(this.levelModel.fowPlane);
this.events.forEach(e => e({ eventType: EventType.WhenNightGlobal }));
let entities = this.levelEntity.entityMap;
for (let value of entities) {
let entity = value[1];
this.events.forEach(e => e({ eventType: EventType.WhenNight, targetIdentifier: entity.identifier, targetType: entity.type }));
}
let zombieList = this.levelEntity.getEntitiesOfType("zombie");
for (let i = 0; i < zombieList.length; i++) {
zombieList[i].setBurn(false);
}
if (commandQueueItem !== undefined && commandQueueItem !== null) {
commandQueueItem.succeeded();
}
}
}
initiateDayNightCycle(firstDelay, delayInMs, startTime) {
if (startTime === "day" || startTime === "Day") {
this.timeouts.push(setTimeout(() => {
this.startDay(null);
this.setDayNightCycle(delayInMs, "night");
}, firstDelay));
} else if (startTime === "night" || startTime === "Night") {
this.timeouts.push(setTimeout(() => {
this.startNight(null);
this.setDayNightCycle(delayInMs, "day");
}, firstDelay));
}
}
setDayNightCycle(delayInMs, startTime) {
if (!this.dayNightCycle) {
return;
}
if (startTime === "day" || startTime === "Day") {
this.timeouts.push(setTimeout(() => {
if (!this.dayNightCycle) {
return;
}
this.startDay(null);
this.setDayNightCycle(delayInMs, "night");
}, delayInMs));
} else if (startTime === "night" || startTime === "Night") {
this.timeouts.push(setTimeout(() => {
if (!this.dayNightCycle) {
return;
}
this.startNight(null);
this.setDayNightCycle(delayInMs, "day");
}, delayInMs));
}
}
arrowDown(direction) {
if (!this.levelModel.usePlayer) {
return;
}
this.player.movementState = direction;
this.player.updateMovement();
}
arrowUp(direction) {
if (!this.levelModel.usePlayer) {
return;
}
if (this.player.movementState === direction) {
this.player.movementState = -1;
}
this.player.updateMovement();
}
clickDown() {
if (!this.levelModel.usePlayer) {
return;
}
this.player.movementState = -2;
this.player.updateMovement();
}
clickUp() {
if (!this.levelModel.usePlayer) {
return;
}
if (this.player.movementState === -2) {
this.player.movementState = -1;
}
this.player.updateMovement();
}
updateFowPlane() {
this.levelModel.computeFowPlane();
this.levelView.updateFowGroup(this.levelModel.fowPlane);
}
updateShadingPlane() {
this.levelModel.computeShadingPlane();
this.levelView.updateShadingGroup(this.levelModel.shadingPlane);
}
}
|
JavaScript
|
class AllClearCommand extends CommandAbstract {
name = 'allClear';
constructor(payload) {
super(payload);
}
execute() {
this.state.output = '0';
}
}
|
JavaScript
|
class Manager extends EventEmitter {
constructor(databaseUpdateRate = 1000 * 60 * 5, databasePath = "./chunkdata/", maxFileHandles = 500) {
super();
this.databasePath = databasePath;
this.pchunksPath = "pchunks.bin";
this.propsPath = "props.txt";
this.pxrPath = "r.{x}.{y}.pxr";
this.databaseUpdateRate = databaseUpdateRate;
this.maxFileHandles = maxFileHandles;
if (!fs.existsSync(this.databasePath)) {
fs.mkdirSync(this.databasePath, 0o777);
}
this.fileHandles = {}; // "worldName;clusterX;clusterY"
this.pendingUnload = {};
this.chunkWrites = {}; // pending chunk updates
this.chunkCache = {};
this.loadedProps = {}; // properties
this.loadedProts = {}; // protections
//this.pixelQueue = {}; // {worldName: {chunkX,chunkY: {i: [...color]}}}
this.pendingLoad = {}; // {worldName: {chunkX,chunkY: promise}}
this.databaseUpdateInterval = setInterval(this.updateDatabase.bind(this), this.databaseUpdateRate); //dont remove bind cuz then the emit will not work
}
chunkIsProtected(worldName, x, y) {
if (!this.loadedProts[worldName]) throw "World " + worldName + " is not initialized";
var hash = this.loadedProts[worldName].hashTable;
if (!hash[y]) return false;
return !!hash[y][x];
}
async _getChunk(worldName, x, y) {
if(this.pendingLoad[worldName][x + "," + y]) {
await this.pendingLoad[worldName][x + "," + y];
}
if(this.chunkCache[worldName][x + "," + y]) {
return this.chunkCache[worldName][x + "," + y];
}
let regX = x >> 5;
let regY = y >> 5;
var fd = null;
if (this.fileHandles[worldName + ";" + regX + ";" + regY]) {
fd = this.fileHandles[worldName + ";" + regX + ";" + regY];
} else {
var clusterPath = this.databasePath + worldName + "/" + this.pxrPath.replace("{x}", regX).replace("{y}", regY);
if (!await file_exists(clusterPath)) {
return null
};
}
if (fd == null) {
var keys = Object.keys(this.fileHandles);
if (keys.length >= this.maxFileHandles) {
var key = keys[0];
await file_close(this.fileHandles[key]);
delete this.fileHandles[key];
}
fd = await file_open(clusterPath);
this.fileHandles[worldName + ";" + regX + ";" + regY] = fd;
}
var clusterSize = await file_size(fd);
if (clusterSize < 3072) {
return null;
}
var lookup = 3 * ((x & 31) + (y & 31) * 32);
var chunkpos = await file_read(fd, lookup, 3);
chunkpos = chunkpos[2] * 16777216 + chunkpos[1] * 65536 + chunkpos[0] * 256;
if (chunkpos == 0) {
return null;
}
var cdata = await file_read(fd, chunkpos, 16 * 16 * 3);
this.chunkCache[worldName][x + "," + y] = cdata;
return cdata;
}
getChunk(worldName, x, y) {
let chunk = this._getChunk(worldName, x, y);
this.pendingLoad[worldName][x + "," + y] = new Promise(async resolve=>{
await chunk;
resolve();
delete this.pendingLoad[worldName][x + "," + y];
});
return chunk;
}
async _setChunk(worldName, x, y, cdata) { // cdata = 16*16*3 RGB
var regX = x >> 5;
var regY = y >> 5;
var fd = null;
if (this.fileHandles[worldName + ";" + regX + ";" + regY]) {
fd = this.fileHandles[worldName + ";" + regX + ";" + regY];
} else {
var clusterPath = this.databasePath + worldName + "/" + this.pxrPath.replace("{x}", regX).replace("{y}", regY);
if (await file_exists(clusterPath)) {
fd = await file_open(clusterPath);
this.fileHandles[worldName + ";" + regX + ";" + regY] = fd;
} else {
await write_file(clusterPath, new Uint8Array(3072));
fd = await file_open(clusterPath);
this.fileHandles[worldName + ";" + regX + ";" + regY] = fd;
}
}
var clusterSize = await file_size(fd);
if (clusterSize < 3072) { // pad remaining lookup table
await file_write(fd, clusterSize, new Uint8Array(3072 - clusterSize));
}
var lookup = 3 * ((x & 31) + (y & 31) * 32);
var chunkpos = await file_read(fd, lookup, 3);
chunkpos = chunkpos[2] * 16777216 + chunkpos[1] * 65536 + chunkpos[0] * 256;
if (chunkpos == 0) {
var val = clusterSize;
await file_write(fd, lookup, new Uint8Array([Math.floor((val / 256)) % 256, Math.floor((val / 65536)) % 256, Math.floor((val / 16777216)) % 256]));
chunkpos = await file_size(fd);
}
await file_write(fd, chunkpos, cdata);
}
async loadProps(worldName) {
var prop_path = this.databasePath + worldName + "/" + this.propsPath;
if (!await file_exists(prop_path)) return {};
var data = (await file_read_all(prop_path)).toString("utf8").split("\n");
var props = {};
for (var i = 0; i < data.length; i++) {
if (!data[i]) continue;
var line = data[i].split(" ");
var key = line[0];
var prop = data[i].substr(key.length + 1);
props[key] = prop;
}
return props
}
async worldInit(worldName) {
if (this.pendingUnload[worldName]) {
delete this.pendingUnload[worldName];
return;
}
if (this.chunkCache[worldName] || this.loadedProps[worldName] || this.loadedProts[worldName]) return;
if (!await file_exists(this.databasePath + worldName)) {
await file_mkdir(this.databasePath + worldName, 0o777);
}
worldName = worldName.replace(/\//g, "").replace(/\\/g, "").replace(/\"/g, "");
var protPath = this.databasePath + worldName + "/" + this.pchunksPath;
if (await file_exists(protPath)) {
var protData = await file_read_all(protPath.slice(0));
var protTotal = Math.floor(protData.length / 8);
var protInt = new Int32Array(new Uint8Array(protData).buffer);
var protHash = {};
for (var i = 0; i < protTotal; i++) {
var pos = i * 2;
var x = protInt[pos];
var y = protInt[pos + 1];
if (!protHash[y]) protHash[y] = {};
protHash[y][x] = true;
}
this.loadedProts[worldName] = {
hashTable: protHash,
updated: false
};
} else {
this.loadedProts[worldName] = {
hashTable: {},
updated: false
};
}
this.loadedProps[worldName] = {
data: await this.loadProps(worldName),
updated: false
};
this.chunkCache[worldName] = {};
this.chunkWrites[worldName] = {};
this.pendingLoad[worldName] = {};
}
worldUnload(worldName) {
this.pendingUnload[worldName] = true;
}
getProp(worldName, key, defval) {
if (!this.loadedProps[worldName]) throw "World " + worldName + " is not initialized";
if (key in this.loadedProps[worldName].data) return this.loadedProps[worldName].data[key].replace(/\\n/gm, "\n");;
return defval;
}
setProp(worldName, key, val) {
if (!this.loadedProps[worldName]) throw "World " + worldName + " is not initialized";
if (!val) {
delete this.loadedProps[worldName].data[key];
this.loadedProps[worldName].updated = true;
return;
}
val = val.toString().replace(/\n/gm, "\\n");
this.loadedProps[worldName].data[key] = val;
this.loadedProps[worldName].updated = true;
}
setChunkProtection(worldName, x, y, isProtected) {
var protStat = this.chunkIsProtected(worldName, x, y);
var protHash = this.loadedProts[worldName].hashTable;
if (isProtected) {
if (protStat) return;
if (!protHash[y]) protHash[y] = {};
protHash[y][x] = true;
this.loadedProts[worldName].updated = true;
} else {
if (!protStat) return;
delete protHash[y][x];
if (Object.keys(protHash[y]).length == 0) {
delete protHash[y];
}
this.loadedProts[worldName].updated = true;
}
}
async setChunk(worldName, chunkX, chunkY, chunkData) {
var chunk = await this.getChunk(worldName, chunkX, chunkY);
if (!chunk) {
chunk = new Uint8Array(16 * 16 * 3);
this.chunkCache[worldName][chunkX + "," + chunkY] = chunk;
}
for (var i = 0; i < 16 * 16 * 3; i++) {
chunk[i] = chunkData[i];
}
this.chunkWrites[worldName][chunkX + "," + chunkY] = true;
}
async closeDatabase() {
clearInterval(this.databaseUpdateInterval);
await this.updateDatabase();
for (var i in this.fileHandles) {
await file_close(this.fileHandles[i]);
}
}
async setPixel(worldName, x, y, r, g, b) {
var chunkX = Math.floor(x / 16);
var chunkY = Math.floor(y / 16);
var pixelX = x - Math.floor(x / 16) * 16;
var pixelY = y - Math.floor(y / 16) * 16;
var chunk = await this.getChunk(worldName, chunkX, chunkY);
if (!chunk) {
chunk = new Uint8Array(16 * 16 * 3);
let chunkColor = hexToRgb(this.getProp(worldName, "bgcolor", "fff")) || [255, 255, 255];
for (var i = 0; i < chunk.length;) {
chunk[i++] = chunkColor[0];
chunk[i++] = chunkColor[1];
chunk[i++] = chunkColor[2];
}
this.chunkCache[worldName][chunkX + "," + chunkY] = chunk;
}
var idx = (pixelY * 16 + pixelX) * 3;
chunk[idx] = r;
chunk[idx + 1] = g;
chunk[idx + 2] = b;
this.chunkWrites[worldName][chunkX + "," + chunkY] = true;
}
async getPixel(worldName, x, y) {
var chunkX = Math.floor(x / 16);
var chunkY = Math.floor(y / 16);
var pixelX = x - Math.floor(x / 16) * 16;
var pixelY = y - Math.floor(y / 16) * 16;
var chunk = await this.getChunk(worldName, chunkX, chunkY);
if (!chunk) {
return null;
}
var idx = (pixelY * 16 + pixelX) * 3;
return [chunk[idx], chunk[idx+1], chunk[idx+2]]
}
async updateDatabase() {
for (var world in this.loadedProts) {
if (this.loadedProts[world].updated) {
this.loadedProts[world].updated = false;
} else {
continue;
}
var protArray = [];
var hashTable = this.loadedProts[world].hashTable;
for (var y in hashTable) {
for (var x in hashTable[y]) {
protArray.push([parseInt(x), parseInt(y)]);
}
}
var protBuffer = new Int32Array(protArray.length * 2);
for (var i = 0; i < protArray.length; i++) {
var idx = i * 2;
protBuffer[idx] = protArray[i][0];
protBuffer[idx + 1] = protArray[i][1];
}
await write_file(this.databasePath + world + "/" + this.pchunksPath, protBuffer);
}
for (var world in this.loadedProps) {
if (this.loadedProps[world].updated) {
this.loadedProps[world].updated = false;
} else {
continue;
}
var propStr = "";
var data = this.loadedProps[world].data;
for (var i in data) {
propStr += i + " " + data[i] + "\n";
}
await write_file(this.databasePath + world + "/" + this.propsPath, propStr);
}
for (var world in this.chunkCache) {
var chunks = this.chunkCache[world];
for (var c in chunks) {
var pos = c.split(",");
var chunkX = parseInt(pos[0]);
var chunkY = parseInt(pos[1]);
if (this.chunkWrites[world][chunkX + "," + chunkY]) {
this.chunkWrites[world][chunkX + "," + chunkY] = false;
} else {
delete chunks[c];
continue;
}
await this._setChunk(world, chunkX, chunkY, chunks[c]);
delete chunks[c];
}
}
for (var world in this.pendingUnload) {
for (var i in this.fileHandles) {
var hdl = i.split(";");
if (hdl[0] == world) {
await file_close(this.fileHandles[i]);
delete this.fileHandles[i];
}
}
delete this.pendingUnload[world];
delete this.pendingLoad[world];
delete this.loadedProts[world];
delete this.loadedProps[world];
delete this.chunkCache[world];
delete this.chunkWrites[world];
}
this.emit("savedWorlds");
}
}
|
JavaScript
|
class MessageBox extends THREE.Mesh {
constructor(width=1, height=1, x=0, y=0) {
var geometry = new THREE.PlaneGeometry(width, height);
super(geometry);
// Setting initial data
this.visible = false;
this.position.set(x, y, -1); // z = -1 to be in front of the camera
this.userData.ortho = this.position.clone();
this.userData.persp = this.position.clone();
// Setting texture map
this.material = new THREE.MeshBasicMaterial( { side: THREE.DoubleSide } );
this.textures = {};
}
add(path) {
// FIXME: use remote texture
return this.textures[path] = LocalTextures.load(path);
}
apply(path) {
// if path was already added, use it; else, load it to memory.
var texture = path in this.textures ? this.textures[path] : this.add(path);
this.material.map = texture;
this.needsUpdate = true;
}
switchCamera(camera) {
var oldCamera = this.parent;
if (oldCamera != undefined) {
oldCamera.remove(this);
}
camera.add(this);
if (camera instanceof THREE.PerspectiveCamera) {
this.scale.set(0.0015, 0.0015, 0.0015); // FIXME: calculate values
this.position.copy(this.userData.persp);
} else if (camera instanceof THREE.OrthographicCamera) {
this.scale.set(1, 1, 1);
this.position.copy(this.userData.ortho);
}
}
}
|
JavaScript
|
class DisplayIdenticons extends Component {
render() {
const { animateRefreshIcon, onRefresh, identiconsId } = this.props;
const items = [];
for (let i = 0; i < 6; i += 1) {
const item = (
<IdenticonsIcon
accountIcon={identiconsId}
key={i}
{...this.props}
index={i}
/>
);
items.push(item);
}
return (
<div className="avatar-selector">
<Row>
<Col>
<ul className="identicon">{items}</ul>
</Col>
<Col className="identicon-refresh">
<img
aria-hidden
src={refreshIcon}
alt="Refresh"
className={`${animateRefreshIcon && 'rotation anti-clock'}`}
onClick={() => onRefresh()}
/>
</Col>
</Row>
</div>
);
}
}
|
JavaScript
|
class Writer {
constructor() {
}
/**
* Reads a source object and transcribes it to the target object.
*
* @public
* @param {Object} source
* @param {Object} target
* @returns {Object}
*/
write(source, target) {
if (this.canWrite(source, target)) {
this._write(source, target);
}
return target;
}
/**
* @protected
* @abstract
* @param {Object} source
* @param {Object} target
* @returns {Object}
*/
_write(source, target) {
return;
}
/**
* @public
* @param {Object} source
* @param {Object} target
* @return {Boolean}
*/
canWrite(source, target) {
return this._canWrite(source, target);
}
/**
* @protected
* @abstract
* @param {Object} source
* @param {Object} target
* @return {Boolean}
*/
_canWrite(source, target) {
return true;
}
static get SEPARATOR() {
return '.';
}
toString() {
return '[Writer]';
}
}
|
JavaScript
|
class QBConnectService {
constructor(qb) {
this.qb = _.clone(qb);
}
}
|
JavaScript
|
class GeocodingView extends Oskari.clazz.get('Oskari.mapframework.bundle.search.DefaultView') {
constructor(instance) {
super(instance);
let epsg = this.sandbox.findRegisteredModuleInstance('MainMapModule').getProjection(),
epsgCode = epsg.split(':')[1],
lang = Oskari.getLang(),
urls = instance.conf.urls;
this.service = new GeocodingService(urls, epsgCode, lang);
this.lastSearchString = undefined;
}
createUi(tab) {
super.createUi(tab);
let searchContainerEl = this.getContainer()[0],
controlsEl = searchContainerEl.querySelector('div.controls'),
similarEl = document.createElement('div');
controlsEl.appendChild(similarEl)
this.similarEl = similarEl;
}
__checkSearchString(searchString) {
if (!searchString || searchString.length == 0) {
return false;
}
if (this.lastSearchString === searchString) {
return false;
}
return true;
}
__doSearch() {
let self = this,
field = this.getField(),
button = this.getButton(),
searchContainer = this.getContainer(),
searchString = field.getValue(this.instance.safeChars),
resultsEl = searchContainer[0].querySelectorAll('div.resultList'),
infoEl = searchContainer[0].querySelectorAll('div.info');
if (!this.__checkSearchString(searchString)) {
self.progressSpinner.stop();
field.setEnabled(true);
button.setEnabled(true);
return;
}
while (resultsEl.firstChild)
resultsEl.removeChild(resultsEl.firstChild);
while (infoEl.firstChild)
infoEl.removeChild(infoEl.firstChild);
this.service.search(searchString).then(r => r.json()).then(json => {
let res = {
locations: json.features.map(f => {
return {
"zoomScale": 5000,
"name": f.properties.label,
"rank": f.properties.rank,
"lon": f.geometry.coordinates[0],
"id": f.properties.placeId,
"type": f.properties['label:placeType'],
"region": f.properties['label:municipality'],
"village": f.properties['label'],
"lat": f.geometry.coordinates[1],
"channelId": "GEOCODING"
}
})
};
res.totalCount = res.locations.length;
if (res.totalCount == 0) {
res.totalCount = -2;
}
self.lastSearchString = searchString;
self.handleSearchResult(true, res, searchString);
}).catch(function (err) {
/* we fail often due to autocomplete*/
});
}
__doAutocompleteSearch() {
let self = this,
field = self.getField(),
searchString = field.getValue(this.instance.safeChars);
if (!searchString || searchString.length == 0) {
return;
}
if (this.lastSimilarString === searchString) {
return;
}
this.__doSearch();
this.service.similar(searchString).then(r => r.json()).then(json => {
if (!json.terms || !json.terms.length) {
return;
}
let autocompleteValues = json.terms.map(f => {
return {
value: f.text.indexOf(' ') != -1 ? '"' + f.text + '"' : f.text,
data: f.text
};
});
this.lastSimilarString = searchString;
self.renderSimilar(autocompleteValues);
}).catch(function (err) {
});
}
renderSimilar(autocompleteValues) {
let similarEl = this.similarEl,
self = this;
while (similarEl.firstChild)
similarEl.removeChild(similarEl.firstChild);
autocompleteValues.forEach(e => {
let spacing = document.createTextNode(' '),
el = document.createElement('a');
el.setAttribute('href', 'javascript:void(0)');
el.innerHTML = e.value;
el.dataset.value = e.value;
el.addEventListener("click", ev => {
self.getField().setValue(ev.target.dataset.value);
self.__doAutocompleteSearch();
});
similarEl.appendChild(el);
similarEl.appendChild(spacing);
});
}
nearby(lonlat) {
let self = this,
field = this.getField(),
searchContainer = this.getContainer(),
searchString = field.getValue(this.instance.safeChars),
resultsEl = searchContainer[0].querySelectorAll('div.resultList'),
infoEl = searchContainer[0].querySelectorAll('div.info');
while (resultsEl.firstChild)
resultsEl.removeChild(resultsEl.firstChild);
while (infoEl.firstChild)
infoEl.removeChild(infoEl.firstChild);
this.service.reverse(lonlat).then(r => r.json()).then(json => {
let res = {
locations: json.features.map(f => {
return {
"zoomScale": 5000,
"name": f.properties.label,
"rank": f.properties.rank,
"lon": f.geometry.coordinates[0],
"id": f.properties.placeId,
"type": f.properties['label:placeType'],
"region": f.properties['label:municipality'],
"village": f.properties['label'],
"lat": f.geometry.coordinates[1],
"channelId": "GEOCODING"
}
})
};
res.totalCount = res.locations.length;
if (res.totalCount == 0) {
res.totalCount = -2;
}
self.lastSearchString = searchString;
self.handleSearchResult(true, res, searchString);
}).catch(function (err) {
/* we fail often due to autocomplete*/
});
}
_validateSearchKey(key) {
return true;
}
__getSearchResultHeader(count, hasMore) {
return "";
}
}
|
JavaScript
|
class Histogram extends Range{
constructor(data, config, view){
super(data, config, view);
let range = this.group.children[1];
let mc = view.measureConfig;
let max = mc.max;
let min = mc.min;
let val = config.value_type === 'value_attr' ? data.attribute.value : data.score;
if(config.value_distribution !== 'linear') val = transformValue(val,config.value_distribution, config.value_base);
if( val < min) val = min;
if( val > max) val = max;
let offset = calculateDistance(val,{start:config.offset, stop:config.offset+config.max_distance},{start:min,stop:max},config.invert_value);
if(!config.offsetDir){
offset = -offset;
range.translate(config.width,0);
}
range.bounds.width = offset;
/** if labelOffset and offset are same direction, shift label) */
if(offsetSign(config.label_offset) === config.offsetDir){
this.group.children[0].translate(offset , 0);
}
}
}
|
JavaScript
|
class BasicOrganizationDto {
/**
* Constructs a new <code>BasicOrganizationDto</code>.
* @alias module:model/BasicOrganizationDto
* @class
*/
constructor () {}
/**
* Constructs a <code>BasicOrganizationDto</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/BasicOrganizationDto} obj Optional instance to populate.
* @return {module:model/BasicOrganizationDto} The populated <code>BasicOrganizationDto</code> instance.
*/
static constructFromObject (data, obj) {
if (data) {
obj = obj || new BasicOrganizationDto()
if (data.hasOwnProperty('authMethods'))
obj.authMethods = ApiClient.convertToType(data['authMethods'], [
BasicAuthMethodDto
])
if (data.hasOwnProperty('name'))
obj.name = ApiClient.convertToType(data['name'], 'String')
if (data.hasOwnProperty('status'))
obj.status = ApiClient.convertToType(data['status'], 'String')
if (data.hasOwnProperty('uuid'))
obj.uuid = ApiClient.convertToType(data['uuid'], 'String')
}
return obj
}
}
|
JavaScript
|
class ProblemsController {
async index(req, res) {
const { page = 1 } = req.query;
const limit = 10;
const offset = (page - 1) * limit;
const problems = await DeliveryProblem.findAndCountAll({
limit,
offset,
include: [
{
model: Delivery,
as: 'delivery',
where: { canceled_at: null },
},
],
});
const next = !(offset + limit >= problems.count);
problems.next = next;
return res.json({ problems });
}
}
|
JavaScript
|
class Polygon {
/**
* @param {Point[]} points
*/
constructor(points) {
this._points = points;
this._classNames = [];
this._type = graphicTypes.POLYGON;
this._onUpdate = null;
}
/**
* @param {number} x
* @param {number} y
*/
translate(x, y) {
this._points = this._points.map((p) => p.add(x, y));
if (this._onUpdate) this._onUpdate(this);
}
/**
* @param {number} c
*/
scale(c) {
this._points = this._points.map((p) => p.multiply(c));
if (this._onUpdate) this._onUpdate(this);
}
/**
* @param {number} index
* @param {number} x
* @param {number} y
*/
translatePoint(index, x, y) {
this._points[index].x = x;
this._points[index].y = y;
if (this._onUpdate) this._onUpdate(this);
}
/**
* @param {Point} point
* @returns {boolean}
*/
containsPoint(point) {
// Source: https://stackoverflow.com/questions/22521982/check-if-point-is-inside-a-polygon
let contains = false;
let x = point.x;
let y = point.y;
let v = this._points.map((p) => [p.x, p.y]);
for (let i = 0, j = v.length - 1; i < v.length; j = i++) {
let xi = v[i][0],
yi = v[i][1],
xj = v[j][0],
yj = v[j][1];
if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi)
contains = !contains;
}
return contains;
}
/**
* @param {Polygon} polygon
* @returns {boolean}
*/
containsPolygon(polygon) {
let contains = true;
polygon.points.forEach((p) => {
contains = contains && this.containsPoint(p);
});
return contains;
}
/**
* @param {number} graphHeight
* @returns {JSON}
*/
asGraphic(graphHeight) {
let points = this._points.map((p) => p.asGraphic(graphHeight));
return {
pointArray: points,
pointString: points.map((p) => `${p.x},${p.y}`).join(" "),
classNames: this._classNames,
};
}
/**
* @param {string} className
*/
addClassName(className) {
this._classNames.push(className);
}
set points(points) {
this._points = points;
}
get points() {
return this._points;
}
get segments() {
let segments = [];
for (let i = 0; i < this._points.length; i++) {
let next = i === this._points.length - 1 ? 0 : i + 1;
segments.push(new Line(this._points[i], this._points[next]));
}
return segments;
}
get classNames() {
return this._classNames;
}
get type() {
return this._type;
}
get onUpdate() {
return this._onUpdate;
}
set onUpdate(onUpdate) {
this._onUpdate = onUpdate;
}
}
|
JavaScript
|
class TestRunner extends hasEngine() {
/**
* Class dependencies: <code>['app']</code>.
*
* @type {Array<string>}
*/
static get dependencies() {
return (super.dependencies || []).concat(['app']);
}
/**
* Run a list of tests.
*
* @param {Array<{instane: test.TestCase, name: string, namespace: string, tests: Array<{method: string, description: string}>}>} testList - List of tests.
*/
run(testList = []) {
testList.forEach(this.runTest.bind(this));
}
/**
* Run every tests of a single test case instance.
*
* @param {{instance: test.TestCase, name: string, namespace: string, tests: Array<{method: string, description: string}>}} test - Single test.
*/
runTest({ instance, name, namespace, tests }) {
if (typeof this.engine === 'undefined') {
throw new TypeError('Test engine is not defined');
}
instance
.setEngine(this.engine);
this.describe(namespace, () => {
this.describe(name, () => {
this.beforeEach(() => {
instance.setApp(this.app.make('app'));
});
this.beforeAll((...parameters) => { return instance.beforeAll(...parameters); });
this.beforeEach((...parameters) => { return instance.beforeEach(...parameters); });
tests.forEach(({ method, description }) => {
this.test(description, (...parameters) => { return instance[method](...parameters); });
});
this.afterEach((...parameters) => { return instance.afterEach(...parameters); });
this.afterAll((...parameters) => { return instance.afterAll(...parameters); });
});
});
}
/**
* Describe the inner tests.
*
* @param {...*} parameters - Call parameters.
* @returns {*} The call returned value.
*/
describe(...parameters) {
return this.engine.describe(...parameters);
}
/**
* Setup before the first inner test.
*
* @param {...*} parameters - Call parameters.
* @returns {*} The call returned value.
*/
beforeAll(...parameters) {
return this.engine.beforeAll(...parameters);
}
/**
* Setup before any inner test.
*
* @param {...*} parameters - Call parameters.
* @returns {*} The call returned value.
*/
beforeEach(...parameters) {
return this.engine.beforeEach(...parameters);
}
/**
* Tear down after the last inner test.
*
* @param {...*} parameters - Call parameters.
* @returns {*} The call returned value.
*/
afterAll(...parameters) {
return this.engine.afterAll(...parameters);
}
/**
* Tear down after any inner test.
*
* @param {...*} parameters - Call parameters.
* @returns {*} The call returned value.
*/
afterEach(...parameters) {
return this.engine.afterEach(...parameters);
}
/**
* Test a given case.
*
* @param {...*} parameters - Call parameters.
* @returns {*} The call returned value.
*/
test(...parameters) {
return this.engine.test(...parameters);
}
}
|
JavaScript
|
class Extensions {
constructor() {
throw new Error('StaticClassError');
}
/**
* Initializes all extensions
* @param {Object} LU - The layout utils class
*/
static init(LU) {
TweensExtension.init();
CoordinatesExtension.init(LU);
}
}
|
JavaScript
|
class Api {
constructor() {
this.current = Immutable.Map();
this[LOG_LIST] = Immutable.List();
this.loadInvokeCount = 0;
}
/**
* Initializes the UIHarness environment.
* @return {Promise}.
*/
init() {
return new Promise((resolve) => {
// Put state into global namespace.
bdd.register();
global.UIHarness = global.uih = apiConsole;
// Ensure the last loaded suite is set as the current state.
const suite = this.lastSelectedSuite();
if (suite) {
this.loadSuite(this.lastSelectedSuite(), { storeAsLastSuite: false });
}
// Show 'getting started' if empty.
if (Object.keys(bdd.suites).length === 0) {
this.setCurrent({
header: '## Getting Started',
hr: true,
scroll: 'y',
width: '100%',
});
this.loadComponent(GettingStarted);
}
// Done.
resolve({});
});
}
/**
* Resets the internal API.
* @param {boolean} hard: Flag indicating if all state from local-storage
* should be cleared away, or just current selection state.
*/
reset({ hard = true } = {}) {
if (hard) {
this.clearLocalStorage();
} else {
this.clearLocalStorage('lastInvokedSpec:');
}
this.lastSelectedSuite(null);
this.setCurrent(null);
this.component(null);
return this;
}
/**
* Removes all ui-harness values stored in local-storage.
*/
clearLocalStorage(startsWith = null) {
localStorage.keys().forEach(key => {
let match = 'ui-harness:';
if (startsWith) { match += startsWith; }
if (key.startsWith(match)) {
localStorage.prop(key, null); // Remove.
}
});
}
/**
* Gets or sets the current component instance.
* Pass {null} to clear.
*/
component(value) {
// WRITE.
if (value !== undefined) {
if (value === null) {
// Unload component.
delete this[COMPONENT];
delete apiConsole.component;
this.setCurrent({
componentType: undefined,
componentProps: undefined,
componentChildren: undefined,
component: undefined,
});
} else {
// Store component instance.
this[COMPONENT] = value;
apiConsole.component = value;
if (this.current.get('component') !== value) {
// NB: Perform instance comparison before updating the
// current state to prevent render loop.
this.setCurrent({ component: value });
}
}
}
// READ.
return this[COMPONENT];
}
/**
* Loads the current suite into the Harness.
*
* @param suite: The {Suite} to load.
* @param options
* - storeAsLastSuite: Flag indicating if the suite should be stored
* as the last invoked suite in localStorage.
* Default: true.
*/
loadSuite(suite, { storeAsLastSuite = true } = {}) {
// Setup initial conditions.
if (!suite) { return this; }
if (this.current.get('suite') === suite) { return this; }
// Only load the suite if it does not have children
// ie. is not a container/folder suite.
if (suite.childSuites.length === 0) {
// Clear the current state.
this.setCurrent(null);
// Prepare the new current state.
const current = suite.meta.thisContext.toValues();
current.suite = suite;
current.indexMode = this.indexMode();
current.isBeforeInvoked = false;
this.setCurrent(current);
if (storeAsLastSuite) { this.lastSelectedSuite(suite); }
// Invoke before handlers.
this.invokeBeforeHandlers(suite);
// If the last invoked spec on the suite contained a load.
const lastInvokedSpec = this.lastInvokedSpec(suite);
if (lastInvokedSpec && lastInvokedSpec.spec && lastInvokedSpec.isLoader) {
this.invokeSpec(lastInvokedSpec.spec);
}
}
// Finish up.
return this;
}
/**
* Loads the given component.
*
* @param component: The component Type
* or created component element (eg: <MyComponent/>).
*
* @param props: Optional. The component props (if not passed in with
* a component element).
*
* @param children: Optional. The component children (if not passed in
* with a component element).
*
*/
loadComponent(component) {
invariant(component, 'Component not specified in this.component().');
// If a React element was passed pull out its type.
const updates = {};
if (React.isValidElement(component)) {
updates.componentType = component.type;
} else {
updates.componentType = component;
}
// Store on the current state.
this.setCurrent(updates);
// Finish up.
this.loadInvokeCount += 1;
return this;
}
/**
* Invokes the [before] handlers for
* the given suite if required.
* @return {boolean} - true if the handlers were invoked
* - false if they have already been invoked.
*/
invokeBeforeHandlers(suite) {
if (this.current.get('isBeforeInvoked')) { return false; }
const self = suite.meta.thisContext;
suite.beforeHandlers.invoke(self);
this.current = this.current.set('isBeforeInvoked', true);
return true;
}
/**
* Invokes the given spec.
* @param spec: The [Spec] to invoke.
* @param callback: Invoked upon completion.
* Immediately if the spec is not asynchronous.
*/
invokeSpec(spec, callback) {
// Setup initial conditions.
const suite = spec.parentSuite;
const self = suite.meta.thisContext;
this.invokeBeforeHandlers(suite);
const loadInvokeCountBefore = this.loadInvokeCount;
// Invoke the methods.
spec.invoke(self, callback);
// Store a reference to last-invoked spec.
this.lastInvokedSpec(suite, {
spec,
isLoader: (this.loadInvokeCount > loadInvokeCountBefore),
});
// Increment the current invoke count for the spec.
const specInvokeCount = this.current.get('specInvokeCount') || {};
const total = specInvokeCount[spec.id] || 0;
specInvokeCount[spec.id] = total + 1;
this.setCurrent({ specInvokeCount });
// Finish up.
return this;
}
/**
* Gets or sets the last selected [Suite].
*/
lastSelectedSuite(suite) {
if (suite) { suite = suite.id; }
const result = this.localStorage('lastSelectedSuite', suite);
return bdd.suites[result];
}
/**
* Gets or sets the last spec for the given suite
* that was invoked that had a `.load()` call within it.
*/
lastInvokedSpec(suite, { spec, isLoader = false } = {}) {
const KEY = `lastInvokedSpec:${ suite.id }`;
let value;
if (spec !== undefined) {
// WRITE.
value = { isLoader, spec: spec.id };
spec = spec.id;
}
// READ.
const result = this.localStorage(KEY, value);
if (result) {
result.spec = R.find(s => s.id === result.spec, suite.specs);
}
return result;
}
/**
* Gets or sets the display mode of the left-hand index.
* @param {string} mode: tree|suite
*/
indexMode(mode) {
let result = this.localStorage('indexMode', mode, { default: 'tree' });
if (mode !== undefined) {
// WRITE (store in current state).
this.setCurrent({ indexMode: mode });
}
// READ.
result = result || 'tree';
if (result !== 'tree' && this.current.get('suite') === undefined) {
result = 'tree';
}
return result;
}
/**
* Updates the current state with the given values.
* NOTE: These values are cumulatively added to the state.
* Use 'reset' to clear the state.
*
* @param args: An object containing they [key:values] to set
* or null to clear values.
*/
setCurrent(args) {
// Update the state object.
if (args) {
Object.keys(args).forEach(key => {
const value = args[key];
this.current = value === undefined
? this.current.remove(key)
: this.current.set(key, args[key]);
});
} else {
this.current = this.current.clear();
}
// Apply to the <Shell>.
if (this.shell) { this.shell.setState({ current: this.current }); }
return this;
}
/**
* Logs a value to the output.
* @param {array} values: The value or values to append.
*/
log(...values) {
values = R.flatten(values);
const item = { time: new Date(), values };
this[LOG_LIST] = this[LOG_LIST].push(item);
this.setCurrent({ log: this[LOG_LIST], showLog: true });
return this;
}
/**
* Clears the output log.
*/
clearLog() {
// console.log('clear log');
this[LOG_LIST] = this[LOG_LIST].clear();
this.setCurrent({ log: this[LOG_LIST], showLog: false });
}
/**
* Provides common access to localStorage.
*
* @param key: The unique identifier of the value (this is
* prefixed with the namespace).
*
* @param value: (optional). The value to set (pass null to remove).
*
* @param options:
* default: (optional). The default value to return if the session
* does not contain the value (ie. undefined).
*
* @return the read value.
*/
localStorage(key, value, options) {
return localStorage.prop(`ui-harness:${ key }`, value, options);
}
}
|
JavaScript
|
class DocumentTable extends React.Component {
// Props is received via the constructor
constructor(props) {
//...and props is sent back to the parent Component
//class using super()
super(props);
}
// Formatting Date Column
_dataFormatDateDoc(cell,row){
return row.doc_year+'-'+row.doc_month+'-'+row.doc_day || 'Not defined!';
}
// Formating TypeDoc Column : binding real name
_dataFormatTypeDoc(cell,row){
var resultat = cell;
if(cell) {
var lObjCat = LocalData.getTypeDocById(cell);
resultat = lObjCat.tdoc_title;
}
return resultat;
}
// Formating TypeDoc Column : binding real name
_dataFormatTiers(cell,row){
var lStrResultat = '';
for(var i=0;i<cell.length;i++){
var title = cell[i].tier_title;
lStrResultat += '<Badge> '+title+' </Badge><br />';
}
return lStrResultat;
}
// Formating TypeDoc Column : binding real name
_dataFormatCats(cell,row){
var lStrResultat = '';
for(var i=0;i<cell.length;i++){
var title = cell[i].cat_title;
lStrResultat += '<Badge> '+title+' </Badge><br />';
}
return lStrResultat;
}
handlerSelectDocument(row,isSelected,event){
pubsub.publish('app-doc-edit', row.doc_id);
}
// Render Components !
render() {
var rows = LocalData.getAllDocuments();
var selectPropsRow = {
mode: "radio", //checkbox for multi select, radio for single select.
clickToSelect: true, //click row will trigger a selection on that row.
bgColor: "rgb(238, 193, 213)", //selected row background color
onSelect:this.handlerSelectDocument
};
return (
<div>
<h2> Liste des documents </h2>
<BootstrapTable
data={rows}
striped={true}
hover={true}
condensed={true}
pagination={false}
selectRow={selectPropsRow}
insertRow={false}
deleteRow={false}
columnFilter={false}
search={true}>
<TableHeaderColumn dataField="doc_id" isKey={true} hidden={true} dataAlign="left" dataSort={true}>ID</TableHeaderColumn>
<TableHeaderColumn dataField="tdoc_id" dataSort={true} dataFormat={this._dataFormatTypeDoc}>Type</TableHeaderColumn>
<TableHeaderColumn dataField="doc_title" dataSort={true}>Titre</TableHeaderColumn>
<TableHeaderColumn dataField="doc_year" dataAlign="left" dataFormat={this._dataFormatDateDoc}>Date</TableHeaderColumn>
<TableHeaderColumn dataField="doc_month" hidden={true} dataAlign="left">Mois</TableHeaderColumn>
<TableHeaderColumn dataField="doc_day" hidden={true} dataAlign="left">Jour</TableHeaderColumn>
<TableHeaderColumn dataField="cats" dataAlign="center" dataFormat={this._dataFormatCats}>Catégorie(s)</TableHeaderColumn>
<TableHeaderColumn dataField="tiers" dataAlign="center" dataFormat={this._dataFormatTiers}>Tier(s)</TableHeaderColumn>
<TableHeaderColumn dataField="doc_desc" dataAlign="center">Description</TableHeaderColumn>
<TableHeaderColumn dataField="doc_code" dataAlign="center">Code</TableHeaderColumn>
</BootstrapTable>
</div>
);
}
}
|
JavaScript
|
class Bigboy {
static DEFAULT_BYTE_WIDTH = 32;
static JSON_TYPE = "b1gb0y";
/**
* JavaScript converts Number types to 32-bit integers before bitwise manipulation, so the
* behavior of the default constructor is undefined for values larger than 0xFFFFFFFF
*/
constructor({len = Bigboy.DEFAULT_BYTE_WIDTH, val = 0} = {}) {
if (!Number.isInteger(val) || len < Math.ceil(Math.log2(val + 1) / 8) ||
val < 0 || val > 0xFFFFFFFF) {
throw new TypeError("Argument error");
}
this._data = new Uint8Array(len);
for (let i = 0; val > 0; i += 1) {
this._data[i] = val & 0xFF;
val >>>= 0x08;
}
}
static json_revive(key, val) {
if (typeof val === "object" && val !== null && val.type === Bigboy.JSON_TYPE) {
return Bigboy.from_hex_str({len: val.len, str: val.data});
}
return val;
}
toJSON() {
return {
type: Bigboy.JSON_TYPE,
data: this.to_hex_str(),
len: this.length()
};
}
// TODO: Validate the string
static from_hex_str({len = Bigboy.DEFAULT_BYTE_WIDTH, str = "00"} = {}) {
if (len < Math.ceil(str.length / 2)) {
throw new RangeError("Argument error");
}
const bigboy = new this({len: len});
for (let i = 0; i < str.length; i += 2) {
const start = str.length - 2 - i;
const end = start + 2;
bigboy._data[i / 2] = Number(`0x${str.substring(start, end)}`);
}
return bigboy;
}
// TODO: Validate the string
static from_base2_str({len = Bigboy.DEFAULT_BYTE_WIDTH, str = "00"} = {}) {
if (len < Math.ceil(str.length / 8)) {
throw new RangeError("Argument error");
}
const bigboy = new this({len: len});
for (let i = 0; i < str.length; i += 8) {
const start = str.length - 8 - i;
const end = start + 8;
bigboy._data[i / 8] = Number(`0b${str.substring(start, end)}`);
}
return bigboy;
}
// TODO: Typecheck
static from_uint8(arr) {
const bigboy = new this({len: 0});
bigboy._data = Uint8Array.from(arr);
return bigboy;
}
static unsafe_random(len = Bigboy.DEFAULT_BYTE_WIDTH) {
const bigboy = new this({len: len});
for (let i = 0; i < len; i += 1) {
bigboy._data[i] = Math.floor(Math.random() * 256);
}
return bigboy;
}
equals(op) {
if (this._data.length !== op._data.length) {
throw new TypeError("Length mismatch");
}
for (let i = 0; i < this._data.length; i += 1) {
if (this._data[i] !== op._data[i]) {
return false;
}
}
return true;
}
/**
* Compare this Bigboy to op and return the index of their most significant unequal byte (or just
* return index 0 if all their bytes are equal)
*/
_get_high_order_diff(op) {
let i = this._data.length - 1;
while (this._data[i] === op._data[i] && i > 0) {
i -= 1;
}
return i;
}
greater(op) {
if (this._data.length !== op._data.length) {
throw new TypeError("Length mismatch");
}
const i = this._get_high_order_diff(op);
return this._data[i] > op._data[i];
}
less(op) {
if (this._data.length !== op._data.length) {
throw new TypeError("Length mismatch");
}
const i = this._get_high_order_diff(op);
return this._data[i] < op._data[i];
}
greater_equal(op) {
if (this._data.length !== op._data.length) {
throw new TypeError("Length mismatch");
}
const i = this._get_high_order_diff(op);
return this._data[i] >= op._data[i];
}
less_equal(op) {
if (this._data.length !== op._data.length) {
throw new TypeError("Length mismatch");
}
const i = this._get_high_order_diff(op);
return this._data[i] <= op._data[i];
}
and(op) {
if (this._data.length !== op._data.length) {
throw new TypeError("Length mismatch");
}
const bigboy = new Bigboy({len: this._data.length});
for (let i = 0; i < this._data.length; i += 1) {
bigboy._data[i] = this._data[i] & op._data[i];
}
return bigboy;
}
or(op) {
if (this._data.length !== op._data.length) {
throw new TypeError("Length mismatch");
}
const bigboy = new Bigboy({len: this._data.length});
for (let i = 0; i < this._data.length; i += 1) {
bigboy._data[i] = this._data[i] | op._data[i];
}
return bigboy;
}
xor(op) {
if (this._data.length !== op._data.length) {
throw new TypeError("Length mismatch");
}
const bigboy = new Bigboy({len: this._data.length});
for (let i = 0; i < this._data.length; i += 1) {
bigboy._data[i] = this._data[i] ^ op._data[i];
}
return bigboy;
}
shift_left(n_bits) {
if (n_bits < 0) {
throw new RangeError("Argument error");
}
const bigboy = new Bigboy({len: this._data.length});
for (let i = 0; i < this._data.length; i += 1) {
bigboy._data[i + Math.floor(n_bits / 8)] = this._data[i] << (n_bits % 8) |
this._data[i - 1] >> 8 - (n_bits % 8);
}
return bigboy;
}
shift_right(n_bits) {
if (n_bits < 0) {
throw new RangeError("Argument error");
}
const bigboy = new Bigboy({len: this._data.length});
for (let i = 0; i < this._data.length; i += 1) {
bigboy._data[i - Math.floor(n_bits / 8)] = this._data[i] >>> (n_bits % 8) |
this._data[i + 1] << 8 - (n_bits % 8);
}
return bigboy;
}
get_bit(idx) {
if (idx < 0) {
throw new RangeError("Argument error");
}
return this._data[Math.floor(idx / 8)] >>> (idx % 8) & 0x01;
}
to_hex_str() {
return Array.from(this._data).map(byte => byte.toString(16).padStart(2, "0")).reverse().join("");
}
to_base2_str() {
return Array.from(this._data).map(byte => byte.toString(2).padStart(8, "0")).reverse().join("");
}
to_base64_str() {
return to_base64(this._data);
}
length() {
return this._data.length;
}
}
|
JavaScript
|
class StepReportDeviceScreenshotsItemScreenshot {
/**
* Create a StepReportDeviceScreenshotsItemScreenshot.
* @property {object} urls
* @property {string} [urls.original]
* @property {string} [urls.small]
* @property {string} [urls.medium]
* @property {string} [urls.large]
* @property {number} rotation
* @property {boolean} landscape
*/
constructor() {
}
/**
* Defines the metadata of StepReportDeviceScreenshotsItemScreenshot
*
* @returns {object} metadata of StepReportDeviceScreenshotsItemScreenshot
*
*/
mapper() {
return {
required: false,
serializedName: 'StepReport_deviceScreenshotsItem_screenshot',
type: {
name: 'Composite',
className: 'StepReportDeviceScreenshotsItemScreenshot',
modelProperties: {
urls: {
required: true,
serializedName: 'urls',
type: {
name: 'Composite',
className: 'StepReportDeviceScreenshotsItemScreenshotUrls'
}
},
rotation: {
required: true,
serializedName: 'rotation',
type: {
name: 'Number'
}
},
landscape: {
required: true,
serializedName: 'landscape',
type: {
name: 'Boolean'
}
}
}
}
};
}
}
|
JavaScript
|
class Application {
constructor(session, params) {
this.log = logger.getLogger(this.constructor.name);
this.session = session;
this.conversations = {};
this.synced_conversations_count = 0;
this.start_sync_time = 0;
this.stop_sync_time = 0;
this.me = null;
Object.assign(this, params);
WildEmitter.mixin(Application);
}
/**
* Update Conversation instance or create a new one.
*
* Pre-created conversation exist from getConversations
* like initialised templates. When we explicitly ask to
* getConversation(), we receive members and other details
*
* @param {object} payload Conversation payload
* @private
*/
updateOrCreateConversation(payload) {
const conversation = this.conversations[payload.id];
if (conversation) {
conversation.updateObjectInstance(conversation, payload);
this.conversations[payload.id] = conversation;
} else {
this.conversations[payload.id] = new Conversation(this, payload);
}
return this.conversations[payload.id];
}
/**
* Application listening for invites.
*
* @event Application#member:invited
*
* @property {Member} member - The invited member
* @property {Event} event - The invitation event
*
* @example <caption>listen for your invites</caption>
* application.on("member:invited",(member, event) => {
* console.log("Invited to the conversation: " + event.conversation.display_name || event.conversation.name);
*
* //identify the sender.
* console.log("Invited by: " + member.invited_by);
*
* //accept an invitation.
* application.conversations[event.conversation.id].join();
*
* //decline the invitation.
application.conversations[event.conversation.id].leave();
*/
/**
* Application listening for joins.
*
* @event Application#member:joined
*
* @property {Member} member - the member that joined the conversation
* @property {Event} event - the join event
*
* @example <caption>listen join events in Application level</caption>
* application.on("member:joined",(member, event) => {
* console.log("JOINED", "Joined conversation: " + event.conversation.display_name || event.conversation.name);
* });
* });
*/
/**
* Application listening for calls.
*
* @event Application#member:call
*
* @property {Member} member - the member that initiated the call
* @property {Call} call - resolves the call object
*
* @example <caption>listen for calls in Application level</caption>
* application.on("member:call", (member, call) => {
* console.log("Call ", call;
* });
* });
*/
/*
* Entry point for events in Application level
**/
_handleEvent(event) {
const cid = event.cid;
if (cid in this.conversations) {
this.conversations[cid]._handleEvent(event);
} else {
//get the conversation you don't know about (case: joined by another user)
this.getConversation(cid)
.then((conversation) => {
this.conversations[cid] = conversation;
this._handleApplicationEvent(event);
}).catch((error) => {
this.log.error(error);
});
}
}
/*
* Update the event to map local generated events
* in case we need a more specific event to pass in the application listener
* or f/w the event as it comes
**/
_handleApplicationEvent(event) {
const conversation = this.conversations[event.cid];
const copied_event = Object.assign({}, event);
let payload;
switch (event.type) {
case 'member:invited':
if (conversation.me && (conversation.me.user.name === event.body.invited_by)) return;
//media audio invite
if (copied_event.body.user.media && copied_event.body.user.media.audio) {
if (conversation.display_name && conversation.display_name.startsWith('CALL_')) {
//audio call module (IP - IP call) //TODO split in other function getCallType()
const caller = Utils.getMemberFromNameOrNull(conversation, copied_event.body.invited_by) || 'unknown';
const call = new Call(this, conversation, caller);
payload = call;
copied_event.type = 'member:call';
} else {
payload = new Event(conversation, copied_event);
}
if (!copied_event.body.invited_by) {
// VAPI invites (PHONE - IP)
const call = new Call(this, conversation, "unknown");
call.type = call.TYPES.PHONE;
payload = call;
copied_event.type = 'member:call';
}
} else {
payload = new Event(conversation, copied_event);
}
break;
default:
payload = new Event(conversation, copied_event);
break;
}
this.emit(copied_event.type, conversation.members[copied_event.from], payload);
}
/**
* Creates a call to specified user/s.
* @classdesc creates a call between the defined users
* @param {string[]} usernames - the user names for those we want to call
* @returns {Call} a Call object with all the call properties
*/
call(usernames) {
return new Promise((resolve, reject) => {
if (!usernames || !Array.isArray(usernames) || usernames.length === 0) {
return reject(new NexmoClientError("error:application:call:params"));
}
const call = new Call(this);
return call.createCall(usernames)
.then(() => {
return resolve(call);
});
});
}
/**
* Creates a call to phone a number.
* @classdesc creates a call to a phone number
* @param {string} phoneNumber - the number you want to call
* @returns {Call} a Call object with all the call properties
*/
callPhone(phoneNumber) {
return new Promise((resolve, reject) => {
if (!phoneNumber || (typeof phoneNumber) !== 'string') {
return reject(new NexmoClientError("error:application:callPhone:params"));
}
const call = new Call(this);
return call.createPhoneCall(phoneNumber)
.then(() => {
return resolve(call);
});
});
}
/**
* Query the service to create a new conversation
* The conversation name must be unique per application.
* @param {object} [params] - leave empty to get a GUID as name
* @param {string} params.name - the name of the conversation. A UID will be assigned if this is skipped
* @param {string} params.display_name - the display_name of the conversation.
* @returns {Promise<Conversation>} - the created Conversation
* @example <caption>Create a conversation and join</caption>
* application.newConversation().then((conversation) => {
*
* //join the created conversation
* conversation.join().then((member) => {
* //Get the user's member belonging in this conversation.
* //You can also access it via conversation.me
*
* console.log("Joined as " + member.user.name);
* });
*
* }).catch((error) => {
* console.log(error);
* });
*/
newConversation(params) {
return new Promise((resolve, reject) => {
this.session.sendRequest({
type: 'new:conversation',
body: params
}, (response) => {
if (response.type === 'new:conversation:success') {
const conv = new Conversation(this, response.body);
this.conversations[conv.id] = conv;
// do a get conversation to get the whole model as shaped in the service,
this.getConversation(conv.id)
.then((conversation) => {
resolve(conversation);
});
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Query the service to create a new conversation and join it
* The conversation name must be unique per application.
* @param {object} [params] - leave empty to get a GUID as name
* @param {string} params.name - the name of the conversation. A UID will be assigned if this is skipped
* @param {string} params.display_name - the display_name of the conversation.
* @returns {Promise<Conversation>} - the created Conversation
* @example <caption>Create a conversation and join</caption>
* application.newConversationAndJoin().then((conversation) => {
* //join the created conversation
* conversation.join().then((member) => {
* //Get the user's member belonging in this conversation.
* //You can also access it via conversation.me
* console.log("Joined as " + member.user.name);
* });
* }).catch((error) => {
* console.log(error);
* });
*/
newConversationAndJoin(params) {
return this.newConversation(params).then((conversation) => {
return conversation.join().then(() => {
return conversation;
});
});
}
/**
* Query the service to see if this conversation exists with the
* logged in user as a member and retrieve the data object
* Result added (or updated) in this.conversations
*
* @param {string} id - the id of the conversation to fetch
* @returns {Promise<Conversation>} - the requested conversation
*/
getConversation(id) {
return new Promise((resolve, reject) => {
this.session.sendRequest({
type: 'conversation:get',
cid: id,
body: {}
}, (response) => {
if (response.type === 'conversation:get:success') {
const conversation_object = this.updateOrCreateConversation(response.body);
// Populate the events
conversation_object.getEvents()
.then((events) => {
conversation_object.events = events;
resolve(conversation_object);
});
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Query the service to obtain a complete list of conversations of which the
* logged-in user is a member with a state of `JOINED` or `INVITED`.
*
* @returns {Promise<Object<Conversation>>} - Populate Application.conversations.
*/
getConversations(params) {
return new Promise((resolve, reject) => {
this.session.sendRequest({
type: 'user:conversations',
body: params
}, (response) => {
if (response.type === 'user:conversations:success') {
// Iterate and create the conversations if not existent
response.body.forEach((c) => {
this.updateOrCreateConversation(c);
});
this.syncConversations(response.body);
resolve(this.conversations);
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Application listening sync status.
*
* @event Application#sync:progress
*
* @property {number} status.sync_progress - Percentage of fetched conversations
* @example <caption>listening for changes in the synchronisation progress</caption>
* application.on("sync:progress",(status) => {
* console.log(data.sync_progress);
* });
* });
*/
syncConversations(conversations) {
const conversations_length = conversations.length;
const d = new Date();
this.start_sync_time = (window && window.performance) ? window.performance.now() : d.getTime();
const fetchConversationForStorage = () => {
this.synced_conversations_percentage = ((this.synced_conversations_count / conversations_length) * 100).toFixed(2);
const status_payload = {
sync_progress: this.synced_conversations_percentage
};
this.emit('sync:progress', status_payload);
this.log.debug('Loading sync progress: ' + this.synced_conversations_count + '/' +
conversations_length + ' - ' + this.synced_conversations_percentage + '%');
if (this.synced_conversations_percentage >= 100) {
const d = new Date();
this.stop_sync_time = (window && window.performance) ? window.performance.now() : d.getTime();
this.log.info('Loaded conversations in ' + (this.stop_sync_time - this.start_sync_time) + 'ms');
}
if (this.synced_conversations_count < conversations_length) {
this.getConversation(conversations[this.synced_conversations_count].id).then(() => {
fetchConversationForStorage();
});
this.synced_conversations_count++;
this.sync_progress_buffer++;
}
};
fetchConversationForStorage();
}
/**
* Get Details of a user
* @param {string} [id] - the id of the user to fetch, if skipped, it returns your own user details
* @returns {Promise<User>}
*/
getUser(user_id = this.me.id) {
return new Promise((resolve, reject) => {
const params = {
user_id: user_id
};
this.session.sendRequest({
type: 'user:get',
from: this.me.id,
body: params
}, (response) => {
if (response.type === 'user:get:success') {
resolve(new User(this, response.body));
} else {
reject(new NexmoApiError(response));
}
});
});
}
}
|
JavaScript
|
class Conversation {
constructor(application, params) {
this.log = logger.getLogger(this.constructor.name);
this.application = application;
this.id = null;
this.name = null;
this.display_name = null;
this.timestamp = null;
this.members = {};
this.events = new Map();
this.sequence_number = 0;
this.media = new Media(this);
/**
* A Member Object representing the current user.
* Only set if the user is or has been a member of the Conversation,
* otherwise the value will be `null`.
* @type Member
*/
this.me = null; // We are not in the conversation ourselves by default
// Map the params (which includes the id)
this.updateObjectInstance(application, params);
WildEmitter.mixin(Conversation);
}
updateObjectInstance(application, params) {
for (let key in params) {
switch (key) {
case 'id':
this.id = params.id;
break;
case 'name':
this.name = params.name;
break;
case 'display_name':
this.display_name = params.display_name;
break;
case 'members':
//update the conversation javascript object
//CASE1 conversations:get:success,
//PATCH this responds with member[0].user_id and name
// Iterate the list
params.members.map((m) => {
const member = new Member(this, m);
if (m.user_id === this.application.me.id) {
this.me = member;
}
this.members[member.id] = member;
});
break;
case 'timestamp':
this.timestamp = params.timestamp;
break;
case 'sequence_number':
this.sequence_number = params.sequence_number;
break;
case 'member_id':
// filter needed params to create the object
// the conversation list gives us the member_id to prepare the member/this object
const object_params = {
id: params.member_id,
state: params.state,
user: this.application.me
};
// update the member object or create a new instance
let member_object = this.members[params.member_id];
if (member_object) {
Object.assign(member_object, object_params);
} else {
const member = new Member(this, object_params);
this.me = member;
this.members[member.id] = member;
}
break;
}
}
}
/**
* Join the given user to this conversation, will typically use this to join
* ourselves to a conversation we create.
* Accept an invitation if our member has state INVITED and no user_id / user_name is given
*
* @param {object} [params = this.application.me.id] The user to join (defaults to this)
* @param {string} params.user_name the user_name of the user to join
* @param {string} params.user_id the user_id of the user to join
* @return {Promise<Member>}
*
* @example <caption>join a user to a conversation</caption>
*
* conversation.join().then((member) => {
* console.log("joined as member: ", member)
* })
*/
join(params) {
const request_body = {};
if (params) {
if (params.user_id) {
request_body.user_id = params.user_id;
}
if (params.user_name) {
request_body.user_name = params.user_name;
}
} else {
if (this.me && this.me.id && this.me.state === 'INVITED') {
request_body.member_id = this.me.id;
}
request_body.user_name = this.application.me.name;
request_body.user_id = this.application.me.id;
}
return new Promise((resolve, reject) => {
this.application.session.sendRequest({
type: 'conversation:join',
cid: this.id,
body: request_body
}, (response) => {
if (response.type === 'conversation:join:success') {
// Create a new member object, response.body will contain all the parameters from the service
const member = new Member(this, response.body);
if (response.body.user_id === this.application.me.id) {
this.me = member;
}
this.members[member.id] = member;
resolve(member);
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Delete a conversation
*
* @return {Promise}
*
* @example <caption>delete the conversation</caption>
*
* conversation.del().then(() => {
* console.log("conversation deleted");
* })
*/
del() {
return new Promise((resolve, reject) => {
this.application.session.sendRequest({
type: 'conversation:delete',
cid: this.id
}, (response) => {
if (response.type === 'conversation:delete:success') {
delete this.application.conversations[this.id];
resolve();
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Delete an Event (e.g. Text)
* @param {Event} event
* @returns {Promise}
*
*/
deleteEvent(event) {
return event.del();
}
/**
* Invite the given user (id or name) to this conversation
* @param {Member} params
* @param {string} [params.id or username] - the id or the username of the user to invite
*
* @returns {Promise<Member>}
*
* @example <caption>invite a user to a conversation</caption>
* const user_id = 'user to invite';
* const user_name = 'username to invite';
*
* conversation.invite({
* id: user_id,
* user_name: user_name
* })
* .then((member) => {
* displayMessage(member.state + " user: " + user_id + " " + user_name);
* }).catch((error) => {
* console.log(error);
* });
*
*/
invite(params) {
if (!params || (!params.id && !params.user_name)) {
return Promise.reject(new NexmoClientError('error:invite:missing:params'));
}
return new Promise((resolve, reject) => {
this.application.session.sendRequest({
type: 'conversation:invite',
cid: this.id,
body: {
user_id: params.id,
user_name: params.user_name,
media: params.media
}
}, (response) => {
if (response.type === 'conversation:invite:success') {
// Create a new member object, response.body will contain all the parameters from the service
const member = new Member(this, response.body);
this.members[member.id] = member;
resolve(member);
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Invite the given user (id or name) to this conversation with media audio
* @param {Member} params
* @param {string} [params.id or username] - the id or the username of the user to invite
*
* @returns {Promise<Member>}
*
* @example <caption>invite a user to a conversation</caption>
* const user_id = 'user to invite';
* const user_name = 'username to invite';
*
* conversation.inviteWithAudio({
* id: user_id,
* user_name: user_name
* })
* .then((member) => {
* displayMessage(member.state + " user: " + user_id + " " + user_name);
* }).catch((error) => {
* console.log(error);
* });
*
*/
inviteWithAudio(params) {
if (!params || (!params.id && !params.user_name)) {
return Promise.reject(new NexmoClientError('error:invite:missing:params'));
}
params.media = {
audio: {
muted: false,
earmuffed: false
}
};
return this.invite(params);
}
/**
* Leave from the conversation
* @returns {Promise}
*/
leave() {
return this.me.kick();
}
/**
* Send a text message to the conversation, which will be relayed to every other member of the conversation
* @param {string} - text the text message to be sent
*
* @returns {Promise<TextEvent>} - the text message that was sent
*
* @example <caption> sending a text </caption>
* conversation.sendText("Hi Nexmo").then(() => {
* console.log('message was sent');
* }).catch((error)=>{
* console.log('error sending the message', error);
* });
*
*/
sendText(text) {
return new Promise((resolve, reject) => {
if (this.me === null) {
reject(new NexmoClientError('error:self'));
} else {
const msg = {
type: 'text',
cid: this.id,
from: this.me.id,
body: {
text: text
}
};
this.application.session.sendRequest(msg, (response) => {
if (response.type === 'text:success') {
msg.id = response.body.id;
msg.body.timestamp = response.body.timestamp;
const text_event = new TextEvent(this, msg);
resolve(text_event);
} else {
reject(new NexmoApiError(response));
}
});
}
});
}
/**
* Send an Image message to the conversation, which will be relayed to every other member of the conversation.
* implements xhr (https://xhr.spec.whatwg.org/) - this.imageRequest
*
* @param {File} file single input file (jpeg/jpg)
* @param {string} [params.quality_ratio = 100] a value between 0 and 100. 0 indicates 'maximum compression' and the lowest quality, 100 will result in the highest quality image
* @param {string} [params.medium_size_ratio = 50] a value between 1 and 100. 1 indicates the new image is 1% of original, 100 - same size as original
* @param {string} [params.thumbnail_size_ratio = 10] a value between 1 and 100. 1 indicates the new image is 1% of original, 100 - same size as original
*
* @returns {Promise<XMLHttpRequest>}
*
* @example <caption>sending an image</caption>
* conversation.sendImage(fileInput.files[0]).then((imageRequest) => {
*
* imageRequest.onabort = (e) => {
* console.log(e);
* console.log("Image:" + e.type);
* };
* imageRequest.onloadend = (e) => {
* console.log("Image:" + e.type);
* };
* });
*/
sendImage(fileInput, params) {
params = params || {
quality_ratio: 100,
medium_size_ratio: 50,
thumbnail_size_ratio: 30
};
const formData = new FormData();
formData.append("file", fileInput);
formData.append("quality_ratio", params.quality_ratio);
formData.append("medium_size_ratio", params.medium_size_ratio);
formData.append("thumbnail_size_ratio", params.thumbnail_size_ratio);
const IPS_url = this.application.session.config.ips_url;
return Utils.networkSend(IPS_url, formData)
.then((imageRequest) => {
imageRequest.upload.addEventListener("progress", (evt) => {
if (evt.lengthComputable) {
this.log.debug("uploading image " + evt.loaded + "/" + evt.total);
}
}, false);
imageRequest.onreadystatechange = () => {
if (imageRequest.readyState === 4 && imageRequest.status === 200) {
const msg = {
type: 'image',
cid: this.id,
from: this.me.id,
body: {
representations: JSON.parse(imageRequest.responseText)
}
};
this.application.session.sendRequest(msg, (response) => {
if (response.type !== 'image:success') {
this.log.debug(new NexmoApiError(response));
}
});
this.log.info(imageRequest);
}
if (imageRequest.status !== 200) {
this.log.error(imageRequest);
}
};
return Promise.resolve(imageRequest);
});
}
/**
* Cancel sending an Image message to the conversation.
*
* @param {XMLHttpRequest} imageRequest
*
* @returns void
*
* @example <caption>cancel sending an image</caption>
* conversation.sendImage(fileInput.files[0]).then((imageRequest) => {
* conversation.abortSendImage(imageRequest);
* });
*/
abortSendImage(imageRequest) {
if (imageRequest instanceof XMLHttpRequest) {
return imageRequest.abort();
} else {
return new NexmoClientError('error:invalid:param:type');
}
}
_typing(state) {
return new Promise((resolve, reject) => {
const params = {
activity: (state === 'on') ? 1 : 0
};
this.application.session.sendRequest({
type: 'text:typing:' + state,
cid: this.id,
from: this.me.id,
body: params
}, (response) => {
if (response.type === 'text:typing:' + state + ':success') {
resolve(response.type);
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Send start typing indication
*
* @returns {Promise} - resolves the promise on successful sent
*/
startTyping() {
return this._typing('on');
}
/**
* Send stop typing indication
*
* @returns {Promise} - resolves the promise on successful sent
*/
stopTyping() {
return this._typing('off');
}
/**
* Query the service to get a list of events in this conversation.
*
* @param {object} [params] - leave empty to get all the events
* @param {string} params.start_id - the id of the event to begin the batch
* @param {string} params.end_id - the id of the event to finish the batch
*
* @returns {Promise<Array<Event>>} - A promise to the Events list
*/
getEvents(params) {
return new Promise((resolve, reject) => {
this.application.session.sendRequest({
type: 'conversation:events',
cid: this.id,
body: params
}, (response) => {
if (response.type === 'conversation:events:success') {
// Iterate and create the events
const events_map = new Map();
for (let key in response.body) {
if (response.body.hasOwnProperty(key)) {
const event = response.body[key];
switch (event.type) {
// Event types with corresponding classes
case 'text':
events_map.set(event.id, new TextEvent(this, event));
break;
case 'image':
events_map.set(event.id, new ImageEvent(this, event));
break;
default:
// Events we want to be persisted, CS is sending more.
if (['member:joined', 'member:left', 'member:invited', 'member:media', 'audio:dtmf',
'audio:record', 'audio:record:done', 'audio:ringing:stop', 'say:text',
'audio:ringing:start'].includes(event.type)) {
events_map.set(event.id, new Event(this, event));
}
break;
}
}
}
//update the events Map
this.events = new Map([...this.events, ...events_map]);
resolve(this.events);
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Handle and event from the cloud.
*
* Identify the type of the event,
* create the corresponding Class instance
* to emit to the corresponding Objects
* @param {object} event
* @private
*/
_handleEvent(event) {
let persist_event;
// TODO Check local/remote sequence number matching
// rtc:* and sip* events are not part of the history, and are session specific.
// just f/w them to allow internal modules to work
const event_sub_type = event.type.split(":")[0];
if (event_sub_type === "rtc" || event_sub_type === "sip") {
this.emit(event.type, event);
return;
}
this.sequence_number++;
if (event.from && !this.members[event.from]) { //TODO - remove when CSJ-695
this.members[event.from] = new Member(this, event);
}
//make sure the event_id is not a string
if (event.body && event.body.event_id && typeof event.body.event_id === "string") {
event.body.event_id = parseInt(event.body.event_id);
}
const from = this.members[event.from];
switch (event.type) {
case 'audio:record':
case 'audio:record:done':
persist_event = new Recording(this, event);
break;
case 'image':
persist_event = new ImageEvent(this, event);
// Automatically send a delivery
// avoid sending delivered to our own events
if (this.me.id !== persist_event.from) {
persist_event.delivered().catch((error) => {
this.log.debug(error);
});
}
break;
case 'text':
persist_event = new TextEvent(this, event);
// Automatically send a delivery
// avoid sending delivered to our own events
if (this.me.id !== persist_event.from) {
persist_event.delivered().catch((error) => {
this.log.debug(error);
});
}
break;
case 'image:seen':
persist_event = new ImageEvent(this, event);
case 'text:seen':
persist_event = persist_event || new TextEvent(this, event);
const seen_id = event.body.event_id;
if (this.events.has(seen_id)) {
let event_to_mark = this.events.get(seen_id);
event_to_mark.state = event_to_mark.state || {};
event_to_mark.state.seen_by = event_to_mark.state.seen_by || {};
event_to_mark.state.seen_by[event.from] = event.timestamp;
persist_event = event_to_mark;
} else {
this.log.warn('try to mark seen an unknown event');
}
break;
case 'image:delivered':
persist_event = new ImageEvent(this, event);
case 'text:delivered':
persist_event = persist_event || new TextEvent(this, event);
const delivered_id = event.body.event_id;
if (this.events.has(delivered_id)) {
let event_to_mark = this.events.get(delivered_id);
event_to_mark.state = event_to_mark.state || {};
event_to_mark.state.delivered_to = event_to_mark.state.delivered_to || {};
event_to_mark.state.delivered_to[event.from] = event.timestamp;
persist_event = event_to_mark;
} else {
this.log.warn('try to mark delivered an unknown event');
}
break;
case 'event:delete':
//handle both text events or image
const event_to_delete = this.events.get(event.body.event_id);
if (event_to_delete.body.text) event_to_delete.body.text = "";
if (event_to_delete.body.representations) event_to_delete.body.representations = "";
event_to_delete.body.timestamp = {
deleted: event.timestamp
};
persist_event = event_to_delete;
break;
case 'member:joined':
case 'member:invited':
case 'member:left':
//use the member object to handle the state
from._handleEvent(event);
persist_event = new Event(this, event);
break;
case 'member:media':
persist_event = new Event(this, event);
this.members[event.from]._handleEvent(event);
break;
case 'audio:dtmf':
case 'audio:ringing:stop':
case 'audio:ringing:start':
case 'say:text':
persist_event = new Event(this, event);
break;
case 'audio:mute:on':
case 'audio:mute:off':
case 'video:mute:on':
case 'video:mute:off':
if (this.rtcObjects[event.body.rtc_id]) {
const streamIndex = this.rtcObjects[event.body.rtc_id].streamIndex;
event.index = streamIndex;
} else if (this.remoteMembers) {
const remote = this.remoteMembers.find((remoteMember) => remoteMember.remote_leg_id === event.body.rtc_id);
if (remote) {
event.index = remote.streamIndex;
}
}
default:
persist_event = new Event(this, event);
}
// Unless they are typing events, add the event to the conversation.events map
if (!["text:typing:on", "text:typing:off"].includes(event.type)) {
this.events.set(persist_event.id, persist_event);
}
this.emit(event.type, from, persist_event);
}
}
|
JavaScript
|
class Event {
constructor(conversation, params) {
this.conversation = conversation;
if (params) {
for (const key in params) {
switch (key) {
case "type":
this.type = params.type;
break;
case "cid":
this.cid = params.cid;
break;
case "from":
this.from = params.from;
break;
case "timestamp":
this.timestamp = params.timestamp;
break;
case "id":
this.id = params.id;
break;
case "state":
this.state = params.state;
break;
case "index":
this.index = params.index;
break;
case "body":
this.body = params.body;
if (this.body.user && this.body.user.user_id) {
this.body.user.id = this.body.user.user_id;
delete this.body.user.user_id;
}
break;
}
}
}
WildEmitter.mixin(Event);
}
/**
* Delete the event
* @param {number} [event_id=this.event_id] if the event id param is not present, "this" event will be default
* @returns {Promise}
* @private
*/
del(event_id = this.id) {
return new Promise((resolve, reject) => {
this.conversation.application.session.sendRequest({
type: 'event:delete',
cid: this.conversation.id,
from: this.conversation.me.id,
body: {
event_id: event_id
}
}, (response) => {
if (response.type === 'event:delete:success') {
resolve();
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Mark as Delivered the event
* @param {number} [event_id=this.event_id] if the event id is not provided, the this event will be used
* @returns {Promise}
* @private
*/
delivered(event_id = this.id) {
if (this.type !== "text" && this.type !== "image") {
this.type = "event";
}
return new Promise((resolve, reject) => {
if (this.conversation.me.id === this.from) {
reject(new NexmoClientError("error:delivered:own-message"));
} else if (this.state && this.state.delivered_to && this.state.delivered_to[this.conversation.me.id]) {
reject(new NexmoClientError("error:already-delivered"));
} else {
const params = {
event_id: event_id
};
this.conversation.application.session.sendRequest({
type: this.type + ':delivered',
from: this.conversation.me.id,
cid: this.conversation.id,
body: params
}, (response) => {
if (response.type === this.type + ':delivered:success') {
resolve();
} else {
reject(new NexmoApiError(response));
}
});
resolve();
}
});
}
/**
* Mark as Seen the event
* @param {number} [event_id=this.event_id] if the event id is not provided, the this event will be used
* @returns {Promise}
* @private
*/
seen(event_id = this.id) {
if (this.type !== "text" && this.type !== "image") {
this.type = "event";
}
return new Promise((resolve, reject) => {
if (this.conversation.me.id === this.from) {
reject(new NexmoClientError("error:seen:own-message"));
} else if (this.state && this.state.seen_by && this.state.seen_by[this.conversation.me.id]) {
reject(new NexmoClientError("error:already-seen"));
} else {
const params = {
event_id: event_id
};
this.conversation.application.session.sendRequest({
type: this.type + ':seen',
from: this.conversation.me.id,
cid: this.conversation.id,
body: params
}, (response) => {
if (response.type === this.type + ':seen:success') {
resolve();
} else {
reject(new NexmoApiError(response));
}
});
}
});
}
}
|
JavaScript
|
class ImageEvent extends Event {
constructor(conversation, params) {
super(conversation, params);
this.log = logger.getLogger(this.constructor.name);
this.type = "image";
this.conversation = conversation;
this.state = {
seen_by: {},
delivered_to: {}
};
if (params && params.body) {
if (params.body.timestamp)
this.timestamp = params.body.timestamp;
}
Object.assign(this, params);
}
/**
* Set the message status to 'seen'
*/
seen() {
return super.seen();
}
/**
* Set the message status to 'delivered'
*/
delivered() {
return super.delivered();
}
/**
* Delete the image event
* @returns {Promise}
*/
del() {
return super.del();
}
/**
* Download an Image from Media service //3 representations
* @param {string} [type="thumbnail"] original, medium, thumbnail,
* @param {string} [representations=this.body.representations] the ImageEvent.body for the image to download
* @returns {string} the dataUrl "data:image/jpeg;base64..."
* @example <caption>Downloading an image from the imageEvent</caption>
* imageEvent.fetchImage().then((imagedata) => {
* var img = new Image();
* img.onload = function () {
* copyCanvas(img);
* };
* img.src = imagedata;
*
* // to cancel the request:
* // conversation.abortSendImage(imageRequest);
* });
*/
fetchImage(type = "thumbnail", imageDataObject = this.body.representations) {
const url = imageDataObject[type].url;
return Utils.networkFetch(url)
.then((response) => {
const responseArray = new Uint8Array(response);
// Convert the int array to a binary String
// We have to use apply() as we are converting an *array*
// and String.fromCharCode() takes one or more single values, not
// an array.
//support large image files (Chunking)
let res = "";
const chunk = 8 * 1024;
let i;
for (i = 0; i < responseArray.length / chunk; i++) {
res += String.fromCharCode.apply(null, responseArray.subarray(i * chunk, (i + 1) * chunk));
}
res += String.fromCharCode.apply(null, responseArray.subarray(i * chunk));
const b64 = btoa(res);
const dataUrl = "data:image/jpeg;base64," + b64;
return Promise.resolve(dataUrl);
}).catch((error) => {
this.log.warn(error);
return Promise.reject(new NexmoClientError("error:fetch-image"));
});
}
}
|
JavaScript
|
class Recording extends Event {
constructor(conversation, params) {
super(conversation, params);
this.conversation = conversation;
Object.assign(this, params);
}
/**
* Stop the recording
* @returns {Promise}
*/
stop() {
return super.del();
}
}
|
JavaScript
|
class TextEvent extends Event {
constructor(conversation, params) {
super(conversation, params);
this.type = "text";
this.conversation = conversation;
this.state = {
seen_by: {},
delivered_to: {}
};
if (params && params.body && params.body.timestamp) {
this.timestamp = params.body.timestamp;
}
Object.assign(this, params);
}
/**
* Set the message status to 'seen'
* @returns {Promise}
*/
seen() {
return super.seen();
}
/**
* Set the message status to 'delivered'.
* handled by the SDK
* @returns {Promise}
*/
delivered() {
return super.delivered();
}
/**
* Delete the event
* @returns {Promise}
*/
del() {
return super.del();
}
}
|
JavaScript
|
class Member {
constructor(conversation, params) {
this.conversation = conversation;
this._normalise(params);
WildEmitter.mixin(Member);
}
/**
* Update object instance and align attribute names
*
* Handle params input to keep consistent the member object
* @param {object} params member attributes
* @private
*/
_normalise(params) {
if (params) {
this.user = this.user || {};
this.channel = params.channel || {
type: "app"
};
for (let key in params) {
switch (key) {
case "member_id":
this.id = params.member_id;
break;
case "timestamp":
this.timestamp = params.timestamp;
break;
case "state":
this.state = params.state;
break;
case "from":
this.id = params.from; //special case for member events
break;
case "user_id":
this.user.id = params.user_id;
break;
case "name":
this.user.name = params.name;
break;
case "user":
this.user = {
name: params.user.name,
id: params.user.user_id || params.user.id
};
break;
case "invited_by":
this.invited_by = params.invited_by;
break;
default:
if (!params.type) //TODO identify when an event payload comes to update a member object.
this[key] = params[key];
}
}
// join conversation returns our member with only id,
// compare it for now and use the username we have in the application object
if (this.conversation.application.me && params.user_id === this.conversation.application.me.id) {
this.user.name = this.conversation.application.me.name;
}
//make sure we don't keep a member.user_id, name in any flow
delete this.user_id;
delete this.name;
delete this.user.user_id;
}
}
/**
* Play the given stream only to this member within the conversation
*
* @param {string} [params]
*
* @returns {Promise<Event>}
* @private
*/
playStream(params) {
return new Promise((resolve, reject) => {
this.conversation.application.session.sendRequest({
type: 'audio:play',
cid: this.id,
to: this.id,
body: params
}, (response) => {
if (response.type === 'audio:play:success') {
resolve(new Event(this.conversation, response));
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Speak the given text only to this member within the conversation
*
* @param {string} [params]
*
* @returns {Promise<Event>}
* @private
*/
sayText(params) {
return new Promise((resolve, reject) => {
this.conversation.application.session.sendRequest({
type: 'audio:say',
cid: this.id,
from: this.conversation.me.id,
to: this.id,
body: params
}, (response) => {
if (response.type === 'audio:say:success') {
resolve(new Event(this.conversation, response));
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Kick this member from the conversation
*
* @returns {Promise}
*/
kick() {
return new Promise((resolve, reject) => {
this.conversation.application.session.sendRequest({
type: 'conversation:member:delete',
cid: this.conversation.id,
from: this.conversation.me.id,
to: this.id,
body: {
"member_id": this.id
}
}, (response) => {
if (response.type === 'conversation:member:delete:success') {
resolve(response.body);
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Mute this member
* @param {Boolean} [mute] is muted
*
* @returns {Promise}
*
*/
mute(mute) {
return new Promise((resolve, reject) => {
const type = (mute) ? 'audio:mute:on' : 'audio:mute:off';
this.conversation.application.session.sendRequest({
type: type,
cid: this.id,
to: this.id
}, (response) => {
if (response.type === 'audio:mute:success') {
resolve(response.body);
} else {
reject(new NexmoApiError(response));
}
});
});
}
/*
* Control the volume of this member
*
* @param {string} [params]
*
* @returns {Promise} - not tested yet
*/
volume(up) {
return new Promise((resolve, reject) => {
const type = (up) ? 'audio:volume:up' : 'audio:volume:down';
this.conversation.application.session.sendRequest({
type: type,
cid: this.id,
to: this.id
}, (response) => {
if (response.type === 'audio:volume:success') {
resolve(response.body);
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Earmuff this member
*
* @param {Boolean} [params]
*
* @returns {Promise}
*
*/
earmuff(earmuff) {
return new Promise((resolve, reject) => {
if (this.me === null) {
reject(new NexmoClientError("error:self"));
} else {
let type = (earmuff) ? 'audio:earmuff:on' : 'audio:earmuff:off';
this.conversation.application.session.sendRequest({
type: type,
cid: this.id,
to: this.id
}, (response) => {
if (response.type === 'audio:earmuff:success') {
resolve(response.body);
} else {
reject(new NexmoApiError(response));
}
});
}
});
}
/*
* Record this member
*
* @param {string} [params]
*
* @returns {Promise}
*/
record(params) {
return new Promise((resolve, reject) => {
this.conversation.application.session.sendRequest({
type: 'audio:record',
cid: this.id,
to: this.id,
body: params
}, (response) => {
if (response.type === 'audio:record:success') {
resolve(new Event(this.conversation, response));
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Handle member object events
*
* Handle events that are modifying this member instance
* @param {Event} event invited, joined, left, media events
* @private
*/
_handleEvent(event) {
switch (event.type) {
case 'member:invited':
this._normalise(event.body); // take care of misaligned objects.
this.state = 'INVITED';
this.timestamp.invited = event.body.timestamp.invited;
break;
case 'member:joined':
this._normalise(event.body); // take care of misaligned objects.
this.state = 'JOINED';
this.timestamp.joined = event.body.timestamp.joined;
break;
case 'member:left':
this._normalise(event.body); // take care of misaligned objects.
this.state = 'LEFT';
this.timestamp.left = event.body.timestamp.left;
break;
case 'member:media':
this.media = event.body;
break;
default:
break;
}
}
}
|
JavaScript
|
class Call {
constructor(application, conversation, from) {
this.application = application;
this.log = logger.getLogger(this.constructor.name);
this.from = from;
/**
* Enum for Call Member states.
* @readonly
* @enum {string}
*/
this.MEMBER_CALL_STATES = {
/** A Member is in ringing state */
RINGING: 'ringing',
/** A Member hung up the call */
HUNGUP: 'hungup',
/** A Member answered the call */
ANSWERED: 'answered',
/** A Member rejected the call */
REJECTED: 'rejected'
};
/**
* Enum for Call types.
* @readonly
* @enum {string}
*/
this.TYPES = {
/** A Call originated from APP */
APP: 'APP',
/** A Call originated from PHONE */
PHONE: 'PHONE'
};
this.type = this.TYPES.APP;
this._setupConversationObject(conversation);
WildEmitter.mixin(Call);
}
/**
* Attach member event listeners from the conversation
* map them to call:member:state events
* provided states member: hungup, rejected and answered
* @private
*/
_attachCallListeners() {
this.conversation.releaseGroup('call_module');
this.conversation.on('member:left', 'call_module', (from, event) => {
let state = this.MEMBER_CALL_STATES.HUNGUP;
if (from.timestamp.joined) {
state = this.MEMBER_CALL_STATES.HUNGUP;
} else {
state = this.MEMBER_CALL_STATES.REJECTED;
}
this.emit('call:member:state', from, state, event);
this._hangUpIfAllLeft();
});
this.conversation.on('member:joined', 'call_module', (from, event) => {
const state = this.MEMBER_CALL_STATES.ANSWERED;
this.emit('call:member:state', from, state, event);
});
this.conversation.on('member:invited', 'call_module', (from, event) => {
const state = this.MEMBER_CALL_STATES.RINGING;
this.emit('call:member:state', from, state, event);
});
}
/**
* Go through the members of the conversation and if .me is the only one (JOINED or INVITED)
* call call.hangUp().
* @returns {Promise} - empty promise or the call.hangUp promise chain
* @private
*/
_hangUpIfAllLeft() {
if (!this.conversation.me || this.conversation.me.state === "LEFT") return Promise.resolve();
if (Object.keys(this.conversation.members).length > 1) {
for (const member_id in this.conversation.members) {
if (!this.conversation.members[member_id]) continue;
const member = this.conversation.members[member_id];
if (member.state !== "LEFT" && (this.conversation.me.user.id !== member.user.id)) {
return Promise.resolve();
}
}
return this.hangUp();
} else {
return Promise.resolve();
}
}
/**
* Set the conversation object of the Call
* update call.from, and call.to attributes based on the conversation members
* @private
*/
_setupConversationObject(conversation) {
if (!conversation) return;
this.conversation = conversation;
if (!conversation.me) {
this.log.debug("missing own member object");
} else {
this.to = Object.assign({}, conversation.members);
if (this.from) {
delete this.to[this.from.id];
}
}
this._attachCallListeners();
}
/**
* Trigger the call flow for the input users.
* Create a conversation with prefix name "CALL_"
* and invite all the users.
* If at least one user is successfully invited, enable the audio.
*
* @param {string[]} usernames the usernames of the users to call
* @returns {Promise[]} an array of the invite promises for the provided usernames
* @private
*/
createCall(usernames) {
if (!usernames || !Array.isArray(usernames) || usernames.length === 0) {
return Promise.reject(new NexmoClientError("error:application:call:params"));
}
return this.application.newConversationAndJoin(
{ display_name: "CALL_" + this.application.me.name + "_" + usernames.join("_").replace(" ", "") })
.then((conversation) => {
this.from = conversation.me;
this.successful_invited_members = [];
const invites = usernames.map((username) => {
//check all invites, if at least one is resolved enable audio
// we need to catch rejections to allow all the chain to go through (all invites)
// we then catch-reject a promise so that the errors are passing through the end of the chain
return conversation.inviteWithAudio({ user_name: username })
.then((member) => {
this.successful_invited_members.push(member);
return Promise.resolve(member);
})
.catch((error) => {
this.log.warn(error);
// resolve the error to allow the promise.all to collect
// and return all the promises
return Promise.resolve(error);
})
});
//helper function to process in Promise.all() the failed invites too
const process_invites = () => {
if (this.successful_invited_members.length > 0) {
return conversation.media.enable({ audio: { muted: false, earmuffed: false } })
.then(() => {
return Promise.resolve(invites);
})
} else {
return Promise.reject(invites);
}
};
// we need to continue the invites even if one fails,
// in process_invites we do the check if at least one was successful
return Promise.all(invites)
.then(() => {
this._setupConversationObject(conversation);
return process_invites();
});
});
}
/**
* Trigger the call flow for the phone call.
* Create a knocking event
*
* @param {string} phoneNumber the phone number to call
* @returns {Promise}
* @private
*/
createPhoneCall(phoneNumber) {
return new Promise((resolve, reject) => {
this.application.session.sendRequest({
type: 'knocking:new',
body: {
channel: {
type: "app",
from: {
type: "app"
},
to: {
type: "phone",
number: phoneNumber
}
}
}
}, (response) => {
if (response.type === 'knocking:new:success') {
resolve(response.type);
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Hangs up the call
* Leave from the conversation
* Disable the audio
*
* @returns {Promise}
*/
hangUp() {
return this.conversation.leave();
}
/**
* Rejects an incoming call
* Leave from the conversation that you are invited
*
* @returns {Promise}
*/
reject() {
if (this.conversation) {
return this.conversation.leave();
} else {
return Promise.reject(new NexmoClientError("error:call:reject"));
}
}
/**
* Answers an incoming call
* Join the conversation that you are invited
*
* @returns {Promise}
*/
answer() {
if (this.conversation) {
return this.conversation.join()
.then(() => {
return this.conversation.media.enable();
});
} else {
return Promise.reject(new NexmoClientError("error:call:answer"));
}
}
}
|
JavaScript
|
class Media {
constructor(conversation) {
this.log = logger.getLogger("Media");
if (conversation) {
this.parentConversation = conversation;
this.application = conversation.application;
this.parentConversation.rtcObjects = {};
this.eventsQueue = [];
this.application.activeStreams = [];
this.parentConversation.remoteMembers = [];
this.extensionId = this.application.session.config.screenshareExtensionId;
this.streamIndex = 0;
this.rtcHelper = new RtcHelper(this.extensionId);
setWsConnection(this.rtcHelper);
}
this.log_rtcstats = logger.getLogger("RTCStats");
wsConnection.reset({
traceEnabled: this.application.session.config.rtcstarts_enables,
rtcstatsUri: this.application.session.config.rtcstarts_url,
logger: {
log: this.log_rtcstats.debug
}
})
}
/**
* Earmuff our member
*
* @param {Boolean} [params]
*
* @returns {Promise}
*/
earmuff(earmuff) {
return new Promise((resolve, reject) => {
if (this.me === null) {
reject(new NexmoClientError("error:self"));
} else {
let type = 'audio:earmuff:off';
if (earmuff) {
type = 'audio:earmuff:on';
}
this.application.session.sendRequest({
type: type,
cid: this.parentConversation.id,
to: this.parentConversation.me.id
}, (response) => {
const onoff = (earmuff) ? 'on' : 'off';
if (response.type === 'audio:earmuff:' + onoff + ':success') {
resolve(response.body);
} else {
reject(new NexmoApiError(response));
}
});
}
});
}
_handleVideo(params) {
return Promise.resolve()
.then(() => {
if (params.video) {
let direction = 'none';
let name = 'video';
if (params.video === Object(params.video)) {
direction = params.video.direction;
name = params.video.name || 'video';
} else {
direction = params.video;
}
switch (direction) {
case 'both':
case 'send_only':
case true:
return this.rtcHelper.getUserVideo().then((localStream) => {
return this._handleVideoSend(localStream, direction === 'send_only', 'video', name, params);
});
case 'receive_only':
this.log.debug('video - receive_only not implemented yet');
return Promise.reject(new NexmoApiError('Not implemented yet'));
case 'none':
break;
default:
if (direction === false) {
let rtcObjectWithType = this._findRtcObjectByType('video');
if (rtcObjectWithType) {
return this._disableLeg(rtcObjectWithType.id);
}
}
break;
}
} else {
Promise.resolve();
}
}).then(() => {
if (params.screenshare) {
let direction = false;
let name = 'screenshare';
let sources = ['screen', 'window', 'tab'];
if (params.screenshare === Object(params.screenshare)) {
direction = params.screenshare.direction;
name = params.screenshare.name || 'screenshare';
sources = params.screenshare.sources || sources;
} else {
direction = params.screenshare;
}
switch (direction) {
case 'send_only':
case true:
return this.rtcHelper.getUserScreen(sources).then((localStream) => {
return this._handleVideoSend(localStream, true, 'screenshare', name, params);
});
case 'none':
break;
default:
if (direction === false) {
let rtcObjectWithType = this._findRtcObjectByType('screenshare');
if (rtcObjectWithType) {
return this._disableLeg(rtcObjectWithType.id);
}
}
break;
}
} else {
Promise.resolve();
}
})
}
_emitEventsByRtcId(rtc_id) {
this.eventsQueue.filter((event) => event.id === rtc_id)
.forEach((event) => {
event.func();
event.ran = true;
});
this.eventsQueue = this.eventsQueue.filter((event) => event.ran === false);
}
_runWhenLegInitialized(rtc_id, func) {
if (this.parentConversation.rtcObjects[rtc_id]) {
func();
} else {
this.eventsQueue.push({
id: rtc_id,
func: func,
ran: false
})
}
}
_handleVideoSend(localStream, isSendOnly, type, name, params) {
const clientId = Utils.allocateUUID();
const pc = this.rtcHelper.createRTCPeerConnection({
'iceServers': [this.application.session.config.iceServers],
'iceTransportPolicy': 'all',
'bundlePolicy': 'balanced',
'rtcpMuxPolicy': 'require',
'iceCandidatePoolSize': '0'
}, {
optional: [{
'DtlsSrtpKeyAgreement': 'true'
}]
}, clientId);
pc.trace('conversation_id', this.parentConversation.id);
pc.trace('member_id', this.parentConversation.me.id);
// We want to be able to handle these events, for this member, before they get propagated out
if (!this.listeningToRtcEvent) {
this.parentConversation.on('rtc:answer', 'media_module', (event) => {
let setRemoveDescriptionFunc =
() => {
this.parentConversation.rtcObjects[event.body.rtc_id].pc.setRemoteDescription(new RTCSessionDescription({
type: 'answer',
sdp: event.body.answer
})).then(() => {
this.log.debug('remote description is set');
}).catch((e) => {
this.log.warn('set remote description failed with error', e);
});
};
this._runWhenLegInitialized(event.body.rtc_id, setRemoveDescriptionFunc)
});
}
if (!isSendOnly && !this.listeningToRtcEvent) {
this.parentConversation.on('rtc:offer', 'media_module', (event) => {
let handleOfferFunc = () => {
this._handleNewOffer(params, event);
};
this._runWhenLegInitialized(event.body.leg_id, handleOfferFunc);
});
this.parentConversation.on('rtc:terminate', 'media_module', (event) => {
this._handleParticipantRtcTerminate(event);
})
}
this.listeningToRtcEvent = true;
pc.ontrack = (evt) => {
this.log.debug('ontrack');
this.application.activeStreams.push(evt.streams[0]);
};
pc.addStream(localStream);
let index = this.streamIndex;
this.streamIndex++;
this.parentConversation.me.emit("media:stream:on", {
type,
name: name,
index: index,
localStream
});
const p = new Promise((resolve, reject) => {
pc.createOffer()
.then((desc) => {
return pc.setLocalDescription(desc);
})
.then(() => {
const direction = isSendOnly ? 'send_only' : 'both';
const event_to_emit = {
type: 'rtc:new',
cid: this.parentConversation.id,
from: this.parentConversation.me.id,
body: {
offer: {
sdp: pc.localDescription.sdp
},
video: {
direction,
name
}
}
};
if (params && params.label) {
event_to_emit.label = params.label;
}
this.log.debug('sending rtc:new event');
this.application.session.sendRequest(event_to_emit, (response) => {
if (response.type === 'rtc:new:success') {
this.log.debug('getting rtc:new:success');
const rtc_id = response.body.rtc_id;
this.parentConversation.rtcObjects[rtc_id] = {
id: rtc_id,
pc: pc,
localStream: localStream,
type: type,
streamIndex: index
};
this._emitEventsByRtcId(rtc_id);
pc.trace('rtc_id', rtc_id);
localStream.getVideoTracks()[0].onended = () => {
this._disableLeg(rtc_id)
.then(() => { this.parentConversation.me.emit("media:stream:off", index); })
.catch(() => { this.parentConversation.me.emit("media:stream:off", index); })
};
resolve(rtc_id);
} else {
reject(new NexmoApiError(response));
}
});
}).catch((e) => {
reject(new NexmoApiError(e));
})
})
const promisesArray = [];
pc.onicecandidate = (event) => {
p.then((rtc_id) => {
const body = {};
this._onIceCandidate(promisesArray, event, body, rtc_id);
})
};
pc.oniceconnectionstatechange = (status) => {
switch (pc.iceConnectionState) {
//https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/iceConnectionState
case 'disconnected':
case 'failed':
this.log.warn('One or more transports has terminated unexpectedly or in an error', status);
break;
default:
this.log.debug('The ice connection status changed', pc.iceConnectionState);
break;
}
}
pc.onicegatheringstatechange = () => {
switch (pc.iceGatheringState) {
case 'new':
this.log.debug('ice gathering new');
break;
case 'complete':
this.log.debug('ice gathering complete');
break;
case 'gathering':
this.log.debug('ice gathering gathering');
break;
}
}
//on member delete (our this)
//terminate media
this.parentConversation.on('member:left', 'media_module', (member) => {
if (member.user.id === this.application.me.id) {
this.disable();
}
});
this.log.debug('sending local stream');
return p;
}
_sendIceRequest(body, rtc_id) {
return new Promise((resolve, reject) => {
const event_to_emit = {
type: 'rtc:ice',
cid: this.parentConversation.id,
from: this.parentConversation.me.id,
rtc_id: rtc_id,
body: body
}
this.application.session.sendRequest(event_to_emit, (response) => {
if (response.type === 'rtc:ice:success') {
resolve();
} else {
reject(new NexmoApiError(response));
}
});
})
}
_onIceCandidate(promiseArray, event, body, rtc_id) {
const bodyToSend = body;
if (event.candidate) {
bodyToSend.candidates = event.candidate;
this.log.debug('sending trickle candidates: ', bodyToSend);
promiseArray.push(this._sendIceRequest(bodyToSend, rtc_id))
} else {
bodyToSend.candidates = {
completed: true
};
return Promise.all(promiseArray)
.then(this._sendIceRequest(bodyToSend, rtc_id))
.then(() => {
this.log.debug('successfully sent trickle candidates', bodyToSend);
})
.catch(() => {
this.log.error('failed to sent trickle candidates', bodyToSend);
});
}
}
_handleNewOffer(params, event) {
const remoteMemberObject = {
remote_member_id: event.body.member_id,
remote_leg_id: event.body.member_leg_id,
local_leg_id: event.body.leg_id,
name: event.body.name,
streamIndex: this.streamIndex
};
this.streamIndex++;
for (let member_id in this.parentConversation.members) {
if (member_id === event.body.member_id) {
remoteMemberObject.remote_member = this.parentConversation.members[member_id];
}
}
this.parentConversation.remoteMembers.push(remoteMemberObject);
this.log.debug('handle rtc:offer for member ' + remoteMemberObject.remote_member_id);
const clientId = Utils.allocateUUID();
remoteMemberObject.pc = this.rtcHelper.createRTCPeerConnection({
'iceServers': [this.application.session.config.iceServers],
'iceTransportPolicy': 'all',
'bundlePolicy': 'balanced',
'rtcpMuxPolicy': 'require',
'iceCandidatePoolSize': '0'
}, {
optional: [{
'DtlsSrtpKeyAgreement': 'true'
}]
}, clientId);
remoteMemberObject.pc.trace('conversation_id', this.parentConversation.id);
remoteMemberObject.pc.trace('member_id', this.parentConversation.me.id);
remoteMemberObject.pc.trace('rtc_id', remoteMemberObject.local_leg_id);
remoteMemberObject.pc.trace('other_member_id', remoteMemberObject.remote_member_id);
remoteMemberObject.pc.ontrack = (evt) => {
if (remoteMemberObject.stream !== evt.streams[0]) {
remoteMemberObject.stream = evt.streams[0];
remoteMemberObject.remote_member.emit("media:stream:on",
{
index: remoteMemberObject.streamIndex,
remote_member_id: remoteMemberObject.remote_member_id,
name: remoteMemberObject.name,
stream: remoteMemberObject.stream
});
}
};
let p = Promise.resolve();
const promisesArray = [];
remoteMemberObject.pc.onicecandidate = (event) => {
p = p.then(() => {
const body = {
other_member_id: remoteMemberObject.remote_member_id,
leg_id: remoteMemberObject.remote_leg_id
};
this._onIceCandidate(promisesArray, event, body, remoteMemberObject.local_leg_id);
})
}
remoteMemberObject.pc.oniceconnectionstatechange = (status) => {
switch (remoteMemberObject.pc.iceConnectionState) {
//https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/iceConnectionState
case 'disconnected':
case 'failed':
this.log.warn('transports has terminated or failed for member ' + event.body.member_id, status);
break;
default:
this.log.debug('The ice connection status changed for member ' + event.body.member_id, remoteMemberObject.pc.iceConnectionState);
break;
}
};
remoteMemberObject.pc.onicegatheringstatechange = () => {
switch (remoteMemberObject.pc.iceGatheringState) {
case 'new':
this.log.debug('ice gathering new for member ' + event.body.member_id);
break;
case 'complete':
this.log.debug('ice gathering complete for member ' + event.body.member_id);
break;
case 'gathering':
this.log.debug('ice gathering gathering for member ' + event.body.member_id);
break;
}
};
const rtcAnswerFunc = () => {
remoteMemberObject.pc.setRemoteDescription(new RTCSessionDescription({
type: 'offer',
sdp: event.body.sdp
}))
.then(() => {
return remoteMemberObject.pc.createAnswer()
})
.then((answer) => {
return remoteMemberObject.pc.setLocalDescription(answer);
})
.then(() => {
const event_to_emit = {
type: 'rtc:answer',
cid: this.parentConversation.id,
rtc_id: remoteMemberObject.local_leg_id,
from: this.parentConversation.me.id,
body: {
other_member_id: remoteMemberObject.remote_member_id,
answer: remoteMemberObject.pc.localDescription.sdp,
leg_id: remoteMemberObject.remote_leg_id
}
};
if (params && params.label) {
event_to_emit.label = params.label;
}
this.application.session.sendRequest(event_to_emit,
(response) => {
if (response.type === 'rtc:answer:success') {
this.log.debug('successfully set answer for member ' + remoteMemberObject.remote_member_id);
} else {
this.log.error(response.type + ': failed to set answer for member ' + remoteMemberObject.remote_member_id);
}
});
});
}
this._runWhenLegInitialized(remoteMemberObject.local_leg_id, rtcAnswerFunc);
}
_handleParticipantRtcTerminate(event) {
const member = this.parentConversation.remoteMembers.find((member) => {
return member.remote_leg_id === event.body.rtc_id
});
if (!member) {
this.log.error('rtc:terminate was sent with invalid member id');
return;
}
this.parentConversation.remoteMembers = this.parentConversation.remoteMembers.filter((remoteMember) => {
return remoteMember.remote_leg_id !== event.body.rtc_id
});
this._deleteMemberMedia(member);
member.remote_member.emit("media:stream:off", {
remote_member_id: member.remote_member_id,
index: member.streamIndex
});
}
_deleteMemberMedia(member) {
this._closeStream(member.stream);
member.pc.close();
}
/**
* Enable media participation in the conversation for this application (requires WebRTC)
* @param {object} params - rtc params
* @param {string} params.label - Label is an application defined tag, eg. ‘fullscreen’
* @param {object} [params.audio=true] - audio enablement mode. possible values "both", "send_only", "receive_only", "none", true or false
* * <!-- the following line should be added when deploying video to prod.
* @param {object} [params.video=false] - video enablement mode. possible values "both", "send_only", "receive_only", "none", true or false
* @param {object} [params.screenshare=false] -screen sharing enablement mode. possible values "send_only", "none", true or false -->
* @returns {Promise<MediaStream>}
* @example
* Enable media in this conversation
* function enable() {
* conversation.media.enable()
* .then((stream) => {
const media = document.createElement("video");
const source = document.createElement("source");
const media_div = document.createElement("div");
media.appendChild(source);
media_div.appendChild(media);
document.insertBefore(media_div);
// Older browsers may not have srcObject
if ("srcObject" in media) {
media.srcObject = stream;
} else {
// Avoid using this in new browsers, as it is going away.
media.src = window.URL.createObjectURL(stream);
}
media.onloadedmetadata = (e) => {
media.play();
};
*
* }).catch((error) => {
* console.log(error);
* });
* }
*
*
*
**/
enable(params) {
return new Promise((resolve, reject) => {
const onError = (error) => {
this.log.error(error);
reject(new NexmoApiError(error));
}
if (this.parentConversation.me === null) {
reject(new NexmoClientError('error:self'));
} else {
if (params && (params.video || params.screenshare)) {
return this._handleVideo(params).catch(reject)
.then(() => {
const types = ['video', 'screenshare'];
let disablePromises = [];
types.forEach((type) => {
if (!params[type]) {
let rtcObjectWithType = this._findRtcObjectByType(type);
if (rtcObjectWithType) {
disablePromises.push(this._disableLeg(rtcObjectWithType.id));
}
}
});
return Promise.all(disablePromises)
.then(resolve)
.catch(reject);
})
}
if (this.application.activeStream) {
reject(new NexmoClientError('error:media:already-connecting'));
}
this.application.activeStream = {
conversation: this.parentConversation
};
this.rtcHelper.getUserAudio()
.then((localStream) => {
const clientId = Utils.allocateUUID();
/* jshint -W117 */
const pc = this.rtcHelper.createRTCPeerConnection({
'iceServers': [this.application.session.config.iceServers],
'iceTransportPolicy': 'all',
'bundlePolicy': 'balanced',
'rtcpMuxPolicy': 'require',
'iceCandidatePoolSize': '0'
}, {
optional: [{
'DtlsSrtpKeyAgreement': 'true'
}]
}, clientId);
pc.trace('conversation_id', this.parentConversation.id);
pc.trace('member_id', this.parentConversation.me.id);
this.parentConversation.pc = pc;
this.parentConversation.localStream = localStream;
pc.ontrack = (evt) => {
this.application.activeStream.stream = evt.streams[0];
resolve(evt.streams[0]);
};
pc.addStream(localStream);
pc.createOffer((desc) => {
pc.setLocalDescription(desc, () => {
}, onError);
},
onError);
pc.oniceconnectionstatechange = (status) => {
switch (pc.iceConnectionState) {
//https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/iceConnectionState
case 'disconnected':
case 'failed':
onError(status);
this.log.warn('One or more transports has terminated unexpectedly or in an error', status);
break;
default:
this.log.debug('The ice connection status changed', pc.iceConnectionState);
break;
}
}
pc.onicegatheringstatechange = () => {
switch (pc.iceGatheringState) {
case 'new':
this.log.debug('ice gathering new');
break;
case 'complete':
this.log.debug('ice gathering complete');
const event_to_emit = {
type: 'rtc:new',
cid: this.parentConversation.id,
from: this.parentConversation.me.id,
body: {
offer: this.parentConversation.pc.localDescription
}
}
if (params && params.label) {
event_to_emit.label = params.label;
}
this.application.session.sendRequest(event_to_emit, (response) => {
if (response.type === 'rtc:new:success') {
this.application.activeStream.rtc_id = response.body.rtc_id;
pc.trace('rtc_id', this.application.activeStream.rtc_id);
//dont resolve yet, wait for the answer
// resolve(response.type);
} else {
reject(new NexmoApiError(response));
}
});
break;
case 'gathering':
this.log.debug('ice gathering gathering');
break;
}
}
})
.then(() => {
// We want to be able to handle these events, for this member, before they get propagated out
this.parentConversation.on('rtc:answer', 'media_module', (event) => {
if (this.application.activeStream.rtc_id !== event.body.rtc_id) {
this.log.warn("RTC: skipping rtc answer for different rtc_id");
return;
}
if (!this.parentConversation.pc) {
// this .log.warn('RTC: received an answer too late');
return;
}
this.parentConversation.pc.setRemoteDescription(new RTCSessionDescription({
type: 'answer',
sdp: event.body.answer
}),
() => {
this.log.debug('remote description is set');
},
onError);
});
//on member delete (our this)
//terminate media
this.parentConversation.on('member:left', 'media_module', (member) => {
if (member.user.id === this.application.me.id && this.application.activeStream) {
this.disable();
}
});
})
.catch((error) => {
reject(new NexmoClientError(error));
});
}
});
}
_findRtcObjectByType(type) {
return Object.values(this.parentConversation.rtcObjects)
.find((rtcObject) => rtcObject.type === type);
}
update(params) {
return new Promise((resolve, reject) => {
this._validateUpdateParams(params)
.then(() => {
if (params.video) {
const rtcObject = this._findRtcObjectByType('video');
if ((rtcObject && params.video.direction) || (!rtcObject && !params.video.direction)) {
return reject(new NexmoClientError('error:media:update:invalid'));
}
} else if (params.screenshare) {
const rtcObject = this._findRtcObjectByType('screenshare');
if ((rtcObject && params.screenshare.direction) || (!rtcObject && !params.screenshare.direction)) {
return reject(new NexmoClientError('error:media:update:invalid'));
}
}
return this._handleVideo(params).then(resolve).catch(reject);
}).catch(err => reject(err));
})
}
_validateUpdateParams(params) {
return new Promise((resolve, reject) => {
if (params && (params.video || params.screenshare)) {
if (params.video && params.screenshare) {
return reject(new NexmoClientError('error:media:update:streams'));
}
} else {
return reject(new NexmoClientError('error:media:update:unsupported'));
}
resolve();
});
}
_closeStream(stream) {
stream.getTracks().forEach((track) => {
track.stop();
});
}
/**
* Disable media particiaption in the conversation for this application
*
* @returns {Promise}
* @example
*
* function disable() {
* conversation.media.disable()
* .then((response) => {
* }).catch((error) => {
* console.log(error);
* });
* }
*
**/
disable() {
this.parentConversation.releaseGroup('media_module');
if (this.parentConversation.remoteMembers) {
this.parentConversation.remoteMembers.forEach((member) => {
this._deleteMemberMedia(member);
});
}
delete this.parentConversation.remoteMembers;
let promises = [];
promises.push(this._disableActiveStream());
promises.push(this._cleanConversationProperties());
for (const leg_id in this.parentConversation.rtcObjects) {
promises.push(this._disableLeg(leg_id));
}
return Promise.all(promises);
}
_disableActiveStream() {
if (!this.application.activeStream || !this.application.activeStream.rtc_id) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
this.application.session.sendRequest({
type: 'rtc:terminate',
cid: this.parentConversation.id,
from: this.parentConversation.me.id,
rtc_id: this.application.activeStream.rtc_id
}, (response) => {
if (response.type === 'rtc:terminate:success') {
resolve(response.type);
} else {
//make sure we have cleaned the objects
reject(new NexmoApiError(response));
}
});
});
}
_cleanConversationProperties() {
return Promise.resolve().then(() => {
if (this.parentConversation.pc) this.parentConversation.pc.close();
if (this.parentConversation.remoteMembers) {
this.parentConversation.remoteMembers.forEach((member) => {
this._deleteMemberMedia(member);
});
}
// stop active stream
this.log.debug(this.application);
this.log.debug(this.parentConversation);
if (this.application.localStream) {
this._closeStream(this.application.localStream);
}
if (this.application.activeStream && this.application.activeStream.stream) {
this._closeStream(this.application.activeStream.stream);
}
if (this.parentConversation.localStream) {
this._closeStream(this.parentConversation.localStream);
}
delete this.parentConversation.pc;
delete this.parentConversation.localStream;
delete this.application.activeStream;
delete this.parentConversation.remoteMembers;
});
}
_disableLeg(leg_id) {
const csRequestPromise = new Promise((resolve, reject) => {
this.application.session.sendRequest({
type: 'rtc:terminate',
cid: this.parentConversation.id,
from: this.parentConversation.me.id,
rtc_id: leg_id
}, (response) => {
if (response.type === 'rtc:terminate:success') {
resolve(response.type);
} else {
//make sure we have cleaned the objects
reject(new NexmoApiError(response));
}
});
});
const closeResourcesPromise = Promise.resolve().then(() => {
if (this.parentConversation.rtcObjects[leg_id].pc) this.parentConversation.rtcObjects[leg_id].pc.close();
if (this.parentConversation.rtcObjects[leg_id].localStream) {
this._closeStream(this.parentConversation.rtcObjects[leg_id].localStream);
}
});
return Promise.all([csRequestPromise, closeResourcesPromise]).then(() => {
this.parentConversation.me.emit("media:stream:off", this.parentConversation.rtcObjects[leg_id].streamIndex);
delete this.parentConversation.rtcObjects[leg_id];
return Promise.resolve('rtc:terminate:success')
}).catch((error) => {
return Promise.reject(error);
});
}
/**
* Mute our member
*
* @param {int} [streamIndex] stream id to set
* @param {Boolean} [mute] true for mute, false for unmute
* @param {Boolean} [audio=true] true for audio stream
* @param {Boolean} [video=false] true for video stream
* @example <caption>Mute audio stream</caption>
* media.mute(true, true, false)
* @example <caption>Mute audio and video streams</caption>
* media.mute(true, true, true)
* @example <caption>Mute only video</caption>
* media.mute(true, false, true)
*/
mute(mute, audio = true, video = false, streamIndex) {
let tracks = [];
const state = mute ? 'on' : 'off';
const audioType = 'audio:mute:' + state;
const videoType = 'video:mute:' + state;
const audioSuccess = audioType + ':success';
const videoSuccess = videoType + ':success';
let promises = [];
const self = this;
if (audio) {
let rtcObjects = [];
if (streamIndex !== undefined) {
const rtcObject = Object.values(this.parentConversation.rtcObjects).find((rtcObj => rtcObj.streamIndex === streamIndex));
if (rtcObject) {
tracks = tracks.concat(rtcObject.localStream.getAudioTracks());
rtcObjects.push(rtcObject);
}
} else {
rtcObjects = rtcObjects.concat(Object.values(this.parentConversation.rtcObjects));
}
rtcObjects.forEach((rtcObject) => {
let audioPromise = new Promise((resolve, reject) => {
this._sendMuteRequest(rtcObject.id, audioType, (response) => {
if (response.type === audioSuccess) {
resolve(response.body);
} else {
reject(new NexmoApiError(response));
}
})
});
promises.push(audioPromise);
});
if (this.application.activeStream && this.application.activeStream.rtc_id) {
const rtc_id = this.application.activeStream.rtc_id;
tracks = tracks.concat(this.parentConversation.localStream.getVideoTracks());
let audioPromise = new Promise((resolve, reject) => {
this._sendMuteRequest(rtc_id, audioType, (response) => {
if (response.type === audioSuccess) {
resolve(response.body);
} else {
reject(new NexmoApiError(response));
}
})
});
promises.push(audioPromise);
}
}
if (video) {
let rtcObjects = [];
if (streamIndex !== undefined) {
const rtcObject = Object.values(this.parentConversation.rtcObjects).find((rtcObj => rtcObj.streamIndex === streamIndex));
if (rtcObject) {
tracks = tracks.concat(rtcObject.localStream.getVideoTracks());
rtcObjects.push(rtcObject);
}
} else {
rtcObjects = rtcObjects.concat(Object.values(this.parentConversation.rtcObjects));
}
rtcObjects.forEach((rtcObject) => {
let videoPromise = new Promise((resolve, reject) => {
this._sendMuteRequest(rtcObject.id, videoType, (response) => {
if (response.type === videoSuccess) {
resolve(response.body);
} else {
reject(new NexmoApiError(response));
}
})
});
promises.push(videoPromise);
});
}
this._enableMediaTracks(tracks, !mute);
return Promise.all(promises).catch(function(response) {
self._enableMediaTracks(tracks, mute);
throw response;
});
}
_sendMuteRequest(rtc_id, type, callback) {
let params = { rtc_id: rtc_id };
let request = {
type: type,
cid: this.parentConversation.id,
to: this.parentConversation.me.id,
from: this.parentConversation.me.id,
body: params
};
this.application.session.sendRequest(request, callback);
}
_enableMediaTracks(tracks, enabled) {
tracks.forEach((mediaTrack) => {
mediaTrack.enabled = enabled;
});
}
/**
* Play a voice text in a conversation
* @param {object} params
* @param {string} params.text - the text to say in the conversation
* @param {string} params.voice_name -
* @param {number} params.level - [0] -
* @param {Boolean} params.queue -
* @param {Boolean} params.loop -
*
* @returns {Promise<Event>}
* @example
* conversation.media.say({text:'hi'})
**/
sayText(params) {
return new Promise((resolve, reject) => {
const msg = {
type: 'audio:say',
cid: this.parentConversation.id,
body: {
text: params.text,
voice_name: params.voice_name || 'Amy',
level: params.level || 1,
queue: params.queue || true,
loop: params.loop || 1,
ssml: params.ssml || false
}
};
this.application.session.sendRequest(msg, (response) => {
if (response.type === 'audio:say:success') {
msg.id = response.body.id;
resolve(new Event(this.parentConversation, response));
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Record the audio stream in a conversation
* @param {object} params
* @param {string} params.format = (mp3, wav, ogg)
* @param {Boolean} params.streamed -
* @param {number} params.validity_time -
* @param {Boolean} params.beep_start -
* @param {Boolean} params.beep_stop -~
* @param {Boolean} params.detect_speech -
*
* @returns {Promise<Recording>}
* @example
* conversation.audio.record()
*/
record(params) {
return new Promise((resolve, reject) => {
const msg = {
type: 'audio:record',
cid: this.id,
body: {
format: params.format,
destination_url: params.destination_url,
streamed: params.streamed,
validity_time: params.validity_time,
beep_start: params.beep_start,
beep_stop: params.beep_stop,
detect_speech: params.detect_speech
}
};
this.application.session.sendRequest(msg, (response) => {
if (response.type === 'audio:record:success') {
msg.id = response.body.id;
resolve(new Recording(this.parentConversation, response));
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Download the recoding file
* @param {string} url the recording url coming in the recording event
* @returns {Promise<Event>}
*/
fetchRecording(url) {
return new Promise((resolve, reject) => {
if (!localStorage.getItem("NXMO_user_data")) {
reject(new NexmoClientError("error:user:relogin"));
} else {
const xhr = new XMLHttpRequest();
const token = JSON.parse(localStorage.getItem("NXMO_user_data")).token;
xhr.open("GET", url);
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
const blob = new Blob([xhr.response], {
type: 'audio/ogg'
});
resolve(URL.createObjectUrl(blob));
} else {
reject(new NexmoClientError("error:fetch-recording"));
}
};
xhr.send();
}
});
}
/**
* Play an audio stream in a conversation
* @returns {Promise<Event>}
*/
playStream(params) {
return new Promise((resolve, reject) => {
const msg = {
type: 'audio:play',
cid: this.parentConversation.id,
body: params
};
this.application.session.sendRequest(msg, (response) => {
if (response.type === 'audio:play:success') {
msg.id = response.body.id;
resolve(new Event(this.parentConversation, response));
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Send start ringing event
* @returns {Promise<Event>}
* @example
* Send ringing event
* function startRinging() {
* conversation.media.startRinging()
* .then((response) => {
* }).catch((error) => {
* console.log(error);
* });
* }
*
* conversation.on('audio:ringing:start', (data) => {
* console.log("ringing");
* });
*/
startRinging() {
return new Promise((resolve, reject) => {
const msg = {
type: 'audio:ringing:start',
cid: this.parentConversation.id,
from: this.parentConversation.me.id,
body: {}
};
this.application.session.sendRequest(msg, (response) => {
if (response.type === 'audio:ringing:start:success') {
resolve(new Event(this.parentConversation, response));
} else {
reject(new NexmoApiError(response));
}
});
});
}
/**
* Send stop ringing event
* @returns {Promise<Event>}
* @example
* Send ringing event
* function stopRinging() {
* conversation.media.stopRinging()
* .then(function(response) {
* }).catch(function(error) {
* console.log(error);
* });
* }
*
* conversation.on('audio:ringing:stop', function(data)){
* console.log("ringing stopped");
* }
*/
stopRinging() {
return new Promise((resolve, reject) => {
const msg = {
type: 'audio:ringing:stop',
cid: this.parentConversation.id,
from: this.parentConversation.me.id,
body: {}
};
this.application.session.sendRequest(msg, (response) => {
if (response.type === 'audio:ringing:stop:success') {
resolve(new Event(this.parentConversation, response));
} else {
reject(new NexmoApiError(response));
}
});
});
}
}
|
JavaScript
|
class RtcHelper {
constructor(screenShareExtensionId) {
this.log = logger.getLogger(this.constructor.name);
this.chromeHelper = new ChromeHelper(screenShareExtensionId);
}
getUserAudio() {
return navigator.mediaDevices.getUserMedia({
video: false,
audio: true
});
}
getUserVideo() {
return navigator.mediaDevices.getUserMedia({
video: true,
audio: true
});
}
getUserScreen(sources) {
return this.checkBrowserRunOnHttps()
.then(() => {
return this.checkChromeExtensionIsInstalled();
})
.then(() => {
return this.getShareScreenStream(sources);
});
}
createRTCPeerConnection(config, constraints, clientId) {
constraints.optional.push({ clientId: clientId });
return new RTCPeerConnection(config, constraints);
}
checkBrowserRunOnHttps() {
return new Promise((resolve, reject) => {
if (this._getWindowLocationProtocol() !== 'https:') {
reject(new NexmoClientError('error:media:unsupported-browser'));
}
resolve();
});
}
checkChromeExtensionIsInstalled() {
return new Promise((resolve, reject) => {
if (this._getBrowserName() === 'chrome') {
this.chromeHelper.checkScreenShareInstalled()
.then(()=>resolve())
.catch((err)=>reject(err));
} else {
// Firefox or others, no need for the extension (but this doesn't mean it will work)
return resolve();
}
});
}
getShareScreenStream(sources) {
switch (this._getBrowserName()) {
case 'chrome':
return this.chromeGetShareScreenStream(sources);
case 'firefox':
return this.fireFoxGetShareScreenStream();
default:
return Promise.reject(new NexmoClientError('error:media:unsupported-browser'));
}
}
fireFoxGetShareScreenStream() {
let constraints = {
video: {
mozMediaSource: 'screen',
mediaSource: 'screen',
},
audio: false,
};
return new Promise((resolve, reject) => {
navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
resolve(stream);
}).catch((e) => {
reject(e);
});
});
}
chromeGetShareScreenStream(sources) {
return new Promise((resolve, reject) => {
this.chromeHelper.getScreenShare(sources)
.then((streamId)=> {
const constraints = {
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
maxWidth: window.screen.width,
maxHeight: window.screen.height,
maxFrameRate: 15,
chromeMediaSourceId: streamId
},
optional: []
}
};
return navigator.mediaDevices.getUserMedia(constraints)
.then((stream) => resolve(stream))
.catch(err => reject(err));
})
.catch(err=>reject(err));
});
}
firefoxGetShareScreenStream() {
Promise.reject(new NexmoClientError('Not support'));
}
_getWindowLocationProtocol() {
return window.location.protocol;
}
_getBrowserName() {
return browser.name;
}
isNode() {
return browser.name === 'node';
}
}
|
JavaScript
|
class ConversationClient {
constructor(params) {
//save an array of instances
const options = params || {};
const config = this.config = {
autoConnect: true,
bugsnag_key: 'cd2dcd56892c3cd260b12caf6eecf022',
cache: true,
debug: false,
enable_log_reporter: true,
environment: 'production',
forceNew: true,
ips_url: 'https://api.nexmo.com/v1/image',
path: '/rtc',
reconnection: true,
repository: 'https://github.com/Nexmo/conversation-js-sdk',
SDK_version: '1.0.9',
url: 'https://ws.nexmo.com',
iceServers: {
urls: 'stun:stun.l.google.com:19302'
},
rtcstarts_enables: false,
rtcstarts_url: '@@rtcstarts_url'
};
let connection;
this.sessionReady = false;
this.requests = {};
this.application = null;
// set our config from options
Object.assign(this.config, options);
if (config.debug === true) {
logger.setLevel("debug");
} else {
logger.setLevel("silent");
}
this.log = logger.noConflict();
//inject bug reporting tool
if (config.enable_log_reporter) {
function j(u, c) {
let h = document.getElementsByTagName('head')[0],
s = document.createElement('script');
s.async = true;
s.src = u;
s.onload = s.onreadystatechange = function() {
if (!s.readyState || /loaded|complete/.test(s.readyState)) {
s.onload = s.onreadystatechange = null;
s = undefined;
if (c) {
c();
}
}
};
h.insertBefore(s, h.firstChild);
}
if (typeof document !== "undefined") {
j("//d2wy8f7a9ursnm.cloudfront.net/bugsnag-3.min.js", () => {
if (typeof Bugsnag !== "undefined") {
if (!Bugsnag.apiKey) {
Bugsnag.apiKey = this.config.bugsnag_key;
Bugsnag.releaseStage = this.config.environment;
Bugsnag.appVersion = this.config.SDK_version;
Bugsnag.repository = this.config.repository;
Bugsnag.disableAutoBreadcrumbs();
}
}
});
}
}
// Create the socket.io connection and allow multiple instances
connection = socket_io.connect(config.url, {
path: config.path,
forceNew: config.forceNew,
reconnection: config.reconnection,
autoConnect: config.autoConnect
});
this.connection = connection;
if (config.cache) {
this.cache = new RTC_Cache(this);
this.cache.init(this);
}
/**
* Ready event.
*
* @event ConversationClient#ready
* @example <caption>Listen to websocket ready event </caption>
* rtc.on("ready", () => {
* console.log("connection ready");
* });
*/
connection.on('connect', () => {
this.emit('ready');
this.sessionReady = true;
this.log.info('websocket ready');
});
// Listen to socket.io events
/**
* Connecting event.
*
* @event ConversationClient#connecting
* @example <caption>Listen to websocket connecting event </caption>
* rtc.on("connecting", () => {
* console.log("connecting");
* });
*/
connection.on('connecting', () => {
this.emit('connecting');
this.log.info('websocket connecting');
});
/**
* Disconnect event.
*
* @event ConversationClient#disconnect
* @example <caption>Listen to websocket disconnect event </caption>
* rtc.on("disconnect", () => {
* console.log("disconnect");
* });
*/
connection.on('disconnect', () => {
this.emit('disconnect');
this.log.info('websocket disconnected');
});
/**
* Reconnect event.
*
* @event ConversationClient#reconnect
* @example <caption>Listen to websocket reconnect event </caption>
* rtc.on("reconnect", (retry_number) => {
* console.log("reconnect", retry_number);
* });
*/
connection.on('reconnect', (retry_number) => {
this.emit('reconnect', retry_number);
if (this.cache && this.cache.user_data) {
this.login(this.cache.user_data.token);
this.log.info('websocket reconnected');
}
});
/**
* Reconnecting event.
*
* @event ConversationClient#reconnecting
* @example <caption>Listen to websocket reconnecting event </caption>
* rtc.on("reconnecting", (retry_number) => {
* console.log("reconnecting", retry_number);
* });
*/
connection.on('reconnecting', (retry_number) => {
this.emit('reconnecting', retry_number);
this.log.info('websocket reconnecting');
});
/**x
* Error event.
*
* @event ConversationClient#error
* @example <caption>Listen to websocket error event </caption>
* rtc.on("error", (error) => {
* console.log("error", error);
* });
*/
connection.on('error', (error) => {
this.emit('error', new NexmoClientError(error))
this.log.error("Socket.io reported a generic error", error);
});
connection.io.on('packet', (packet) => {
if (packet.type !== 2) return;
if (packet.data[0] === 'echo') return; //ignore echo events
const response = packet.data[1];
// Set the type of the response
response.type = packet.data[0];
this.log.debug('<--', response.type, response);
if (response.rid in this.requests) {
const callback = this.requests[response.rid].callback;
delete this.requests[response.rid];
delete response.delay;
callback(response);
} else {
// This is an unsolicited event
// we emit it in application level.
if (this.application)
this.application._handleEvent(response);
}
});
WildEmitter.mixin(ConversationClient);
}
/**
* Conversation listening for text events.
*
* @event Conversation#text
*
* @property {Member} sender - The sender of the text
* @property {Text} text - The text message received
* @example <caption>listen for text events</caption>
* conversation.on("text",(sender, message) => {
* console.log(sender,message);
*
* // Identify your own message.
* if (message.from !== conversation.me.id)
*
* // Identify if the event corresponds to the currently open conversation.
* if (message.cid === conversation.id)
* });
*/
/**
*
* Conversation listening for image events.
*
* @event Conversation#image
*
* @property {Member} sender - The sender of the image
* @property {ImageEvent} image - The image message received
* @example <caption>listen for image events</caption>
* conversation.on("image", (sender, image) => {
* console.log(sender,image);
*
* // Identify your own imageEvent.
* if (image.from !== conversation.me.id)
*
* // Identify if the event corresponds to the currently open conversation.
* if (image.cid === conversation.id)
* });
*/
/**
* Conversation listening for deleted events.
*
* @event Conversation#event:delete
*
* @property {Member} member - the member who deleted an event
* @property {Event} event - deleted event: event.id
* @example <caption>get details about the deleted event</caption>
* conversation.on("event:delete", (member, event) => {
* console.log(event.id);
* console.log(event.body.timestamp.deleted);
* });
*/
/**
* Conversation listening for new members.
*
* @event Conversation#member:joined
*
* @property {Member} member - the member that joined
* @property {Event} event - the join event
* @example <caption>get the name of the new member</caption>
* conversation.on("member:joined", (member, event) => {
* console.log(event.id)
* console.log(member.user.name+ " joined the conversation");
* });
*/
/**
* Conversation listening for members being invited.
*
* @event Conversation#member:invited
*
* @property {Member} member - the member that is invited
* @property {Event} event - data regarding the receiver of the invitation
* @example <caption>get the name of the invited member</caption>
* conversation.on("member:invited", (member, event) => {
* console.log(member.user.name + " invited to the conversation");
* });
*/
/**
* Conversation listening for members leaving (kicked or left).
*
* @event Conversation#member:left
*
* @property {Member} member - the member that has left
* @property {Event} event - data regarding the receiver of the invitation
* @example <caption>get the username of the member that left</caption>
* conversation.on("member:left", (member , event) => {
* console.log(member.user.name + " left");
* });
*/
/**
* Conversation listening for members typing.
*
* @event Conversation#text:typing:on
*
* @property {Member} member - the member that started typing
* @property {Event} event - the start typing event
* @example <caption>get the username of the member that is typing</caption>
* conversation.on("text:typing:on", (data) => {
* console.log(data.name + " is typing...");
* });
*/
/**
* Conversation listening for members stopped typing.
*
* @event Conversation#text:typing:off
*
* @property {Member} member - the member that stopped typing
* @property {Event} event - the stop typing event
* @example <caption>get the username of the member that stopped typing</caption>
* conversation.on("text:typing:off", (data) => {
* console.log(data.name + " stopped typing...");
* });
*/
/**
* Conversation listening for members' seen texts.
*
* @event Conversation#text:seen
*
* @property {Member} member - the member that saw the text
* @property {Text} text - the text that was seen
* @example <caption>listen for seen text events</caption>
* conversation.on("text:seen", (data, text) => {
* console.log(text);
*
* // Check if the event belongs to this conversation
* if (text.cid === conversation.id)
*
* // Get the list of members that have seen this event
* for (let member_id in text.state.seen_by) {
* if (conversation.me.id !== member_id) {
* console.log(conversation.members[member_id].name);
* }
* }
* });
*/
/**
* Conversation listening for members' seen images.
* @event Conversation#image:seen
*
* @property {Member} member - the member that saw the image
* @property {ImageEvent} image - the image that was seen
* @example <caption>listen for seen image events</caption>
* conversation.on("image:seen", (data, image) => {
* console.log(image);
*
* // Check if the event belongs to this conversation
* if (image.cid === conversation.id)
* // Get the list of members that have seen this event
* for (let member_id in image.state.seen_by) {
* if (conversation.me.id !== member_id) {
* console.log(conversation.members[member_id].name);
* }
* }
* });
*/
/**
* Conversation listening for members media changes (audio, video,text)
*
* Change in media presence state. They are in the conversation with text, audio or video.
*
* @event Conversation#member:media
*
* @property {Member} member - the member object linked to this event
* @property {Event} event - information about media presence state
* @property {boolean} event.body.audio - is audio enabled
* @example <caption>get every member's media change events </caption>
* conversation.on("member:media", (from, media) => {
* console.log(from.media.audio); //true
* console.log(event.body.media); //{"audio":true}
* });
*/
sendRequest(request, callback) {
// Add a message ID to the request and set up a listener for the reply (or error)
request.tid = Utils.allocateUUID();
const type = request.type;
delete request.type;
this.log.debug('-->', type, request);
this.log.info('-->', type, request.tid);
this.connection.emit(type, request);
this.requests[request.tid] = {
type: type,
request: request,
callback: callback
};
}
/**
* Login to the cloud.
*x
* @param {string} params.token - the login token
*/
login(token) {
// return a promise for the application
return new Promise((resolve, reject) => {
//make sure the token gets removed from localstorage
if (typeof (Storage) !== "undefined") {
localStorage.removeItem("NXMO_user_data");
}
this.sendRequest({
type: 'session:login',
body: {
token: token,
SDK_version: this.config.SDK_version,
//device_id: //can use https://github.com/Valve/fingerprintjs2,
OS_family: 'js',
OS_revision: (typeof navigator !== "undefined") ? navigator.userAgent : (typeof window !== "undefined") ? window.navigator.userAgent : "Generic JS navigator"
}
}, (response) => {
if (response.type === "session:success") {
const application = new Application(this);
const me = new User(application, {
id: response.body.user_id,
name: response.body.name
});
this.application = application;
this.application.me = me;
if (this.cache) this.cache.updateToken({
token: token,
username: response.body.name
});
// Retrieve the existing conversation data for this user
application.getConversations()
.then(() => {
// Complete the login process
resolve(this.application);
if (typeof Bugsnag !== "undefined") {
Bugsnag.user = {
id: application.me.id
};
}
}, (reason) => {
reject(new NexmoApiError(reason));
});
} else {
reject(new NexmoApiError(response));
//TODO move this in cache module
if (this.cache && this.cache.worker) {
this.cache.worker.terminate();
}
}
}
);
});
}
/**
* logout from the cloud.
*
*/
logout() {
return new Promise((resolve, reject) => {
const logoutRequest = () => {
return this.sendRequest({
type: 'session:logout',
body: {}
}, (response) => {
if (response.type === "session:logged-out" || response.type === "session:terminated") {
this.disconnect();
delete this.application;
delete this.cache;
this.callbacks = {};
this.requests = {};
this.sessionReady = false;
resolve(response);
} else {
reject(new NexmoApiError(response));
if (typeof Bugsnag !== "undefined") Bugsnag.notifyException(Error(response.reason));
}
});
}
// prepare for logout
if (this.application) {
let disablePromises = [];
for (let conversation_id in this.application.conversations) {
disablePromises.push(this.application.conversations[conversation_id].media.disable());
}
Promise.all(disablePromises)
.then(() => { }).catch((err) => { this.log.info(err); }).then(() => {
logoutRequest();
});
} else {
logoutRequest();
}
});
}
/**
* Disconnect from the cloud.
*
*/
disconnect() {
return this.connection.disconnect();
}
/**
* Connect from the cloud.
*
*/
connect() {
return this.connection.connect();
}
}
|
JavaScript
|
class Utils {
/**
* Get the Member from the username of a conversation
*
* @param {string} username the username of the member to get
* @param {Conversation} conversation the Conversation to search in
* @returns {Member} the requested Member
* @static
* @private
*/
static getMemberFromNameOrNull(conversation, username) {
if (!conversation || !username) return null;
for (var member_id in conversation.members) {
if (conversation.members[member_id].user.name === username) {
return conversation.members[member_id];
}
}
return null;
}
/**
* Perform a network GET request to the given url with the given data object
*
* @param {string} url the url to GET
* @param {object} [data] the data to send
* @returns {Promise<XMLHttpRequest.response>} the XMLHttpRequest.response
* @static
* @private
*/
static networkFetch(url, data) {
return Utils.getToken().then((token) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(this.response);
}
};
xhr.onerror = (error) => {
reject(new NexmoClientError(error));
}
xhr.send(data);
});
});
}
/**
* Perform a network POST request to the given url with the given data object
*
* @param {string} url the url to POST
* @returns {Promise<XMLHttpRequest>} the XMLHttpRequest
* @static
* @private
*/
static networkSend(url, data) {
return Utils.getToken().then((token) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.onloadstart = () => {
resolve(xhr);
};
xhr.onerror = (error) => {
reject(new NexmoClientError(error));
}
xhr.send(data);
});
});
}
static getToken() {
if (!localStorage.getItem("NXMO_user_data")) {
return Promise.reject(new NexmoClientError("error:user:relogin"));
} else {
return Promise.resolve(JSON.parse(localStorage.getItem("NXMO_user_data")).token);
}
}
static allocateUUID() {
return uuid.v4();
}
}
|
JavaScript
|
class Portrait extends Photo {
/**
* @param {!MediaStream} stream
* @param {!Facing} facing
* @param {?Resolution} captureResolution
* @param {!PhotoHandler} handler
*/
constructor(stream, facing, captureResolution, handler) {
super(stream, facing, captureResolution, handler);
}
/**
* @override
*/
async start_() {
if (this.crosImageCapture_ === null) {
this.crosImageCapture_ =
new CrosImageCapture(this.stream_.getVideoTracks()[0]);
}
let photoSettings;
if (this.captureResolution_) {
photoSettings = /** @type {!PhotoSettings} */ ({
imageWidth: this.captureResolution_.width,
imageHeight: this.captureResolution_.height,
});
} else {
const caps = await this.crosImageCapture_.getPhotoCapabilities();
photoSettings = /** @type {!PhotoSettings} */ ({
imageWidth: caps.imageWidth.max,
imageHeight: caps.imageHeight.max,
});
}
const filenamer = new Filenamer();
const refImageName = filenamer.newBurstName(false);
const portraitImageName = filenamer.newBurstName(true);
if (this.metadataObserverId_ !== null) {
[refImageName, portraitImageName].forEach((/** string */ imageName) => {
this.metadataNames_.push(Filenamer.getMetadataName(imageName));
});
}
let /** ?Promise<!Blob> */ reference;
let /** ?Promise<!Blob> */ portrait;
try {
[reference, portrait] = await this.crosImageCapture_.takePhoto(
photoSettings, [cros.mojom.Effect.PORTRAIT_MODE]);
this.handler_.playShutterEffect();
} catch (e) {
toast.show('error_msg_take_photo_failed');
throw e;
}
state.set(PerfEvent.PORTRAIT_MODE_CAPTURE_POST_PROCESSING, true);
let hasError = false;
/**
* @param {!Promise<!Blob>} p
* @param {string} imageName
* @return {!Promise}
*/
const saveResult = async (p, imageName) => {
const isPortrait = Object.is(p, portrait);
let /** ?Blob */ blob = null;
try {
blob = await p;
} catch (e) {
hasError = true;
toast.show(
isPortrait ? 'error_msg_take_portrait_bokeh_photo_failed' :
'error_msg_take_photo_failed');
throw e;
}
const {width, height} = await util.blobToImage(blob);
await this.handler_.handleResultPhoto(
{resolution: new Resolution(width, height), blob}, imageName);
};
const refSave = saveResult(reference, refImageName);
const portraitSave = saveResult(portrait, portraitImageName);
try {
await portraitSave;
} catch (e) {
hasError = true;
// Portrait image may failed due to absence of human faces.
// TODO(inker): Log non-intended error.
}
await refSave;
state.set(
PerfEvent.PORTRAIT_MODE_CAPTURE_POST_PROCESSING, false,
{hasError, facing: this.facing_});
}
}
|
JavaScript
|
class PortraitFactory extends PhotoFactory {
/**
* @override
*/
produce_() {
return new Portrait(
this.previewStream_, this.facing_, this.captureResolution_,
this.handler_);
}
}
|
JavaScript
|
class Cmd_Reload extends Command {
constructor(client) {
super(client, {
name: "reload",
description: "Reloads a command that has been modified.",
category: "System",
usage: "reload [command]",
permLevel: "Bot Admin"
});
}
async run(message, args) { // eslint-disable-line no-unused-vars
if (!args || args.size < 1)
return message.reply("Must provide a resource to reload. Derp.");
if (args[0] === 'dashboard')
{
this.client.site.close();
delete require.cache[require.resolve("../../util/dashboard.js")];
require("../../util/dashboard.js")(this.client);
message.reply(`The dashboard has been reloaded`);
}
else
{
const commands = this.client.commands.get(args[0]) || this.client.commands.get(this.client.aliases.get(args[0]));
if (!commands) return message.reply(`The command \`${args[0]}\` does not exist, nor is it an alias.`);
let response = await this.client.unloadCommand(commands.conf.location, commands.help.name);
if (response) return message.reply(`Error Unloading: ${response}`);
response = this.client.loadCommand(commands.conf.location, commands.help.name);
if (response) return message.reply(`Error loading: ${response}`);
message.reply(`The command \`${commands.help.name}\` has been reloaded`);
}
}
}
|
JavaScript
|
class CreateGoal extends React.Component {
static navigationOptions = { headerTitle: 'Create New Goal', headerLeft: null };
/**
* Creates an instance of CreateGoal.
*
* @param {*} props
* @memberof CreateGoal
*/
constructor(props) {
super(props);
this.userId = props.navigation.getParam('user_id');
this.state = {
goal_name: '',
isStartDateTimePickerVisible: false,
isEndDateTimePickerVisible: false,
startDate: Date.now(),
endDate: Date.now() * 2,
frequency: 'daily',
};
}
/**
* Toggle display of start date picker
*
* @memberof CreateGoal
*/
toggleStartDateTimePickerDisplay = () => {
this.setState({ isStartDateTimePickerVisible: !this.state.isStartDateTimePickerVisible });
};
/**
* Toggle display of end date picker
*
* @memberof CreateGoal
*/
toggleEndDateTimePickerDisplay = () => {
this.setState({ isEndDateTimePickerVisible: !this.state.isEndDateTimePickerVisible });
};
/**
* Sets date for start date of goal
*
* @memberof CreateGoal
*/
handleStartDatePicked = (date) => {
this.setState({ startDate: date.getTime() });
this.toggleStartDateTimePickerDisplay();
};
/**
* Sets date for end date of goal
*
* @memberof CreateGoal
*/
handleEndDatePicked = (date) => {
this.setState({ endDate: date.getTime() });
this.toggleEndDateTimePickerDisplay();
};
/**
* Make post request to add goal to database and return to dashboard
*
* @memberof CreateGoal
*/
makeGoal = async () => {
if (!this.state.goal_name) {
return;
}
await fetch(FETCH_CREATE_GOAL_URL, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
goal_user_id: this.userId,
goal_name: this.state.goal_name,
goal_start_date: this.state.startDate,
goal_end_date: this.state.endDate,
frequency: this.state.frequency,
}),
});
this.props.navigation.navigate('Dashboard');
};
render() {
return (
<>
<View
style={{
width: '90%',
height: '80%',
marginLeft: '5%',
marginTop: '40%',
}}
>
<TextInput
style={{
height: 40,
paddingLeft: 6,
fontSize: 25,
}}
onChangeText={(name) => this.setState({ goal_name: name })}
placeholder="Give your goal a name"
/>
<Button
title="Start Date"
onPress={this.toggleStartDateTimePickerDisplay}
style={{ width: '90%', marginLeft: '5%', marginTop: '5%' }}
/>
<DateTimePicker
isVisible={this.state.isStartDateTimePickerVisible}
onConfirm={this.handleStartDatePicked}
onCancel={this.toggleStartDateTimePickerDisplay}
/>
<Button
title="End Date"
color="orange"
onPress={this.toggleEndDateTimePickerDisplay}
style={{ width: '90%', marginLeft: '5%', marginTop: '5%' }}
/>
<DateTimePicker
isVisible={this.state.isEndDateTimePickerVisible}
onConfirm={this.handleEndDatePicked}
onCancel={this.toggleEndDateTimePickerDisplay}
/>
<Button title="Submit" style={{ marginTop: '20%' }} onPress={this.makeGoal} />
</View>
</>
);
}
}
|
JavaScript
|
class roleController {
/**
* Method createRole
* @param {Object} request - request Object
* @param {Object} response - request Object
* @return {Object} response Object
*/
static createRole(request, response) {
model.Role.sync();
model.Role.create(request.body)
.then((newRole) => {
response.status(201).send(newRole)
})
.catch(error => response.status(400).send(error.message)
);
}
/**
* Method getRoles to obtain all roles
* @param {Object} request - request Object
* @param {Object} response - request Object
* @return {Object} response Object
*/
static getRoles(request, response) {
const limit = request.query.limit || '10';
const offset = request.query.offset || '0';
model.Role.findAndCountAll({
limit,
offset,
order: '"createdAt" ASC'
})
.then((roles) => {
if (!roles) {
return response.status(404).send({ msg: 'role does not exist' });
}
const metadata = limit && offset ? { totalCount: roles.count,
pages: Math.ceil(roles.count / limit),
currentPage: Math.floor(offset / limit) + 1,
pageSize: roles.rows.length } : null;
return response.status(200).send({ roles: roles.rows, metadata });
})
.catch(error => response.status(400).send(error.message));
}
}
|
JavaScript
|
class AbstractService {
/**
* @param {PSV.Viewer} psv
*/
constructor(psv) {
/**
* @summary Reference to main controller
* @type {PSV.Viewer}
* @readonly
*/
this.psv = psv;
/**
* @summary Configuration holder
* @type {PSV.Options}
* @readonly
*/
this.config = psv.config;
/**
* @summary Properties holder
* @type {Object}
* @readonly
*/
this.prop = psv.prop;
}
/**
* @summary Destroys the service
*/
destroy() {
delete this.psv;
delete this.config;
delete this.prop;
}
}
|
JavaScript
|
class AuthManager {
constructor () {
this._serializers = {}
this._schemes = {}
}
/**
* Extend authenticator by adding a new scheme or serializer.
* You make use of this method via `Ioc.extend` interface
*
* @method extend
*
* @param {String} key
* @param {Object} implementation
* @param {String} type
*
* @return {void}
*/
extend (key, implementation, type) {
if (type === 'scheme') {
this._schemes[key] = implementation
return
}
if (type === 'serializer') {
this._serializers[key] = implementation
return
}
throw GE
.InvalidArgumentException
.invalidParameter(`Auth.extend type must be a serializer or scheme, instead received ${type}`)
}
/**
* Returns the instance of a given serializer
*
* @method getSerializer
*
* @param {String} name
*
* @return {Object}
*/
getSerializer (name) {
const serializer = Serializers[name] || this._serializers[name]
if (!serializer) {
throw GE.RuntimeException.incompleteConfig([`${name} serializer`], 'config/auth.js', 'auth')
}
return ioc.make(serializer)
}
/**
* Returns the instance of a given scheme
*
* @method getScheme
*
* @param {String} name
*
* @return {Object}
*/
getScheme (name) {
const scheme = Schemes[name] || this._schemes[name]
if (!scheme) {
throw GE.RuntimeException.incompleteConfig([`${name} scheme`], 'config/auth.js', 'auth')
}
return ioc.make(scheme)
}
}
|
JavaScript
|
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(a, b) {
if (a instanceof Point == false || b instanceof Point == false) {
throw new TypeError('Parameter must be of type Point');
}
return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2);
}
}
|
JavaScript
|
class CustomState extends state_1.State {
/**
* @experimental
*/
constructor(scope, id, props) {
super(scope, id, {});
this.endStates = [this];
this.stateJson = props.stateJson;
}
/**
* (experimental) Continue normal execution with the given state.
*
* @experimental
*/
next(next) {
super.makeNext(next.startState);
return __1.Chain.sequence(this, next);
}
/**
* (experimental) Returns the Amazon States Language object for this state.
*
* @experimental
*/
toStateJson() {
return {
...this.renderNextEnd(),
...this.stateJson,
};
}
}
|
JavaScript
|
class EventedState extends ToMix {
// eslint-disable-next-line jsdoc/check-param-names
/**
* The internal implementation for {@link EventedState#changeState `.changeState()`}, performing actual change in state.
* @param {string} [state] The new state. Can be an omitted, which means toggling.
* @param {Object} [detail]
* The object that should be put to event details that is fired before/after changing state.
* Can have a `group` property, which specifies what state to be changed.
* @param {EventedState~changeStateCallback} callback The callback called once changing state is finished or is canceled.
* @private
*/
_changeState() {
throw new Error(
'_changeState() should be overriden to perform actual change in state.'
);
}
// eslint-disable-next-line jsdoc/check-param-names
/**
* Changes the state of this component.
* @param {string} [state] The new state. Can be an omitted, which means toggling.
* @param {Object} [detail]
* The object that should be put to event details that is fired before/after changing state.
* Can have a `group` property, which specifies what state to be changed.
* @param {EventedState~changeStateCallback} [callback] The callback called once changing state is finished or is canceled.
*/
changeState(...args) {
const state = typeof args[0] === 'string' ? args.shift() : undefined;
const detail =
Object(args[0]) === args[0] && typeof args[0] !== 'function'
? args.shift()
: undefined;
const callback = typeof args[0] === 'function' ? args.shift() : undefined;
if (
typeof this.shouldStateBeChanged === 'function' &&
!this.shouldStateBeChanged(state, detail)
) {
if (callback) {
callback(null, true);
}
return;
}
const data = {
group: detail && detail.group,
state,
};
const eventNameSuffix = [data.group, state]
.filter(Boolean)
.join('-')
.split('-') // Group or state may contain hyphen
.map(item => item[0].toUpperCase() + item.substr(1))
.join('');
const eventStart = new CustomEvent(
this.options[`eventBefore${eventNameSuffix}`],
{
bubbles: true,
cancelable: true,
detail,
}
);
const fireOnNode = (detail && detail.delegatorNode) || this.element;
const canceled = !fireOnNode.dispatchEvent(eventStart);
if (canceled) {
if (callback) {
const error = new Error(
`Changing state (${JSON.stringify(data)}) has been canceled.`
);
error.canceled = true;
callback(error);
}
} else {
const changeStateArgs = [state, detail].filter(Boolean);
this._changeState(...changeStateArgs, () => {
fireOnNode.dispatchEvent(
new CustomEvent(this.options[`eventAfter${eventNameSuffix}`], {
bubbles: true,
cancelable: true,
detail,
})
);
if (callback) {
callback();
}
});
}
}
/**
* Tests if change in state should happen or not.
* Classes inheriting {@link EventedState `EventedState`} should override this function.
* @function EventedState#shouldStateBeChanged
* @param {string} [state] The new state. Can be an omitted, which means toggling.
* @param {Object} [detail]
* The object that should be put to event details that is fired before/after changing state.
* Can have a `group` property, which specifies what state to be changed.
* @returns {boolean}
* `false` if change in state shouldn't happen, e.g. when the given new state is the same as the current one.
*/
}
|
JavaScript
|
class MTNT {
constructor() {
this.url = "http://svc.metrotransit.org/NexTrip";
this.format = "json";
this.DIRECTION = {
SOUTH: 1,
EAST: 2,
WEST: 3,
NORTH: 4
};
}
getProviders() {
return new Promise((resolve, reject) => {
let result;
let data;
(async () => {
try {
result = await fetch(`${this.url}/Providers?format=${this.format}`);
data = await result.json();
} catch (error) {
return reject(error);
}
let modeled = data.map(provider => new Provider(provider));
return resolve(modeled);
})();
return undefined;
});
}
getRoutes() {
return new Promise((resolve, reject) => {
let result;
let data;
(async () => {
try {
result = await fetch(`${this.url}/Routes?format=${this.format}`);
data = await result.json();
} catch (error) {
return reject(error);
}
let modeled = data.map(route => new Route(route));
return resolve(modeled);
})();
return undefined;
});
}
getDirectionsForRoute(route_id) {
return new Promise((resolve, reject) => {
//No values given
if (!route_id) return reject(new Error("You must supply a route id."));
//Invalid value type
if (!(typeof route_id == "string") && isNaN(route_id)) return reject(new Error("Route id should be a number or a string."));
let result;
let data;
(async () => {
try {
result = await fetch(`${this.url}/Directions/${route_id}?format=${this.format}`);
data = await result.json();
} catch (error) {
return reject(error);
}
let modeled = data.map(direction => new Direction(direction));
return resolve(modeled);
})();
return undefined;
});
}
getStopsForRouteGoing(route_id, direction) {
return new Promise((resolve, reject) => {
//No values given
if (!route_id) return reject(new Error("You must supply a route id."));
if (!direction) return reject(new Error("You must supply a direction."));
//Invalid value type
if (!(typeof route_id == "string") && isNaN(route_id)) return reject(new Error("Route id should be a number or a string."));
if (direction < 1 || direction > 4) return reject(new Error("Direction must be between 1 and 4."));
let result;
let data;
(async () => {
try {
result = await fetch(`${this.url}/Stops/${route_id}/${direction}?format=${this.format}`);
data = await result.json();
} catch (error) {
return reject(error);
}
let modeled = data.map(stop => new Stop(stop));
return resolve(modeled);
})();
return undefined;
});
}
getDeparturesForRouteGoingAndEnding(route_id, direction, stop) {
return new Promise((resolve, reject) => {
//No values given
if (!route_id) return reject(new Error("You must supply a route id."));
if (!direction) return reject(new Error("You must supply a direction."));
if (!stop) return reject(new Error("You must supply a stop."));
//Invalid value type
if (!(typeof route_id == "string") && isNaN(route_id)) return reject(new Error("Route id should be a number or a string."));
if (direction < 1 || direction > 4) return reject(new Error("Direction must be between 1 and 4."));
if (!(typeof stop == "string") || stop.length != 4) return reject(new Error("Stop identifier must be a 4 character string."));
let result;
let data;
(async () => {
try {
result = await fetch(`${this.url}/${route_id}/${direction}/${stop}?format=${this.format}`);
data = await result.json();
} catch (error) {
return reject(error);
}
let modeled = data.map(departure => new Departure(departure));
return resolve(modeled);
})();
return undefined;
});
}
getVehicleLocationsForRoute(route_id) {
return new Promise((resolve, reject) => {
//No values given
if (!route_id) return reject(new Error("You must supply a route id."));
//Invalid value type
if (!(typeof route_id == "string") && isNaN(route_id)) return reject(new Error("Route id should be a number or a string."));
let result;
let data;
(async () => {
try {
result = await fetch(`${this.url}/VehicleLocations/${route_id}?format=${this.format}`);
data = await result.json();
} catch (error) {
return reject(error);
}
let modeled = data.map(vehicle_location => new VehicleLocation(vehicle_location));
return resolve(modeled);
})();
return undefined;
});
}
}
|
JavaScript
|
class LoginController {
/**
* Constructor of LoginController
*
* @param $state - service in module ui.router.state
* @param $rootScope - service in module ng
* @param AuthenticationService - service in module konko.authentication
* @constructs
*/
/*@ngInject;*/
constructor($state, $rootScope, AuthenticationService) {
// set locals const
AUTH.set(this, AuthenticationService);
STATE.set(this, $state);
// other vars
this.user = {};
this.alert = null;
// update html title
$rootScope.$broadcast('title_update', 'Login');
}
/**
* Logs an user in.
*
* @param {Boolean} isValid - Form validation
*/
login(isValid) {
if (!isValid) {
return false;
}
AUTH.get(this).login(this.user).then(data => {
this.alert = null;
AUTH.get(this).saveToken(data.data.token);
STATE.get(this).go(STATE.get(this).previous.state.name, STATE.get(this).previous.params, { reload: true });
}).catch(err => this.alert = { type: 'danger', message: err.data.message });
}
}
|
JavaScript
|
class ExtendedTextPresentationFactory {
constructor(classList, expectedLength) {
this.constants = {
// QTI 3 Shared Vocabulary constants
// Defines the Counter style
QTI_COUNTER_NONE: 'none',
QTI_COUNTER_UP: 'qti-counter-up',
QTI_COUNTER_DOWN: 'qti-counter-down',
// Defines the height of the input area of the control
QTI_HEIGHT_LINES_3: 'qti-height-lines-3',
QTI_HEIGHT_LINES_6: 'qti-height-lines-6',
QTI_HEIGHT_LINES_15: 'qti-height-lines-15',
SBAC_HEIGHT_LINES_95: 'sbac-height-lines-95',
// Sbac
SBAC_PRESENTATION: 'sbac'
}
this.classList = classList
this.expectedLength = expectedLength
// Default, 3 lines tall
this.presentation_HeightClass = this.constants.QTI_HEIGHT_LINES_3
// Default, hide character counter.
this.presentation_CounterStyle = this.constants.QTI_COUNTER_NONE
// Default, not sbac presentation.
this.presentation_Sbac = false
// Sniff for shared CSS vocabulary
this.processClassAttribute()
return this
}
/**
* @description The class attribute on the interaction may contain
* QTI 3 shared vocabulary.
*/
processClassAttribute () {
if ((typeof this.classList === 'undefined') || (this.classList === null) || (this.classList.length == 0)) {
return
}
const clazzTokens = this.classList.split(' ')
for (let index = 0; index < clazzTokens.length; index++) {
switch (clazzTokens[index]) {
case this.constants.SBAC_PRESENTATION:
this.presentation_Sbac = true
break
case this.constants.SBAC_HEIGHT_LINES_95:
this.presentation_HeightClass = this.constants.SBAC_HEIGHT_LINES_95
break
case this.constants.QTI_COUNTER_UP:
this.presentation_CounterStyle = 'up'
this.expectedLength = this.processExpectedLength()
break
case this.constants.QTI_COUNTER_DOWN:
this.presentation_CounterStyle = 'down'
this.expectedLength = this.processExpectedLength()
break
case this.constants.QTI_HEIGHT_LINES_3:
this.presentation_HeightClass = this.constants.QTI_HEIGHT_LINES_3
break
case this.constants.QTI_HEIGHT_LINES_6:
this.presentation_HeightClass = this.constants.QTI_HEIGHT_LINES_6
break
case this.constants.QTI_HEIGHT_LINES_15:
this.presentation_HeightClass = this.constants.QTI_HEIGHT_LINES_15
break
default:
} // end switch
} // end for
}
processExpectedLength () {
if ((typeof this.expectedLength === 'undefined') || (this.expectedLength === null) || (this.expectedLength.length == 0)) {
return 400
}
if (this.expectedLength === '0') {
return 400
}
return this.expectedLength*1
}
getCounterStyle () {
return this.presentation_CounterStyle
}
getHeightClass () {
return this.presentation_HeightClass
}
getExpectedLength () {
return this.expectedLength
}
getIsSbac () {
return this.presentation_Sbac
}
}
|
JavaScript
|
class Strategy {
/**
* @param {Array} solvers List of line solvers sorted by speed
* @param {boolean} randomize `false` to run trial and error in order. Defaults to `true`.
* In practice, using random guessing mostly yields faster results.
*/
constructor(solvers, randomize = true) {
this.solvers = solvers;
this.randomize = randomize;
}
/**
* Solve the puzzle.
* @param {Puzzle} puzzle The puzzle to solve
* @param {boolean} withTrialAndError `false` to stop without trial and error. Defaults to `true`.
*/
solve(puzzle, withTrialAndError = true) {
if (debugMode) {
var start = Date.now();
var statistics = Array(this.solvers.length).fill(0);
var solutionSequence = [];
}
// keep tracks of visited lines
this.visited = {
rows: Array(puzzle.height).fill(0).map(() => new Uint8Array(this.solvers.length)),
columns: Array(puzzle.width).fill(0).map(() => new Uint8Array(this.solvers.length))
};
// repeatedly run all solvers on puzzle
let progress;
do {
let snapshot = puzzle.snapshot;
progress = false;
this.solvers.forEach((solver, i) => {
if (progress) {
return;
}
// run one line solver on the whole puzzle
this.solveOnce(puzzle, solver, i, solutionSequence);
progress = puzzle.snapshot.toString() !== snapshot.toString();
if (debugMode) {
statistics[i]++;
}
});
} while(progress);
// no solution found… trial and error now
if (withTrialAndError && !puzzle.isFinished) {
if (debugMode) {
console.log('must start guessing');
}
let deepResult = guessAndConquer(this, puzzle);
if (deepResult) {
puzzle.import(deepResult);
}
}
if (debugMode) {
console.log(`Solution sequence: [${solutionSequence.join(',')}]`);
console.log(`Time elapsed: ${Date.now() - start}ms`);
console.log(`Runs (on puzzle) per solver: ${JSON.stringify(statistics)}`);
}
}
/**
* @private
* Run one solver on the puzzle
* @param {Puzzle} puzzle The puzzle to solve
* @param {Solver} solver The solver to use
* @param {number} solverIndex The solver's index in `this.solvers`
* @param {Array} solutionSequence Array of strings for statistics in debug mode
*/
solveOnce(puzzle, solver, solverIndex, solutionSequence) {
// If we're dealing with a slow solver, we want to skip as soon as one line is partially solved
let skipEarly = solver.speed === 'slow';
let skip = false;
// Optimize iteration order
let optimizeOrder = (lines, hints) => {
// remove already solved lines
let unsolvedLines = lines.reduce((result, line, index) => {
let zeros = line.reduce((count, x) => count + (x === 0 ? 1 : 0), 0);
if (!zeros) {
return result;
}
result.push({line, index, zeros});
return result;
}, []);
// sort by estimated computation effort
if (skipEarly) {
unsolvedLines.forEach(lineMeta => {
let {index, zeros} = lineMeta;
let hintSum = util.hintSum(hints[index]);
let estimate = zeros < hintSum ? 0 : Math.pow(zeros - hintSum, hints[index].length);
lineMeta.estimate = estimate;
});
unsolvedLines.sort(({estimate: left}, {estimate: right}) => left - right);
}
return unsolvedLines;
};
// the actual execution
let run = (lines, hints, onRow) => {
let visited = onRow ?
{current: this.visited.rows, other: this.visited.columns} :
{current: this.visited.columns, other: this.visited.rows};
let rearrangedLines = optimizeOrder(lines, hints);
rearrangedLines.forEach(({line, index: i, estimate}) => {
if (skip || visited.current[i][solverIndex]) {
return;
}
if (debugMode) {
console.log(`Running solver ${solverIndex} on ${onRow ? 'row' : 'column'} ${i}`, JSON.stringify(line.slice()), hints[i]);
if (estimate) {
console.log(`Estimated effort: ${estimate}`);
}
}
visited.current[i][solverIndex] = 1;
// First, trim unnecessary information from the line
let [trimmedLine, trimmedHints, trimInfo] = util.trimLine(line, hints[i]);
if (debugMode) {
var start = Date.now();
}
// solver run
let newLine = solver(trimmedLine, trimmedHints);
if (debugMode) {
let end = Date.now();
if (end - start > 100) {
console.log(`Long run: ${end - start}ms`);
}
}
// now, restore the trimmed line and analyze the result
let hasChanged = false;
let changedLines = [];
if (newLine) { // the solver may return null to indicate no progress
newLine = util.restoreLine(newLine, trimInfo);
line.forEach((el, i) => {
// What has changed?
if (el !== newLine[i]) {
line[i] = newLine[i];
// These perpendicular lines must be revisited
visited.other[i].fill(0);
if (debugMode) {
changedLines.push(i);
}
}
});
hasChanged = changedLines.length > 0;
skip = hasChanged && skipEarly;
}
if (!debugMode) {
util.spinner.spin();
} else if (hasChanged) {
console.log(`found ${newLine}`);
console.log(puzzle);
console.log(`Must revisit ${onRow ? 'column' : 'row'}${changedLines.length > 1 ? 's' : ''} ${changedLines.join(',')}`);
solutionSequence.push(`(${solverIndex})${onRow ? 'r' : 'c'}${i}[${changedLines.join(',')}]`);
}
});
};
// run on rows
run(puzzle.rows, puzzle.rowHints, true);
if (skip) {
return;
}
// …and then on columns
run(puzzle.columns, puzzle.columnHints);
}
}
|
JavaScript
|
class XLSXWriteStream extends _stream.Transform {
/**
* Create new stream transform that handles Array or Object as input chunks.
* Be aware that first row chunk is determinant in the transform configuration process for further row chunks.
* @class XLSXWriteStream
* @extends Transform
* @param {Object} [options]
* @param {Boolean} [options.header=false] - Display the column names on the first line if the columns option is provided or discovered.
* @param {Array|Object} [options.columns] - List of properties when records are provided as objects.
* Work with records in the form of arrays based on index position; order matters.
* Auto discovered in the first record when the user write objects, can refer to nested properties of the input JSON, see the `header` option on how to print columns names on the first line.
* @param {Boolean} [options.format=true] - If set to false writer will not format cells with number, date, boolean and text.
* @param {Object} [options.styleDefs] - If set you can overwrite default standard type styles by other standard ones or even define custom `formatCode`.
* @param {Boolean} [options.immediateInitialization=false] - If set to true writer will initialize archive and start compressing xlsx common stuff immediately, adding subsequently a little memory and processor footprint. If not, initialization will be delayed to the first data processing.
*/
constructor(options) {
super({
objectMode: true
});
this.pipelineInitialized = false;
this.initialized = false;
this.arrayMode = null;
this.options = (0, _defaultsDeep.default)({}, options, {
header: false,
format: true,
immediateInitialization: false
});
if (this.options.immediateInitialization) this._initializePipeline();
}
_transform(chunk, encoding, callback) {
if (!this.initialized) this._initialize(chunk);
this.toXlsxRow.write(this.normalize(chunk), encoding, callback);
}
_initialize(chunk) {
this._initializePipeline();
this._initializeHeader(chunk);
if (chunk) {
this.arrayMode = Array.isArray(chunk);
this.normalize = chunk => this.columns.map(key => chunk[key]);
}
this.initialized = true;
}
/**
* Initialize pipeline with xlsx archive common files
*/
_initializePipeline() {
if (this.pipelineInitialized) return;
this.zip = (0, _archiver.default)('zip', {
forceUTC: true
});
this.zip.catchEarlyExitAttached = true; // Common xlsx archive files (not editable)
this.zip.append(templates.ContentTypes, {
name: '[Content_Types].xml'
});
this.zip.append(templates.Rels, {
name: '_rels/.rels'
});
this.zip.append(templates.Workbook, {
name: 'xl/workbook.xml'
});
this.zip.append(templates.WorkbookRels, {
name: 'xl/_rels/workbook.xml.rels'
}); // Style xlsx definitions (one time generation)
const styles = new templates.Styles(this.options.styleDefs);
this.zip.append(styles.render(), {
name: 'xl/styles.xml'
});
this.zip.on('data', data => this.push(data)).on('warning', err => this.emit('warning', err)).on('error', err => this.emit('error', err));
this.toXlsxRow = new _XLSXRowTransform.default({
format: this.options.format,
styles
});
this.sheetStream = new _stream.PassThrough();
this.sheetStream.write(templates.SheetHeader);
this.toXlsxRow.pipe(this.sheetStream, {
end: false
});
this.zip.append(this.sheetStream, {
name: 'xl/worksheets/sheet1.xml'
});
this.pipelineInitialized = true;
}
_initializeHeader(chunk = []) {
if (Array.isArray(chunk)) {
this.columns = (this.options.columns ? this.options.columns : chunk).map((value, index) => index);
if (Array.isArray(this.options.columns)) {
this.header = [...this.options.columns];
} else if ((0, _isObject.default)(this.options.columns)) {
this.header = [...Object.values(this.options.columns)];
}
} else {
if (Array.isArray(this.options.columns)) {
this.header = [...this.options.columns];
this.columns = [...this.options.columns];
} else if ((0, _isObject.default)(this.options.columns)) {
this.header = [...Object.values(this.options.columns)];
this.columns = [...Object.keys(this.options.columns)];
} else {
// Init header and columns from chunk
this.header = [...Object.keys(chunk)];
this.columns = [...Object.keys(chunk)];
}
}
if (this.options.header && this.header) {
this.toXlsxRow.write(this.header);
}
}
_final(callback) {
if (!this.initialized) this._initialize();
this.toXlsxRow.end();
this.toXlsxRow.on('end', () => this._finalize().then(() => {
callback();
}));
}
/**
* Finalize the zip archive
*/
_finalize() {
this.sheetStream.end(templates.SheetFooter);
return this.zip.finalize();
}
}
|
JavaScript
|
class PasswordBuilder {
constructor() {
this.length = 15;
this.letters = "ABCDEFGHIJKLMNOPQRSTUVWXZY";
this.numbers = "0123456789";
this.symbols = "!@#$%^&*()";
this.conditionsToCheck = 3;
this.conditions = {
letters: false,
numbers: false,
symbols: false
};
this.charType = {
LETTER: "letters",
NUMBER: "numbers",
SYMBOL: "symbols"
};
}
setLength(length) {
// TODO: check validity
this.length = length;
return this;
}
setLetters(letters) {
if (letters.length === 0 || !letters) {
this.conditions[this.charType.LETTER] = true;
this.conditionsToCheck -= 1;
this.letters = "";
}else{
this.letters = letters;
}
return this;
}
setNumbers(numbers) {
if (numbers.length === 0 || !numbers) {
this.conditions[this.charType.NUMBER] = true;
this.conditionsToCheck -= 1;
this.numbers = ""
}else{
this.numbers = numbers;
}
return this;
}
setSymbols(symbols) {
if (symbols.length === 0 || ! symbols) {
this.conditions[this.charType.SYMBOL] = true;
this.conditionsToCheck -= 1;
this.symbols = "";
}else{
this.symbols = symbols;
}
return this;
}
_checkCondition(char) {
const getCharType = (char) => {
if (typeof char !== "string" || char.length !== 1) {
throw new Error("Invalid char type");
}
if (this.letters.includes(char)) {
return this.charType.LETTER;
} else if (this.numbers.includes(char)) {
return this.charType.NUMBER;
} else if (this.symbols.includes(char)) {
return this.charType.SYMBOL;
} else {
throw new Error("Unknown char type");
}
}
const charType = getCharType(char);
this.conditions[charType] = this.conditions[charType] || true;
}
generate() {
const choices = this.letters + this.numbers + this.symbols;
let generatedPassword = "";
for (let i = 0; i < this.length; i++) {
let selectedChar;
const lastChars = this.length - i <= this.conditionsToCheck;
if (lastChars && !this.conditions[this.charType.LETTER]) {
// We are still missing a letter char and we are getting to the end
const randomLetterChoice = Math.floor((Math.random() * (this.letters.length - 1)) + 0);
selectedChar = this.letters[randomLetterChoice];
}
else if (lastChars && !this.conditions[this.charType.NUMBER]) {
// We are still missing a number char and we are getting to the end
const randomNumberChoice = Math.floor((Math.random() * (this.numbers.length - 1)) + 0);
selectedChar = this.numbers[randomNumberChoice];
}
else if (lastChars && !this.conditions[this.charType.SYMBOL]) {
// We are still missing a symbol char and we are getting to the end
const randomSymbolChoice = Math.floor((Math.random() * (this.symbols.length - 1)) + 0);
selectedChar = this.symbols[randomSymbolChoice];
} else {
const randomChoice = Math.floor((Math.random() * (choices.length - 1)) + 0);
selectedChar = choices[randomChoice];
}
this._checkCondition(selectedChar);
generatedPassword += selectedChar;
}
return generatedPassword;
}
}
|
JavaScript
|
class VpnDeviceScriptParameters {
/**
* Create a VpnDeviceScriptParameters.
* @property {string} [vendor] The vendor for the vpn device.
* @property {string} [deviceFamily] The device family for the vpn device.
* @property {string} [firmwareVersion] The firmware version for the vpn
* device.
*/
constructor() {
}
/**
* Defines the metadata of VpnDeviceScriptParameters
*
* @returns {object} metadata of VpnDeviceScriptParameters
*
*/
mapper() {
return {
required: false,
serializedName: 'VpnDeviceScriptParameters',
type: {
name: 'Composite',
className: 'VpnDeviceScriptParameters',
modelProperties: {
vendor: {
required: false,
serializedName: 'vendor',
type: {
name: 'String'
}
},
deviceFamily: {
required: false,
serializedName: 'deviceFamily',
type: {
name: 'String'
}
},
firmwareVersion: {
required: false,
serializedName: 'firmwareVersion',
type: {
name: 'String'
}
}
}
}
};
}
}
|
JavaScript
|
class LeastTrimmedSquaresRegression {
// http://sfb649.wiwi.hu-berlin.de/fedc_homepage/xplore/tutorials/xaghtmlnode12.html
/**
* @param {number} h
*/
constructor(h = 0.9) {
this._w = null
this._h = h
}
_ls(x, y) {
const xtx = x.tDot(x)
return xtx.solve(x.tDot(y))
}
/**
* Fit model.
* @param {Array<Array<number>>} x
* @param {Array<Array<number>>} y
*/
fit(x, y) {
x = Matrix.fromArray(x)
y = Matrix.fromArray(y)
const xh = x.resize(x.rows, x.cols + 1, 1)
const wls = this._ls(xh, y)
const yls = xh.dot(wls)
yls.sub(y)
yls.mult(yls)
const r = yls.sum(1).value.map((v, i) => [v, i])
r.sort((a, b) => a[0] - b[0])
const h = Math.max(1, Math.floor(r.length * this._h))
const xlts = xh.row(r.slice(0, h).map(v => v[1]))
const ylts = y.row(r.slice(0, h).map(v => v[1]))
this._w = this._ls(xlts, ylts)
}
/**
* Returns predicted values.
* @param {Array<Array<number>>} x
* @returns {Array<Array<number>>}
*/
predict(x) {
x = Matrix.fromArray(x)
const xh = x.resize(x.rows, x.cols + 1, 1)
return xh.dot(this._w).toArray()
}
}
|
JavaScript
|
class CaptionLinks {
/**
* @param {string} rawString The raw string
*/
constructor(rawString) {
/**
* @private
* @type {Array<CaptionLink>}
*/
this.links = this.parse(rawString);
}
/**
* Turn the caption links into an array
* @returns {Array<CaptionLink>} The raw links array
*/
toArray() {
return this.links;
}
/**
* Turn the caption links into a list
* @returns {Array<string>} The list with the all caption links
*/
toList() {
const result = [];
for (let i = 0; i < this.links.length; i++) {
const { baseUrl } = this.links[i];
result[i] = baseUrl;
}
return result;
}
/**
* Turns the caption links into an object
* @returns {Object<string, string>} The object with the `languageCode` keys and the `baseUrl` values
*/
toObject() {
const result = [];
for (let i = 0; i < this.links.length; i++) {
const { baseUrl, languageCode } = this.links[i];
result[languageCode] = baseUrl;
}
return result;
}
/**
* Parse the caption links from the string
* @private
* @param {string} rawString The raw string
* @returns {Array<CaptionLink>} The caption links
*/
parse(rawString) {
const decoded = new URLSearchParams(rawString);
const playerResponse = JSON.parse(decoded.get('player_response'));
const captionLinks = playerResponse.captions.playerCaptionsTracklistRenderer.captionTracks;
return captionLinks;
}
}
|
JavaScript
|
class AmpStoryTooltip {
/**
* @param {!Window} win
* @param {!Element} storyEl
*/
constructor(win, storyEl) {
/** @private {!Window} */
this.win_ = win;
/** @private {!Element} */
this.storyEl_ = storyEl;
/** @private {boolean} */
this.isBuilt_ = false;
/** @private {?Element} */
this.shadowRoot_ = null;
/** @private {?Element} */
this.tooltipOverlayEl_ = null;
/** @private {?Element} */
this.tooltip_ = null;
/** @private {?Element} */
this.tooltipArrow_ = null;
/** @private @const {!./amp-story-store-service.AmpStoryStoreService} */
this.storeService_ = getStoreService(this.win_);
/** @private @const {!../../../src/service/resources-impl.Resources} */
this.resources_ = Services.resourcesForDoc(getAmpdoc(this.win_.document));
/**
* Clicked element producing the tooltip. Used to avoid building the same
* element twice.
* @private {?Element} */
this.clickedEl_ = null;
this.storeService_.subscribe(StateProperty.TOOLTIP_ELEMENT, el => {
this.onTooltipStateUpdate_(el);
});
}
/**
* Builds the tooltip overlay and appends it to the provided story.
* @private
*/
build_() {
this.isBuilt_ = true;
this.shadowRoot_ = this.win_.document.createElement('div');
this.tooltipOverlayEl_ =
dev().assert(this.buildTemplate_(this.win_.document));
createShadowRootWithStyle(this.shadowRoot_, this.tooltipOverlayEl_, CSS);
this.tooltipOverlayEl_
.addEventListener('click', event => this.onOutsideTooltipClick_(event));
this.storeService_.subscribe(StateProperty.UI_STATE, isDesktop => {
this.onUIStateUpdate_(isDesktop);
}, true /** callToInitialize */);
this.storeService_.subscribe(StateProperty.CURRENT_PAGE_ID, () => {
// Hide active tooltip when page switch is triggered by keyboard or
// desktop buttons.
if (this.storeService_.get(StateProperty.TOOLTIP_ELEMENT)) {
this.closeTooltip_();
}
});
return this.shadowRoot_;
}
/**
* Hides the tooltip layer.
* @private
*/
closeTooltip_() {
this.storeService_.dispatch(Action.TOGGLE_TOOLTIP, null);
}
/**
* Reacts to store updates related to tooltip active status.
* @param {!Element} clickedEl
* @private
*/
onTooltipStateUpdate_(clickedEl) {
if (!clickedEl) {
this.resources_.mutateElement(dev().assertElement(this.tooltipOverlayEl_),
() => {
this.tooltipOverlayEl_
.classList.toggle('i-amphtml-hidden', true);
});
return;
}
if (!this.isBuilt_) {
this.storyEl_.appendChild(this.build_());
}
if (clickedEl != this.clickedEl_) {
this.clickedEl_ = clickedEl;
this.attachTooltipToEl_(clickedEl);
}
this.resources_.mutateElement(dev().assertElement(this.tooltipOverlayEl_),
() => {
this.tooltipOverlayEl_
.classList.toggle('i-amphtml-hidden', false);
});
}
/**
* Reacts to desktop state updates and hides navigation buttons since we
* already have in the desktop UI.
* @param {!UIType} uiState
* @private
*/
onUIStateUpdate_(uiState) {
this.resources_.mutateElement(dev().assertElement(this.tooltipOverlayEl_),
() => {
[UIType.DESKTOP_FULLBLEED, UIType.DESKTOP_PANELS].includes(uiState) ?
this.tooltipOverlayEl_.setAttribute('desktop', '') :
this.tooltipOverlayEl_.removeAttribute('desktop');
});
}
/**
* Builds tooltip and attaches it depending on the clicked element content and
* position.
* @param {!Element} clickedEl
* @private
*/
attachTooltipToEl_(clickedEl) {
const elUrl = clickedEl.getAttribute('href');
if (!isProtocolValid(elUrl)) {
user().error(TAG, 'The tooltip url is invalid');
return;
}
const iconUrl = clickedEl.getAttribute('data-tooltip-icon');
if (!isProtocolValid(iconUrl)) {
user().error(TAG, 'The tooltip icon url is invalid');
return;
}
const {href} = parseUrlDeprecated(elUrl);
const tooltipText = clickedEl.getAttribute('data-tooltip-text') ||
getSourceOriginForElement(clickedEl, href);
this.updateTooltipText_(tooltipText);
const iconSrc = iconUrl ? parseUrlDeprecated(iconUrl).href :
DEFAULT_ICON_SRC;
this.updateTooltipIcon_(iconSrc);
addAttributesToElement(dev().assertElement(this.tooltip_),
dict({'href': href}));
this.positionTooltip_(clickedEl);
}
/**
* Updates tooltip text content.
* @param {string} tooltipText
* @private
*/
updateTooltipText_(tooltipText) {
const existingTooltipText =
this.tooltip_.querySelector('.i-amphtml-tooltip-text');
existingTooltipText.textContent = tooltipText;
}
/**
* Updates tooltip icon. If no icon src is declared, it sets a default src and
* hides it.
* @param {string} iconSrc
* @private
*/
updateTooltipIcon_(iconSrc) {
const existingTooltipIcon =
this.tooltip_.querySelector('.i-amphtml-story-tooltip-icon');
if (existingTooltipIcon.firstElementChild) {
addAttributesToElement(existingTooltipIcon.firstElementChild,
dict({'src': iconSrc}));
}
existingTooltipIcon.classList.toggle('i-amphtml-hidden',
iconSrc == DEFAULT_ICON_SRC);
}
/**
* Positions tooltip and its pointing arrow according to the position of the
* clicked element.
* @param {!Element} clickedEl
* @private
*/
positionTooltip_(clickedEl) {
const state = {arrowOnTop: false};
this.resources_.measureMutateElement(this.storyEl_,
/** measure */
() => {
const storyPage =
this.storyEl_.querySelector('amp-story-page[active]');
const clickedElRect = clickedEl./*OK*/getBoundingClientRect();
const pageRect = storyPage./*OK*/getBoundingClientRect();
this.verticalPositioning_(clickedElRect, pageRect, state);
this.horizontalPositioning_(clickedElRect, pageRect, state);
},
/** mutate */
() => {
// Arrow on top or bottom of tooltip.
this.tooltip_.classList.toggle('i-amphtml-tooltip-arrow-on-top',
state.arrowOnTop);
setImportantStyles(dev().assertElement(this.tooltipArrow_),
{left: `${state.arrowLeftOffset}px`});
setImportantStyles(dev().assertElement(this.tooltip_),
{top: `${state.tooltipTop}px`, left: `${state.tooltipLeft}px`});
});
}
/**
* In charge of deciding where to position the tooltip depending on the
* clicked element's position and size, and available space in the page. Also
* places the tooltip's arrow on top when the tooltip is below an element.
* @param {!ClientRect} clickedElRect
* @param {!ClientRect} pageRect
* @param {!Object} state
*/
verticalPositioning_(clickedElRect, pageRect, state) {
const clickedElTopOffset = clickedElRect.top - pageRect.top;
const clickedElBottomOffset = clickedElRect.bottom - pageRect.top;
if (clickedElTopOffset > MIN_VERTICAL_SPACE) { // Tooltip fits above clicked element.
state.tooltipTop = clickedElRect.top - MIN_VERTICAL_SPACE;
} else if (pageRect.height - clickedElBottomOffset >
MIN_VERTICAL_SPACE) { // Tooltip fits below clicked element. Place arrow on top of the tooltip.
state.tooltipTop = clickedElRect.bottom + EDGE_PADDING * 2;
state.arrowOnTop = true;
} else { // Element takes whole vertical space. Place tooltip on the middle.
state.tooltipTop = pageRect.height / 2;
}
}
/**
* In charge of positioning the tooltip and the tooltip's arrow horizontally.
* @param {!ClientRect} clickedElRect
* @param {!ClientRect} pageRect
* @param {!Object} state
*/
horizontalPositioning_(clickedElRect, pageRect, state) {
const clickedElLeftOffset = clickedElRect.left - pageRect.left;
const elCenterLeft = clickedElRect.width / 2 + clickedElLeftOffset;
const tooltipWidth = this.tooltip_./*OK*/offsetWidth;
state.tooltipLeft = elCenterLeft - (tooltipWidth / 2);
const maxHorizontalLeft = pageRect.width - tooltipWidth - EDGE_PADDING;
// Make sure tooltip is not out of the page.
state.tooltipLeft = Math.min(state.tooltipLeft, maxHorizontalLeft);
state.tooltipLeft = Math.max(EDGE_PADDING, state.tooltipLeft);
state.arrowLeftOffset = Math.abs(elCenterLeft - state.tooltipLeft -
this.tooltipArrow_./*OK*/offsetWidth / 2);
// Make sure tooltip arrow is not out of the tooltip.
state.arrowLeftOffset =
Math.min(state.arrowLeftOffset, tooltipWidth - EDGE_PADDING * 3);
state.tooltipLeft += pageRect.left;
}
/**
* Handles click outside the tooltip.
* @param {!Event} event
* @private
*/
onOutsideTooltipClick_(event) {
if (!closest(dev().assertElement(event.target),
el => el == this.tooltip_)) {
event.stopPropagation();
this.closeTooltip_();
}
}
/**
* Builds the template and adds corresponding listeners to nav buttons.
* @param {!Document} doc
* @return {!Element}
* @private
*/
buildTemplate_(doc) {
const html = htmlFor(doc);
const tooltipOverlay =
html`
<section class="i-amphtml-story-tooltip-layer i-amphtml-hidden">
<div class="i-amphtml-story-tooltip-layer-nav-button-container
i-amphtml-story-tooltip-nav-button-left">
<button role="button" ref="buttonLeft"
class="i-amphtml-story-tooltip-layer-nav-button
i-amphtml-story-tooltip-nav-button-left">
</button>
</div>
<div class="i-amphtml-story-tooltip-layer-nav-button-container
i-amphtml-story-tooltip-nav-button-right">
<button role="button" ref="buttonRight"
class="i-amphtml-story-tooltip-layer-nav-button
i-amphtml-story-tooltip-nav-button-right">
</button>
</div>
<a class="i-amphtml-story-tooltip" target="_blank" ref="tooltip">
<div class="i-amphtml-story-tooltip-icon"><img ref="icon"></div>
<p class="i-amphtml-tooltip-text" ref="text"></p>
<div class="i-amphtml-tooltip-launch-icon"></div>
<div class="i-amphtml-story-tooltip-arrow" ref="arrow"></div>
</a>
</section>`;
const overlayEls = htmlRefs(tooltipOverlay);
const {tooltip, buttonLeft, buttonRight, arrow} =
/** @type {!tooltipElementsDef} */ (overlayEls);
this.tooltip_ = tooltip;
this.tooltipArrow_ = arrow;
const rtlState = this.storeService_.get(StateProperty.RTL_STATE);
buttonLeft.addEventListener('click', e =>
this.onNavigationalClick_(e, rtlState ?
EventType.NEXT_PAGE : EventType.PREVIOUS_PAGE));
buttonRight.addEventListener('click', e =>
this.onNavigationalClick_(e, rtlState ?
EventType.PREVIOUS_PAGE : EventType.NEXT_PAGE));
return tooltipOverlay;
}
/**
* Navigates to next/previous page.
* @param {!Event} event
* @param {string} direction
* @private
*/
onNavigationalClick_(event, direction) {
event.preventDefault();
dispatch(
this.win_,
dev().assertElement(this.shadowRoot_),
direction,
undefined,
{bubbles: true});
}
}
|
JavaScript
|
class Scriptex {
/**
* A reference to Scripter.
*
* NOTE: Spying/stubbing this property is useful for BDD/TDD tests.
*
* @type {Object}
* @see [Scripter]{@link Scripter}
*/
static get SYSTEM() {
return Scripter
}
/**
* The default Scripter/Scriptex integration fields and methods
*
* | Scripter | Scriptex |
* |------------------------|---------------|
* | PluginParameters | parameters |
* | NeedsTimingInfo | needsTiming |
* | ResetParameterDefaults | needsDefaults |
* | ParameterChanged | onParameter |
* | ProcessMIDI | onProcess |
* | HandleMIDI | onMIDI |
* | Reset | onReset |
* | Idle | onIdle |
*
* @type {Map<string, string>}
*/
static get API () {
return new Map(
[
[ `NeedsTimingInfo`, `needsTiming`]
, [ `ResetParameterDefaults`, `needsDefaults`]
, [ `PluginParameters`, `parameters`]
, [ `HandleMIDI`, `onMIDI`]
, [ `ProcessMIDI`, `onProcess`]
, [ `ParameterChanged`, `onParameter`]
, [ `Reset`, `onReset`]
, [ `Idle`, `onIdle`]
]
)
}
/**
* Create a new Scripter instance.
*
* @param {Object} [system=Scripter] The integration environment to use.
* @param {Map} [api=new.target.API] The plugin integration API to use.
* @param {Boolean} [configurable=false] Define integration properties as configurable or not.
* @see [Scriptex.API]{@link Scriptex.API}
* @see [Scriptex.SYSTEM]{@link Scriptex.SYSTEM}
* @see [Object.defineProperty]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Description}
*/
constructor (system= new.target.SYSTEM, api= new.target.API, configurable=false) {
this._system= system
this._api= api
this._configurable= configurable
}
/**
* Deploy a plugin to the Scripter runtime by integrating appropriate properties with
* the Scripter API.
*
* @param {Object} plugin The plugin instance to deploy.
* @return {Array<string>} An enumeration of the Scripter integration properties.
* @see [API]{@link Scriptex.API}
*/
deploy (plugin) {
/* a property stash */
let mem= null
/* all Scripter property keys that have been integrated with the plugin */
let api= []
/* a reference to the system that the plugin as been deployed to */
let sys= (plugin.system = this._system)
/* define a propety on an object target */
let def= (target, key, val, atr=`value`, configurable=this._configurable) =>
Reflect.defineProperty(target, key, { [atr]: val, configurable} )
/* define a plugin accessor delegate on Scripter */
let get= (systemKey, pluginKey) =>
def(plugin, pluginKey, mem, `value`, true)
&& def(sys, systemKey, () => plugin[pluginKey], `get`)
/* define a plugin method delegate on Scripter */
let fun = (systemKey, pluginKey) =>
(typeof(mem) === `function`)
&& def(sys, systemKey, (...args) => plugin[pluginKey](...args))
/* integrate the plugin with Scripter */
let put= (pluginKey, systemKey) =>
(mem = plugin[pluginKey], pluginKey in plugin)
&& (fun(systemKey, pluginKey) || get(systemKey, pluginKey))
&& api.push(systemKey)
/* start integrating */
this._api.forEach(put)
/* return the manifest */
return api
}
}
|
JavaScript
|
class BaseAdapter {
/**
* Constructor of adapter
* @param {Object?} opts
*/
constructor(opts) {
/** @type {BaseDefaultOptions} */
this.opts = _.defaultsDeep({}, opts, {
consumerName: null,
prefix: null,
serializer: "JSON",
maxRetries: 3,
maxInFlight: 1,
deadLettering: {
enabled: false,
queueName: "FAILED_MESSAGES"
}
});
/**
* Tracks the messages that are still being processed by different clients
* @type {Map<string, Array<string|number>>}
*/
this.activeMessages = new Map();
/** @type {Boolean} Flag indicating the adapter's connection status */
this.connected = false;
}
/**
* Initialize the adapter.
*
* @param {ServiceBroker} broker
* @param {Logger} logger
*/
init(broker, logger) {
this.broker = broker;
this.logger = logger;
this.Promise = broker.Promise;
if (!this.opts.consumerName) this.opts.consumerName = this.broker.nodeID;
if (this.opts.prefix == null) this.opts.prefix = broker.namespace;
this.logger.info("Channel consumer name:", this.opts.consumerName);
this.logger.info("Channel prefix:", this.opts.prefix);
// create an instance of serializer (default to JSON)
/** @type {Serializer} */
this.serializer = Serializers.resolve(this.opts.serializer);
this.serializer.init(this.broker);
this.logger.info("Channel serializer:", this.broker.getConstructorName(this.serializer));
this.registerAdapterMetrics(broker);
}
/**
* Register adapter related metrics
* @param {ServiceBroker} broker
*/
registerAdapterMetrics(broker) {
if (!broker.isMetricsEnabled()) return;
broker.metrics.register({
type: METRIC.TYPE_COUNTER,
name: C.METRIC_CHANNELS_MESSAGES_ERRORS_TOTAL,
labelNames: ["channel", "group"],
rate: true,
unit: "msg"
});
broker.metrics.register({
type: METRIC.TYPE_COUNTER,
name: C.METRIC_CHANNELS_MESSAGES_RETRIES_TOTAL,
labelNames: ["channel", "group"],
rate: true,
unit: "msg"
});
broker.metrics.register({
type: METRIC.TYPE_COUNTER,
name: C.METRIC_CHANNELS_MESSAGES_DEAD_LETTERING_TOTAL,
labelNames: ["channel", "group"],
rate: true,
unit: "msg"
});
}
/**
*
* @param {String} metricName
* @param {Channel} chan
*/
metricsIncrement(metricName, chan) {
if (!this.broker.isMetricsEnabled()) return;
this.broker.metrics.increment(metricName, {
channel: chan.name,
group: chan.group
});
}
/**
* Check the installed client library version.
* https://github.com/npm/node-semver#usage
*
* @param {String} library
* @param {String} requiredVersions
* @returns {Boolean}
*/
checkClientLibVersion(library, requiredVersions) {
const pkg = require(`${library}/package.json`);
const installedVersion = pkg.version;
if (semver.satisfies(installedVersion, requiredVersions)) {
return true;
} else {
this.logger.warn(
`The installed ${library} library is not supported officially. Proper functionality cannot be guaranteed. Supported versions:`,
requiredVersions
);
return false;
}
}
/**
* Init active messages list for tracking messages of a channel
* @param {string} channelID
*/
initChannelActiveMessages(channelID) {
if (this.activeMessages.has(channelID)) {
throw new MoleculerError(`Already tracking active messages of channel ${channelID}`);
}
this.activeMessages.set(channelID, []);
}
/**
* Remove active messages list of a channel
* @param {string} channelID
*/
stopChannelActiveMessages(channelID) {
if (!this.activeMessages.has(channelID)) {
throw new MoleculerError(`Not tracking active messages of channel ${channelID}`);
}
if (this.activeMessages.get(channelID).length !== 0) {
throw new MoleculerError(
`Can't stop tracking active messages of channel ${channelID}. It still has ${
this.activeMessages.get(channelID).length
} messages being processed.`
);
}
this.activeMessages.delete(channelID);
}
/**
* Add IDs of the messages that are currently being processed
*
* @param {string} channelID Channel ID
* @param {Array<string|number>} IDs List of IDs
*/
addChannelActiveMessages(channelID, IDs) {
if (!this.activeMessages.has(channelID)) {
throw new MoleculerError(`Not tracking active messages of channel ${channelID}`);
}
this.activeMessages.get(channelID).push(...IDs);
}
/**
* Remove IDs of the messages that were already processed
*
* @param {string} channelID Channel ID
* @param {string[]|number[]} IDs List of IDs
*/
removeChannelActiveMessages(channelID, IDs) {
if (!this.activeMessages.has(channelID)) {
throw new MoleculerError(`Not tracking active messages of channel ${channelID}`);
}
const messageList = this.activeMessages.get(channelID);
IDs.forEach(id => {
const idx = messageList.indexOf(id);
if (idx != -1) {
messageList.splice(idx, 1);
}
});
}
/**
* Get the number of active messages of a channel
*
* @param {string} channelID Channel ID
*/
getNumberOfChannelActiveMessages(channelID) {
if (!this.activeMessages.has(channelID)) {
//throw new MoleculerError(`Not tracking active messages of channel ${channelID}`);
return 0;
}
return this.activeMessages.get(channelID).length;
}
/**
* Get the number of channels
*/
getNumberOfTrackedChannels() {
return this.activeMessages.size;
}
/**
* Given a topic name adds the prefix
*
* @param {String} topicName
* @returns {String} New topic name
*/
addPrefixTopic(topicName) {
if (this.opts.prefix != null && this.opts.prefix != "" && topicName) {
return `${this.opts.prefix}.${topicName}`;
}
return topicName;
}
/**
* Connect to the adapter.
*/
async connect() {
/* istanbul ignore next */
throw new Error("This method is not implemented.");
}
/**
* Disconnect from adapter
*/
async disconnect() {
/* istanbul ignore next */
throw new Error("This method is not implemented.");
}
/**
* Subscribe to a channel.
*
* @param {Channel} chan
*/
async subscribe(chan) {
/* istanbul ignore next */
throw new Error("This method is not implemented.");
}
/**
* Unsubscribe from a channel.
*
* @param {Channel} chan
*/
async unsubscribe(chan) {
/* istanbul ignore next */
throw new Error("This method is not implemented.");
}
/**
* Publish a payload to a channel.
* @param {String} channelName
* @param {any} payload
* @param {Object?} opts
*/
async publish(channelName, payload, opts) {
/* istanbul ignore next */
throw new Error("This method is not implemented.");
}
}
|
JavaScript
|
class JavaScriptSerializer {
constructor(_unit) {
/** @internal */
this._creations = [];
/** @internal */
this._creationsById = {};
/** @internal */
this._varNamesById = {};
/** @internal */
this._varNames = {};
this._unit = _unit;
}
/**
* Given a unit, generates JavaScript(/TypeScript) code that would re-create the same unit.
* Useful as scaffolding for model generators.
*/
static serializeToJs(unit) {
if (!unit.isLoaded) {
throw new Error("serializeToJs can be used on loaded units only!");
}
const serializer = new JavaScriptSerializer(unit);
serializer.schedule(unit);
return serializer.source();
}
schedule(structure) {
if (!structure || this._creationsById[structure.id]) {
return;
}
this._creationsById[structure.id] = true;
this._creations.push(this._asCreation(structure));
}
source() {
// 1. compute varNames:
for (const creation of this._creations) {
this._computeVarName(creation);
}
// 2. build source for everything but assignments of by-id references and local by-name reference:
const phase1 = this._creations.map(creation => this._creationAsSource(creation)).join("\n");
// 3. add source for assignments of by-id references and local by-name reference:
const phase2Creations = this._creations.filter(creation => creation.settings.some(setting => setting.kind === PropertyKind.ByIdReference || setting.kind === PropertyKind.LocalByNameReference));
const phase2 = phase2Creations
.map(creation => "\n" +
creation.settings
.filter(setting => setting.kind === PropertyKind.ByIdReference || setting.kind === PropertyKind.LocalByNameReference)
.map(setting => "\t" + this._settingAsSource(this._varNamesById[creation.id], setting) + "\n")
.join(""))
.join("");
const today = new Date();
const header = `(function (unit, model) {
\t/*
\t * JavaScript code generated by mendixmodelsdk.sdk.extras.JavaScriptSerializer
\t * from unit with id "${this._unit.id}" of type ${this._unit.structureTypeName}
\t * in working copy "${this._unit._model.workingCopy.metaData.name}"
\t * on ${today.getDate()}-${today.getMonth() + 1}-${today.getFullYear()}.
\t */
`;
return header + phase1 + phase2 + "\n})";
}
/** @internal */
_computeVarName(creation) {
let preName;
let name;
let uniqueIndex = 0;
let addUnderscore = false;
if (creation.name) {
preName = this._sanitizeName(creation.name);
addUnderscore = /\d$/.test(preName);
}
else {
preName = toFirstLowerCase(creation.unqualifiedTypeName);
}
do {
uniqueIndex++;
name = preName + (addUnderscore ? "_" : "") + uniqueIndex;
} while (this._varNames[name]);
this._varNamesById[creation.id] = name;
this._varNames[name] = true;
}
/** @internal */
_sanitizeName(name) {
name = name.replace(/[!\"#$%&'\(\)\*\+,\.\/:;<=>\?\@\[\\\]\^`\{\|\}~]/g, "");
name = name.replace(/^\d+/, "");
name = name.replace(/\s/g, ""); // Remove white spaces
name = toFirstLowerCase(name);
return name;
}
/** @internal */
_creationAsSource(creation) {
const lines = [];
const varName = this._varNamesById[creation.id];
lines.push(`var ${varName} = ${creation.subMetaModel.toLowerCase()}.${creation.unqualifiedTypeName}.create${creation.unit ? "In(unit" : "(model"});`);
creation.settings
.filter(setting => setting.kind !== PropertyKind.ByIdReference && setting.kind !== PropertyKind.LocalByNameReference)
.forEach(setting => lines.push(...this._settingAsSource(varName, setting)));
return lines.map(line => "\t" + line + "\n").join("");
}
/** @internal */
_settingAsSource(varName, setting) {
const commentsPostfix = setting.couldBeDefaultValue ? " // Note: for this property a default value is defined." : "";
if (setting.updateWithRawValue) {
return [
"// Note: this is an unsupported internal property of the Model SDK which is subject to change.",
`${varName}.__${setting.propertyName}.updateWithRawValue("${setting.value}");${commentsPostfix}`
];
}
return setting.listy
? setting.value.map(singleValue => `${varName}.${setting.propertyName}.push(${this._singleValueAsTsExpr(varName, setting, singleValue)});${commentsPostfix}`)
: [`${varName}.${setting.propertyName} = ${this._singleValueAsTsExpr(varName, setting, setting.value)};${commentsPostfix}`];
}
/** @internal */
_singleValueAsTsExpr(varName, setting, singleValue) {
switch (setting.kind) {
case PropertyKind.Primitive:
return JSON.stringify(singleValue);
case PropertyKind.Enumeration:
return singleValue.qualifiedTsLiteralName();
case PropertyKind.ByIdReference:
return this._varNamesById[singleValue];
case PropertyKind.ByNameReference:
const $index = setting.targetType.indexOf("$");
return `model.find${setting.targetType.substring($index + 1)}ByQualifiedName("${singleValue}")`;
case PropertyKind.LocalByNameReference:
return this._varNamesById[singleValue];
case PropertyKind.Part:
return !singleValue ? null : this._varNamesById[singleValue.id];
default:
throw new Error(`unmapped property kind (${setting.kind}) for setting of ${setting.propertyName} in ${varName}`);
}
}
/** @internal */
_asCreation(structure) {
const typeParts = structure.structureTypeName.split("$");
const creation = {
id: structure.id,
subMetaModel: typeParts[0],
unqualifiedTypeName: typeParts[1],
settings: [],
unit: false
};
if (structure.name) {
creation.name = structure.name;
}
if (structure instanceof units.ModelUnit || structure instanceof units.StructuralUnit) {
// i.e. structure instanceof units.AbstractUnit if the TS type hierarchy actually matched the one in MxCore
creation.unit = true;
}
structure.allProperties().forEach(property => {
if (property instanceof properties.EnumProperty) {
const value = property.get();
if (value !== property.defaultValue) {
creation.settings.push({
propertyName: property["name"],
kind: PropertyKind.Enumeration,
value: value
});
}
return;
}
if (property instanceof properties.EnumListProperty) {
const value = property.get();
if (value.length > 0) {
creation.settings.push({
propertyName: property["name"],
kind: PropertyKind.Enumeration,
value: value,
listy: true
});
}
return;
}
// Primitive(List)Property must be handled _after_ Enum(List)Property since the latter inherit from the first!
if (property instanceof properties.PrimitiveProperty) {
if (property["primitiveType"] === properties.PrimitiveTypeEnum.Guid) {
return;
}
const value = property.get();
if (value !== property.defaultValue) {
creation.settings.push({
propertyName: property["name"],
kind: PropertyKind.Primitive,
value: value
});
}
return;
}
if (property instanceof properties.PrimitiveListProperty) {
const value = property.get();
if (value.length > 0) {
creation.settings.push({
propertyName: property["name"],
kind: PropertyKind.Primitive,
value: value,
listy: true
});
}
return;
}
if (property instanceof properties.PartProperty) {
const value = property.get();
if (value) {
this.schedule(value);
}
if (property.hasDefaultValue || value) {
creation.settings.push({
propertyName: property["name"],
kind: PropertyKind.Part,
value: value,
couldBeDefaultValue: property.hasDefaultValue
});
}
return;
}
if (property instanceof properties.PartListProperty) {
const value = property.get();
if (value.length > 0) {
value.forEach(item => this.schedule(item));
creation.settings.push({
propertyName: property["name"],
kind: PropertyKind.Part,
value: value,
listy: true
});
}
return;
}
if (property instanceof properties.ByNameReferenceProperty) {
const value = property.get();
if (value || property.qualifiedName()) {
creation.settings.push({
propertyName: property["name"],
kind: PropertyKind.ByNameReference,
value: property.qualifiedName(),
targetType: property.targetType,
updateWithRawValue: !value
});
}
return;
}
if (property instanceof properties.LocalByNameReferenceProperty) {
const value = property.get();
if (value) {
creation.settings.push({
propertyName: property["name"],
kind: PropertyKind.LocalByNameReference,
value: value.id
});
}
return;
}
if (property instanceof properties.ByNameReferenceListProperty) {
const value = property.get();
if (value.length > 0) {
creation.settings.push({
propertyName: property["name"],
kind: PropertyKind.ByNameReference,
value: property.qualifiedNames(),
targetType: property.targetType,
listy: true
});
}
return;
}
if (property instanceof properties.ByIdReferenceProperty) {
const value = property.get();
if (value) {
this.schedule(value);
creation.settings.push({
propertyName: property["name"],
kind: PropertyKind.ByIdReference,
value: value.id
});
}
return;
}
throw new Error(`cannot serialize property: ${property.name} in object of type ${structure.structureTypeName}`);
});
return creation;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.