Beispiel #1
0
    public RestApi(string key, string domain, string peerId, bool turn)
    {
        var peerParams = new PeerOptions();

        peerParams.key     = key;
        peerParams.domain  = domain;
        peerParams.peer_id = peerId;
        peerParams.turn    = turn;
        string peerParamsJson = JsonUtility.ToJson(peerParams);

        byte[] peerParamsBytes = Encoding.UTF8.GetBytes(peerParamsJson);
        //SkyWayサーバとの接続開始するためのAPIを叩く
        ObservableWWW.Post(entryPoint + "/peers", peerParamsBytes).Subscribe(x =>
        {
            //この時点ではSkyWay WebRTC GWが「このPeer IDで処理を開始する」という応答でしかなく、
            //SkyWayサーバで利用できるPeer IDとは限らない(重複で弾かれる等があり得るので)
            var response   = Json.Deserialize(x) as Dictionary <string, object>;
            var parameters = (IDictionary)response["params"];
            var peer_id    = (string)parameters["peer_id"];
            var token      = (string)parameters["token"];
            //SkyWayサーバとSkyWay WebRTC Gatewayが繋がって初めてPeer ID等が正式に決定するので、
            //イベントを監視する
            var url = string.Format("{0}/peers/{1}/events?token={2}", entryPoint, peer_id, token);
            ObservableWWW.Get(url).Repeat().Where(wx =>
            {
                //この時点ではOPENイベント以外はいらないので弾く
                var res = Json.Deserialize(wx) as Dictionary <string, object>;
                return(res.ContainsKey("event") && (string)res["event"] == "OPEN");
            }).First().Subscribe(sx =>             //ここでは最初の一回しか監視しない。着信等のイベントは後で別の場所で取ることにする
            {
                var response_j   = Json.Deserialize(sx) as Dictionary <string, object>;
                var parameters_s = (IDictionary)response_j["params"];
                //正式決定したpeer_idとtokenを記録しておく
                _peerId    = (string)parameters_s["peer_id"];
                _peerToken = (string)parameters_s["token"];
                //SkyWayサーバと繋がったときの処理を始める
                _OnOpen();
            }, ex =>
            {
                //ここが発火する場合は多分peer_idやtoken等が間違っている
                //もしくはSkyWay WebRTC GWとSkyWayサーバの間で通信ができてない
                Debug.LogError(ex);
            });
        }, ex =>
        {
            //ここが発火する場合はSkyWay WebRTC GWと通信できてないのでは。
            //そもそも起動してないとか
            //他には、前回ちゃんとClose処理をしなかったため前のセッションが残っている場合が考えられる。
            //その場合はWebRTC GWを再起動するか、別のPeer IDを利用する
            //時間が経てば勝手に開放されるのでそこまで気にしなくてもよい(気にしなくてもいいとは言ってない)
            Debug.LogError("error");
            Debug.LogError(ex);
        });
    }
        private IObservable <string> SendPostAsObservable(string _url, string _json)
        {
            Debug.Log($"Sending POST request to {_url}");

            Dictionary <string, string> header = new Dictionary <string, string>();

            header.Add("Content-Type", "application/json");

            byte[] data = System.Text.Encoding.UTF8.GetBytes(_json);

            return(ObservableWWW.Post(_url, data, header));
        }
Beispiel #3
0
        public static IObservable <string> Post(string url, string body, Dictionary <string, string> header = null)
        {
            var requestHeader = RestClient.mHeader;

            if (header != null)
            {
                header.ToList().ForEach(m => requestHeader.Add(m.Key, m.Value));
            }

            var b = Encoding.ASCII.GetBytes(body);

            return(ObservableWWW.Post(url, b, requestHeader));
        }
Beispiel #4
0
        //public static IObservable<T> Post<T>(string url, T postData, Dictionary<string, string> header = null)
        //{
        //    return Observable.FromCoroutine<T>((observer, cancellation) => UnityPost(url, postData, observer, cancellation, header));
        //}

        public static IObservable <T> Post <T>(string url, T body, Dictionary <string, string> header = null)
        {
            var requestHeader = RestClient.mHeader;

            if (header != null)
            {
                header.ToList().ForEach(m => requestHeader.Add(m.Key, m.Value));
            }

            var bodyJson = JsonConvert.SerializeObject(body);
            var b        = Encoding.ASCII.GetBytes(bodyJson);

            return(ObservableWWW.Post(url, b, requestHeader).Select(data => JsonConvert.DeserializeObject <T>(data)));
        }
    // シェア処理
    private IEnumerator Share()
    {
        // 画面をキャプチャ
        Application.CaptureScreenshot("screenShot.png");

        // キャプチャを保存するので1フレーム待つ
        yield return(new WaitForEndOfFrame());

        // シェアテキスト設定
        string text = "シェアする内容";
        string url  = "http://google.com/";

        // キャプチャの保存先を指定
        string texture_url = Application.persistentDataPath + "/screenShot.png";

        // iOS側の処理を呼び出す
        //SocialConnector.SocialConnector.Share(text, url);

        Dictionary <string, string> headers = new Dictionary <string, string>();

        headers.Add("consumer_key", "IrwkW1kQMD9ok0PeGP1l3mKCU");
        headers.Add("consumer_secret", "lvEYsOeypdi4FzpuWi13r7Q9iRadR5Czk5PvF5lCLeJol6Jgfu");
        headers.Add("token", "832955370649759744-IX8KrW26yA9tzoPauUPb0hgpKvllP4I");
        headers.Add("secret", "	YpljKtgeEmJyXCkcCCshL1KrumOJs2CZOZzr0tsjCSsGH");



        WWWForm form = new WWWForm();

        form.AddBinaryData("media_data", MakeScreenShot());

        var www = ObservableWWW.Post("https://upload.twitter.com/1.1/media/upload.json", form.data, headers).ToYieldInstruction();

        while (!(www.HasResult || www.IsCanceled || www.HasError)) // 3つもプロパティ並べるのダルいので次回アップデートでIsDoneを追加します予定
        {
            yield return(null);
        }

        string result = "";

        if (www.HasResult == true && CommonFunction.IsNullOrWhiteSpace(www.Result) == false)
        {
            result = www.Result;
        }
        Debug.Log(www.Error);


        //string xml = Account.oAuthMediaRequest(oAuthTwitter.Method.POST, "https://upload.twitter.com/1.1/media/upload.json", "");
    }
Beispiel #6
0
    public void Upload()
    {
        if (string.IsNullOrEmpty(pathInput.text) || !System.IO.File.Exists(pathInput.text))
        {
            errorLabel.text = "Please Select File!!!";
            errorLabel.gameObject.SetActive(true);
            return;
        }
        else

        {
            errorLabel.text = "Uploading";
            errorLabel.gameObject.SetActive(true);

            manager.Lock = true;

            WWWForm form = new WWWForm();

            var file = File.ReadAllBytes(pathInput.text);
            form.AddBinaryData("file", file);
            var fileinfo = (new System.IO.FileInfo(pathInput.text));
            form.AddField("filename", fileinfo.Name);

            string authorization = authenticate(Registry.username, Registry.password);
            Dictionary <string, string> headers = new Dictionary <string, string>();
            headers.Add("AUTHORIZATION", authorization);

            var progressNotifier = new ScheduledNotifier <float>();
            progressNotifier.Subscribe(x => progress.fillAmount = x);

            ObservableWWW.Post(Constants.API_FILE, form, headers, progressNotifier)
            .Subscribe(
                x =>
            {
                Debug.Log("Upload success");
                errorLabel.text = "upload success";
                errorLabel.gameObject.SetActive(true);

                manager.Lock = false;
            },          // onSuccess
                ex =>
            {
                Debug.Log(ex.ToString());
                errorLabel.text = ex.ToString();
                errorLabel.gameObject.SetActive(true);
                manager.Lock = false;
            });          // onError
        }
    }
Beispiel #7
0
        /// <summary>
        /// Coroutine of posting to slack.
        /// </summary>
        /// <returns>The coroutine.</returns>
        /// <param name="url">URL.</param>
        /// <param name="jsonData">Json data.</param>
        private static IEnumerator PostCoroutine(string url, string jsonData)
        {
            Dictionary<string, string> header = new Dictionary<string, string>();

            header.Add("Content-Type", "application/json; charset=UTF-8");

            byte[] postBytes = Encoding.UTF8.GetBytes(jsonData);

            IDisposable www =
                ObservableWWW.Post(url, postBytes, header)
                             .Retry(3)
                             .Subscribe();

            yield return www;
        }
Beispiel #8
0
    public void Logout()
    {
        WWWForm form = new WWWForm();

        ObservableWWW.Post(Constants.API_LOGOUT, form).Subscribe(
            x =>
        {
            Debug.Log("[*] Logout success");
            manager.SetPanel(PANEL.Login);
        },    // onSuccess
            ex =>
        {
            Debug.Log("[*] Error: " + ex.ToString());
        });    // onError
    }
Beispiel #9
0
    public void Register()
    {
        if (userInput.text == "")
        {
            error.text = "username is not empty";
            error.gameObject.SetActive(true);
            return;
        }

        if (emailInput.text == "")
        {
            error.text = "email is not empty";
            error.gameObject.SetActive(true);
            return;
        }

        if (pass1Input.text == "" || pass1Input.text != pass2Input.text)
        {
            error.text = "Pass is not similar";
            error.gameObject.SetActive(true);
            return;
        }


        WWWForm form = new WWWForm();

        form.AddField("username", userInput.text);
        form.AddField("email", emailInput.text);
        form.AddField("password1", pass1Input.text);
        form.AddField("password2", pass2Input.text);
        Registry.username = userInput.text;
        Registry.password = pass1Input.text;
        ObservableWWW.Post(Constants.API_REGISTER, form).Subscribe(
            x =>
        {
            Debug.Log("[*] Registing success");
            manager.SetPanel(PANEL.Menu);
        },     // onSuccess
            ex =>
        {
            Debug.Log("[*] Error: " + ex.ToString());
            error.text = ex.ToString();
            error.gameObject.SetActive(true);
        });     // onError
    }
Beispiel #10
0
    static void SendPost(string param_json, Action <ConnectResult> result)
    {
        Debug.Log("send : " + param_json);
        WWWForm frm = new WWWForm();

        frm.AddField("param", param_json);

        ObservableWWW.Post(url, frm)
        .Subscribe(_ =>
        {
            Debug.Log("result : " + _);
            if (result != null)
            {
                ConnectResult r = JsonUtility.FromJson <ConnectResult>(_);
                result.Invoke(r);
            }
        });
    }
Beispiel #11
0
        public static async Task <T> PostRequestAsync <T>(string endpoint, byte[] post)
        {
            int number;

#if UNITY_EDITOR
            InstantLog.StringLog($"POST@REQUEST#{_requestNumber}: {endpoint}", StringExtensions.TextColor.yellow);
            number = _requestNumber++;
#endif
            var www = await ObservableWWW.Post(endpoint, post);

            if (www == null)
            {
                Debug.LogError("www request error");
            }
#if UNITY_EDITOR
            InstantLog.StringLog($"POST@RESPONCE#{number}: {www}", StringExtensions.TextColor.yellow);
#endif
            return(JsonUtility.FromJson <T>(www));
        }
Beispiel #12
0
        public static async Task <string> PostRequestAsync(string endpoint, WWWForm form)
        {
            int number;

#if UNITY_EDITOR
            InstantLog.StringLog($"POST@REQUEST#{_requestNumber}: {endpoint}", StringExtensions.TextColor.yellow);
            number = _requestNumber++;
#endif
            var www = await ObservableWWW.Post(endpoint, form);

            if (www == null)
            {
                Debug.LogError("www request error");
            }
#if UNITY_EDITOR
            InstantLog.StringLog($"POST@RESPONCE#{number}: {www}", StringExtensions.TextColor.yellow);
#endif
            return(www);
        }
Beispiel #13
0
    private void PostRequestObservable()
    {
        var form = new WWWForm();

        form.AddField(key, zipcode);

        var progress = new ScheduledNotifier <float>();

        progress.Subscribe(prog => Debug.Log(prog))
        .AddTo(this);

        ObservableWWW.Post(url, form, progress)
        .Subscribe(x =>
        {
            Debug.Log($"post success. {nameof(WWWSamples)}.{nameof(PostRequestObservable)}");
            Debug.Log(x);
        })
        .AddTo(this);
    }
Beispiel #14
0
        /// <summary>
        /// オーディオのバイナリをAzureに渡して、その結果をJSONで得る(非同期)
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public async Task <string> GetTextFromAudioClipAsync(byte[] bytes)
        {
            if (_isRequest)
            {
                // 本来はエラー仕様をちゃんと設計して返すべき
                return(Error);
            }

            _isRequest = true;

            var requestUrl = $@"{_endPoint}{_recognitionMode}/cognitiveservices/v1?language={_lang}&format={_format}";

            var form = new WWWForm();

            form.AddBinaryData("file", bytes, "voice.wav", @"application/octet-stream");

            var headers = new Dictionary <string, string>
            {
                { "Ocp-Apim-Subscription-Key", _subscriptionKey },
            };

            try
            {
                // Azureへのアクセスは別スレッドで行う
                var resultText = await ObservableWWW.Post(requestUrl, form, headers);

                return(resultText);
            }
            catch (WWWErrorException ex)
            {
                Debug.Log(ex.StatusCode);
                Debug.Log(ex.RawErrorMessage);
                Debug.Log(ex.Message);
                Debug.Log(ex.Text);
                // 本来はエラー仕様をちゃんと設計して返すべき
                return(Error);
            }
            finally
            {
                _isRequest = false;
            }
        }
Beispiel #15
0
    public static IObservable <string> PostWithSign(string url, Dictionary <string, object> param,
                                                    string fileName = null, string filePath = null, bool showToast = true)
    {
        var formParam = new WWWForm();

        if (token.IsNullOrEmpty())
        {
            token = PlayerPrefsUtil.GetToken();
        }

        if (!token.IsNullOrEmpty())
        {
            param.Add("token", token);
        }

        if (param.Count > 0)
        {
            param.ForEach(pair => { formParam.AddField(pair.Key, pair.Value.ToString()); });
            string sign = SignUtil.getSign(param);
            formParam.AddField("sign", sign);
            formParam.AddField("appid", AppConst.APPID);
        }

        return(ObservableWWW.Post(url, formParam).DoOnError(e =>
        {
            LoadingManager.GetInstance().DismissLoading();
            if (showToast)
            {
                if (e is HttpException)
                {
                }
                else if (e is WWWErrorException)
                {
                    ToastManager.GetInstance().CreatToast("网络连接失败,请检查网络连接");
                }
                else
                {
                    ToastManager.GetInstance().CreatToast(e.Message);
                }
            }
        }));
    }
Beispiel #16
0
    public void Register()
    {
        if (userInput.text == "")
        {
            error.text = "username is not empty";
            error.gameObject.SetActive(true);
            return;
        }



        if (passInput.text == "")
        {
            error.text = "Pass is not similar";
            error.gameObject.SetActive(true);
            return;
        }


        WWWForm form = new WWWForm();

        Registry.username = userInput.text;
        Registry.password = passInput.text;
        form.AddField("username", userInput.text);
        form.AddField("password", passInput.text);
        ObservableWWW.Post(Constants.API_LOGIN, form)
        .Subscribe(
            x =>
        {
            Debug.Log("[*] Login success");
            manager.SetPanel(PANEL.Menu);
        },                // onSuccess
            ex =>
        {
            error.text = ex.ToString();
            error.gameObject.SetActive(true);
        });                // onError
    }
Beispiel #17
0
        public static void DoGetToken(string username, string password, Action <string> onTokenGetted)
        {
            var form = new WWWForm();

            form.AddField("username", username);
            form.AddField("password", password);

            ObservableWWW.Post(URL, form)
            .Subscribe(response =>
            {
                Debug.Log(response);

                var responseJson = JObject.Parse(response);

                var code = responseJson["code"].Value <int>();

                if (code == 1)
                {
                    var token = responseJson["data"]["token"].Value <string>();
                    onTokenGetted(token);
                }
            });
        }
Beispiel #18
0
        protected override void OnBegin()
        {
            Debug.Log(mId);

            var form = new WWWForm();

            form.AddField("username", User.Username.Value);
            form.AddField("password", User.Password.Value);
            form.AddField("id", mId);

            ObservableWWW.Post("https://api.liangxiegame.com/qf/v4/package/delete", form)
            .Subscribe(response =>
            {
                var result = JObject.Parse(response);

                if (result.Value <int>("code") == 1)
                {
                    Debug.Log("删除成功");
                }

                Finish();
            });
        }
Beispiel #19
0
        public IObservable <TOut> Post <TIn, TOut, TResponse>(HttpRequestMessage <TIn> message) where TIn : class where TOut : class where TResponse : HttpResponseMessage <HttpResponseData <TOut>, TOut>, new()
        {
            Debug.Log("Http Path: " + Url + message.Path);
            string request = protocol.EncodeMessage(message);
            var    subject = new Subject <TOut>();

            ObservableWWW.Post(Url + message.Path, Encoding.UTF8.GetBytes(request), Header).CatchIgnore(
                (WWWErrorException ex) =>
            {
                Debug.Log(ex.RawErrorMessage);
                errorHandle.Handel(new HttpException(ex.RawErrorMessage,
                                                     -1));
                subject.OnError(new HttpException(ex.RawErrorMessage,
                                                  -1));
            }).Subscribe(data =>
            {
                HttpResponseMessage <HttpResponseData <TOut>, TOut> response = protocol.DecodeMessage <TOut, TResponse>(data);

                if (response.IsOK)
                {
                    Debug.Log("HttpRequest Response: " + data);
                    subject.OnNext(response.Data);
                }
                else
                {
                    Debug.LogError("HttpRequest Response: " + data);
                    errorHandle.Handel(new HttpException(response.ErrorMessage,
                                                         Convert.ToInt32(response.ErrorCode)));
                    subject.OnError(new HttpException(response.ErrorMessage,
                                                      Convert.ToInt32(response.ErrorCode)));
                }
                subject.OnCompleted();
            }
                         );

            return(subject);
        }
Beispiel #20
0
 public static IDisposable UploadFile(string filePath, Action <string, string> onCallback = null)
 {
     if (!File.Exists(filePath))
     {
         PTDebug.LogError("文件不存在!路径:{0}", filePath);
         onCallback.InvokeGracefully(filePath, null);
         return(null);
     }
     return(GetUploadToken(token =>
     {
         if (token.IsNullOrEmpty())
         {
             PTDebug.LogError("获取UploadToken失败!");
             onCallback.InvokeGracefully(filePath, null);
             return;
         }
         var data = GetUploadFliePostData(filePath, token);
         ObservableWWW.Post(data.Url, data.Form).Timeout(TimeSpan.FromSeconds(30)).Subscribe(res =>
         {
             var resData = RespUploadData.Parse(res);
             if (resData.code == 0)
             {
                 onCallback.InvokeGracefully(filePath, RespUploadData.GetFileName(res));
             }
             else
             {
                 PTDebug.LogError(resData.message);
                 onCallback.InvokeGracefully(filePath, null);
             }
         }, e =>
         {
             PTDebug.LogError("Error:" + e.ToString());
             onCallback.InvokeGracefully(filePath, null);
         });
     }));
 }
Beispiel #21
0
 public static IObservable <string> Post(string url, WWWForm content, IProgress <float> progress = null)
 {
     return(ObservableWWW.Post(url, content, progress));
 }
Beispiel #22
0
    public static IObservable <T> PostWithSign <T>(string url, Dictionary <string, object> param,
                                                   string fileName = null, string filePath = null, bool showToast = true)
    {
        StringBuilder strParam  = new StringBuilder();
        var           formParam = new WWWForm();

        if (token.IsNullOrEmpty())
        {
            token = PlayerPrefsUtil.GetToken();
        }

        if (!token.IsNullOrEmpty())
        {
            param.Add("token", token);
        }

        if (param.Count > 0)
        {
            param.ForEach(pair =>
            {
                strParam.Append(pair.Key);
                strParam.Append(":");
                strParam.Append(pair.Value.ToString());
                strParam.Append("&");
                formParam.AddField(pair.Key, pair.Value.ToString());
            });
            string sign = SignUtil.getSign(param);
            formParam.AddField("sign", sign);
            formParam.AddField("appid", AppConst.APPID);
            strParam.Append("sign");
            strParam.Append(":");
            strParam.Append(sign);
            strParam.Append("&");
            strParam.Append("appid");
            strParam.Append(":");
            strParam.Append(AppConst.APPID);
        }

        if (filePath.IsNotNullAndEmpty())
        {
            formParam.AddBinaryData("file", File.ReadAllBytes(filePath), fileName);
            strParam.Append("&");
            strParam.Append("file");
            strParam.Append(":");
            strParam.Append(File.ReadAllBytes(filePath));
        }

        return(ObservableWWW.Post(url, formParam).Select <string, T>(s =>
        {
            Log.I("url==" + url);
            Log.I("formParam==" + strParam);
            Log.I("返回信息是" + s);
            if (s.IsNullOrEmpty())
            {
                throw new HttpException("104", "网络连接失败", 104);
            }

            BaseEntity <T> deserializeObject = JsonConvert.DeserializeObject <BaseEntity <T> >(s);
            if (deserializeObject.status != 1)
            {
                CommonUtil.error(deserializeObject.errCode, deserializeObject.message, deserializeObject.status);
                throw new HttpException(deserializeObject.errCode, deserializeObject.message, deserializeObject.status);
            }

            return deserializeObject.data;
        }).DoOnError(e =>
        {
            LoadingManager.GetInstance().DismissLoading();
            if (showToast)
            {
                if (e is HttpException)
                {
                    CommonUtil.toast(((HttpException)e).ErrMessage);
                }
                else if (e is WWWErrorException)
                {
                    ToastManager.GetInstance().CreatToast("网络连接失败,请检查网络连接");
                }
                else
                {
                    ToastManager.GetInstance().CreatToast(e.Message);
                }
            }
        }));
    }
Beispiel #23
0
 public static UniRx.IObservable <string> Upload(this byte[] binary, string url, Action <string> completeCallback, UniRx.IProgress <float> progressCallback, Dictionary <string, string> headers = null)
 {
     UniRx.IObservable <string> obs = ObservableWWW.Post(url, binary, headers, progressCallback);
     obs.Subscribe(completeCallback);
     return(obs);
 }
Beispiel #24
0
        protected override void OnBegin()
        {
            IObservable <string> www = null;

            if (User.Logined)
            {
                Dictionary <string, string> headers = new Dictionary <string, string>();
                headers.Add("Authorization", "Token " + User.Token);

                var form = new WWWForm();

                form.AddField("username", User.Username.Value);
                form.AddField("password", User.Password.Value);

                www = ObservableWWW.Post("https://api.liangxiegame.com/qf/v4/package/list", form, headers);
            }
            else
            {
                www = ObservableWWW.Post("https://api.liangxiegame.com/qf/v4/package/list", new WWWForm());
            }


            www.Subscribe(response =>
            {
                var responseJson = JObject.Parse(response);

                if (responseJson["code"].Value <string>() == "1")
                {
                    var packageInfosJson = responseJson["data"];

                    var packageDatas = new List <PackageData>();
                    foreach (var packageInfo in packageInfosJson)
                    {
                        var name = packageInfo["name"].Value <string>();

                        var package = packageDatas.Find(packageData => packageData.Name == name);

                        if (package == null)
                        {
                            package = new PackageData()
                            {
                                Name = name,
                            };

                            packageDatas.Add(package);
                        }

                        var id          = packageInfo["id"].Value <string>();
                        var version     = packageInfo["version"].Value <string>();
                        var url         = packageInfo["downloadUrl"].Value <string>();            // download_url
                        var installPath = packageInfo["installPath"].Value <string>();
                        var releaseNote = packageInfo["releaseNote"].Value <string>();
                        var createAt    = packageInfo["createAt"].Value <string>();
                        var creator     = packageInfo["username"].Value <string>();
//					    var docUrl = packageInfo["doc_url"].Value<string>();
                        var releaseItem     = new ReleaseItem(version, releaseNote, creator, DateTime.Parse(createAt));
                        var accessRightName = packageInfo["accessRight"].Value <string>();
                        var typeName        = packageInfo["type"].Value <string>();

                        var packageType = PackageType.FrameworkModule;

                        switch (typeName)
                        {
                        case "fm":
                            packageType = PackageType.FrameworkModule;
                            break;

                        case "s":
                            packageType = PackageType.Shader;
                            break;

                        case "agt":
                            packageType = PackageType.AppOrGameDemoOrTemplate;
                            break;

                        case "p":
                            packageType = PackageType.Plugin;
                            break;
                        }

                        var accessRight = PackageAccessRight.Public;

//					    accessRightName.LogInfo();
                        switch (accessRightName)
                        {
                        case "public":
                            accessRight = PackageAccessRight.Public;
                            break;

                        case "private":
                            accessRight = PackageAccessRight.Private;
                            break;
                        }

                        package.PackageVersions.Add(new PackageVersion()
                        {
                            Id          = id,
                            Version     = version,
                            DownloadUrl = url,
                            InstallPath = installPath,
                            Type        = packageType,
                            AccessRight = accessRight,
                            Readme      = releaseItem,
//						    DocUrl = docUrl,
                        });

                        package.readme.AddReleaseNote(releaseItem);
                    }

                    packageDatas.ForEach(packageData =>
                    {
                        packageData.PackageVersions.Sort((a, b) =>
                                                         b.VersionNumber - a.VersionNumber);
                        packageData.readme.items.Sort((a, b) =>
                                                      b.VersionNumber - a.VersionNumber);
                    });

                    mOnGet.InvokeGracefully(packageDatas);

                    new PackageInfosRequestCache()
                    {
                        PackageDatas = packageDatas
                    }.Save();

                    Finished = true;
                }
            }, e =>
            {
                mOnGet.InvokeGracefully(null);
                Log.E(e);
            });
        }
 static public void Broadcast(Transaction transaction, NBitcoin.Network network, BroadcastResponse response)
 {
     ObservableWWW.Post(URL(network, "transactions"), transaction.ToBytes(), HEADER()).
     Subscribe(x => response(JsonUtility.FromJson <Models.BroadcastResponse>(x).Result(), network),
               ex => Debug.Log("error : " + ex.Message));
 }
Beispiel #26
0
 void PushMessage(byte[] postData)
 {
     ObservableWWW.Post(_host, postData, _headers).ObserveOnMainThread().Subscribe(mes => {}, ex => Debug.LogError("Logserver, ex = " + ex));
 }
Beispiel #27
0
        public static void DoUpload(PackageVersion packageVersion, System.Action succeed)
        {
            EditorUtility.DisplayProgressBar("插件上传", "打包中...", 0.1f);

            var fileName = packageVersion.Name + "_" + packageVersion.Version + ".unitypackage";
            var fullpath = PackageManagerView.ExportPaths(fileName, packageVersion.InstallPath);
            var file     = File.ReadAllBytes(fullpath);

            var form = new WWWForm();

            form.AddField("username", User.Username.Value);
            form.AddField("password", User.Password.Value);
            form.AddField("name", packageVersion.Name);
            form.AddField("version", packageVersion.Version);
            form.AddBinaryData("file", file);
            form.AddField("version", packageVersion.Version);
            form.AddField("releaseNote", packageVersion.Readme.content);
            form.AddField("installPath", packageVersion.InstallPath);
            form.AddField("accessRight", packageVersion.AccessRight.ToString().ToLower());
            form.AddField("docUrl", packageVersion.DocUrl);

            if (packageVersion.Type == PackageType.FrameworkModule)
            {
                form.AddField("type", "fm");
            }
            else if (packageVersion.Type == PackageType.Shader)
            {
                form.AddField("type", "s");
            }
            else if (packageVersion.Type == PackageType.AppOrGameDemoOrTemplate)
            {
                form.AddField("type", "agt");
            }
            else if (packageVersion.Type == PackageType.Plugin)
            {
                form.AddField("type", "p");
            }
            else if (packageVersion.Type == PackageType.Master)
            {
                form.AddField("type", "master");
            }

            Debug.Log(fullpath);

            EditorUtility.DisplayProgressBar("插件上传", "上传中...", 0.2f);


            ObservableWWW.Post(UPLOAD_URL, form,
                               new Dictionary <string, string> {
                { "Authorization", "Token " + User.Token.Value }
            })
            .Subscribe(responseContent =>
            {
                EditorUtility.ClearProgressBar();
                Debug.Log(responseContent);
                succeed.InvokeGracefully();
                File.Delete(fullpath);
            }, e =>
            {
                EditorUtility.ClearProgressBar();
                EditorUtility.DisplayDialog("插件上传", "上传失败!{0}".FillFormat(e.Message), "确定");
                File.Delete(fullpath);
            });
        }
        private IEnumerator CheckNews()
        {
            T_RLU_NewsHistory input = new T_RLU_NewsHistory();

            input.iSequence = NewsNumber;
            input.vcVersion = CommonConst.SystemValue.CurrentVersion;
            input.vcGameId  = GameStateInformation.GameId.ToString("D");

            string json = JsonMapper.ToJson(input);
            //jsonを暗号化
            string ecjson = CryptInformation.EncryptString(json, CommonConst.CryptKey.GetNews);

            //ニュースを取得
            Dictionary <string, string> headers = new Dictionary <string, string>();

#if UNITY_EDITOR
            //sessionid = sessionid.Replace("ASP.NET_SessionId=", "");
            //Regex rgx = new Regex(";.+");
            //sessionid = rgx.Replace(sessionid, "");
            //headers.Add("Cookie", string.Format("ASP.NET_SessionId={0};", sessionid));
#endif

            WWWForm form = new WWWForm();
            form.AddField("input", ecjson);

#if UNITY_EDITOR
#else
            headers = form.headers;
            headers.Add("Access-Control-Allow-Credentials", "true");
            headers.Add("Access-Control-Allow-Headers", "Accept");
            headers.Add("Access-Control-Allow-Methods", "POST");
            headers.Add("Access-Control-Allow-Origin", "*");
#endif

            //WWW www = new WWW(UrlNews, form.data, headers);

            //while (www.isDone == false && www.progress != 1)
            //{
            //    yield return null;
            //}
            //yield return www;

            var www = ObservableWWW.Post(UrlNews, form.data, headers).ToYieldInstruction();
            while (!(www.HasResult || www.IsCanceled || www.HasError)) // 3つもプロパティ並べるのダルいので次回アップデートでIsDoneを追加します予定
            {
                yield return(null);
            }

            string result = "";
            if (www.HasResult == true && CommonFunction.IsNullOrWhiteSpace(www.Result) == false)
            {
                result = www.Result;
            }

            //if(CommonFunction.IsNullOrWhiteSpace(www.error) == true)
            //{
            //    result = www.text;
            //}

            www.Dispose();

            yield return(null);

            //yield return Observable.FromMicroCoroutine(() => DisplayNews(result)).Subscribe();
            MainThreadDispatcher.StartUpdateMicroCoroutine(DisplayNews(result));
            //yield return  StartCoroutine(DisplayNews(result));

            NewsCheckCoroutine = null;
        }