def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    objectPrefix = Namespace("/ndn/eb/run/28/description", keyChain)

    dump("Register prefix", objectPrefix.name)
    # Set the face and register to receive Interests.
    objectPrefix.setFace(
        face,
        lambda prefixName: dump("Register failed for prefix", prefixName))

    dump("Preparing data for", objectPrefix.name)
    GeneralizedObjectHandler().setObject(objectPrefix,
                                         Blob("EB run #28. Ham and oats"),
                                         "text/html")

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    publishIntervalMs = 1000.0
    stream = Namespace("/ndn/eb/stream/run/28/annotations", keyChain)
    handler = GeneralizedObjectStreamHandler(stream)

    dump("Register prefix", stream.name)
    # Set the face and register to receive Interests.
    stream.setFace(face,
      lambda prefixName: dump("Register failed for prefix", prefixName))

    # Loop, producing a new object every publishIntervalMs milliseconds (and
    # also calling processEvents()).
    previousPublishMs = 0
    while True:
        now = Common.getNowMilliseconds()
        if now >= previousPublishMs + publishIntervalMs:
            dump("Preparing data for sequence",
              handler.getProducedSequenceNumber() + 1)
            handler.addObject(
              Blob("Payload " + str(handler.getProducedSequenceNumber() + 1)),
              "application/json")

            previousPublishMs = now

        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 3
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Create an in-memory key chain with default keys.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    streamNamespace = Namespace(Name("/example-data"), keyChain)

    dump("Register prefix", streamNamespace.name)
    # Set the face and register to receive Interests.
    streamNamespace.setFace(face,
      lambda prefixName: dump("Register failed for prefix", prefixName))

    # /example-data/2~3
    for sequenceNumber in range(2, 4):
        sequenceNamespace = streamNamespace[str(sequenceNumber)]
        dump("Preparing data for", sequenceNamespace.name)

        # Prepare the _meta packet.
        contentMetaInfo = ContentMetaInfo()
        contentMetaInfo.setContentType("jpeg")
        contentMetaInfo.setTimestamp(Common.getNowMilliseconds())
        contentMetaInfo.setHasSegments(True)
        sequenceNamespace["_meta"].serializeObject(contentMetaInfo.wireEncode())

        # Read jpeg file
        img_path = os.path.join(root_path, "sample420x236.jpg")
        with open(img_path, "rb") as f:
            data = f.read()
        segment_size = face.getMaxNdnPacketSize() // 2
        segment_cnt = (len(data) + segment_size - 1) // segment_size

        # We know the content has two segments.
        metaInfo = MetaInfo()
        metaInfo.setFinalBlockId(Name().appendSegment(segment_cnt - 1)[0])
        sequenceNamespace.setNewDataMetaInfo(metaInfo)
        for i in range(segment_cnt):
            start_offset = i * segment_size
            end_offset = start_offset + segment_size
            sequenceNamespace[Name.Component.fromSegment(i)].serializeObject(
                Blob(bytearray(data[start_offset:end_offset])))

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 4
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    face = Face("memoria.ndn.ucla.edu")
    page = Namespace("/ndn/edu/ucla/remap/demo/ndn-js-test/named-data.net/project/ndn-ar2011.html/%FDT%F7n%9E")
    page.setFace(face)

    enabled = [True]
    def onSegmentedObject(objectNamespace):
        dump("Got segmented object size", objectNamespace.obj.size())
        enabled[0] = False
    SegmentedObjectHandler(page, onSegmentedObject).objectNeeded()

    # Loop calling processEvents until a callback sets enabled[0] = False.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 5
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    if sys.version_info[0] <= 2:
        userName = raw_input("Enter your user name (e.g. \"a\" or \"b\"): ")
    else:
        userName = input("Enter your user name (e.g. \"a\" or \"b\"): ")
    if userName == "":
        dump("You must enter a user name")
        return

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    applicationPrefix = Namespace(Name("/test/app"), keyChain)
    applicationPrefix.setFace(face,
      lambda prefix: dump("Register failed for prefix", prefix))
    applicationPrefix.enableSync()

    userPrefix = applicationPrefix[Name.Component(userName)]

    def onStateChanged(nameSpace, changedNamespace, state, callbackId):
        if (state == NamespaceState.NAME_EXISTS and
             not userPrefix.name.isPrefixOf(changedNamespace.name)):
            dump("Received", changedNamespace.name.toUri())

    applicationPrefix.addOnStateChanged(onStateChanged)

    publishIntervalMs = 1000.0
    component = Name("/%00").get(0)

    # Loop, producing a new name every publishIntervalMs milliseconds (and also
    # calling processEvents()).
    previousPublishMs = 0.0
    while True:
        now = Common.getNowMilliseconds()
        if now >= previousPublishMs + publishIntervalMs:
            # If userName is "a", this makes /test/app/a/%00, /test/app/a/%01, etc.
            newNamespace = userPrefix[component]
            dump("Publish", newNamespace.name.toUri())
            component = component.getSuccessor()

            previousPublishMs = now

        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 6
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    groupName = Name("/Prefix/READ")
    userName = Name("/U")
    userKeyName = Name("/U/Key")
    contentPrefix = Name("/Prefix/SAMPLE")
    contentName = Name(contentPrefix).append("Content")

    keyChain = createVerifyKeyChain()

    # Imitate test_consumer from the PyNDN integration tests.
    databaseFilePath = "test.db"
    try:
        os.remove(databaseFilePath)
    except OSError:
        pass

    namespace = Namespace(contentName)
    namespace.setFace(face)
    handler = NacConsumerHandler(
      namespace, keyChain, groupName, userName, Sqlite3ConsumerDb(databaseFilePath))
    fixtureUserDKeyBlob = Blob(FIXTURE_USER_D_KEY)
    handler.addDecryptionKey(userKeyName, fixtureUserDKeyBlob)

    enabled = [True]
    def onContentSet(namespace, contentNamespace, callbackId):
        if contentNamespace == namespace:
            dump("Got segmented content", contentNamespace.content.toRawStr())
            enabled[0] = False
    namespace.addOnContentSet(onContentSet)

    segmentStream = SegmentStream(namespace)
    SegmentedContent(segmentStream)
    segmentStream.start()

    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 7
0
def main():
    face = Face("memoria.ndn.ucla.edu")
    page = Namespace("/ndn/edu/ucla/remap/demo/ndn-js-test/named-data.net/project/ndn-ar2011.html/%FDT%F7n%9E")
    page.setFace(face)

    enabled = [True]
    def onContentSet(namespace, contentNamespace, callbackId):
        if contentNamespace == namespace:
            dump("Got segmented content size", contentNamespace.content.size())
            enabled[0] = False
    page.addOnContentSet(onContentSet)

    segmentStream = SegmentStream(page)
    SegmentedContent(segmentStream)
    segmentStream.start()

    # Loop calling processEvents until a callback sets enabled[0] = False.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 8
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    memberName = Name("/first/user")
    memberKeyName = Name(memberName).append(Name("/KEY/%0C%87%EB%E6U%27B%D6"))

    memberKeyChain = KeyChain("pib-memory:", "tpm-memory:")
    memberKeyChain.importSafeBag(SafeBag
      (memberKeyName, Blob(MEMBER_PRIVATE_KEY, False),
       Blob(MEMBER_PUBLIC_KEY, False)))
    # TODO: Use a real Validator.
    decryptor = DecryptorV2(
      memberKeyChain.getPib().getIdentity(memberName).getDefaultKey(),
      ValidatorNull(), memberKeyChain, face)

    contentPrefix = Name("/testname/content")
    contentNamespace = Namespace(contentPrefix)
    contentNamespace.setFace(face)
    contentNamespace.setDecryptor(decryptor)

    enabled = [True]
    def onSegmentedObject(objectNamespace):
        dump("Got segmented content", objectNamespace.obj.toRawStr())
        enabled[0] = False
    SegmentedObjectHandler(contentNamespace, onSegmentedObject).objectNeeded()

    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 9
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    prefix = Namespace("/ndn/test/status")
    prefix.setFace(face)

    enabled = [True]

    # This is called to print the content after it is re-assembled from segments.
    def onGeneralizedObject(contentMetaInfo, objectNamespace):
        dump("Got generalized object", objectNamespace.name, ", content-type",
             contentMetaInfo.contentType, ":", str(objectNamespace.obj))
        enabled[0] = False

    handler = GeneralizedObjectHandler(prefix, onGeneralizedObject)
    # Allow one component after the prefix for the <version>.
    handler.setNComponentsAfterObjectNamespace(1)
    # In objectNeeded, set mustBeFresh == true so we avoid expired cached data.
    prefix.objectNeeded(True)

    # Loop calling processEvents until a callback sets enabled[0] = False.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 10
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    prefix = Name("/icear-server/result/example-data/2/deeplab")
    prefixNamespace = Namespace(prefix)
    prefixNamespace.setFace(face)

    enabled = [True]
    img = [None]

    def onGeneralizedObject(contentMetaInfo, obj):
        data = obj.toBytes()
        dump("Got generalized object, content-type",
             contentMetaInfo.getContentType(), ":", repr(data))
        print(len(data))
        enabled[0] = False
        img[0] = data

    goh = GeneralizedObjectHandler(onGeneralizedObject)
    prefixNamespace.setHandler(goh).objectNeeded()

    # Loop calling processEvents until a callback sets enabled[0] = False.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    image = Image.open(io.BytesIO(img[0]))
    image.show()
Esempio n. 11
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    stream = Namespace("/ndn/eb/stream/run/28/annotations")
    stream.setFace(face)

    def onNewObject(sequenceNumber, contentMetaInfo, objectNamespace):
        dump("Got generalized object, sequenceNumber", sequenceNumber,
             ", content-type", contentMetaInfo.contentType, ":",
             str(objectNamespace.obj))

    pipelineSize = 10
    GeneralizedObjectStreamHandler(stream, pipelineSize,
                                   onNewObject).objectNeeded()

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 12
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    objectPrefix = Namespace("/ndn/eb/run/28/description")
    objectPrefix.setFace(face)

    enabled = [True]

    def onGeneralizedObject(contentMetaInfo, objectNamespace):
        dump("Got generalized object, content-type",
             contentMetaInfo.contentType, ":", str(objectNamespace.obj))
        enabled[0] = False

    GeneralizedObjectHandler(objectPrefix, onGeneralizedObject).objectNeeded()

    # Loop calling processEvents until a callback sets enabled[0] = False.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 13
0
    def process():
        # while True:
        # Set timeout to 0 for an immediate check.
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "exit":
                stopGui()
                # We will send the leave message below.
                # break

            # before producer has namespace.publish call, we manually call onNameAdded as a hack to publish
            namesync.onNameAdded(None, Namespace(Name(input)), 0, True)
        face.processEvents()
        if root: 
            root.after(100, process)
Esempio n. 14
0
    def fetch_data(self, prefix, start_frame, end_frame):
        # type: (Name, int, int) -> None
        for frame_id in range(start_frame, end_frame + 1):
            name = Name(prefix).append(str(frame_id))

            # Feed server with existing data
            if self.storage.exists(name):
                self.on_payload(name)

            # Fetching new data
            logging.info("Fetching: %s", name.toUri())
            # TODO: Namespace will put everything into memory
            frame_namespace = Namespace(name)
            frame_namespace.setFace(self.face)
            frame_namespace.setHandler(
                GeneralizedObjectHandler(partial(self.on_generalized_obj,
                                                 name))).objectNeeded()
Esempio n. 15
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    prefix = Namespace("/ndn/test/status", keyChain)

    dump("Register prefix", prefix.name)
    # Set the face and register to receive Interests.
    prefix.setFace(face,
      lambda prefixName: dump("Register failed for prefix", prefixName))

    handler = GeneralizedObjectHandler()
    # Each generalized object will have a 1000 millisecond freshness period.
    metaInfo = MetaInfo()
    metaInfo.setFreshnessPeriod(1000.0)

    # This is called when the library receives an Interest which is not
    # satisfied by Data already in the Namespace tree.
    def onObjectNeeded(namespace, neededNamespace, callbackId):
        if not (neededNamespace is prefix):
            # This is not the expected Namespace.
            return False

        # Make a version from the current time.
        versionNamespace = prefix[
          Name.Component.fromVersion(Common.getNowMilliseconds())]
        # The metaInfo has the freshness period.
        versionNamespace.setNewDataMetaInfo(metaInfo)
        dump("Producing the generalized object for", versionNamespace.name)
        handler.setObject(
          versionNamespace, Blob("Status as of " + str(datetime.datetime.now())),
          "text/html")
        return True

    prefix.addOnObjectNeeded(onObjectNeeded)

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 16
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    groupName = Name("/Prefix/READ")
    userName = Name("/U")
    userKeyName = Name("/U/Key")
    contentPrefix = Name("/Prefix/SAMPLE")
    contentName = Name(contentPrefix).append("Content")

    keyChain = createVerifyKeyChain()

    # Imitate test_consumer from the PyNDN integration tests.
    databaseFilePath = "test.db"
    try:
        os.remove(databaseFilePath)
    except OSError:
        pass

    namespace = Namespace(contentName)
    namespace.setFace(face)
    handler = NacConsumerHandler(namespace, keyChain, groupName, userName,
                                 Sqlite3ConsumerDb(databaseFilePath))
    fixtureUserDKeyBlob = Blob(FIXTURE_USER_D_KEY)
    handler.addDecryptionKey(userKeyName, fixtureUserDKeyBlob)

    enabled = [True]

    def onContentSet(namespace, contentNamespace, callbackId):
        if contentNamespace == namespace:
            dump("Got segmented content", contentNamespace.content.toRawStr())
            enabled[0] = False

    namespace.addOnContentSet(onContentSet)
    SegmentedContent(namespace).start()

    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 17
0
def main():
    face = Face("memoria.ndn.ucla.edu")
    page = Namespace(
        "/ndn/edu/ucla/remap/demo/ndn-js-test/named-data.net/project/ndn-ar2011.html/%FDX%DC5B"
    )
    page.setFace(face)

    enabled = [True]

    def onContentSet(namespace, contentNamespace, callbackId):
        if contentNamespace == namespace:
            dump("Got segmented content size", contentNamespace.content.size())
            enabled[0] = False

    page.addOnContentSet(onContentSet)
    SegmentedContent(page).start()

    # Loop calling processEvents until a callback sets enabled[0] = False.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 18
0
def main(args):
    face = Face()

    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    gobj = Namespace(args['<prefix>'], keyChain)

    gobj.setFace(
        face,
        lambda prefixName: dump("Register failed for prefix", prefixName))

    handler = GeneralizedObjectHandler()

    metaInfo = MetaInfo()
    if args['--freshness']:
        metaInfo.setFreshnessPeriod(float(args['--freshness']))
    else:
        metaInfo.setFreshnessPeriod(1000.0)

    def onObjectNeeded(namespace, neededNamespace, callbackId):
        if not (neededNamespace is gobj):
            # This is not the expected Namespace.
            return False

        # Make a version from the current time.
        versionNamespace = gobj[Name.Component.fromVersion(
            Common.getNowMilliseconds())]
        # The metaInfo has the freshness period.
        versionNamespace.setNewDataMetaInfo(metaInfo)

        with open(args['<file>'], 'r') as f:
            handler.setObject(versionNamespace, Blob(f.read()), "text/html")
        return True

    gobj.addOnObjectNeeded(onObjectNeeded)
    while True:
        face.processEvents()
        time.sleep(0.01)
Esempio n. 19
0
def main(args):
    face = Face()

    prefix = Namespace(args['<prefix>'])
    prefix.setFace(face)

    enabled = [True]

    # This is called to print the content after it is re-assembled from segments.
    def onGeneralizedObject(contentMetaInfo, objectNamespace):
        if args['--verbose']:
            print(objectNamespace.getName())
        print(str(objectNamespace.obj))
        enabled[0] = False

    handler = GeneralizedObjectHandler(onGeneralizedObject)
    handler.setNComponentsAfterObjectNamespace(1)
    prefix.setHandler(handler).objectNeeded(True)

    # Loop calling processEvents until a callback sets enabled[0] = False.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 20
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Create an in-memory key chain with default keys.
    # keyChain = KeyChain("pib-memory:", "tpm-memory:")
    # keyChain.importSafeBag(SafeBag
    #   (Name("/testname/KEY/123"),
    #    Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
    #    Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    # face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Use default keys
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    publishIntervalMs = 1000.0 / 10
    stream = Namespace("/ndn/eb/stream/run/28/annotations", keyChain)
    handler = GeneralizedObjectStreamHandler()
    stream.setHandler(handler)

    dump("Register prefix", stream.name)
    # Set the face and register to receive Interests.
    stream.setFace(
        face,
        lambda prefixName: dump("Register failed for prefix", prefixName))

    # Loop, producing a new object every previousPublishMs milliseconds (and
    # also calling processEvents()).
    previousPublishMs = 0

    # test with publishing existing jason file by json string input
    jsonString = "data/faith.json"
    curr = []
    for line in open(jsonString, 'r'):
        curr.append(json.loads(line))

    # curr_list = []
    # for ann in curr:
    #     temp = []
    #     frameName = ann['frameName']
    #     for k in ann["annotations"]:
    #         # temp.append({"label": ''.join([i for i in k["label"] if not i.isdigit()]), "prob": k["prob"]})
    #         temp.append({"label": ''.join([i for i in k["label"] if not i.isdigit()]), "ytop": k["ytop"],
    #                      "ybottom": k["ybottom"], "xleft": k["xleft"], "xright": k["xright"], "prob": k["prob"],
    #                      "frameName": frameName})
    #
    #     curr_list.append(temp)

    total_cnt = len(curr)

    cnt = 0
    while cnt < total_cnt:
        now = Common.getNowMilliseconds()
        if now >= previousPublishMs + publishIntervalMs:
            dump("Preparing data for sequence",
                 handler.getProducedSequenceNumber() + 1)

            print(curr[cnt])

            handler.addObject(Blob(json.dumps(curr[cnt])), "application/json")

            # handler.addObject(
            #     Blob(json.dumps() + str(handler.getProducedSequenceNumber() + 1)),
            #     "application/json")

            cnt += 1

            if cnt == total_cnt:
                cnt = 0

            previousPublishMs = now

        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 21
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Create an in-memory key chain with default keys.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    # Enable Interest loopback so that the EncryptorV2 can fetch Data packets
    # from the AccessManagerV2.
    face.setInterestLoopbackEnabled(True)

    contentPrefix = Name("/testname/content")
    contentNamespace = Namespace(contentPrefix, keyChain)

    # We know the content has two segments.
    metaInfo = MetaInfo()
    metaInfo.setFinalBlockId(Name().appendSegment(1)[0])
    contentNamespace.setNewDataMetaInfo(metaInfo)

    ckPrefix = Name("/some/ck/prefix")
    encryptor = prepareData(ckPrefix, keyChain, face)

    # Make the callback to produce a Data packet for a content segment.
    def onObjectNeeded(namespace, neededNamespace, id):
        if not (len(neededNamespace.name) == len(contentPrefix) + 1
                and contentPrefix.isPrefixOf(neededNamespace.name)
                and neededNamespace.name[-1].isSegment()):
            # Not a content segment, ignore.
            return False

        # Get the segment number.
        segment = neededNamespace.name[-1].toSegment()
        if not (segment >= 0 and segment <= 1):
            # An invalid segment was requested.
            return False

        segmentContent = ("This test message was decrypted"
                          if segment == 0 else " from segments.")
        # Now call serializeObject which will answer the pending incoming Interest.
        dump("Producing Data", neededNamespace.name)
        neededNamespace.serializeObject(
            encryptor.encrypt(Blob(segmentContent)).wireEncodeV2())

        return True

    contentNamespace.addOnObjectNeeded(onObjectNeeded)

    dump("Register prefix", contentNamespace.name)
    # Set the face and register to receive Interests.
    contentNamespace.setFace(
        face,
        lambda prefixName: dump("Register failed for prefix", prefixName))

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
def main(index_f, weight_f, config_f, consumerMode, th, fetchPrefix,
         publishPrefix):
    # The default Face will connect using a Unix socket, or to "localhost".
    instance_prefix = fetchPrefix.split("/")[-1]
    sl = SegmentLabel(index_f, weight_f, instance_prefix, th)

    if config_f != "":
        sl.readConfig(config_f)

    face = Face()
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    #stream_annConsumer_test = Namespace("/ndn/eb/stream/run/28/annotations")
    #stream_annConsumer_test.setFace(face)
    print(' > Will fetch from ' + str(fetchPrefix))
    stream_annConsumer_show = Namespace(fetchPrefix)
    stream_annConsumer_show.setFace(face)

    log_f = open(str("seglab_log") + ".txt", "w")
    log_f.close()

    stream_segProducer = Namespace(
        Name(publishPrefix).append(Name(fetchPrefix)[-1]), keyChain)
    print(' > Will publish segments under ' +
          str(stream_segProducer.getName()))
    publish_handler = GeneralizedObjectStreamHandler()
    # publish_handler.setLatestPacketFreshnessPeriod(30)
    stream_segProducer.setHandler(publish_handler)

    stream_segProducer.setFace(
        face,
        lambda prefixName: dump("Register failed for prefix", prefixName),
        lambda prefixName, whatever: dump("Register success for prefix",
                                          prefixName))

    def onNewAnnotation(sequenceNumber, contentMetaInfo, objectNamespace):
        ann = str(objectNamespace.obj)
        segment_result = []

        jsonAnn = json.loads(ann)
        # print(jsonAnn["frameName"])

        if not "error" in ann:
            jsonAnn = json.loads(ann)
            # print(jsonAnn["frameName"])
            segment_result = sl.sceneDetection(jsonAnn)
            if segment_result and len(segment_result) > 0:
                print(segment_result)
                #dump("Got generalized object, sequenceNumber", sequenceNumber,
                #     ", content-type", contentMetaInfo.getContentType(), ":",
                #     str(jsonAnn["frameName"]), 'at', str(time.time()))

                publish_handler.addObject(Blob(json.dumps(segment_result)),
                                          "application/json")
                print(" > PUBLISHED SCENE " +
                      str(publish_handler.getProducedSequenceNumber()))

                # # logging the result
                # if segment_result:
                with open(str("seglab_log") + ".txt", "w+") as f:
                    f.write("PUBLISHED SCENE: %s" %
                            str(publish_handler.getProducedSequenceNumber()))
                    f.write("%s\r\n" % segment_result)

    pipelineSize = 0

    #if consumerMode == 'default':
    #    stream_annConsumer_default.setHandler(
    #      GeneralizedObjectStreamHandler(pipelineSize, onNewAnnotation)).objectNeeded()

    stream_annConsumer_show.setHandler(
        GeneralizedObjectStreamHandler(pipelineSize,
                                       onNewAnnotation)).objectNeeded()

    #stream_annConsumer_test.setHandler(
    #    GeneralizedObjectStreamHandler(pipelineSize, onNewAnnotation)).objectNeeded()

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Esempio n. 23
0
def main():
    # Uncomment these lines to print ChronoSync debug messages.
    # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout))
    # logging.getLogger('').setLevel(logging.INFO)

    defaultUserPrefix = "com/newspaper/USER/bob"
    userPrefix = promptAndInput("Enter user prefix: [" + defaultUserPrefix + "]")
    if userPrefix == "":
        userPrefix = defaultUserPrefix

    defaultNamespacePrefix = "/ndn/hackathon/cnl-demo/slides" #"com/newspaper"
    namespacePrefix = promptAndInput("Enter namespace prefix [" + defaultNamespacePrefix + "]: ")
    if namespacePrefix == "":
        namespacePrefix = defaultNamespacePrefix

    host = "localhost" #"memoria.ndn.ucla.edu"
    print("Connecting to " + host)
    print("")

    # Set up the key chain.
    face = Face(host)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())
    keyChain.setFace(face)
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
    face.setCommandSigningInfo(keyChain, certificateName)

    newspaper = Namespace(namespacePrefix)
    
    def onContentSet(namespace, contentNamespace, callbackId):
        global currentSlideName
        if contentNamespace == namespace:
            print("content size "+str(contentNamespace.content.size()))
            currentSlideName = contentNamespace.getName()
            displayImage(contentNamespace.content.toRawStr(), contentNamespace.getName().toUri())
            # dump("Got segmented content ", contentNamespace.content.toRawStr())

    def onNewName(namespace, addedNamespace, callbackId):
        print("namespace ("+addedNamespace.getName().toUri()+") added to "+namespace.getName().toUri())
        if addedNamespace.getName().get(-1).isSegment() and addedNamespace.getName().get(-1).toSegment() == 0:
            addedNamespace.getParent().addOnContentSet(onContentSet)
            SegmentedContent(addedNamespace.getParent()).start()

    newspaper.addOnNameAdded(onNewName)
    newspaper.setFace(face)

    namesync = NameSyncHandler(newspaper, userPrefix, keyChain, certificateName)

    # The main loop to process Chat while checking stdin to send a message.
    print("Enter your namespace update. To quit, enter \"exit\".")

    def process():
        # while True:
        # Set timeout to 0 for an immediate check.
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "exit":
                stopGui()
                # We will send the leave message below.
                # break

            # before producer has namespace.publish call, we manually call onNameAdded as a hack to publish
            namesync.onNameAdded(None, Namespace(Name(input)), 0, True)
        face.processEvents()
        if root: 
            root.after(100, process)

    def leftKey(event):
        global currentSlideName
        allVersions = newspaper.getChildComponents()
        currentVersion = currentSlideName[-1]
        selected = allVersions[0]
        for c in allVersions:
            print(str(c.toVersion()))
            if c.toVersion() == currentVersion.toVersion():
                break
            selected = c
        currentSlideName = Name(newspaper.getName()).append(selected)
        displayImage(newspaper.getChild(selected).content.toRawStr(), currentSlideName.toUri())

    def rightKey(event):
        global currentSlideName
        allVersions = newspaper.getChildComponents()
        currentVersion = currentSlideName[-1]
        selected = None
        for c in allVersions[::-1]:
            if c.toVersion() == currentVersion.toVersion():
                break
            selected = c
        if selected:
            currentSlideName = Name(newspaper.getName()).append(selected)
            displayImage(newspaper.getChild(selected).content.toRawStr(), currentSlideName.toUri())
        else:
            print("no slides to show")

    runGui(process, leftKey, rightKey)
Esempio n. 24
0
def main(index_f, weight_f, consumerMode, k, query_interval, fetchPrefix,
         publishPrefix):
    # The default Face will connect using a Unix socket, or to "localhost".
    instance_prefix = fetchPrefix.split("/")[-1]
    pd = PlayDetect(index_f, weight_f, instance_prefix, k, query_interval)

    face = Face()
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # sceneConsumer = Namespace("/ndn/eb/stream/run/28/annotation")
    engine = str(Name(fetchPrefix)[-1])
    sceneFetchPrefix = Name('/eb/seglab').append(engine)

    print(' > Will fetch annotations from ' + fetchPrefix)
    print(' > Will fetch scenes from ' + sceneFetchPrefix.toUri())

    sceneConsumer = Namespace(sceneFetchPrefix)
    sceneConsumer.setFace(face)

    annotationsConsumer = Namespace(fetchPrefix)

    #if consumerMode == "test":
    #    annotationsConsumer = Namespace("/ndn/eb/stream/run/28/annotations")
    #elif consumerMode == "default":
    #    annotationsConsumer = Namespace('/eb/proto/test/ml_processing/yolo_default')

    annotationsConsumer.setFace(face)

    log_f = open(str("playdetect_log") + ".txt", "w")
    log_f.close()

    playdetectProducer = Namespace(
        Name(publishPrefix).append(engine), keyChain)
    print(' > Will publish playdetect data under ' +
          playdetectProducer.getName().toUri())

    playdSegmentsHandler = GeneralizedObjectStreamHandler()
    # set freshness to 30
    # playdSegmentsHandler.setLatestPacketFreshnessPeriod(30)
    playdetectProducer.setHandler(playdSegmentsHandler)

    playdetectProducer.setFace(
        face,
        lambda prefixName: dump("Register failed for prefix", prefixName),
        lambda prefixName, whatever: dump("Register success for prefix",
                                          prefixName))

    def onNewScene(sequenceNumber, contentMetaInfo, objectNamespace):
        dump("Got scene (segment) :", str(objectNamespace.getName()))

        if str(objectNamespace.obj):
            # Store scene segment AND scene segment NAME into a database
            sceneSegmentName = objectNamespace.getName()
            sceneSegment = json.loads(str(objectNamespace.obj))
            pd.storeToDatabase(sceneSegmentName, sceneSegment)

    def onNewAnnotation(sequenceNumber, contentMetaInfo, objectNamespace):
        # dump("Got new annotation")
        stringObj = str(objectNamespace.obj)
        # print(stringObj)
        now = Common.getNowMilliseconds()
        if stringObj and pd.itIsTimeToQueryDatabase():
            # TBD
            # query interval configurable
            itIsTimeToQueryDatabase = True
            if itIsTimeToQueryDatabase:
                # TBD
                # run query against the databse, using recevied annotation
                # the result should be a list that contains scene segment names (see above)
                # FOR NOW: let's have startFrame end endFrame in the results
                # most likely -- parameterize query, i.e. give argument maxResultNum
                result = pd.pickTops(json.loads(stringObj), k)
                if result:
                    playdSegmentsHandler.addObject(Blob(json.dumps(result)),
                                                   "application/json")

                    print(
                        "PUBLISH SIMILAR SCENES: %s" %
                        str(playdSegmentsHandler.getProducedSequenceNumber()))

                    #logging the result
                    with open(str("playdetect_log") + ".txt", "w+") as f:
                        f.write("PUBLISHED SCENE: %s" % str(
                            playdSegmentsHandler.getProducedSequenceNumber()))
                        f.write("%s\r\n" % result)

    pipelineSize_segConsume = 3
    sceneConsumer.setHandler(
        GeneralizedObjectStreamHandler(pipelineSize_segConsume,
                                       onNewScene)).objectNeeded()

    pipelineSize_annoConsume = 3
    annotationsConsumer.setHandler(
        GeneralizedObjectStreamHandler(pipelineSize_annoConsume,
                                       onNewAnnotation)).objectNeeded()

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)