示例#1
0
    private IEnumerator PostNewTarget()
    {
        targetName += UnityEngine.Random.Range(1, 1000);
        string requestPath = "/targets";
        string serviceURI  = url + requestPath;
        string httpAction  = "POST";
        string contentType = "application/json";
        string date        = string.Format("{0:r}", DateTime.Now.ToUniversalTime());

        byte[] image = texture.EncodeToJPG(80);

        byte[] metadata = System.Text.ASCIIEncoding.ASCII.GetBytes(metadataStr);
        PostNewTrackableRequest model = new PostNewTrackableRequest();

        model.name  = targetName;
        model.width = 0.5f; // the distance of the camera will be twice in Unity scale
        model.image = System.Convert.ToBase64String(image);
        model.application_metadata = System.Convert.ToBase64String(metadata);
        string requestBody = JsonUtility.ToJson(model);

        WWWForm form = new WWWForm();

        var headers = form.headers;

        byte[] rawData = form.data;
        headers["host"]         = url;
        headers["date"]         = date;
        headers["content-type"] = contentType;

        MD5 md5 = MD5.Create();

        byte[] contentMD5bytes       = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(requestBody));
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < contentMD5bytes.Length; i++)
        {
            sb.Append(contentMD5bytes[i].ToString("x2"));
        }

        string contentMD5 = sb.ToString();

        string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath);

        HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secret_key));

        byte[]       sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign);
        MemoryStream stream    = new MemoryStream(sha1Bytes);

        byte[] sha1Hash  = sha1.ComputeHash(stream);
        string signature = System.Convert.ToBase64String(sha1Hash);

        headers["authorization"] = string.Format("VWS {0}:{1}", access_key, signature);
        Debug.Log(string.Format("VWS {0}:{1}", access_key, signature));
        Debug.Log("<color=green>Signature: " + signature + "</color>");
        byte[] jsonPost = System.Text.Encoding.UTF8.GetBytes(requestBody);

        WWW request = new WWW(serviceURI, jsonPost, headers);

        yield return(request);

        if (request.error != null)
        {
            Debug.Log("request error: " + request.error);
        }
        else
        {
            Debug.Log("request success");
            Debug.Log("returned data" + request.text);
        }
    }
    //Incarcare imagine noua
    IEnumerator PostNewTarget()
    {
        string requestPath = "/targets";
        string serviceURI  = url + requestPath;
        string httpAction  = "POST";
        string contentType = "application/json";
        string date        = string.Format("{0:r}", DateTime.Now.ToUniversalTime());

        Debug.Log(date);

        // Daca este de format RGB textura nu trebuie modificata
        Texture2D tex = new Texture2D(texture.width, texture.height, TextureFormat.RGB24, false);

        tex.SetPixels(texture.GetPixels());
        tex.Apply();
        byte[] image = tex.EncodeToPNG();

        string metadataStr = "Vuforia metadata";

        byte[] metadata = System.Text.ASCIIEncoding.ASCII.GetBytes(metadataStr);

        //Se creeaza un model nou de imagine
        PostNewTrackableRequest model = new PostNewTrackableRequest();

        model.name  = targetName;
        model.width = 64.0f;
        model.image = System.Convert.ToBase64String(image);


        model.application_metadata = System.Convert.ToBase64String(metadata);
        string  requestBody = JsonUtility.ToJson(model);
        WWWForm form        = new WWWForm();

        var headers = form.headers;

        byte[] rawData = form.data;
        headers["host"]         = url;
        headers["date"]         = date;
        headers["Content-Type"] = contentType;

        //Cerere de la server
        HttpWebRequest httpWReq = (HttpWebRequest)HttpWebRequest.Create(serviceURI);

        MD5 md5             = MD5.Create();
        var contentMD5bytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(requestBody));

        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        for (int i = 0; i < contentMD5bytes.Length; i++)
        {
            sb.Append(contentMD5bytes[i].ToString("x2"));
        }

        string contentMD5 = sb.ToString();

        string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath);

        HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secret_key));

        byte[]       sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign);
        MemoryStream stream    = new MemoryStream(sha1Bytes);

        byte[] sha1Hash  = sha1.ComputeHash(stream);
        string signature = System.Convert.ToBase64String(sha1Hash);

        headers["Authorization"] = string.Format("VWS {0}:{1}", access_key, signature);

        Debug.Log("<color=green>Signature: " + signature + "</color>");

        WWW request = new WWW(serviceURI, System.Text.Encoding.UTF8.GetBytes(JsonUtility.ToJson(model)), headers);

        yield return(request);

        //AssetDatabase.Refresh();

        if (request.error != null)
        {
            Debug.Log("request error: " + request.error);
        }
        else
        {
            Debug.Log("request success");
            Debug.Log("returned data" + request.text);
        }
        //AssetDatabase.Refresh();
    }
示例#3
0
        /// Makes the post request to upload a new image target to the cloud database
        public static IEnumerator PostNewTarget(Texture2D texture, string targetName)
        {
            Debug.Log("<color=red>Posting target: " + targetName + "</color>");
            string requestPath = "/targets";
            string serviceURI  = url + requestPath;
            string httpAction  = "POST";
            string contentType = "application/json";
            string date        = string.Format("{0:r}", DateTime.Now.ToUniversalTime());

            // if your texture2d has RGb24 type, don't need to redraw new texture2d
            Texture2D tex = new Texture2D(texture.width, texture.height, TextureFormat.RGB24, false);

            tex.SetPixels(texture.GetPixels());
            tex.Apply();
            byte[] image = tex.EncodeToPNG();

            string metadataStr = "Vuforia metadata";

            byte[] metadata = System.Text.ASCIIEncoding.ASCII.GetBytes(metadataStr);
            PostNewTrackableRequest model = new PostNewTrackableRequest();

            model.name  = targetName;
            model.width = 100.0f;
            model.image = System.Convert.ToBase64String(image);

            model.application_metadata = System.Convert.ToBase64String(metadata);
            string requestBody = JsonWriter.Serialize(model);

            WWWForm form = new WWWForm();

            // set post request's headers
            var headers = form.headers;

            byte[] rawData = form.data;
            headers["Host"]         = url;
            headers["Date"]         = date;
            headers["Content-Type"] = contentType;

            HttpWebRequest httpWReq = (HttpWebRequest)HttpWebRequest.Create(serviceURI);

            MD5 md5             = MD5.Create();
            var contentMD5bytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(requestBody));

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = 0; i < contentMD5bytes.Length; i++)
            {
                sb.Append(contentMD5bytes[i].ToString("x2"));
            }

            string contentMD5   = sb.ToString();
            string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath);

            // set 'Authorization' field of header
            HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secret_key));

            byte[]       sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign);
            MemoryStream stream    = new MemoryStream(sha1Bytes);

            byte[] sha1Hash  = sha1.ComputeHash(stream);
            string signature = System.Convert.ToBase64String(sha1Hash);

            headers["Authorization"] = string.Format("VWS {0}:{1}", access_key, signature);
            Debug.Log("Signature: " + signature);

            WWW request = new WWW(serviceURI, System.Text.Encoding.UTF8.GetBytes(JsonWriter.Serialize(model)), headers);

            TargetImageController.instance.targetImage = targetName;
            yield return(request);

            if (request.error != null)
            {
                Debug.Log("<color=red>REQUEST ERROR: " + request.error + "</color>");
            }
            else
            {
                Debug.Log("<color=green>REQUEST SUCCESS:" + request.text + "</color>");
            }

            MakerSceneManager.instance.callback = true;
        }
示例#4
0
    // https://library.vuforia.com/articles/Solution/How-To-Use-the-Vuforia-Web-Services-API.htm#How-To-Update-a-Target
    IEnumerator PutUpdateTarget(bool updateImage = false)
    {
        Debug.Log("CustomMessage: PutUpdateTarget()");

        // Setting up query.
        string requestPath = "/targets/" + currentImageData.UniqueTargetId;
        string serviceURI  = url + requestPath;
        string httpAction  = "PUT";
        string contentType = "application/json";
        string date        = string.Format("{0:r}", DateTime.Now.ToUniversalTime());

        string metadataStr = jsonData;

        byte[] metadata = System.Text.ASCIIEncoding.ASCII.GetBytes(metadataStr);

        // Create new model to prepare for sending.
        PostNewTrackableRequest model = new PostNewTrackableRequest();

        model.name  = targetName;
        model.width = 64.0f;
        model.application_metadata = System.Convert.ToBase64String(metadata);

        if (updateImage)
        {
            // Create texture and encode pixels to base64.
            Texture2D tex = new Texture2D(texture.width, texture.height, TextureFormat.RGB24, false);
            tex.SetPixels(texture.GetPixels());
            tex.Apply();
            byte[] image = tex.EncodeToPNG();

            model.image = System.Convert.ToBase64String(image);
        }

        // Convert model to json.
        string requestBody = JsonUtility.ToJson(model);

        // Create ContentMD5.
        MD5 md5             = MD5.Create();
        var contentMD5bytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(requestBody));

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < contentMD5bytes.Length; i++)
        {
            sb.Append(contentMD5bytes[i].ToString("x2"));
        }

        string contentMD5   = sb.ToString();
        string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath);

        // Build signature.
        HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secret_key));

        byte[]       sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign);
        MemoryStream stream    = new MemoryStream(sha1Bytes);

        byte[] sha1Hash  = sha1.ComputeHash(stream);
        string signature = System.Convert.ToBase64String(sha1Hash);

        Debug.Log("<color=green>Signature: " + signature + "</color>");

        // Build Http Request.
        BestHTTP.HTTPRequest request = new BestHTTP.HTTPRequest(new Uri(serviceURI));

        request.MethodType = BestHTTP.HTTPMethods.Put;
        request.RawData    = Encoding.UTF8.GetBytes(requestBody);
        request.AddHeader("Authorization", string.Format("VWS {0}:{1}", access_key, signature));
        request.AddHeader("Content-Type", contentType);
        request.AddHeader("Date", date);
        request.Send();

        yield return(StartCoroutine(request));

        switch (request.State)
        {
        case BestHTTP.HTTPRequestStates.Error:

            Debug.Log("request error: " + request.Exception.Message);

            string errorText = request.Exception.Message;
            PrintStatusText("Exception: " + errorText);

            break;

        case BestHTTP.HTTPRequestStates.Finished:

            // There is an error
            if (request.Response.StatusCode != 200)
            {
                Debug.Log("request error: " + request.Response.Message);

                string result_code = JsonUtility.FromJson <VWSResponse>(request.Response.DataAsText).result_code;

                // The target is still being processed in Vuforia API.
                if (result_code == "TargetStatusNotSuccess")
                {
                    PrintStatusText("Error: Profile is still being processed in Vuforia!");
                }
                else
                {
                    PrintStatusText("Error: " + result_code);
                }
            }
            else
            {
                Debug.Log("request success");
                PrintStatusText("Saved!");

                if (rescanCloudAfterEdit)
                {
                    // We disable cloud tracking for x seconds. The reason why we do this is because it takes time for
                    // Vuforia to actually delete the record. If we continue cloud tracking, it would retrack the record.
                    DisableCloudTracking(2f);

                    // To get all the tracked targets. For testing.
                    // IEnumerable<Vuforia.ObjectTarget> obj = Vuforia.TrackerManager.Instance.GetTracker<Vuforia.ObjectTracker>().GetTargetFinder<Vuforia.ImageTargetFinder>().GetObjectTargets();
                    // IEnumerator myEnum = obj.GetEnumerator();

                    // while(myEnum.MoveNext()){
                    //     print(myEnum.Current);
                    // }

                    // Clear local copy.
                    Vuforia.TrackerManager.Instance.GetTracker <Vuforia.ObjectTracker>().GetTargetFinder <Vuforia.ImageTargetFinder>().ClearTrackables(false);
                }
                else
                {
                    // Since the image is saved to the cloud, we can change the local copy.
                    currentImageData.MetaData   = metadataStr;
                    currentImageData.TargetName = targetName;

                    // Force update of target info.
                    cloudContentManager.HandleTargetFinderResult(currentImageData);

                    // The only issue with this method is we do not know the new tracking rating of the copy.
                    // However, since our version of profiler does not show tracking rating, it should work fine.

                    // Also, if the new image fails the processor on Vuforia's side, it wouldn't make sense to
                    // change the local copy's data. However, it would be more convenient for the user to see
                    // the new updated version. Therefore, when changing the local copy, we are assuming the
                    // new image to be processed successfully.
                }

                // Close edit menu.
                ToggleEditMenu();
            }

            break;
        }

        // Enable buttons.
        deleteDeleteButton.interactable = true;
        putEditButton.interactable      = true;
        editButton.interactable         = true;
    }
示例#5
0
    // https://library.vuforia.com/articles/Solution/How-To-Use-the-Vuforia-Web-Services-API.htm#How-To-Add-a-Target
    IEnumerator PostNewTarget()
    {
        Debug.Log("CustomMessage: PostNewTarget()");

        string requestPath = "/targets";
        string serviceURI  = url + requestPath;
        string httpAction  = "POST";
        string contentType = "application/json";
        string date        = string.Format("{0:r}", DateTime.Now.ToUniversalTime());


        Texture2D tex = new Texture2D(texture.width, texture.height, TextureFormat.RGB24, false);

        tex.SetPixels(texture.GetPixels());
        tex.Apply();
        byte[] image = tex.EncodeToPNG();


        string metadataStr = jsonData;

        byte[] metadata = System.Text.ASCIIEncoding.ASCII.GetBytes(metadataStr);
        PostNewTrackableRequest model = new PostNewTrackableRequest();

        model.name  = targetName;
        model.width = 64.0f; // don't need same as width of texture
        model.image = System.Convert.ToBase64String(image);
        model.application_metadata = System.Convert.ToBase64String(metadata);

        string requestBody = JsonUtility.ToJson(model);

        WWWForm form = new WWWForm();

        var headers = form.headers;

        byte[] rawData = form.data;
        headers["host"]         = url;
        headers["date"]         = date;
        headers["Content-Type"] = contentType;

        MD5 md5             = MD5.Create();
        var contentMD5bytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(requestBody));

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < contentMD5bytes.Length; i++)
        {
            sb.Append(contentMD5bytes[i].ToString("x2"));
        }

        string contentMD5   = sb.ToString();
        string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath);

        HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secret_key));

        byte[]       sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign);
        MemoryStream stream    = new MemoryStream(sha1Bytes);

        byte[] sha1Hash  = sha1.ComputeHash(stream);
        string signature = System.Convert.ToBase64String(sha1Hash);

        headers["Authorization"] = string.Format("VWS {0}:{1}", access_key, signature);

        Debug.Log("<color=green>Signature: " + signature + "</color>");

        foreach (System.Collections.Generic.KeyValuePair <string, string> kvp in headers)
        {
            print(string.Format("{0}: {1}", kvp.Key, kvp.Value));
        }

        WWW request = new WWW(serviceURI, System.Text.Encoding.UTF8.GetBytes(requestBody), headers);

        yield return(request);

        if (request.error != null)
        {
            Debug.Log("request error: " + request.error);

            string result_code = JsonUtility.FromJson <VWSResponse>(request.text).result_code;

            // The target's name is already in Vuforia database.
            if (result_code == "TargetNameExist")
            {
                PrintStatusText("Error: Name already exist! Please choose a different name.");
            }
            else
            {
                PrintStatusText("Error: " + result_code);
            }
        }
        else
        {
            Debug.Log("request success");
            Debug.Log("returned data" + request.text);
            PrintStatusText("Uploaded!");

            // Close upload menu.
            ToggleUploadMenu();
        }

        postUploadButton.interactable = true;
        uploadButton.interactable     = true;
    }
示例#6
0
    IEnumerator PostNewTarget(Texture2D tex, string targetName, string metadataStr)
    {
        string requestPath = "/targets";
        string serviceURI  = url + requestPath;
        string httpAction  = "POST";
        string contentType = "application/json";
        string date        = string.Format("{0:r}", DateTime.Now.ToUniversalTime());

        // if your texture2d has RGb24 type, don't need to redraw new texture2d
        byte[] image = tex.EncodeToPNG();

        byte[] metadata = System.Text.ASCIIEncoding.ASCII.GetBytes(metadataStr);
        PostNewTrackableRequest model = new PostNewTrackableRequest();

        model.name  = targetName;
        model.width = 64.0f;         // don't need same as width of texture
        model.image = System.Convert.ToBase64String(image);

        model.application_metadata = System.Convert.ToBase64String(metadata);
        string requestBody = JsonUtility.ToJson(model);

        HttpWebRequest httpWReq = (HttpWebRequest)HttpWebRequest.Create(serviceURI);

        MD5 md5             = MD5.Create();
        var contentMD5bytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(requestBody));

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < contentMD5bytes.Length; i++)
        {
            sb.Append(contentMD5bytes[i].ToString("x2"));
        }

        string contentMD5 = sb.ToString();

        string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath);

        HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(server_secret_key));

        byte[]       sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign);
        MemoryStream stream    = new MemoryStream(sha1Bytes);

        byte[] sha1Hash  = sha1.ComputeHash(stream);
        string signature = System.Convert.ToBase64String(sha1Hash);

        Debug.Log("<color=green>Signature: " + signature + "</color>");

        // Make the Web Request
        Dictionary <string, string> headers = new Dictionary <string, string> ();

        headers.Add("host", url);
        headers.Add("date", date);
        headers.Add("content-type", contentType);
        headers.Add("authorization", string.Format("VWS {0}:{1}", server_access_key, signature));
        WWW request = new WWW(serviceURI, System.Text.Encoding.UTF8.GetBytes(JsonUtility.ToJson(model)), headers);

        yield return(request);

        if (request.error != null && request.error.ToString().Contains("403"))
        {
            // Attempt to replace the target if it already exists
            GameObject.Find("MASTER_Controller").GetComponent <scr_SceneController>().DebugMessage("Attempting to replace old marker...");
            yield return(StartCoroutine(PutNewTarget(tex, targetName, metadataStr)));
        }
        else if (request.error != null)
        {
            GameObject.Find("MASTER_Controller").GetComponent <scr_SceneController>().DebugMessage(request.error, "error");
        }
        else
        {
            string markerID = request.text.Substring(request.text.IndexOf("target_id\":\""));
            markerID = markerID.Substring(12);
            markerID = markerID.Substring(0, markerID.Length - 2);
            // Save the target ID
            GameObject.Find("MASTER_Controller").GetComponent <scr_SceneController>().SetMarkerID(markerID);
        }
    }
示例#7
0
    IEnumerator PostNewTarget()
    {
        string requestPath = "/targets";
        string serviceURI  = url + requestPath;
        string httpAction  = "POST";
        string contentType = "application/json";
        string date        = string.Format("{0:r}", DateTime.Now.ToUniversalTime());

        Debug.Log(date);

        // if your texture2d has RGb24 type, don't need to redraw new texture2d
        Texture2D tex = new Texture2D(texture.width, texture.height, TextureFormat.RGB24, false);

        tex.SetPixels(texture.GetPixels());
        tex.Apply();
        byte[] image = tex.EncodeToPNG();

        string metadataStr = "Metadata regarding the target to store and call when image target is detected ";//May use for key,name...in game

        byte[] metadata = System.Text.ASCIIEncoding.ASCII.GetBytes(metadataStr);
        PostNewTrackableRequest model = new PostNewTrackableRequest();

        model.name  = targetName;
        model.width = 64.0f; // don't need same as width of texture
        model.image = System.Convert.ToBase64String(image);

        model.application_metadata = System.Convert.ToBase64String(metadata);
        //string requestBody = JsonWriter.Serialize(model);
        string requestBody = JsonUtility.ToJson(model);

        WWWForm form = new WWWForm();

        var headers = form.headers;

        byte[] rawData = form.data;
        headers["host"]         = url;
        headers["date"]         = date;
        headers["Content-Type"] = contentType;

        HttpWebRequest httpWReq = (HttpWebRequest)HttpWebRequest.Create(serviceURI);

        MD5 md5             = MD5.Create();
        var contentMD5bytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(requestBody));

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < contentMD5bytes.Length; i++)
        {
            sb.Append(contentMD5bytes[i].ToString("x2"));
        }

        string contentMD5 = sb.ToString();

        string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath);

        HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secret_key));

        byte[]       sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign);
        MemoryStream stream    = new MemoryStream(sha1Bytes);

        byte[] sha1Hash  = sha1.ComputeHash(stream);
        string signature = System.Convert.ToBase64String(sha1Hash);

        headers["Authorization"] = string.Format("VWS {0}:{1}", access_key, signature);

        Debug.Log("<color=green>Signature: " + signature + "</color>");

        WWW request = new WWW(serviceURI, System.Text.Encoding.UTF8.GetBytes(JsonUtility.ToJson(model)), headers);

        yield return(request);

        if (request.error != null)
        {
            Debug.Log("request error: " + request.error + request.text);
        }
        else
        {
            Debug.Log("request success");
            Debug.Log("returned data" + request.text);
            CreateList(request.text);
        }
    }