2
0
mirror of https://github.com/esiur/esiur-js.git synced 2025-05-06 12:32:58 +00:00
This commit is contained in:
Ahmed Zamil 2021-03-10 01:25:20 +03:00
parent ca2b89540a
commit a08519bde8
55 changed files with 4190 additions and 6679 deletions

View File

@ -5,6 +5,7 @@
] ]
], ],
"plugins": [ "plugins": [
["@babel/transform-runtime"] ["@babel/transform-runtime"],
["@babel/plugin-proposal-class-properties", { "loose": true }]
] ]
} }

View File

@ -2,3 +2,4 @@
Esiur Library for Javascript Esiur Library for Javascript
# Usage # Usage
npm run demo

File diff suppressed because it is too large Load Diff

96
demo/chat/chat.js Normal file
View File

@ -0,0 +1,96 @@
import DistributedConnection from "../../src/Net/IIP/DistributedConnection.js";
import Warehouse from "../../src/Resource/Warehouse.js";
import { createRequire } from 'module'
import AsyncReply from "../../src/Core/AsyncReply.js";
import DistributedServer from "../../src/Net/IIP/DistributedServer.js";
import IMembership from "../../src/Security/Membership/IMembership.js";
import WSSocket from "../../src/Net/Sockets/WSSocket.js";
import MemoryStore from "../../src/Stores/MemoryStore.js";
import DC from "../../src/Data/DataConverter.js";
import IResource from "../../src/Resource/IResource.js";
import Structure from "../../src/Data/Structure.js";
const require = createRequire(import.meta.url);
const WebSocket = require('ws');
const http = require("http");
const fs = require("fs");
const wss = new WebSocket.Server({port: 8081});
class MyMembership extends IMembership {
userExists(username, domain) {
return new AsyncReply(true);
}
getPassword(username, domain) {
return new AsyncReply(DC.stringToBytes("1234"));
}
};
var server;
class MyChat extends IResource {
static get template() {
return {
namespace: "Chat",
properties: [{name: "title"}, { name: "messages" }, {name: "users"}],
events: [{ name: "message" }, { name: "voice", listenable: true }, {name: "login"}, {name: "logout"}],
functions: [{ name: "send" }]
};
}
constructor(){
super();
this.messages = [new Structure({usr: "Admin", msg: "Welcome to Esiur", date: new Date()})];
this.title = "Chat Room";
}
get users() {
return server.connections.map(x=>x.session.remoteAuthentication.username);
}
send(msg, sender)
{
let s = new Structure({ msg, usr: sender.session.remoteAuthentication.username, date: new Date()});
this.messages.push(s);
this._emit("message", s);
}
query(path, sender) {
return new AsyncReply([this]);
}
}
let sys = await Warehouse.new(MemoryStore, "sys");
let ms = await Warehouse.new(MyMembership, "ms");
let chat = await Warehouse.new(MyChat, "chat", sys);
server = await Warehouse.new(DistributedServer, "dss", sys, null, null, {membership: ms, entryPoint: chat});
wss.on('connection', function connection(ws)
{
let con = server.add();
con.assign(new WSSocket(ws));
con.on("ready", (x)=>{
chat._emit("login", x.session.remoteAuthentication.username);
}).on("close", (x)=>{
chat._emit("logout", x.session.remoteAuthentication.username);
});
});
http.createServer(function (req, res) {
fs.readFile("." + req.url, function (err,data) {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
} else {
res.writeHead(200, {"Content-Type": req.url.split('.').pop() == "js" ? "text/javascript" : "text/html"});
res.end(data);
}
});
}).listen(8080);
console.log(`HTTP Server running http://localhost:8080/demo/chat/index.html`);
console.log(`IIP Server running iip://localhost:8081`);

91
demo/chat/index.html Normal file
View File

@ -0,0 +1,91 @@
<html>
<head>
<script type="module" src="../../src/esiur.js"></script>
<link href="style.css" rel="stylesheet">
<script>
var service;
let $ = document.querySelector;
async function connect(){
let status = document.getElementById("status");
let username = document.getElementById("username").value;
let login = document.getElementById("login");
let chat = document.getElementById("chat");
try {
status.innerHTML = "Connecting...";
service = await wh.get("iip://localhost:8081/chat", {username, password: "1234"});
login.style.display = "none";
service.on("message", appendMessage)
.on(":title", updateTitle)
.on("login", appendUser)
.on("logout", removeUser)
updateTitle();
service.messages.forEach(appendMessage);
service.users.forEach((x)=>appendUser(x, true));
status.innerHTML = "Online";
} catch (ex) {
status.innerHTML = "Error " + ex.toString;
}
}
function appendMessage(message)
{
let el = document.createElement("div");
let list = document.getElementById("list");
el.innerHTML = `<span>${message.usr}</span><span>${message.msg}</span><span>${message.date.toLocaleTimeString()}</span>`;
list.append(el);
list.scrollTop = list.scrollHeight;
}
function appendUser(usr, silent){
let el = document.createElement("div");
let users = document.getElementById("users");
el.innerHTML = usr;
users.append(el);
if (!silent)
appendMessage({usr, msg: "joined the room", date: new Date()});
}
function removeUser(usr){
for(var i = 0; i < users.children.length; i++)
if (users.children[i].innerHTML == usr)
{
users.removeChild(users.children[i]);
break;
}
appendMessage({usr, msg: "left the room", date: new Date()});
}
function updateTitle()
{
document.getElementById("title").value = service.title;
}
function send(){
service.send(document.getElementById("message").value);
}
</script>
</head>
<body>
<div id="login">
Username: <input id="username"> <button onclick="connect()">Connect</button>
</div>
<div id="chat">
<div class="bar">
<input id="title" onkeyup="service.title = this.value"><div id="status"></div>
</div>
<div class="bar">
<div>Online users: </div> <div id="users"></div>
</div>
<div id="list"></div>
<div class="bar">
<input id="message"><button onclick="send()">Send</button>
</div>
</div>
</body>
</html>

62
demo/chat/style.css Normal file
View File

@ -0,0 +1,62 @@
body
{
margin: 10vw 10vh;
}
#list {
display: flex;
flex-direction: column;
padding: 10px;
height: 50vh;
overflow-y: scroll;
}
#list > div {
display: flex;
gap: 10px;
}
#list > div > span:nth-child(1)
{
color: #7159f5;
}
#list > div > span:nth-child(2)
{
flex: 1;
}
#chat {
display: flex;
flex-direction: column;
border: 4px solid #d6d6d6;
border-radius: 23px;
overflow: hidden;
}
#status{
flex: 1;
text-align: end;
}
#login {
padding: 10px;
}
.bar{
display: flex; gap: 10px; background: gainsboro; padding: 10px;
}
#users{
display: flex;
gap: 4px;
color: #d04949;
font-weight: bold;
}
#users > div {
border: 1px solid #b3b3b3;
border-radius: 10px;
background: white;
padding: 0 6px;
}

View File

@ -1,10 +1,11 @@
{ {
"name": "esiur", "name": "esiur",
"version": "1.5.1", "version": "1.6.0",
"description": "Distributed Object Framework", "description": "Distributed Object Framework",
"main": "esiur.js", "main": "esiur.js",
"type": "module",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "demo": "node ./demo/chat/chat.js",
"babel": "./node_modules/.bin/babel src -d build", "babel": "./node_modules/.bin/babel src -d build",
"build": "browserify src/esiur.js -t babelify --outfile build/esiur.js" "build": "browserify src/esiur.js -t babelify --outfile build/esiur.js"
}, },

View File

@ -28,11 +28,22 @@ import ExceptionCode from './ExceptionCode.js';
export default class AsyncException extends Error export default class AsyncException extends Error
{ {
constructor()
{ constructor(type, code, message)
super(); {
this.raised = false; super();
}
if (type instanceof AsyncException) {
this.raise(type.type, type.code, type.message);
} else if (type instanceof Error) {
this.raise(1, 0, type.message);
} else if (type != undefined){
this.raise(type, code, message);
} else {
this.raised = false;
}
}
raise(type, code, message) raise(type, code, message)
{ {

View File

@ -95,13 +95,15 @@ export default class AsyncReply extends Promise
for(var i = 0; i < this.callbacks.length; i++) for(var i = 0; i < this.callbacks.length; i++)
this.callbacks[i](result, this); this.callbacks[i](result, this);
return this;
} }
triggerError(type, code, message) triggerError(type, code, message)
{ {
if (this.ready) if (this.ready)
return; return this;
if (type instanceof AsyncException) if (type instanceof AsyncException)
this.exception.raise(type.type, type.code, type.message); this.exception.raise(type.type, type.code, type.message);
@ -113,18 +115,24 @@ export default class AsyncReply extends Promise
else else
for(var i = 0; i < this.errorCallbacks.length; i++) for(var i = 0; i < this.errorCallbacks.length; i++)
this.errorCallbacks[i](this.exception, this); this.errorCallbacks[i](this.exception, this);
return this;
} }
triggerProgress(type, value, max) triggerProgress(type, value, max)
{ {
for(var i = 0; i < this.progressCallbacks.length; i++) for(var i = 0; i < this.progressCallbacks.length; i++)
this.progressCallbacks[i](type, value, max, this); this.progressCallbacks[i](type, value, max, this);
return this;
} }
triggerChunk(value) triggerChunk(value)
{ {
for(var i = 0; i < this.chunkCallbacks.length; i++) for(var i = 0; i < this.chunkCallbacks.length; i++)
this.chunkCallbacks[i](value, this); this.chunkCallbacks[i](value, this);
return this;
} }
constructor(result) constructor(result)

View File

@ -30,5 +30,9 @@ export default //const ExceptionCode =
SetPropertyDenied: 27, SetPropertyDenied: 27,
ReadOnlyProperty: 28, ReadOnlyProperty: 28,
GeneralFailure: 29, GeneralFailure: 29,
AddToStoreFailed: 30 AddToStoreFailed: 30,
NotAttached: 31,
AlreadyListened: 32,
AlreadyUnlistened: 33,
NotListenable: 34
}; };

View File

@ -1,7 +1,7 @@
export default // const ResourceComparisonResult = export default // const ResourceComparisonResult =
{ {
Null: 0, Null: 0,
Distributed: 1, Distributed: 1,
Local: 2, Local: 2,
Same: 3 Same: 3
}; };

File diff suppressed because it is too large Load Diff

View File

@ -31,6 +31,10 @@ import AsyncReply from '../../Core/AsyncReply.js';
import Codec from '../../Data/Codec.js'; import Codec from '../../Data/Codec.js';
import Structure from '../../Data/Structure.js'; import Structure from '../../Data/Structure.js';
import IIPPacketAction from '../Packets//IIPPacketAction.js'; import IIPPacketAction from '../Packets//IIPPacketAction.js';
import EventTemplate from '../../Resource/Template/EventTemplate.js';
import AsyncException from '../../Core/AsyncException.js';
import ExceptionCode from '../../Core//ExceptionCode.js';
import ErrorType from '../../Core/ErrorType.js';
export default class DistributedResource extends IResource export default class DistributedResource extends IResource
{ {
@ -166,6 +170,32 @@ export default class DistributedResource extends IResource
return true; return true;
} }
listen(event)
{
let et = event instanceof EventTemplate ? event : this.instance.template.getEventTemplateByName(event);
if (et == null)
return new AsyncReply().triggerError(new AsyncException(ErrorType.Management, ExceptionCode.MethodNotFound, ""));
if (!et.listenable)
return new AsyncReply().triggerError(new AsyncException(ErrorType.Management, ExceptionCode.NotListenable, ""));
return this._p.connection.sendListenRequest(this._p.instanceId, et.index);
}
unlisten(event)
{
let et = event instanceof EventTemplate ? event : this.instance.template.getEventTemplateByName(event);
if (et == null)
return new AsyncReply().triggerError(new AsyncException(ErrorType.Management, ExceptionCode.MethodNotFound, ""));
if (!et.listenable)
return new AsyncReply().triggerError(new AsyncException(ErrorType.Management, ExceptionCode.NotListenable, ""));
return this._p.connection.sendUnlistenRequest(this._p.instanceId, et.index);
}
_emitEventByIndex(index, args) _emitEventByIndex(index, args)
{ {
var et = this.instance.template.getEventTemplateByIndex(index); var et = this.instance.template.getEventTemplateByIndex(index);
@ -225,7 +255,7 @@ export default class DistributedResource extends IResource
{ {
if (!this._p.attached) if (!this._p.attached)
{ {
console.log("What ?"); console.log("Resource not attached.");
return; return;
} }

View File

@ -0,0 +1,81 @@
/*
* Copyright (c) 2017-2021 Ahmed Kh. Zamil
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Created by Ahmed Zamil on 03/05/2021.
*/
"use strict";
import IResource from '../../Resource/IResource.js';
import AsyncReply from '../../Core/AsyncReply.js';
import Codec from '../../Data/Codec.js';
import Structure from '../../Data/Structure.js';
import IIPPacketAction from '../Packets//IIPPacketAction.js';
import EventTemplate from '../../Resource/Template/EventTemplate.js';
import AsyncException from '../../Core/AsyncException.js';
import ExceptionCode from '../../Core//ExceptionCode.js';
import ErrorType from '../../Core/ErrorType.js';
import DistributedConnection from './DistributedConnection.js';
export default class DistributedServer extends IResource
{
destroy()
{
this.connections = [];
this.destroyed = true;
this._emit("destroy", this);
}
trigger(type)
{
return new AsyncReply(true);
}
get membership() {
return this.instance.attributes.get("membership");
}
get entryPoint() {
return this.instance.attributes.get("entryPoint");
}
constructor()
{
super();
this.connections = [];
}
add() {
let self = this;
let con = new DistributedConnection(this);
con.on("close", () => self.remove(con));
this.connections.push(con);
return con;
}
remove(connection){
let i = this.connections.indexOf(connection);
if (i > -1)
this.connections.splice(i, 1);
}
}

View File

@ -0,0 +1,8 @@
import IResource from "../../Resource/IResource";
export default class EntryPoint extends IResource
{
query(path, sender) {}
create() {}
}

View File

@ -0,0 +1,7 @@
import IDestructible from "../Core/IDestructible";
export default class INetworkReceiver extends IDestructible {
networkClose(sender);
networkReceive(sender, buffer);
networkConnect(sender);
}

View File

@ -26,7 +26,7 @@
"use strict"; "use strict";
import DC from '../../Data/DataConverter.js'; import DC from '../Data/DataConverter.js';
export default class NetworkBuffer { export default class NetworkBuffer {
constructor() { constructor() {

View File

@ -0,0 +1,5 @@
export default class NetowrkConnection extends INetworkReceiver
{
}

0
src/Net/NetworkServer.js Normal file
View File

View File

View File

@ -391,7 +391,9 @@ export default class IIPPacket
offset += cl; offset += cl;
} }
else if (this.action == IIPPacketAction.GetProperty) else if (this.action == IIPPacketAction.Listen
|| this.action == IIPPacketAction.Unlisten)
//this.action == IIPPacketAction.GetProperty)
{ {
if (this.notEnough(offset, ends, 5)) if (this.notEnough(offset, ends, 5))
return -this.dataLengthNeeded; return -this.dataLengthNeeded;
@ -402,20 +404,20 @@ export default class IIPPacket
this.methodIndex = data.getUint8(offset++); this.methodIndex = data.getUint8(offset++);
} }
else if (this.action == IIPPacketAction.GetPropertyIfModified) // else if (this.action == IIPPacketAction.GetPropertyIfModified)
{ // {
if (this.notEnough(offset, ends, 9)) // if (this.notEnough(offset, ends, 9))
return -this.dataLengthNeeded; // return -this.dataLengthNeeded;
this.resourceId = data.getUint32(offset); // this.resourceId = data.getUint32(offset);
offset += 4; // offset += 4;
this.methodIndex = data[offset++]; // this.methodIndex = data[offset++];
this.resourceAge = data.getUint64(offset); // this.resourceAge = data.getUint64(offset);
offset += 8; // offset += 8;
} // }
else if (this.action == IIPPacketAction.SetProperty) else if (this.action == IIPPacketAction.SetProperty)
{ {
if (this.notEnough(offset, ends, 6)) if (this.notEnough(offset, ends, 6))
@ -552,9 +554,9 @@ export default class IIPPacket
offset += cl; offset += cl;
} }
else if (this.action == IIPPacketAction.InvokeFunctionArrayArguments else if (this.action == IIPPacketAction.InvokeFunctionArrayArguments
|| this.action == IIPPacketAction.InvokeFunctionNamedArguments || this.action == IIPPacketAction.InvokeFunctionNamedArguments)
|| this.action == IIPPacketAction.GetProperty //|| this.action == IIPPacketAction.GetProperty
|| this.action == IIPPacketAction.GetPropertyIfModified) //|| this.action == IIPPacketAction.GetPropertyIfModified)
{ {
if (this.notEnough(offset, ends, 1)) if (this.notEnough(offset, ends, 1))
@ -586,7 +588,9 @@ export default class IIPPacket
offset += size; offset += size;
} }
} }
else if (this.action == IIPPacketAction.SetProperty) else if (this.action == IIPPacketAction.SetProperty
|| this.action == IIPPacketAction.Listen
|| this.action == IIPPacketAction.Unlisten)
{ {
// nothing to do // nothing to do
} }

View File

@ -21,10 +21,10 @@ export default // const IIPPacketAction =
// Request Invoke // Request Invoke
InvokeFunctionArrayArguments: 16, InvokeFunctionArrayArguments: 16,
GetProperty: 17, InvokeFunctionNamedArguments: 17,
GetPropertyIfModified: 18, Listen: 18,
SetProperty: 19, Unlisten: 19,
InvokeFunctionNamedArguments: 20, SetProperty: 20,
// Request Attribute // Request Attribute
GetAllAttributes: 24, GetAllAttributes: 24,

View File

@ -39,7 +39,7 @@ export default class SendList extends BinaryList
done() done()
{ {
this.connection.send(this.toArray()); this.connection.sendAll(this.toArray());
return this.reply; return this.reply;
} }
} }

View File

@ -0,0 +1,34 @@
"use strict";
import IDestructible from "../../Core/IDestructible.js";
import SocketState from "./SocketState.js";
export default class ISocket extends IDestructible
{
//SocketState State { get; }
//INetworkReceiver<ISocket> Receiver { get; set; }
constructor(){
super();
this.state = SocketState.Initial;
}
// get state() {}
sendAsync(message, offset, length) { }
send(message, offset, length) {}
close() {}
connect(hostname, port) {}
begin() {}
beginAsync() {}
acceptAsync() {}
accept() {}
get remoteEndPoint(){}
get localEndPoint() {}
hold() {}
unhold() {}
}

View File

@ -0,0 +1,7 @@
export default {
Initial : 0,
Listening : 1,
Connecting : 2,
Established : 3,
Closed: 4,
}

165
src/Net/Sockets/WSSocket.js Normal file
View File

@ -0,0 +1,165 @@
import AsyncReply from "../../Core/AsyncReply.js";
import ErrorType from "../../Core/ErrorType.js";
import ExceptionCode from "../../Core/ExceptionCode.js";
import ISocket from "./ISocket.js";
import SocketState from "./SocketState.js";
import NetworkBuffer from "../NetworkBuffer.js";
export default class WSSocket extends ISocket
{
//SocketState State { get; }
//INetworkReceiver<ISocket> Receiver { get; set; }
constructor(websocket){
super();
this.receiveNetworkBuffer = new NetworkBuffer();
this.sendNetworkBuffer = new NetworkBuffer();
this.held = false;
if (websocket != null)// instanceof WebSocket)
{
//websocket.onerror = () => {
// self.state = SocketState.Closed;
//};
websocket.onopen = () => {
self.state = SocketState.Established;
};
websocket.onerror = () => {
self.state = SocketState.Closed;
};
this._assign(websocket);
}
}
destroy(){
this.close();
this.receiveNetworkBuffer = null;
this.receiver = null;
thsi.ws = null;
this._emit("destroy");
}
sendAsync(message, offset, length) {
}
sendAll(message)
{
if (this.held)
this.sendNetworkBuffer.writeAll(message);
else
{
try
{
this.ws.send(message);
} catch {
this.state = SocketState.Closed;
}
}
}
send(message, offset, length) {
this.sendAll(message.clip(offset, length));
}
close() {
this.ws.close();
}
connect(hostname, port, secure = false) {
let self = this;
var rt = new AsyncReply();
this.state = SocketState.Connecting;
this.url = `ws${secure ? 's' : ''}://${hostname}:${port}`;
let ws = new WebSocket(this.url, "iip");
ws.binaryType = "arraybuffer";
ws.onopen = () => {
self.state = SocketState.Established;
rt.trigger(true);
};
ws.onerror = () => {
self.state = SocketState.Closed;
rt.triggerError(ErrorType.Management, ExceptionCode.HostNotReachable);
};
this._assign(ws);
return rt;// new AsyncReply(true);
}
_assign(ws)
{
let self = this;
ws.onclose = () => {
self.state = SocketState.Closed;
self.receiver?.networkClose(self);
};
ws.onmessage = function(msg) {
self.receiveNetworkBuffer.writeAll(msg.data);
self.receiver.networkReceive(this, self.receiveNetworkBuffer);
//self.lastAction = new Date();
};
this.ws = ws;
}
begin() {
}
beginAsync() {
}
acceptAsync() {
}
accept() {
}
get remoteEndPoint(){}
get localEndPoint() {}
hold()
{
this.held = true;
}
unhold()
{
this.held = false;
var message = this.sendNetworkBuffer.read();
if (message == null)
return;
// totalSent += message.Length;
try {
this.ws.send(message);
} catch {
this.state = SocketState.Closed;
}
}
}
// if (this.holdSending) {
// //console.log("hold ", data.length);
// this.sendBuffer.writeAll(data);
// }
// else
// //console.log("Send", data.length);

View File

@ -18,14 +18,14 @@ export default class ResourceProxy
for(var i = 0; i < template.properties.length; i++) for(var i = 0; i < template.properties.length; i++)
{ {
let pt = template.properties[i]; let pt = template.properties[i];
let desc = Object.getOwnPropertyDescriptor(Payment.prototype, pt.name); let desc = Object.getOwnPropertyDescriptor(type.prototype, pt.name);
if (desc) if (desc)
{ {
code += `\r\n set ${pt.name}(v) { \r\n if (this.instance) this.instance.emitModification(this.instance.template.properties[${i}], v); \r\n super.${pt.name} = v; } \r\n get ${pt.name}() { \r\n return super.${pt.name};}`; code += `\r\n set ${pt.name}(v) { \r\n if (this.instance) this.instance.emitModification(this.instance.template.properties[${i}], v); \r\n super.${pt.name} = v; } \r\n get ${pt.name}() { \r\n return super.${pt.name};}`;
} }
else else
{ {
code += `\r\n set ${pt.name}(v) { \r\n if (this.instance) this.instance.emitModification(this.instance.template.properties[${i}], v); \r\n super._${pt.name} = v; } \r\n get ${pt.name}() { \r\n return super._${pt.name};}`; code += `\r\n set ${pt.name}(v) { \r\n if (this.instance) this.instance.emitModification(this.instance.template.properties[${i}], v); \r\n this._${pt.name} = v; } \r\n get ${pt.name}() { \r\n return this._${pt.name};}`;
} }
} }

View File

@ -28,10 +28,10 @@
export default class CustomResourceEvent export default class CustomResourceEvent
{ {
constructor(issuer, receivers, params) constructor(issuer, receivers, args)
{ {
this.issuer = issuer; this.issuer = issuer;
this.receivers = receivers; this.receivers = receivers;
this.params = params; this.args = args;
} }
} }

View File

@ -234,7 +234,7 @@ export default class Instance extends IEventHandler
return function(args) return function(args)
{ {
if (args instanceof CustomResourceEvent) if (args instanceof CustomResourceEvent)
self._emitResourceEvent(args.issuer, args.receivers, name, args.params); self._emitResourceEvent(args.issuer, args.receivers, name, args.args);
else else
self._emitResourceEvent(null, null, name, args); self._emitResourceEvent(null, null, name, args);
}; };

View File

@ -46,7 +46,7 @@ export default class EventTemplate extends MemberTemplate
var name = super.compose(); var name = super.compose();
if (this.expansion != null) { if (this.expansion != null) {
var exp = DC.stringToBytes(this.expansion); var exp = DC.stringToBytes(this.expansion);
return rt.addUint8(0x50) return rt.addUint8(this.listenable ? 0x58 : 0x50)
.addUint8(name.length) .addUint8(name.length)
.addUint8Array(name) .addUint8Array(name)
.addUint32(exp.length) .addUint32(exp.length)
@ -54,7 +54,7 @@ export default class EventTemplate extends MemberTemplate
.toArray(); .toArray();
} }
else else
return rt.addUint8(0x40) return rt.addUint8(this.listenable ? 0x48 : 0x40)
.addUint8(name.length) .addUint8(name.length)
.addUint8Array(name) .addUint8Array(name)
.toArray(); .toArray();

View File

@ -123,6 +123,7 @@ export default class ResourceTemplate {
et.name = template.events[i].name; et.name = template.events[i].name;
et.index = i; et.index = i;
et.expansion = template.events[i].help; et.expansion = template.events[i].help;
et.listenable = template.events[i].listenable;
this.events.push(et); this.events.push(et);
} }
@ -266,9 +267,11 @@ export default class ResourceTemplate {
{ {
var et = new EventTemplate(); var et = new EventTemplate();
et.index = eventIndex++; et.index = eventIndex++;
var expansion = ((data.getUint8(offset++) & 0x10) == 0x10); var expansion = ((data.getUint8(offset) & 0x10) == 0x10);
et.listenable = ((data.getUint8(offset++) & 0x8) == 0x8);
var len = data.getUint8(offset++); var len = data.getUint8(offset++);
et.name = data.getString(offset, len); et.name = data.getString(offset, len);
offset += len; offset += len;
if (expansion) // expansion ? if (expansion) // expansion ?

View File

@ -58,22 +58,38 @@ export class WH extends IEventHandler
this._urlRegex = /^(?:([^\s|:]*):\/\/([^\/]*)\/?)/; this._urlRegex = /^(?:([^\s|:]*):\/\/([^\/]*)\/?)/;
} }
newInstance(type, properties)
{
var proxyType = ResourceProxy.getProxy(type);
var res = new proxyType();
if (properties != null)
Object.assign(res, properties);
return type;
}
new(type, name, store = null, parent = null, manager = null, attributes = null, properties = null) new(type, name, store = null, parent = null, manager = null, attributes = null, properties = null)
{ {
var proxyType = ResourceProxy.getProxy(type); var proxyType = ResourceProxy.getProxy(type);
var rt = new AsyncReply();
var res = new proxyType(); var res = new proxyType();
if (properties != null) if (properties != null)
Object.assign(res, properties); Object.assign(res, properties);
this.put(res, name, store, parent, null, 0, manager, attributes) if (store != null || parent != null || res instanceof IStore)
.then((ok)=>rt.trigger(res)) {
.error((ex)=>rt.triggerError(ex)); var rt = new AsyncReply();
return rt; this.put(res, name, store, parent, null, 0, manager, attributes)
.then((ok)=>rt.trigger(res))
.error((ex)=>rt.triggerError(ex));
return rt;
}
else
{
return new AsyncReply(res);
}
} }
getById(id) getById(id)
@ -103,7 +119,6 @@ export class WH extends IEventHandler
else else
rt.triggerError(store); rt.triggerError(store);
}).error(ex=>{ }).error(ex=>{
Warehouse.remove(resource);
rt.triggerError(ex); rt.triggerError(ex);
}); });
} }
@ -202,6 +217,7 @@ export class WH extends IEventHandler
let self = this; let self = this;
const initResource = ()=>{ const initResource = ()=>{
self.resources.add(resource.instance.id, resource); self.resources.add(resource.instance.id, resource);
if (self.warehouseIsOpen) if (self.warehouseIsOpen)
@ -210,16 +226,22 @@ export class WH extends IEventHandler
if (resource instanceof IStore) if (resource instanceof IStore)
resource.trigger(ResourceTrigger.Open).then(y=>{ rt.trigger(true); resource.trigger(ResourceTrigger.Open).then(y=>{ rt.trigger(true);
self._emit("connected", resource) self._emit("connected", resource)
}).error(ex => rt.triggerError(ex)); }).error(ex => {
Warehouse.remove(resource);
rt.triggerError(ex)
});
else else
rt.trigger(true); rt.trigger(true);
}).error(ex=>rt.triggerError(ex)); }).error(ex => {
Warehouse.remove(resource);
rt.triggerError(ex)
});
} }
else else
{ {
if (resource instanceof IStore) if (resource instanceof IStore)
self._emit("connected", resource); self._emit("connected", resource);
rt.trigger(true); rt.trigger(true);
} }
} }
@ -232,7 +254,11 @@ export class WH extends IEventHandler
else else
store.put(resource).then(ok=>{ store.put(resource).then(ok=>{
initResource(); initResource();
}).error(ex=>rt.triggerError(ex)); }).error(ex=> {
// failed to put
Warehouse.remove(resource);
rt.triggerError(ex);
});
return rt; return rt;
} }
@ -268,7 +294,6 @@ export class WH extends IEventHandler
getTemplateByType(type) getTemplateByType(type)
{ {
//debugger;
let className = type.prototype.constructor.name; let className = type.prototype.constructor.name;

View File

@ -0,0 +1,10 @@
import Authentication from "./Authentication.js";
import AuthenticationType from "./AuthenticationType.js";
export default class ClientAuthentication extends Authentication
{
constructor()
{
super(AuthenticationType.Client);
}
}

View File

@ -0,0 +1,10 @@
import Authentication from "./Authentication.js";
import AuthenticationType from "./AuthenticationType.js";
export default class HostAuthentication extends Authentication
{
constructor()
{
super(AuthenticationType.Host);
}
}

View File

@ -0,0 +1,33 @@
import AsyncReply from "../../Core/AsyncReply.js";
import IResource from "../../Resource/IResource.js";
export default class IMembership extends IResource
{
userExists(username, domain){
return new AsyncReply(false);
}
getPassword(username, domain)
{
return new AsyncReply(null);
}
getToken(tokenIndex, domain)
{
return new AsyncReply(null);
}
login(session)
{
}
logout(session)
{
}
tokenExists(tokenIndex, domain)
{
}
}

View File

@ -34,12 +34,13 @@ export default class MemoryStore extends IStore
constructor() constructor()
{ {
super(); super();
this.resources = []; this.resources = new Map();
} }
put(resource) put(resource)
{ {
this.resources[resource.instance.id] = resource; this.resources.set(resource.instance.id, resource);
return new AsyncReply(true);
} }
retrive(id) retrive(id)

View File

@ -6,8 +6,10 @@ import MemoryStore from './Stores/MemoryStore.js';
import IndexedDBStore from './Stores/IndexedDBStore.js'; import IndexedDBStore from './Stores/IndexedDBStore.js';
import IResource from './Resource/IResource.js'; import IResource from './Resource/IResource.js';
import ResourceProxy from './Proxy/ResourceProxy.js'; import ResourceProxy from './Proxy/ResourceProxy.js';
import DistributedConnection from './Net/IIP/DistributedConnection.js';
if (window) { if (typeof window !== 'undefined')
{
window.wh = wh; window.wh = wh;
window.Structure = Structure; window.Structure = Structure;
window.DistributedResource = DistributedResource; window.DistributedResource = DistributedResource;
@ -15,8 +17,9 @@ if (window) {
window.IndexedDBStore = IndexedDBStore; window.IndexedDBStore = IndexedDBStore;
window.IResource = IResource; window.IResource = IResource;
window.ResourceProxy = ResourceProxy; window.ResourceProxy = ResourceProxy;
window.DistributedConnection = DistributedConnection;
} }
else if (global) else if (typeof global !== 'undefined')
{ {
global.wh = wh; global.wh = wh;
global.Structure = Structure; global.Structure = Structure;
@ -24,6 +27,7 @@ else if (global)
global.MemoryStore = MemoryStore; global.MemoryStore = MemoryStore;
global.IndexedDBStore = IndexedDBStore; global.IndexedDBStore = IndexedDBStore;
global.IResource = IResource; global.IResource = IResource;
global.DistributedConnection = DistributedConnection;
} }
export default wh; export default wh;

View File

@ -1,77 +0,0 @@
"use strict";
var demo = null;
class JSResource extends IResource
{
static get template()
{
return {
namespace: "JS",
properties: [{name: "message", recordable: true}],
functions: [{name: "send", void: true, expansion: null}],
events: [{name: "published", expansion: null}]
}
}
constructor()
{
super();
this.message = "hi";
}
send(message)
{
console.log(message);
}
}
function init() {
var local = new MemoryStore();
var con = new DistributedConnection("ws://localhost:5001/iip/system/iip", "localhost", "demo", "1234");
Warehouse.put(con, "remote");
Warehouse.put(local, "local");
Warehouse.put(new JSResource(), "js", local);
con.on("ready", async function (d) {
// var list = await con.query("").task;
// console.log(list);
// debugger;
Warehouse.get("remote/db/my").then(async function(rt){
console.log("Object received.");
demo = rt;
rt.on("LevelUp", function(v){
console.log("LevelUp", v);
});
con.getRecord(rt, new Date(new Date() - 60000000), new Date()).then(function(h){
console.log(h);
});
var l = await rt.Subtract(3).task;
console.log("Await", l);
//rt.Stream(10).then(x=> console.log("finished S"))
// .chunk(x => console.log ("chunk", x))
// .progress((x,y,z) => console.log("progress", x, y, z));
//rt.Enum(4).then(x=> console.log("Enum finished"))
// .chunk(x => console.log ("Enum chunk", x))
// .progress((x,y,z) => console.log("progress", x, y, z));
});
}).on("error", function(sender, code, msg){
console.log(sender, code, msg);
});
}

View File

@ -1,5 +0,0 @@
"use strict";
export * from "../src/IEventHandler.js";
export * from "../src/IDestructible.js";
export * from "../src/IResource.js";

View File

@ -1,8 +0,0 @@
<html>
<head>
<script src='test.js' type="module"></script>
</head>
</body>
</html>

View File

@ -1,30 +0,0 @@
var demo;
import IStore from '../src/Resource/IStore.js';
import wh from '../src/esiur.js';
class MyStore extends IStore
{
}
async function load()
{
// window.x = await wh.get("iip://localhost:5001/db/my", {username: "demo", password: "1234"});
window.x = await wh.get("iip://chat.go.iq:5001/sys/hd", {username: "admin", password: "delta"});
console.log(window.x);
}
load();
/*
wh.get("iip://localhost:5001/db/my", {username: "demo", password: "1234"})
.then(x=>{
console.log("connected", x);
window.x = x;
}).catch(x=>{
console.log("error", x);
});
*/

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1,67 +0,0 @@
.app
{
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
}
.app-tool-bar
{
display: flex;
width: 100%;
height: 60px;
background-color: var(--default-background-color);
}
.app-center
{
flex: 1;
width: 100%;
display: flex;
background-color: yellow;
}
.app-content
{
flex: 1;
}
.app-menu
{
min-width: 300px;
background-color: red;
}
.app-status-bar
{
height: 60px;
background-color: blue;
}
.browser
{
display: flex;
flex-wrap: wrap;
}
.browser > .bar
{
width: 100%;
flex-grow:2;
height: 40px;
}
.browser > .table:nth-child(2)
{
width: 200px;
height: calc(100% - 40px);
}
.browser > .table:nth-child(3)
{
width: calc(100% - 200px);
height: calc(100% - 40px);
}

Binary file not shown.

File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 434 KiB

View File

@ -1,134 +0,0 @@
<html>
<head>
<script src="../../src/IEventHandler.js"></script>
<script src="../../src/IDestructible.js"></script>
<script src="../../src/AutoList.js"></script>
<script src="../../src/KeyList.js"></script>
<script src="../../src/PropertyValue.js"></script>
<script src="../../src/IResource.js"></script>
<script src="../../src/IStore.js"></script>
<script src="../../src/Structure.js"></script>
<script src="../../src/StructureArray.js"></script>
<script src="../../src/ResourceArray.js"></script>
<script src="../../src/MemberTemplate.js"></script>
<script src="../../src/AsyncReply.js"></script>
<script src="../../src/AsyncException.js"></script>
<script src="../../src/Authentication.js"></script>
<script src="../../src/Session.js"></script>
<script src="../../src/IPermissionsManager.js"></script>
<script src="../../src/AsyncBag.js"></script>
<script src="../../src/AsyncQueue.js"></script>
<script src="../../src/BinaryList.js"></script>
<script src="../../src/Codec.js"></script>
<script src="../../src/DataConverter.js"></script>
<script src="../../src/SHA256.js"></script>
<script src="../../src/DataType.js"></script>
<script src="../../src/DistributedConnection.js"></script>
<script src="../../src/DistributedResource.js"></script>
<script src="../../src/DistributedResourceQueueItem.js"></script>
<script src="../../src/EventTemplate.js"></script>
<script src="../../src/FunctionTemplate.js"></script>
<script src="../../src/Guid.js"></script>
<script src="../../src/IIPAuthPacket.js"></script>
<script src="../../src/IIPPacket.js"></script>
<script src="../../src/Instance.js"></script>
<script src="../../src/NetworkBuffer.js"></script>
<script src="../../src/NotModified.js"></script>
<script src="../../src/PropertyTemplate.js"></script>
<script src="../../src/ResourceTemplate.js"></script>
<script src="../../src/SendList.js"></script>
<script src="../../src/Warehouse.js"></script>
<script src="../../src/MemoryStore.js"></script>
<link href="/iui-js/iui.css" rel="stylesheet">
<link rel="stylesheet" href="css/font-awesome.min.css">
<link href="css/style.css" rel="stylesheet">
<script src="/iui-js/iui.js"></script>
<script src="viewers/Esiur.Stores.MemoryStore.js"></script>
<script src="js/browser.js"></script>
<script src="js/app.js"></script>
<script>
</script>
</head>
<body onload="init()">
<div class="app">
<div class="app-tool-bar">
<div class="button-flat" style="width: 50px; padding: 10px">
<i class="fa fa-bars fa-3x" aria-hidden="true"></i>
</div>
<div style="font-size: 30px; padding: 10px; width: 280px">
Resource Manager
</div>
<div style="padding: 10px; font-size: 20px;">
<input type="search" style="font-size: 25px">
</div>
</div>
<div class="app-center">
<div id="treeList" class="app-menu">
</div>
<div class="app-content" id="divContent">
</div>
</div>
<div class="app-status-bar">
</div>
</div>
<div id="dlgLogin">
<table class="dialog-body">
<tr>
<td>Server URL:</td>
<td><input id="txtURL" type="text" class="text" value="ws://localhost:5001/iip/system/iip"></td>
</tr>
<tr>
<td>Domain:</td>
<td><input id="txtDomain" type="text" class="text" value="localhost"></td>
</tr>
<tr>
<td>Username:</td>
<td><input id="txtUsername" type="text" class="text" value="admin"></td>
</tr>
<tr>
<td>Password:</td>
<td><input id="txtPassword" type="password" class="text" value="dijtel"></td>
</tr>
</table>
<div class="dialog-footer">
<button class="button" onclick="connect()">
Connect
</button>
</div>
</div>
</body>
</html>

View File

@ -1,4 +0,0 @@
class IUIView extends IUIWidget
{
}

View File

@ -1,30 +0,0 @@
function init()
{
iui("dlgLogin").dialog().show();
var local = new MemoryStore();
Warehouse.put(local, "local");
iui("divContent").browser();
}
function connect()
{
var url = document.getElementById("txtURL").value;
var domain = document.getElementById("txtDomain").value;
var username = document.getElementById("txtUsername").value;
var password = document.getElementById("txtPassword").value;
iui("dlgLogin").setLoading(true);
var con = new DistributedConnection(url, domain, username, password);
Warehouse.put(con, "remote");
con.on("ready", function (d) {
iui("divContent").setConnection(con);
iui("dlgLogin").hide();
}).on("error", function(sender, code, msg){
console.log(sender, code, msg);
});
}

View File

@ -1,132 +0,0 @@
class ResourceBrowser extends IUIWidget
{
loadClass(className)
{
var rt = new AsyncReply();
if (this.scripts[className] != null)
{
rt.trigger(true);
}
else
{
var script = document.createElement('script');
var self = this;
script.onload = function () {
self.scripts[classsName] = script;
rt.trigger(true);
};
script.src = className + ".js";
document.head.appendChild(script);
}
}
constructor(el, properties)
{
super(el, IUI.extend(properties,
{
customClass: "browser",
visible: false
})
);
var treeLayout = [
{width: '200px', field: "instance", title: "Name", formatter: function(d, v){
if(v.instance.attributes.item("name") == null)
return v.instance.name;
else
return v.instance.attributes.item("name");
}},
];
/*
var contentLayout = [
{field: "instance", title: "Name", formatter: function(d, v){
return v.instance.attributes.item("name");
}},
{field: "instance", title: "Type", formatter: function(d, v){
return v.instance.template.name;
}}
];
*/
this.tree = iui(document.createElement("div")).table({tree: true, layout: treeLayout});
// this.content = iui(document.createElement("div")).table({layout: contentLayout});
this.bar = iui(document.createElement("div")).bar();
this.el.classList.add(this.customClass);
this.el.appendChild(this.bar.el);
this.el.appendChild(this.tree.el);
// this.el.appendChild(this.content.el);
var self = this;
this.tree.on("dblclick", function(item){
self.tree.clear();
self.connection.getAttributes(item, ["name", "parents", "type"]).then(function(attrs){
self.tree.add(item);
// self.content.add(item);
});
}).on("expand", function(e){
self.connection.getAttributes(e.item, ["children"]).then(function(attrs){
attrs.children.forEach(function(child){
self.connection.getAttributes(child, ["name", "parents", "childrenCount", "type"]).then(function(cAttars){
self.tree.add(child, cAttars.childrenCount > 0);
e.success();
});
});
});
});
}
setConnection(connection, query = "")
{
var self = this;
this.connection = connection;
this.connection.query(query).then(function(rt)
{
rt.forEach(function(item){
connection.getAttributes(item, ["name", "childrenCount", "type"]).then(function(attrs){
//connection.getAttributes(item, ["name", "children", "type"]).then(function(attrs){
self.tree.add(item, attrs.childrenCount > 0);
/*
var children = attrs.children;
for(var i = 0; i < children.length; i++)
{
if (!children[i].instance.attributes.contains("parents"))
children[i].instance.attributes.add("parents", []);
children[i].instance.attributes.item("parents").push(item);
self.tree.add(children[i]);
}
*/
});
});
/*
for(var i = 0; i < rt.length; i++)
{
var item = rt[i];
connection.getAttributes(rt[i]).then(function(attrs){
self.tree.add(rt[i]);
self.content.add(rt[i]);
});
}
*/
});
}
}
IUI.module("browser", ResourceBrowser);

View File

@ -1,9 +0,0 @@
class Esiur_Stores_MemoryStore extends IUIWidget
{
constuctor()
{
}
}
IUI.module("Esiur.Stores.MemoryStore", Esiur_Stores_MemoryStore);