Пример #1
0
    def configure(self, config):
        self.stop()
        if not config['couch_host'] or not config['couch_port']:
            return
        if not config['sync_enabled']:
            return
        couch_location = f"{config['couch_host']}:{config['couch_port']}"
        creds = ''
        if config['couch_username'] and config['couch_password']:
            creds = f"{config['couch_username']}:{config['couch_password']}@"
        protocol = 'https' if config['use_tls'] else 'http'
        couch_prefix = f'{protocol}://{creds}{couch_location}'
        for db in ['groceries', 'recipes', 'plans']:
            url = f'{couch_prefix}/{db}'
            # XXX working around some pyodide js bridge weirdness
            sync = eval(
                f"sync = PouchDB.sync('{db}', '{url}', {{live:true,retry:true}})"
            )
            eval(
                f"update_{db}_callback = pyodide.runPython('from config import update_{db}_callback; update_{db}_callback')"
            )
            eval(f"sync.on('change', () => update_{db}_callback())")
            self.syncs.append(sync)

        console.log(self.syncs)
Пример #2
0
    def __init__(self, config):
        self.config = dotdict(config or {})
        super().__init__(logger)
        self.channel = self.config.get("channel") or "imjoy_rpc"
        self._event_handlers = {}
        self.peer_id = str(uuid.uuid4())
        self.debug = True
        _is_web_worker = js.eval(
            "typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope"
        )
        if _is_web_worker:
            self._post_message = js.postMessage
        else:
            self._post_message = js.eval(
                "self._post_message = (msg)=>{parent.postMessage(msg, '*')}")

        def msg_cb(msg):
            data = decode_jsproxy(msg.data)
            # TODO: remove the exception for "initialize"
            if data.get("peer_id") == self.peer_id or data.get(
                    "type") == "initialize":
                if "type" in data:
                    if data["type"] == "execute":
                        self.execute(data)
                        return
                    self._fire(data["type"], data)
            else:
                logger.warn("connection peer id mismatch {} != {}".format(
                    data.get("peer_id"), self.peer_id))

        js.self.addEventListener("message", msg_cb)
Пример #3
0
def pipe(buffer_id=None):
    import js
    if buffer_id is None:
        po = js.eval('new pipe()')
    else:
        po = js.eval('new pipe(%i)'%buffer_id)
    fileNumbers.append(0)
    fileNumbers.append(1)
    re,we=fileNumbers.index(0), fileNumbers.index(1)
    po.read_end.fno=re
    po.write_end.fno=we
    fileNumbers[re],fileNumbers[we]=po.read_end, po.write_end
    return re,we
Пример #4
0
 def test_js_array_access(self):
     import js
     a = js.eval("[1,2,3]")
     assert a[0] == 1
     assert a[1] == 2
     assert a[2] == 3
     assert a.length == len(a) == 3
Пример #5
0
 def handlerDispatch(self, fn):
     wrapper = js.eval('(function(){function %s(){'
                       'var args=[];'
                       'for (var i=1;i<arguments.length;i++){'
                       '   args.push(arguments[i]);'
                       '}'
                       '%s.handler(%r, args);'
                       '}; return %s})()' % (fn, fn, fn, fn))
     wrapper.handler = self.dispatchFunctionWrapper
     return wrapper
Пример #6
0
    def __init__(self, kind, value, maxvalue):
        sl = self._semlock = js.eval('new Semaphore(1);')
        sl.kind=kind
        sl.value=0
        sl.maxvalue=maxvalue
        debug('created semlock with handle %s' % sl.handle)
        self._make_methods()

        if sys.platform != 'win32':
            def _after_fork(obj):
                obj._semlock._after_fork()
            register_after_fork(self, _after_fork)
Пример #7
0
def run_js(code: str, /) -> Any:
    """
    A wrapper for the JavaScript 'eval' function.

    Runs 'code' as a Javascript code string and returns the result. Unlike
    JavaScript's 'eval', if 'code' is not a string we raise a TypeError.
    """
    from js import eval

    if not isinstance(code, str):
        raise TypeError(
            f"argument should have type 'string' not type '{type(code).__name__}'"
        )
    return eval(code)
Пример #8
0
    def execute(self, data):
        try:
            t = data["code"]["type"]
            if t == "script":
                content = data["code"]["content"]
                js.eval(script_template % (content, content))
                self.emit({"type": "executed"})
            elif t == "requirements":

                def success(result):
                    self.emit({"type": "executed"})

                def fail(error):
                    self.emit({"type": "executed", "error": str(error)})

                install_requirements(data["code"]["requirements"], success,
                                     fail)
            else:
                raise Exception("unsupported type")
        except Exception as e:
            traceback_error = traceback.format_exc()
            logger.error("error during execution: %s", traceback_error)
            self.emit({"type": "executed", "error": traceback_error})
Пример #9
0
 def onHtmlUploadUrlAvailable(self, req):
     import js
     data = NetworkService.decode(req)["values"]
     fileObj, dirKey = req.fileUploadTask["args"]
     if "uploadKey" in data:  # New Resumeable upload format
         self.currentHtmlUpload = {
             "key": data["uploadKey"],
             "node": dirKey,
             "skelType": "leaf",
             "fileSize": fileObj.size
         }
         js.window.fetch(data["uploadUrl"], {
             "method": "POST",
             "body": fileObj,
             "mode": "no-cors"
         }).then(self.onHtmlBucketUploadFinished)
     else:
         formData = js.eval("new FormData();")
         for key, value in data["params"].items():
             if key == "key":
                 targetKey = value[:-16]  # Truncate source/file.dat
                 fileName = fileObj.name
                 value = value.replace("file.dat", fileName)
             formData.append(key, value)
         formData.append("file", fileObj)
         self.currentHtmlUpload = {
             "key": targetKey,
             "node": dirKey,
             "skelType": "leaf",
             "fileSize": fileObj.size
         }
         js.window.fetch(data["url"], {
             "method": "POST",
             "body": formData,
             "mode": "no-cors"
         }).then(self.onHtmlBucketUploadFinished)
Пример #10
0
 def test_eval_operates_at_global_scope(self):
     import js
     js.eval("var x = 12")
     assert js.globals.x == 12
Пример #11
0
def Lock():
    import js
    return js.eval('new Semaphore(1)');
Пример #12
0
import js
import bokeh
from bokeh.plotting import figure
import numpy as np

x = np.linspace(-6, 6, 100)
y = np.cos(x)
p = figure(width=500, height=500)
p.circle(x, y, size=7, color="firebrick", alpha=0.5)
script, div = bokeh.embed.components(p)
container = js.document.getElementById("container")
container.innerHTML = div
tmp = js.document.createElement("div")
tmp.innerHTML = script
js.eval(tmp.innerText)
Пример #13
0
 def test_eval_operates_at_global_scope(self):
     import js
     js.eval("var x = 12")
     assert js.globals.x == 12
Пример #14
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import encodings.utf_16_le
import encodings.utf_7
import base64

import pefile
import js

import time
from collections import OrderedDict

bindata = js.eval('bblob')
#tttest=str(ttest);
binarydatastuff = base64.b64decode(str(bindata))
#pe=pefile.PE(data=b);
#print(pe.dump_info());

pe2 = pefile.PE(data=binarydatastuff)
#testi = pe2.dump_dict()
#print(testi)
print(pe2.dump_info())
#imphash = pe.get_imphash()
#print('Imphash: ' + imphash)
#print("PE PRINT:")
#dd = pe.DOS_HEADER.dump_dict()
#js.globals["pe"] = dd;
#print(pe.dump_info())
Пример #15
0
 def eventDispatch(self, fn):
     wrapper = js.eval('(function(){function %s(self, node){'
                       '%s.handler(%r, self, node);'
                       '}; return %s})()' % (fn, fn, fn, fn))
     wrapper.handler = self.dispatchEventWrapper
     return wrapper
Пример #16
0
                else:
                    self.relay(func.func_name, newArgs, kw)
            else:
                js.globals['console'].log(
                    'Skipping call to %s: %s doesn\'t relay and I was called from the wrong side' % (
                        func.func_name, func.func_name))
        executor.func_name = func.func_name
        return executor
    return decorator


if side == 'server':
    def convert(l):
        return l
else:
    jgetattr = js.eval('jgetattr=function(o,attr){return o[attr];};')
    def convert(l):
        if not isinstance(l, (list, tuple, js.Array)):
            if isinstance(l, js.Number):
                return (float(l))
            elif isinstance(l, js.String):
                return (unicode(l))
            elif isinstance(l, js.Object):
                r = {}
                for i in ['name', 'id', 'class', 'value', 'type', '__id__', 'objectID', 'classIdentifier']:
                    r[i] = convert(jgetattr(l, i))
                print 94, r, side
                return r
            elif isinstance(l, js.Undefined):
                return None
            return l
Пример #17
0
 def __setstate__(self, state):
     self._semlock = js.eval('new Semaphore(1);')
     self._semlock.value=state[1]
     self._semlock.maxvalue=state[2]
     debug('recreated blocker with handle %r' % state[0])
     self._make_methods()
Пример #18
0
    nbytes = len(data)
    if nbytes == 0:
        return 0L
    ashex = _binascii.hexlify(data[::-1])
    n = long(ashex, 16) # quadratic time before Python 2.3; linear now
    if data[-1] >= '\x80':
        n -= 1L << (nbytes * 8)
    return n

import js

jdir = js.eval('''function jdir(obj){
    var L = [];
    for (var i in obj) {
        L.push(i);
    }
    return L;
};jdir
''')

jlist = lambda val: [val[i] for i in xrange(val.length)]

Pickler.dispatch[js.Number]=lambda pickler, val: pickler.save(float(val))
Pickler.dispatch[js.String]=lambda pickler, val: pickler.save(unicode(val))
Pickler.dispatch[js.Boolean]=lambda pickler, val: pickler.save(bool(val))
Pickler.dispatch[js.Object]=lambda pickler, val: pickler.save({k:val[k] for k in jlist(jdir(val))})
Pickler.dispatch[js.Array]=lambda pickler, val: pickler.save(jlist(val))

# Shorthands

try: