void downloadFileCompleteCb(object sender, System.ComponentModel.AsyncCompletedEventArgs ar)
        {
            try
            {
                if (ar.Error != null)
                {
                    throw ar.Error;
                }

                image_list_.RemoveAt(0);
                if (image_list_.Count > 0)
                {
                    KeyValuePair <string, string> item = image_list_[0];
                    web_client_.DownloadFileAsync(new Uri(item.Key), item.Value);
                    FunDebug.LogDebug("Announcement - Downloading image: {0}", item.Key);
                }
                else
                {
                    FunDebug.Log("Announcement - All images have been downloaded.\npath:{0}", local_path_);
                    onResult(AnnounceResult.kSucceeded);
                }
            }
            catch (Exception e)
            {
                FunDebug.LogError("Announcement - Failure in downloadFileCompleteCb:\n{0}", e.ToString());
                onResult(AnnounceResult.kExceptionError);
            }
        }
Exemplo n.º 2
0
        protected void LogError(string message, params object[] args)
        {
#if ENABLE_DEBUG
            message = string.Format("[{0}] {1}", hash_, message);
#endif
            FunDebug.LogError(message, args);
        }
Exemplo n.º 3
0
        public static T GetMulticastMessage <T> (FunMulticastMessage msg, MulticastMessageType msg_type)
        {
            try
            {
                object _msg = null;
                Extensible.TryGetValue(serializer_, MessageTable.GetType(msg_type), msg,
                                       (int)msg_type, DataFormat.Default, true, out _msg);

                FunDebug.Assert(_msg != null, "TryGetValue() failed. Please check the message type.");

                return((T)_msg);
            }
            catch (Exception e)
            {
                Type type = MessageTable.GetType(msg_type);
                FunDebug.LogError("FunapiMessage.GetMulticastMessage - Failed to decode '{0}' ({1})\n{2}",
                                  type, msg_type, e.ToString());

                if (ParsingErrorCallback != null)
                {
                    ParsingErrorCallback(type);
                }
            }

            return(default(T));
        }
Exemplo n.º 4
0
        // For FunMessage
        public static FunMessage CreateFunMessage(object msg, MessageType msg_type)
        {
            if (msg is Enum)
            {
                msg = (Int32)msg;
            }

            try
            {
                FunMessage _msg = new FunMessage();
                Extensible.AppendValue(serializer_, _msg, (int)msg_type, DataFormat.Default, msg);
                return(_msg);
            }
            catch (Exception e)
            {
                Type type = MessageTable.GetType(msg_type);
                FunDebug.LogError("FunapiMessage.CreateFunMessage - Failed to create '{0}' ({1})\n{2}",
                                  type, msg_type, e.ToString());

                if (ParsingErrorCallback != null)
                {
                    ParsingErrorCallback(type);
                }
            }

            return(null);
        }
Exemplo n.º 5
0
        public void StartDownload()
        {
            mutex_.WaitOne();

            try
            {
                if (state_ != State.Ready)
                {
                    FunDebug.LogError("You must call GetDownloadList function first "
                                      + "or wait until ready to download.");
                    return;
                }

                if (total_download_count_ > 0)
                {
                    FunDebug.Log("Ready to download {0} files ({1})",
                                 total_download_count_, getSizeString(total_download_size_));
                }

                state_ = State.Downloading;
                retry_download_count_ = 0;
                download_time_.Start();

                // Deletes files
                deleteLocalFiles();

                // Starts download
                downloadResourceFile();
            }
            finally
            {
                mutex_.ReleaseMutex();
            }
        }
        IEnumerator RequestMyInfo()
        {
            oauth_handler_.Clear();
            oauth_handler_.AddParameter("user_id", MyId);

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

            headers["Authorization"] = oauth_handler_.GenerateHeader(kShowUrl, "GET");

            string url = string.Format("{0}?user_id={1}", kShowUrl, MyId);
            WWW    web = new WWW(url.ToString(), null, headers);

            yield return(web);

            if (!string.IsNullOrEmpty(web.error))
            {
                FunDebug.LogError("Failure in RequestMyInfo: {0}", web.error);
                OnEventNotify(SNResultCode.kError);
            }
            else
            {
                Dictionary <string, object> data = Json.Deserialize(web.text) as Dictionary <string, object>;
                string img_url = data["profile_image_url"] as string;
                my_info_.url = img_url.Replace("normal", "bigger");
                StartCoroutine(RequestPicture(my_info_));

                OnEventNotify(SNResultCode.kMyProfile);
            }
        }
        IEnumerator RequestFriendsInfo(string ids)
        {
            oauth_handler_.Clear();
            oauth_handler_.AddParameter("user_id", ids);

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

            headers["Authorization"] = oauth_handler_.GenerateHeader(kLookupUrl, "GET");

            string url = string.Format("{0}?user_id={1}", kLookupUrl, ids);
            WWW    web = new WWW(url.ToString(), null, headers);

            yield return(web);

            if (!string.IsNullOrEmpty(web.error))
            {
                FunDebug.LogError("Failure in RequestUserInfo: {0}", web.error);
                OnEventNotify(SNResultCode.kError);
            }
            else
            {
                List <object> list = Json.Deserialize(web.text) as List <object>;
                if (list.Count <= 0)
                {
                    FunDebug.LogError("RequestUserInfo - Invalid list data. List size is 0.");
                    yield break;
                }
                else
                {
                    lock (friend_list_)
                    {
                        friend_list_.Clear();

                        foreach (Dictionary <string, object> node in list)
                        {
                            UserInfo user = new UserInfo();
                            user.id   = node["id_str"] as string;
                            user.name = node["screen_name"] as string;

                            url      = node["profile_image_url"] as string;
                            user.url = url.Replace("_normal", "_bigger");

                            friend_list_.Add(user);
                            FunDebug.DebugLog1("> id:{0} name:{1} image:{2}", user.id, user.name, user.url);
                        }
                    }

                    FunDebug.Log("Succeeded in getting the friend list. count:{0}", friend_list_.Count);
                    OnEventNotify(SNResultCode.kFriendList);

                    lock (friend_list_)
                    {
                        if (auto_request_picture_ && friend_list_.Count > 0)
                        {
                            StartCoroutine(RequestPictures(GetFriendList()));
                        }
                    }
                }
            }
        }
Exemplo n.º 8
0
        void OnLoginCb(ILoginResult result)
        {
            if (result.Error != null)
            {
                FunDebug.LogError(result.Error);
                OnEventNotify(SNResultCode.kLoginFailed);
            }
            else if (!FB.IsLoggedIn)
            {
                FunDebug.Log("User cancelled login.");
                OnEventNotify(SNResultCode.kLoginFailed);
            }
            else
            {
                FunDebug.Log("Facebook login succeeded!");

                // AccessToken class will have session details
                var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;

                // Print current access token's granted permissions
                StringBuilder perms = new StringBuilder();
                perms.Append("Permissions: ");
                foreach (string perm in aToken.Permissions)
                {
                    perms.AppendFormat("\"{0}\", ", perm);
                }
                FunDebug.Log(perms.ToString());

                // Reqests my info and profile picture
                FB.API("me?fields=id,name,picture.width(128).height(128)", HttpMethod.GET, OnMyProfileCb);

                OnEventNotify(SNResultCode.kLoggedIn);
            }
        }
Exemplo n.º 9
0
        void readCb(IAsyncResult ar)
        {
            try
            {
                Request request = (Request)ar.AsyncState;
                int     nRead   = request.read_stream.EndRead(ar);
                if (nRead > 0)
                {
                    request.read_offset += nRead;
                    request.read_stream.BeginRead(request.body.Array, request.read_offset,
                                                  request.body.Count - request.read_offset,
                                                  new AsyncCallback(readCb), request);
                }
                else
                {
                    if (request.web_response == null)
                    {
                        FunDebug.LogError("Host manager response failed.");
                        return;
                    }

                    webRequestCallback(request);

                    request.read_stream.Close();
                    request.web_response.Close();
                }
            }
            catch (Exception e)
            {
                if (e is ObjectDisposedException || e is NullReferenceException)
                {
                    FunDebug.LogDebug("Dedicated server request operation has been cancelled.");
                }
            }
        }
Exemplo n.º 10
0
        public static bool DownloadMozRoots()
        {
#if !NO_UNITY
            LoadMozRoots();
            string tempPath = FunapiUtils.GetLocalDataPath + "/" + Path.GetRandomFileName();
            try
            {
                // Try to download the Mozilla's root certificates file.
                WebClient webClient = new WebClient();
                webClient.DownloadFile(kMozillaCertificatesUrl, tempPath);
            }
            catch (WebException we)
            {
                FunDebug.LogError("DownloadMozRoots - Download certificates failed.\n{0}", we.Message);
                File.Delete(tempPath);
                return(false);
            }

            try
            {
                using (FileStream readStream = new FileStream(tempPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    byte[] buffer = new byte[readStream.Length];
                    readStream.Read(buffer, 0, buffer.Length);
                    readStream.Close();
                    File.Delete(tempPath);

                    string targetPath = FunapiUtils.GetAssetsPath + kDownloadCertificatesPath;

                    // If there's certificates file, delete the file.
                    if (File.Exists(targetPath))
                    {
                        File.Delete(targetPath);
                    }

                    using (FileStream writeStream = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.Write))
                    {
                        using (ZipOutputStream zipOutputStream = new ZipOutputStream(writeStream))
                        {
                            ZipEntry zipEntry = new ZipEntry("MozRoots");
                            zipEntry.Size     = buffer.Length;
                            zipEntry.DateTime = DateTime.Now;

                            zipOutputStream.PutNextEntry(zipEntry);
                            zipOutputStream.Write(buffer, 0, buffer.Length);
                            zipOutputStream.Close();
                        }
                        writeStream.Close();
                    }
                }
            }
            catch (Exception e)
            {
                FunDebug.LogError("DownloadMozRoots - The creation of the zip file of certificates failed.\n{0}", e.Message);
                return(false);
            }
#endif
            return(true);
        }
        public void GetDownloadList(string url, string target_path, string file_path = "")
        {
            lock (lock_)
            {
                if (ReadyCallback == null)
                {
                    FunDebug.LogError("Downloader.GetDownloadList - You must register the ReadyCallback first.");
                    return;
                }

                if (IsDownloading)
                {
                    FunDebug.LogWarning("The resource file is being downloaded. (Url: {0})\n" +
                                        "Please try again after the download is completed.", url);
                    return;
                }

                state_ = State.Start;

                string host_url = url;
                if (host_url[host_url.Length - 1] != '/')
                {
                    host_url += "/";
                }
                host_url_ = host_url;
                FunDebug.Log("[Downloader] Download from {0}", host_url_);

                target_path_ = target_path;
                if (target_path_[target_path_.Length - 1] != '/')
                {
                    target_path_ += "/";
                }
                target_path_ += kRootPath + "/";
                FunDebug.Log("[Downloader] Save to {0}", target_path_);

                cur_download_count_    = 0;
                cur_download_size_     = 0;
                total_download_count_  = 0;
                total_download_size_   = 0;
                partial_download_size_ = 0;

                setMonoListener();
                loadCachedList();

                // Gets list file
                string request_url = host_url_;
                if (!string.IsNullOrEmpty(file_path))
                {
                    if (file_path[0] == '/')
                    {
                        file_path = file_path.Substring(1);
                    }

                    request_url += file_path;
                }

                downloadListFile(request_url);
            }
        }
Exemplo n.º 12
0
        void OnFriendListCb(IGraphResult result)
        {
            try
            {
                Dictionary <string, object> json = Json.Deserialize(result.RawResult) as Dictionary <string, object>;
                if (json == null)
                {
                    FunDebug.LogError("OnFriendListCb - json is null.");
                    OnEventNotify(SNResultCode.kError);
                    return;
                }

                // friend list
                object friend_list = null;
                json.TryGetValue("friends", out friend_list);
                if (friend_list == null)
                {
                    FunDebug.LogError("OnInviteListCb - friend_list is null.");
                    OnEventNotify(SNResultCode.kError);
                    return;
                }

                lock (friend_list_)
                {
                    friend_list_.Clear();

                    List <object> list = ((Dictionary <string, object>)friend_list)["data"] as List <object>;
                    foreach (object item in list)
                    {
                        Dictionary <string, object> info    = item as Dictionary <string, object>;
                        Dictionary <string, object> picture = ((Dictionary <string, object>)info["picture"])["data"] as Dictionary <string, object>;

                        UserInfo user = new UserInfo();
                        user.id   = info["id"] as string;
                        user.name = info["name"] as string;
                        user.url  = picture["url"] as string;

                        friend_list_.Add(user);
                        FunDebug.DebugLog1("> id:{0} name:{1} image:{2}", user.id, user.name, user.url);
                    }
                }

                FunDebug.Log("Succeeded in getting the friend list. count:{0}", friend_list_.Count);
                OnEventNotify(SNResultCode.kFriendList);

                lock (friend_list_)
                {
                    if (auto_request_picture_ && friend_list_.Count > 0)
                    {
                        StartCoroutine(RequestPictures(GetFriendList()));
                    }
                }
            }
            catch (Exception e)
            {
                FunDebug.LogError("Failure in OnFriendListCb: {0}", e.ToString());
            }
        }
Exemplo n.º 13
0
        protected void LogError(string message, params object[] args)
        {
#if ENABLE_LOG && (LOG_LEVEL_1 || LOG_LEVEL_2 || LOG_LEVEL_3)
#if LOG_LEVEL_3
            message = string.Format("[{0}] {1}", hash_, message);
#endif
            FunDebug.LogError(message, args);
#endif
        }
Exemplo n.º 14
0
        public void GetDownloadList(string url, string target_path)
        {
            mutex_.WaitOne();

            try
            {
                if (ReadyCallback == null)
                {
                    FunDebug.LogError("You must register the ReadyCallback first.");
                    return;
                }

                if (IsDownloading)
                {
                    FunDebug.LogWarning("The resource file is being downloaded. (Url: {0})\n"
                                        + "Please try again after the download is completed.", url);
                    return;
                }

                state_ = State.Start;

                string host_url = url;
                if (host_url[host_url.Length - 1] != '/')
                {
                    host_url += "/";
                }
                host_url_ = host_url;
                FunDebug.Log("Download url: {0}", host_url_);

                target_path_ = target_path;
                if (target_path_[target_path_.Length - 1] != '/')
                {
                    target_path_ += "/";
                }
                target_path_ += kRootPath + "/";
                FunDebug.Log("Download path: {0}", target_path_);

                cur_download_count_   = 0;
                cur_download_size_    = 0;
                total_download_count_ = 0;
                total_download_size_  = 0;

                createUpdater();
                loadCachedList();

                // Gets list file
                downloadListFile(host_url_);
            }
            finally
            {
                mutex_.ReleaseMutex();
            }
        }
        IEnumerator GetAccessToken(string oauth_verifier)
        {
            // header
            oauth_handler_.Clear();
            oauth_handler_.AddParameter("oauth_token", request_token_);
            oauth_handler_.AddParameter("oauth_verifier", oauth_verifier);

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

            headers["Authorization"] = oauth_handler_.GenerateHeader(kAccessUrl, "POST");

            WWW web = new WWW(kAccessUrl, null, headers);

            yield return(web);

            if (!string.IsNullOrEmpty(web.error))
            {
                FunDebug.LogError("Failure in GetAccessToken: {0}\n{1}", web.error, web.text);
                OnEventNotify(SNResultCode.kLoginFailed);
            }
            else
            {
                my_info_.id   = Regex.Match(web.text, @"user_id=([^&]+)").Groups[1].Value;
                my_info_.name = Regex.Match(web.text, @"screen_name=([^&]+)").Groups[1].Value;
                string token  = Regex.Match(web.text, @"oauth_token=([^&]+)").Groups[1].Value;
                string secret = Regex.Match(web.text, @"oauth_token_secret=([^&]+)").Groups[1].Value;

                if (!string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(secret) &&
                    !string.IsNullOrEmpty(my_info_.id) && !string.IsNullOrEmpty(my_info_.name))
                {
                    FunDebug.Log("Succeeded in getting my information of Twitter.\n" +
                                 "id: {0}\nname: {1}\ntoken: {2}\ntoken_secret: {3}",
                                 my_info_.id, my_info_.name, token, secret);

                    oauth_handler_.AddParameter("oauth_token", token);
                    oauth_handler_.AddParameter("oauth_token_secret", secret);

                    PlayerPrefs.SetString("user_id", my_info_.id);
                    PlayerPrefs.SetString("screen_name", my_info_.name);
                    PlayerPrefs.SetString("oauth_token", token);
                    PlayerPrefs.SetString("oauth_token_secret", secret);

                    OnEventNotify(SNResultCode.kLoggedIn);
                }
                else
                {
                    FunDebug.LogError("Failure in GetAccessToken: {0}", web.text);
                    OnEventNotify(SNResultCode.kLoginFailed);
                }
            }
        }
Exemplo n.º 16
0
 void downloadListFile(string url)
 {
     try
     {
         // Request a list of download files.
         FunDebug.Log("Downloader - Getting list file from {0}", url);
         web_client_.DownloadDataAsync(new Uri(url));
     }
     catch (Exception e)
     {
         FunDebug.LogError("Failure in Downloader.downloadListFile: {0}", e.ToString());
         Stop();
     }
 }
        // Coroutine-related functions
        IEnumerator GetRequestToken()
        {
            // form data
            WWWForm form = new WWWForm();

            form.AddField("oauth_callback", "oob");

            // header
            oauth_handler_.Clear();
            oauth_handler_.AddParameter("oauth_callback", "oob");

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

            headers["Authorization"] = oauth_handler_.GenerateHeader(kRequestUrl, "POST");

            // request
            WWW web = new WWW(kRequestUrl, form.data, headers);

            yield return(web);

            if (!string.IsNullOrEmpty(web.error))
            {
                FunDebug.LogError("Failure in GetRequestToken: {0}\n{1}", web.error, web.text);
                OnEventNotify(SNResultCode.kLoginFailed);
            }
            else
            {
                string token  = Regex.Match(web.text, @"oauth_token=([^&]+)").Groups[1].Value;
                string secret = Regex.Match(web.text, @"oauth_token_secret=([^&]+)").Groups[1].Value;

                if (!string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(secret))
                {
                    FunDebug.Log("Succeeded in getting access token of Twitter.\n" +
                                 "token: {0}\nsecret: {1}", token, secret);

                    request_token_ = token;

                    string url = string.Format(kOAuthUrl, token);
                    Application.OpenURL(url);
                }
                else
                {
                    FunDebug.LogError("Failure in GetRequestToken: {0}", web.text);
                    OnEventNotify(SNResultCode.kLoginFailed);
                }
            }
        }
        IEnumerator PostTweet(string message)
        {
            if (string.IsNullOrEmpty(message) || message.Length > 140)
            {
                FunDebug.LogError("PostTweet - message is empty or too long.\nmessage: {0}", message);
                OnEventNotify(SNResultCode.kPostFailed);
            }
            else
            {
                // message
                WWWForm form = new WWWForm();
                form.AddField("status", message);

                // header
                oauth_handler_.Clear();
                oauth_handler_.AddParameter("status", message);

                var headers = new Dictionary <string, string>();
                headers["Authorization"] = oauth_handler_.GenerateHeader(kPostUrl, "POST");

                // request
                WWW web = new WWW(kPostUrl, form.data, headers);
                yield return(web);

                if (!string.IsNullOrEmpty(web.error))
                {
                    FunDebug.LogError("Failure in PostTweet: {0}\n{1}", web.error, web.text);
                    OnEventNotify(SNResultCode.kPostFailed);
                }
                else
                {
                    string error = Regex.Match(web.text, @"<error>([^&]+)</error>").Groups[1].Value;
                    if (!string.IsNullOrEmpty(error))
                    {
                        FunDebug.LogError("Failure in PostTweet(Regex.Match): {0}", error);
                        OnEventNotify(SNResultCode.kPostFailed);
                    }
                    else
                    {
                        FunDebug.Log("Post tweet succeeeded.");
                        OnEventNotify(SNResultCode.kPosted);
                    }
                }
            }
        }
        IEnumerator RequestFriendIds(int limit)
        {
            oauth_handler_.Clear();

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

            headers["Authorization"] = oauth_handler_.GenerateHeader(kFriendsIdsUrl, "GET");

            WWW web = new WWW(kFriendsIdsUrl, null, headers);

            yield return(web);

            if (!string.IsNullOrEmpty(web.error))
            {
                FunDebug.LogError("Failure in RequestFriendIds: {0}", web.error);
                OnEventNotify(SNResultCode.kError);
            }
            else
            {
                Dictionary <string, object> data = Json.Deserialize(web.text) as Dictionary <string, object>;
                List <object> list = data["ids"] as List <object>;

                StringBuilder ids = new StringBuilder();
                int           idx = 0, count = Mathf.Min(list.Count, limit);
                foreach (object id in list)
                {
                    ids.AppendFormat("{0},", Convert.ToUInt32(id));
                    if (++idx >= count)
                    {
                        break;
                    }
                }

                if (ids.Length > 0)
                {
                    StartCoroutine(RequestFriendsInfo(ids.ToString()));
                }
            }
        }
Exemplo n.º 20
0
        void OnMyProfileCb(IGraphResult result)
        {
            FunDebug.DebugLog1("FacebookConnector.OnMyProfileCb called.");
            if (result.Error != null)
            {
                FunDebug.LogError(result.Error);
                OnEventNotify(SNResultCode.kError);
                return;
            }

            try
            {
                Dictionary <string, object> json = Json.Deserialize(result.RawResult) as Dictionary <string, object>;
                if (json == null)
                {
                    FunDebug.LogError("OnMyProfileCb - json is null.");
                    OnEventNotify(SNResultCode.kError);
                    return;
                }

                // my profile
                my_info_.id   = json["id"] as string;
                my_info_.name = json["name"] as string;
                FunDebug.Log("Facebook id: {0}, name: {1}.", my_info_.id, my_info_.name);

                // my picture
                var picture = json["picture"] as Dictionary <string, object>;
                var data    = picture["data"] as Dictionary <string, object>;
                my_info_.url = data["url"] as string;
                StartCoroutine(RequestPicture(my_info_));

                OnEventNotify(SNResultCode.kMyProfile);
            }
            catch (Exception e)
            {
                FunDebug.LogError("Failure in OnMyProfileCb: {0}", e.ToString());
            }
        }
Exemplo n.º 21
0
        public static Encryptor Create(EncryptionType type)
        {
            switch (type)
            {
            case EncryptionType.kDummyEncryption:
                return(new Encryptor0());

            case EncryptionType.kIFunEngine1Encryption:
            case EncryptionType.kIFunEngine2Encryption:
                FunDebug.LogWarning("This plugin is not support '{0}' encryption.", type);
                return(null);

            case EncryptionType.kChaCha20Encryption:
                return(new EncryptorChacha20());

            case EncryptionType.kAes128Encryption:
                return(new EncryptorAes128());

            default:
                FunDebug.LogError("Encryptor.Create - Unknown type: {0}", type);
                return(null);
            }
        }
Exemplo n.º 22
0
        public void GetDownloadList(string url, string target_path, string file_path = "")
        {
            mutex_.WaitOne();

            try
            {
                if (ReadyCallback == null)
                {
                    FunDebug.LogError("Downloader.GetDownloadList - You must register the ReadyCallback first.");
                    return;
                }

                if (IsDownloading)
                {
                    FunDebug.LogWarning("The resource file is being downloaded. (Url: {0})\n" +
                                        "Please try again after the download is completed.", url);
                    return;
                }

                state_ = State.Start;

                string host_url = url;
                if (host_url[host_url.Length - 1] != '/')
                {
                    host_url += "/";
                }
                host_url_ = host_url;
                FunDebug.Log("Downloader - url: {0}", host_url_);

                target_path_ = target_path;
                if (target_path_[target_path_.Length - 1] != '/')
                {
                    target_path_ += "/";
                }
                target_path_ += kRootPath + "/";
                FunDebug.Log("Downloader - path: {0}", target_path_);

                cur_download_count_   = 0;
                cur_download_size_    = 0;
                total_download_count_ = 0;
                total_download_size_  = 0;

                if (host_url.ToLower().Contains("https"))
                {
                    MozRoots.LoadRootCertificates();
                }

                createUpdater();
                loadCachedList();

                // Gets list file
                string request_url = host_url_;
                if (!string.IsNullOrEmpty(file_path))
                {
                    if (file_path[0] == '/')
                    {
                        file_path = file_path.Substring(1);
                    }

                    request_url += file_path;
                }

                downloadListFile(request_url);
            }
            finally
            {
                mutex_.ReleaseMutex();
            }
        }
Exemplo n.º 23
0
        // Callback function for list of files
        void downloadDataCompleteCb(object sender, DownloadDataCompletedEventArgs ar)
        {
            mutex_.WaitOne();

            bool failed = false;

            try
            {
                if (ar.Error != null)
                {
                    FunDebug.LogError("Downloader - Exception error: {0}", ar.Error);
                    failed = true;
                }
                else
                {
                    // It can be true when CancelAsync() called in Stop().
                    if (ar.Cancelled)
                    {
                        return;
                    }

                    // Parse json
                    string data = Encoding.UTF8.GetString(ar.Result);
                    Dictionary <string, object> json = Json.Deserialize(data) as Dictionary <string, object>;

                    //FunDebug.Log("Json data >> {0}", data);

                    // Redirect url
                    if (json.ContainsKey("url"))
                    {
                        string url = json["url"] as string;
                        if (url[url.Length - 1] != '/')
                        {
                            url += "/";
                        }

                        host_url_ = url;
                        FunDebug.Log("Redirect download url: {0}", host_url_);
                    }

                    List <object> list = json["data"] as List <object>;
                    if (list.Count <= 0)
                    {
                        FunDebug.LogWarning("Invalid list data. List count is 0.");
                        FunDebug.Assert(false);
                        failed = true;
                    }
                    else
                    {
                        download_list_.Clear();

                        foreach (Dictionary <string, object> node in list)
                        {
                            DownloadFileInfo info = new DownloadFileInfo();
                            info.path = node["path"] as string;
                            info.size = Convert.ToUInt32(node["size"]);
                            info.hash = node["md5"] as string;
                            if (node.ContainsKey("md5_front"))
                            {
                                info.hash_front = node["md5_front"] as string;
                            }
                            else
                            {
                                info.hash_front = "";
                            }

                            download_list_.Add(info);
                        }

                        // Checks files
#if !NO_UNITY
                        event_list.Add(() => mono.StartCoroutine(checkFileList(download_list_)));
#else
                        event_list.Add(() => mono.StartCoroutine(() => checkFileList(download_list_)));
#endif
                    }
                }
            }
            catch (Exception e)
            {
                FunDebug.LogError("Failure in Downloader.downloadDataCompleteCb: {0}", e.ToString());
                failed = true;
            }
            finally
            {
                mutex_.ReleaseMutex();
            }

            if (failed)
            {
                Stop();
            }
        }
Exemplo n.º 24
0
        void httpPostSync(string command, string data, Action <object> callback = null) // for send version only
        {
            string url = server_url_ + command;

            // Request
            HttpWebRequest web_request = (HttpWebRequest)WebRequest.Create(url);

            web_request.Method      = "POST";
            web_request.ContentType = "application/octet-stream";

            Request request = new Request();

            request.web_request = web_request;
            request.callback    = callback;
            request.command     = command;

            try
            {
                byte[] bytes             = System.Text.Encoding.UTF8.GetBytes(data);
                ArraySegment <byte> body = new ArraySegment <byte>(bytes);
                web_request.ContentLength = body.Count;
                request.body = body;

                Stream stream = web_request.GetRequestStream();
                stream.Write(request.body.Array, 0, request.body.Count);
                stream.Close();

                request.web_response = (HttpWebResponse)web_request.GetResponse();
                request.web_request  = null;

                if (request.web_response.StatusCode == HttpStatusCode.OK)
                {
                    request.read_stream = request.web_response.GetResponseStream();
                    StreamReader sr = new StreamReader(request.read_stream);

                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sr.ReadToEnd());
                    request.body = new ArraySegment <byte>(buffer);

                    webRequestCallback(request);

                    request.read_stream.Close();
                    request.web_response.Close();
                }
                else
                {
                    FunDebug.LogError("Host manager response failed. status:{0}",
                                      request.web_response.StatusDescription);
                }
            }
            catch (Exception e)
            {
                WebException we = e as WebException;
                if (we != null && we.Status == WebExceptionStatus.ConnectFailure)
                {
                    onRequestFailed(request);
                }
                else if ((we != null && we.Status == WebExceptionStatus.RequestCanceled) ||
                         (e is ObjectDisposedException || e is NullReferenceException))
                {
                    FunDebug.LogDebug("Dedicated Server - httpPostServerVersionSync operation has been cancelled.");
                }
            }
        }
Exemplo n.º 25
0
        // Callback function for downloaded file.
        void downloadFileCompleteCb(object sender, System.ComponentModel.AsyncCompletedEventArgs ar)
        {
            mutex_.WaitOne();

            bool failed = false;

            try
            {
                // It can be true when CancelAsync() called in Stop().
                if (ar.Cancelled)
                {
                    File.Delete(cur_download_path_);
                    return;
                }

                if (ar.Error != null)
                {
                    FunDebug.LogError("Downloader - Exception error: {0}", ar.Error);
                    failed = true;
                }
                else
                {
                    var info = (DownloadFileInfo)ar.UserState;
                    if (info == null)
                    {
                        FunDebug.LogWarning("Downloader - DownloadFileInfo object is null.");
                        failed = true;
                    }
                    else
                    {
                        string path = target_path_ + info.path;
                        File.Move(cur_download_path_, path);

                        ++cur_download_count_;
                        retry_download_count_ = 0;
                        cur_download_size_   += info.size;
                        download_list_.Remove(info);
                        cached_list_.Add(info);

                        downloadResourceFile();
                    }
                }
            }
            catch (Exception e)
            {
                FunDebug.LogError("Failure in Downloader.downloadFileCompleteCb: {0}", e.ToString());
                failed = true;
            }
            finally
            {
                mutex_.ReleaseMutex();
            }

            if (failed)
            {
                web_client_.Dispose();
                File.Delete(cur_download_path_);

                if (retry_download_count_ < kRetryCountMax)
                {
                    ++retry_download_count_;
#if !NO_UNITY
                    event_list.Add(() => mono.StartCoroutine(retryDownloadFile()));
#else
                    event_list.Add(() => mono.StartCoroutine(() => retryDownloadFile()));
#endif
                }
                else
                {
                    Stop();
                }
            }
        }
Exemplo n.º 26
0
        public static bool LoadMozRoots()
        {
#if !NO_UNITY
            if (trusted_cerificates_ != null)
            {
                return(true);
            }

            try
            {
                TextAsset zippedMozRootsRawData = Resources.Load <TextAsset>(kResourceCertificatesPath);
                if (zippedMozRootsRawData == null)
                {
                    throw new System.Exception("LoadMozRoots - Certificates file does not exist!");
                }
                if (zippedMozRootsRawData.bytes == null || zippedMozRootsRawData.bytes.Length <= 0)
                {
                    throw new System.Exception("LoadMozRoots - The certificates file is corrupted!");
                }

                trusted_cerificates_ = new X509Certificate2Collection();

                using (MemoryStream zippedMozRootsRawDataStream = new MemoryStream(zippedMozRootsRawData.bytes))
                {
                    using (ZipInputStream zipInputStream = new ZipInputStream(zippedMozRootsRawDataStream))
                    {
                        ZipEntry zipEntry = zipInputStream.GetNextEntry();
                        if (zipEntry != null)
                        {
                            using (StreamReader stream = new StreamReader(zipInputStream))
                            {
                                StringBuilder sb         = new StringBuilder();
                                bool          processing = false;

                                while (true)
                                {
                                    string line = stream.ReadLine();
                                    if (line == null)
                                    {
                                        break;
                                    }
                                    if (processing)
                                    {
                                        if (line.StartsWith("END"))
                                        {
                                            processing = false;
                                            X509Certificate root = decodeCertificate(sb.ToString());
                                            trusted_cerificates_.Add(root);

                                            sb = new StringBuilder();
                                            continue;
                                        }
                                        sb.Append(line);
                                    }
                                    else
                                    {
                                        processing = line.StartsWith("CKA_VALUE MULTILINE_OCTAL");
                                    }
                                }
                                stream.Close();

                                FunDebug.Log("LoadMozRoots - {0} certificates have been loaded.",
                                             trusted_cerificates_.Count);
                            }
                        }
                        zipInputStream.Close();
                    }
                }
            }
            catch (Exception e)
            {
                FunDebug.LogError("LoadMozRoots - Failed to load certificate files.\n{0}", e.Message);
                return(false);
            }

            ServicePointManager.ServerCertificateValidationCallback = CertValidationCallback;
#endif
            return(true);
        }
        void downloadDataCompleteCb(object sender, DownloadDataCompletedEventArgs ar)
        {
            try
            {
                if (ar.Error != null)
                {
                    throw ar.Error;
                }

                // Parse json
                string data = Encoding.UTF8.GetString(ar.Result);
                Dictionary <string, object> json = Json.Deserialize(data) as Dictionary <string, object>;
                if (json == null)
                {
                    FunDebug.LogWarning("Announcement - Deserialize json failed. json: {0}", data);
                    onResult(AnnounceResult.kInvalidJson);
                    return;
                }

                FunDebug.Assert(json.ContainsKey("list"));
                List <object> list = json["list"] as List <object>;
                if (list == null || list.Count <= 0)
                {
                    if (list == null)
                    {
                        FunDebug.LogWarning("Announcement - Announcement list is null.");
                    }
                    else if (list.Count <= 0)
                    {
                        FunDebug.LogWarning("Announcement - There is no announcement list.");
                    }

                    onResult(AnnounceResult.kListIsNullOrEmpty);
                    return;
                }

                announce_list_.Clear();

                foreach (Dictionary <string, object> node in list)
                {
                    announce_list_.Add(node);

                    // download image
                    if (node.ContainsKey(kImageUrlKey) && node.ContainsKey(kImageMd5Key))
                    {
                        checkDownloadImage(node[kImageUrlKey] as string, node[kImageMd5Key] as string);
                    }

                    if (node.ContainsKey(kExtraImagesKey))
                    {
                        List <object> extra_images = node[kExtraImagesKey] as List <object>;
                        foreach (Dictionary <string, object> extra_image in extra_images)
                        {
                            if (extra_image.ContainsKey(kExtraImageUrlKey) && extra_image.ContainsKey(kExtraImageMd5Key))
                            {
                                checkDownloadImage(extra_image[kExtraImageUrlKey] as string, extra_image[kExtraImageMd5Key] as string);
                            }
                        }
                    }
                }

                FunDebug.Log("Announcement - List has been updated. total: {0}", announce_list_.Count);

                if (image_list_.Count > 0)
                {
                    // Request a file.
                    KeyValuePair <string, string> item = image_list_[0];
                    web_client_.DownloadFileAsync(new Uri(item.Key), item.Value);
                    FunDebug.LogDebug("Download announcement image: {0}", item.Key);
                }
                else
                {
                    onResult(AnnounceResult.kSucceeded);
                }
            }
            catch (Exception e)
            {
                FunDebug.LogError("Failure in Announcement.downloadDataCompleteCb:\n{0}", e.ToString());
                onResult(AnnounceResult.kExceptionError);
            }
        }
Exemplo n.º 28
0
        bool readCommandLineArgs()
        {
            isServer = true;

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

            string [] args        = System.Environment.GetCommandLineArgs();
            bool      sendVersion = false;

            foreach (string n in args)
            {
                bool not_user_arg = n.Contains(kServerVersion) || n.Contains(kManagerServer) ||
                                    n.Contains(kHeartbeat) || n.Contains(kPort) ||
                                    n.Contains(kMatchId) || n.Contains("RunDedicatedServer") ||
                                    n.Contains("batchmode") || n.Contains("nographics");
                if (!not_user_arg)
                {
                    user_cmd_options_.Add(n);
                }

                if (n.StartsWith("-") && n.Contains("="))
                {
                    int    index = n.IndexOf("=");
                    string key   = n.Substring(1, index - 1);
                    string value = n.Substring(index + 1, n.Length - index - 1);
                    arg_list.Add(key, value);
                    FunDebug.Log("Commandline argument - key:{0} value:{1}", key, value);
                }
                else if (n.Contains(kServerVersion))
                {
                    sendVersion = true;
                }
            }

            user_cmd_options_.RemoveAt(0); // Remove running path.
            foreach (string cmd in user_cmd_options_)
            {
                FunDebug.Log("User command : {0}", cmd);
            }

            if (arg_list.ContainsKey(kManagerServer))
            {
                server_url_ = string.Format("http://{0}/", arg_list[kManagerServer]);
                server_url_with_match_id_ = string.Format("{0}match/{1}/", server_url_, arg_list[kMatchId]);
            }
            else
            {
                FunDebug.LogError("'{0}' parameter is required.", kManagerServer);
                return(false);
            }

            if (sendVersion)
            {
                instance.httpPostSync(CmdVersion, use_old_version_ ? version : version_, delegate(object obj)
                {
                    FunDebug.Log("Dedicated Server - Sent the version. ({0})", version_);
                });

                return(false);
            }

            if (arg_list.ContainsKey(kHeartbeat))
            {
                if (!float.TryParse(arg_list[kHeartbeat], out heartbeat_seconds_))
                {
                    heartbeat_seconds_ = 0f;
                }

                if (heartbeat_seconds_ == 0f)
                {
                    FunDebug.LogWarning("'{0}' value must be greater than zero and lesser than 60 seconds.", kHeartbeat);
                    return(false);
                }
            }

            if (arg_list.ContainsKey(kPort))
            {
                int port = 0;
                if (int.TryParse(arg_list[kPort], out port))
                {
                    serverPort = port;
                }
            }

            return(true);
        }
Exemplo n.º 29
0
 public virtual bool Handshake(string in_header, ref string out_header)
 {
     FunDebug.LogError("You should override '{0}' Handshake function.", name_);
     return(true);
 }
Exemplo n.º 30
0
        void responseCb(IAsyncResult ar)
        {
            try
            {
                Request request = (Request)ar.AsyncState;
                if (request.was_aborted)
                {
                    FunDebug.Log("Dedicated Server - Response callback. Request aborted.");
                    return;
                }

                request.web_response = (HttpWebResponse)request.web_request.EndGetResponse(ar);
                request.web_request  = null;

                if (request.web_response.StatusCode == HttpStatusCode.OK)
                {
                    byte[]   header     = request.web_response.Headers.ToByteArray();
                    string   str_header = System.Text.Encoding.ASCII.GetString(header, 0, header.Length);
                    string[] lines      = str_header.Replace("\r", "").Split('\n');

                    int length = 0;

                    foreach (string n in lines)
                    {
                        if (n.Length > 0)
                        {
                            string[] tuple = n.Split(kHeaderSeparator, StringSplitOptions.RemoveEmptyEntries);
                            string   key   = tuple[0].ToLower();
                            if (key == "content-length" && tuple.Length >= 2)
                            {
                                length = Convert.ToInt32(tuple[1]);
                                break;
                            }
                        }
                    }

                    byte[] buffer = new byte[length];
                    request.body = new ArraySegment <byte>(buffer);

                    request.read_stream = request.web_response.GetResponseStream();
                    request.read_stream.BeginRead(buffer, 0, length, new AsyncCallback(readCb), request);
                }
                else
                {
                    FunDebug.LogError("Host manager response failed. status:{0}",
                                      request.web_response.StatusDescription);
                }
            }
            catch (Exception e)
            {
                WebException we = e as WebException;
                if (we != null && we.Status == WebExceptionStatus.ConnectFailure)
                {
                    onRequestFailed((Request)ar.AsyncState);
                }
                else if ((we != null && we.Status == WebExceptionStatus.RequestCanceled) ||
                         (e is ObjectDisposedException || e is NullReferenceException))
                {
                    // When Stop is called HttpWebRequest.EndGetResponse may return a Exception
                    FunDebug.LogDebug("Dedicated server request operation has been cancelled.");
                }
            }
        }