Exemplo n.º 1
0
        void deleteLocalFiles()
        {
            if (delete_file_list_.Count <= 0)
            {
                return;
            }

            FunDebug.Log("Downloader - Try to delete {0} local files.", delete_file_list_.Count);

            foreach (string path in delete_file_list_)
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                    FunDebug.DebugLog1("'{0}' file deleted.\npath: {1}", Path.GetFileName(path), path);
                }
            }

            delete_file_list_.Clear();
        }
        void onUserLeft(string channel_id, string user_id)
        {
            FunDebug.Log("[Multicast] '{0}' left the '{1}' channel.", user_id, channel_id);

            if (user_id == sender_)
            {
                lock (channel_lock_)
                {
                    if (tokens_.ContainsKey(channel_id))
                    {
                        tokens_.Remove(channel_id);
                    }
                }
            }

            if (LeftCallback != null)
            {
                LeftCallback(channel_id, user_id);
            }
        }
Exemplo n.º 3
0
        void webRequest(string method, string command, string data, Action <object> callback, Action <int, string> user_callback)
        {
            if (!isActive && needMatchId(command))
            {
                return;
            }

            string url = (needMatchId(command) ? server_url_with_match_id_ : server_url_) + command;

            FunDebug.Log("FunapiDedicatedServer.webRequest called.\n  {0} {1}", method, url);

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

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

            Request request = new Request();

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

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

                web_request.BeginGetRequestStream(new AsyncCallback(requestStreamCb), request);
            }
            else
            {
                IAsyncResult result = web_request.BeginGetResponse(new AsyncCallback(responseCb), request);
                ThreadPool.RegisterWaitForSingleObject(
                    result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), request,
                    heartbeat_seconds_ == 0 ? default_timeout_ : (int)(heartbeat_seconds_ / 2f) * 1000, true);
            }
        }
Exemplo n.º 4
0
        public static void Compute(MonoBehaviour mono, ref string path, ref DownloadFileInfo file, OnResult on_result)
        {
            if (File.Exists(path))
            {
#if !NO_UNITY
                mono.StartCoroutine(asyncCompute(path, file, on_result));
#else
                string           path_ = path;
                DownloadFileInfo file_ = file;
                mono.StartCoroutine(delegate { asyncCompute(path_, file_, on_result); });
#endif
                return;
            }

            FunDebug.Log("MD5Async.Compute - Can't find a file.\npath: {0}", path);

            if (on_result != null)
            {
                on_result(path, file, false);
            }
        }
Exemplo n.º 5
0
        /// The 'channel_id' field is mandatory.
        /// The 'sender' must fill in the message.
        /// The message shouldn't include join and leave flags.
        public bool SendToChannel(FunMulticastMessage mcast_msg)
        {
            if (mcast_msg == null)
            {
                return(false);
            }

            FunDebug.Assert(!mcast_msg.join);
            FunDebug.Assert(!mcast_msg.leave);

            string channel_id = mcast_msg.channel;

            if (channel_id == "")
            {
                FunDebug.LogWarning("You should set a vaild channel id.");
                return(false);
            }

            lock (channel_lock_)
            {
                if (!Connected)
                {
                    FunDebug.Log("Not connected. If you are trying to leave a channel in which you were, "
                                 + "connect first while preserving the session id you used for join.");
                    return(false);
                }
                if (!channels_.ContainsKey(channel_id))
                {
                    FunDebug.Log("You are not in the channel: {0}", channel_id);
                    return(false);
                }
            }

            mcast_msg.sender = sender_;

            FunMessage fun_msg = FunapiMessage.CreateFunMessage(mcast_msg, MessageType.multicast);

            session_.SendMessage(kMulticastMsgType, fun_msg);
            return(true);
        }
Exemplo n.º 6
0
        // Connection from the address pool
        void onConnect(int index)
        {
            if (index >= option_.Addrs.Count)
            {
                FunDebug.Log("[RPC] Invalid connect index. index:{0} list size:{1}",
                             index, option_.Addrs.Count);
                return;
            }

            cur_index_ = index;

            FunapiRpcPeer peer = new FunapiRpcPeer(getNextUid(), option_.DisableNagle);
            KeyValuePair <string, ushort> addr = option_.Addrs[index];

            peer.SetAddr(addr.Key, addr.Value);
            peer.SetEventHandler(onPeerEventBeforeConnect);
            peer.SetMessageHandler(onPeerMessage);

            peer_list_.Add(peer);

            peer.Connect();
        }
Exemplo n.º 7
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.º 8
0
        /// The 'channel_id' field is mandatory.
        /// The 'sender' must fill in the message.
        /// The message shouldn't include join and leave flags.
        public bool SendToChannel(object json_msg)
        {
            if (json_msg == null)
            {
                return(false);
            }

            FunDebug.Assert(!json_helper_.HasField(json_msg, kJoin));
            FunDebug.Assert(!json_helper_.HasField(json_msg, kLeave));

            string channel_id = json_helper_.GetStringField(json_msg, kChannelId);

            if (channel_id == "")
            {
                FunDebug.LogWarning("You should set a vaild channel id.");
                return(false);
            }

            lock (channel_lock_)
            {
                if (!Connected)
                {
                    FunDebug.Log("Not connected. If you are trying to leave a channel in which you were, "
                                 + "connect first while preserving the session id you used for join.");
                    return(false);
                }
                if (!channels_.ContainsKey(channel_id))
                {
                    FunDebug.Log("You are not in the channel: {0}", channel_id);
                    return(false);
                }
            }

            json_helper_.SetStringField(json_msg, kSender, sender_);

            session_.SendMessage(kMulticastMsgType, json_msg);
            return(true);
        }
Exemplo n.º 9
0
        public void RequestChannelList()
        {
            if (!Connected)
            {
                FunDebug.Log("Not connected. First connect before join a multicast channel.");
                return;
            }

            if (encoding_ == FunEncoding.kJson)
            {
                Dictionary <string, object> mcast_msg = new Dictionary <string, object>();
                mcast_msg[kSender] = sender_;
                session_.SendMessage(kMulticastMsgType, mcast_msg);
            }
            else
            {
                FunMulticastMessage mcast_msg = new FunMulticastMessage();
                mcast_msg.sender = sender_;

                FunMessage fun_msg = FunapiMessage.CreateFunMessage(mcast_msg, MessageType.multicast);
                session_.SendMessage(kMulticastMsgType, fun_msg);
            }
        }
        protected IEnumerator RequestPictures(List <UserInfo> list)
        {
            if (list == null || list.Count <= 0)
            {
                yield break;
            }

            foreach (UserInfo user in list)
            {
                WWW www = new WWW(user.url);
                yield return(www);

                if (www.texture != null)
                {
                    FunDebug.DebugLog1("{0}'s profile picture downloaded.", user.name);
                    user.picture = www.texture;
                    OnPictureNotify(user);
                }
            }

            FunDebug.Log("The all requested profile pictures has been downloaded.");
            OnEventNotify(SNResultCode.kDownloadCompleted);
        }
        void requestToLeave(string channel_id)
        {
            if (encoding_ == FunEncoding.kJson)
            {
                Dictionary <string, object> mcast = new Dictionary <string, object>();
                mcast[kChannelId] = channel_id;
                mcast[kSender]    = sender_;
                mcast[kLeave]     = true;

                session_.SendMessage(kMulticastMsgType, mcast, protocol_);
            }
            else
            {
                FunMulticastMessage mcast = new FunMulticastMessage();
                mcast.channel = channel_id;
                mcast.sender  = sender_;
                mcast.leave   = true;

                FunMessage fun_msg = FunapiMessage.CreateFunMessage(mcast, MessageType.multicast);
                session_.SendMessage(kMulticastMsgType, fun_msg, protocol_);
            }

            FunDebug.Log("[Multicast] requested to leave '{0}' channel.", channel_id);
        }
        // Downloading files.
        void downloadResourceFile()
        {
            if (state_ != State.Downloading)
            {
                return;
            }

            if (download_list_.Count <= 0 ||
                (partial_downloading_ && partial_download_list_.Count <= 0))
            {
                updateCachedList();

                download_time_.Stop();
                FunDebug.Log("[Downloader] Took {0:F2}s for downloading all files.",
                             download_time_.ElapsedMilliseconds / 1000f);

                if (partial_downloading_)
                {
                    if (download_list_.Count > 0)
                    {
                        state_ = State.Ready;
                    }
                    else
                    {
                        state_ = State.Completed;
                    }

                    partial_downloading_ = false;
                    FunDebug.Log("[Downloader] Partial downloading completed.");
                }
                else
                {
                    state_ = State.Completed;
                    FunDebug.Log("[Downloader] Download completed.");
                }

                onFinished(DownloadResult.SUCCESS);
            }
            else
            {
                DownloadFileInfo info = null;

                if (partial_downloading_)
                {
                    info = partial_download_list_[0];
                }
                else
                {
                    info = download_list_[0];
                }

                // Check directory
                string path   = target_path_;
                int    offset = info.path.LastIndexOf('/');
                if (offset > 0)
                {
                    path += info.path.Substring(0, offset);
                }

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                string file_path = target_path_ + info.path;
                if (File.Exists(file_path))
                {
                    File.Delete(file_path);
                }

                // Requests a file.
                string request_url = host_url_ + info.path;
                FunDebug.LogDebug("Download a file - {0}\nSave to {1}\n", request_url, file_path);
                cur_download_path_  = Path.GetDirectoryName(file_path);
                cur_download_path_ += "/" + Path.GetRandomFileName();

                web_client_.DownloadFileAsync(new Uri(request_url), cur_download_path_, info);
            }
        }
        void downloadDataCompleteCb(object sender, DownloadDataCompletedEventArgs ar)
        {
            try
            {
                if (ar.Error != null)
                {
                    FunDebug.Log("Exception Error: {0}", ar.Error);
                    onResult(AnnounceResult.kExceptionError);
                    FunDebug.Assert(false);
                }
                else
                {
                    // Parse json
                    string data = Encoding.UTF8.GetString(ar.Result);
                    Dictionary <string, object> json = Json.Deserialize(data) as Dictionary <string, object>;
                    if (json == null)
                    {
                        FunDebug.Log("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.Log("Invalid announcement list. list: {0}", list);
                        }
                        else if (list.Count <= 0)
                        {
                            FunDebug.Log("There are no announcements.");
                        }

                        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);
                        }
                    }

                    FunDebug.Log("Announcement has been updated. total count: {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.Log("Download url: {0}", item.Key);
                    }
                    else
                    {
                        onResult(AnnounceResult.kSucceeded);
                    }
                }
            }
            catch (Exception e)
            {
                FunDebug.Log("Failure in downloadDataCompleteCb: {0}", e.ToString());
                onResult(AnnounceResult.kExceptionError);
            }
        }
    public static void PerformanceTest()
    {
        string dict_str = ("N6Qw7OaV4zEcENhIgAAAAAAA2pAu8cEmbIanlFJKKU0jSZMxINMBAABCIJRW"
        + "+QIAAARAzIeVRcZN0YNRQRiFKgAAAIAAAAAAAAAAAAAAAAAAACRs5KZSRDquS4oAAAAAAAAAAAAAAA"
        + "EAAAAEAAAACAAAADksIl9tc2d0NTI1ODc4OSwiX21zZ196IjotOTAuOTAwMDAxLTIuNSwibG9va196"
        + "IjotOTBvb2tfeCI6LTIuNSwibDAzODE0Njk3MjcsImxvb2tfIjotOS4xMDAwMDAzODE0Njk5MDksIm"
        + "Rpcl96IjotOS4xMDAwMDE1MjU4Nzg5MDksImRpX3giOi0zMy45MDAwMDE1MjUyNDIxOSwiZGlyX3gi"
        + "Oi0zMy4xOTk5OTY5NDgyNDIxOSwicG9zX3oiOi03Ny4xOTk5OTYwOTI2NTEzNywicG9zX3oxMS4xOT"
        + "k5OTk4MDkyNjUxM29zX3giOi0xMS4xOTk5ImlkIjo0NDI4OCwicG9zX3hzdF9tb3ZlIn17ImlkIjo0"
        + "NHBlIjoicmVxdWVzdF9tb3ZlNDgsIl9tc2d0eXBlIjoicmUyMzcwNjA1NDgsIl9tc3oiOi0xNi43OT"
        + "k5OTkyMzEuNSwibG9va196IjotMTYuImxvb2tfeCI6NjEuNSwibG9feiI6LTMwLjUsImxvb2tfeC0z"
        + "OS41LCJkaXJfeiI6LTMwNSwiZGlyX3giOi0zOS41LCJwb3NfeiI6NTEuNSwiZGlyXzIzNzA2MDU1LC"
        + "Jwb3NfeiI6LTU0LjI5OTk5OTIzNzA2MDU0LCJwb3NfeCI6LTU0LjI5OXsiaWQiOjE0NDg0LCJwb3Nf");
        byte[] dict_buf = Convert.FromBase64String(dict_str);

        UIntPtr cdict = ZSTD_createCDict(dict_buf, (UIntPtr)dict_buf.Length, 1);
        UIntPtr ddict = ZSTD_createDDict(dict_buf, (UIntPtr)dict_buf.Length);

        string src = "{\"id\":12032,\"pos_x\":31.01,\"pos_z\":45.5293984741," +
                     "\"dir_x\":-14.199799809265137,\"dir_z\":11.899918530274," +
                     "\"look_x\":1.100000381469727,\"look_z\":11.600100381469727," +
                     "\"_msgtype\":\"request_move\"}";
        var src_buf = Encoding.UTF8.GetBytes(src);
        var dst_buf = new byte[(int)ZSTD_compressBound((UIntPtr)src_buf.Length)];

        ulong size, size2;
        long start, end;
        const int N = 100000;  // 알고리즘 반복 시행 횟수
        size = 0;
        size2 = 0;
        start = DateTime.Now.Ticks / 10000;
        for (int i = 0; i < N; ++i) {
            size += (ulong)CompressForFunapi(dst_buf, (UIntPtr)dst_buf.Length, (IntPtr)0,
                                      src_buf, (UIntPtr)src_buf.Length, (IntPtr)0, (UIntPtr)0);
            size2 += (ulong)DecompressForFunapi(src_buf, (UIntPtr)src_buf.Length, (IntPtr)0,
                    dst_buf, (UIntPtr)dst_buf.Length, (IntPtr)0, (UIntPtr)0);
        }
        end = DateTime.Now.Ticks / 10000;
        FunDebug.Log("Zstd (w/o dict) {0} ms, {1} ms/(enc+dec)", end - start, (end - start) * 1.0 / N);
        FunDebug.Log("String length={0}, compressed={1}", src_buf.Length, size / N);

        size = 0;
        size2 = 0;
        start = DateTime.Now.Ticks / 10000;
        for (int i = 0; i < N; ++i) {
            size += (ulong)CompressForFunapi(dst_buf, (UIntPtr)dst_buf.Length, (IntPtr)0,
                                      src_buf, (UIntPtr)src_buf.Length, (IntPtr)0, cdict);
            size2 += (ulong)DecompressForFunapi(src_buf, (UIntPtr)src_buf.Length, (IntPtr)0,
                    dst_buf, (UIntPtr)dst_buf.Length, (IntPtr)0, ddict);
        }
        end = DateTime.Now.Ticks / 10000;
        FunDebug.Log("Zstd (w/ dict) {0} ms, {1} ms/(enc+dec)", end - start, (end - start) * 1.0 / N);
        FunDebug.Log("String length={0}, compressed={1}", src_buf.Length, size / N);

        ZSTD_freeCDict(cdict);
        ZSTD_freeDDict(ddict);

        size = 0;
        size2 = 0;
        dst_buf = new byte[2 * src_buf.Length];
        start = DateTime.Now.Ticks / 10000;
        for (int i = 0; i < N; ++i) {
            size += (ulong)ZlibCompressForFunapi(dst_buf, (UIntPtr)0, (UIntPtr)dst_buf.Length,
                                      src_buf, (UIntPtr)0, (UIntPtr)src_buf.Length);
            size2 += (ulong)ZlibDecompressForFunapi(src_buf, (UIntPtr)0, (UIntPtr)src_buf.Length,
                    dst_buf, (UIntPtr)0, (UIntPtr)dst_buf.Length);
        }
        end = DateTime.Now.Ticks / 10000;
        FunDebug.Log("Deflate {0} ms, {1} ms/(enc+dec)", end - start, (end - start) * 1.0 / N);
        FunDebug.Log("String length={0}, compressed={1}", src_buf.Length, size / N);

        FunapiCompressor comp = new FunapiZstdCompressor();
        ArraySegment<byte> intermediate = comp.Compress(new ArraySegment<byte>(src_buf));
        ArraySegment<byte> comp_result = comp.Decompress(intermediate, src_buf.Length);

        var test_target = Encoding.UTF8.GetString(comp_result.Array);
        FunDebug.Assert(test_target == src);

        comp = new FunapiDeflateCompressor();
        intermediate = comp.Compress(new ArraySegment<byte>(src_buf));
        comp_result = comp.Decompress(intermediate, src_buf.Length);

        test_target = Encoding.UTF8.GetString(comp_result.Array);
        FunDebug.Assert(test_target == src);
    }
Exemplo n.º 15
0
 public void LogInWithPublish(List <string> perms)
 {
     FunDebug.Log("Request facebook login with publish.");
     FB.LogInWithPublishPermissions(perms, OnLoginCb);
 }
Exemplo n.º 16
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.º 17
0
        void checkFileList(List <DownloadFileInfo> list)
#endif
        {
            List <DownloadFileInfo> tmp_list         = new List <DownloadFileInfo>(list);
            List <string>           verify_file_list = new List <string>();
            List <string>           remove_list      = new List <string>();
            Queue <int>             rnd_list         = new Queue <int>();
            bool verify_success = true;
            int  rnd_index      = -1;

            DateTime  cached_time  = File.GetLastWriteTime(target_path_ + kCachedFileName);
            Stopwatch elapsed_time = new Stopwatch();

            elapsed_time.Start();

            delete_file_list_.Clear();

            // Randomly check list
            if (cached_list_.Count > 0)
            {
                int           max_count = cached_list_.Count;
                int           count     = Math.Min(Math.Max(1, max_count / 10), 10);
                System.Random rnd       = new System.Random((int)DateTime.Now.Ticks);

                while (rnd_list.Count < count)
                {
                    rnd_index = rnd.Next(1, max_count + 1) - 1;
                    if (!rnd_list.Contains(rnd_index))
                    {
                        rnd_list.Enqueue(rnd_index);
                    }
                }
                FunDebug.DebugLog("Random check file count is {0}", rnd_list.Count);

                rnd_index = rnd_list.Count > 0 ? rnd_list.Dequeue() : -1;
            }

            // Checks local files
            int index = 0;

            foreach (DownloadFileInfo file in cached_list_)
            {
                DownloadFileInfo item = list.Find(i => i.path == file.path);
                if (item != null)
                {
                    string   path = target_path_ + file.path;
                    FileInfo info = new FileInfo(path);

                    if (!File.Exists(path) || item.size != info.Length || item.hash != file.hash)
                    {
                        remove_list.Add(file.path);
                    }
                    else
                    {
                        string filename = Path.GetFileName(item.path);
                        if (filename[0] == '_' || index == rnd_index ||
                            File.GetLastWriteTime(path).Ticks > cached_time.Ticks)
                        {
                            if (index == rnd_index)
                            {
                                rnd_index = rnd_list.Count > 0 ? rnd_list.Dequeue() : -1;
                            }

                            verify_file_list.Add(file.path);

                            MD5Async.Compute(mono, ref path, ref item,
                                             delegate(string p, DownloadFileInfo f, bool is_match)
                            {
                                if (VerifyCallback != null)
                                {
                                    VerifyCallback(p);
                                }

                                verify_file_list.Remove(f.path);

                                if (is_match)
                                {
                                    list.Remove(f);
                                }
                                else
                                {
                                    remove_list.Add(f.path);
                                    verify_success = false;
                                }
                            }
                                             );
                        }
                        else
                        {
                            list.Remove(item);
                        }
                    }
                }
                else
                {
                    remove_list.Add(file.path);
                }

                ++index;
            }

            while (verify_file_list.Count > 0)
            {
#if !NO_UNITY
                yield return(new WaitForSeconds(0.1f));
#else
                Thread.Sleep(100);
#endif
            }

            removeCachedList(remove_list);

            FunDebug.Log("Random validation has {0}", (verify_success ? "succeeded" : "failed"));

            // Checks all local files
            if (!verify_success)
            {
                foreach (DownloadFileInfo file in cached_list_)
                {
                    DownloadFileInfo item = tmp_list.Find(i => i.path == file.path);
                    if (item != null)
                    {
                        verify_file_list.Add(file.path);

                        string path = target_path_ + file.path;
                        MD5Async.Compute(mono, ref path, ref item,
                                         delegate(string p, DownloadFileInfo f, bool is_match)
                        {
                            if (VerifyCallback != null)
                            {
                                VerifyCallback(p);
                            }

                            verify_file_list.Remove(f.path);

                            if (!is_match)
                            {
                                remove_list.Add(f.path);

                                if (!list.Contains(f))
                                {
                                    list.Add(f);
                                }
                            }
                        }
                                         );
                    }
                }

                while (verify_file_list.Count > 0)
                {
#if !NO_UNITY
                    yield return(new WaitForSeconds(0.1f));
#else
                    Thread.Sleep(100);
#endif
                }

                removeCachedList(remove_list);
            }

            elapsed_time.Stop();
            FunDebug.Log("File check total time - {0:F2}s", elapsed_time.ElapsedMilliseconds / 1000f);

            total_download_count_ = list.Count;

            foreach (DownloadFileInfo item in list)
            {
                total_download_size_ += item.size;
            }

            if (total_download_count_ > 0)
            {
                state_ = State.Ready;

                event_list.Add(delegate
                {
                    if (ReadyCallback != null)
                    {
                        ReadyCallback(total_download_count_, total_download_size_);
                    }
                });
            }
            else
            {
                deleteLocalFiles();
                updateCachedList();

                state_ = State.Completed;
                FunDebug.Log("All resources are up to date.");
                onFinished(DownloadResult.SUCCESS);
            }
        }
Exemplo n.º 18
0
 public void LogInWithRead(List <string> perms)
 {
     FunDebug.Log("Request facebook login with read.");
     FB.LogInWithReadPermissions(perms, OnLoginCb);
 }
Exemplo n.º 19
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.");
                }
            }
        }
Exemplo n.º 20
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);
        }
Exemplo n.º 21
0
        void updateData(Dictionary <string, object> data)
        {
            if (data.ContainsKey("match_data"))
            {
                lock (lock_match_data)
                {
                    List <object> match_data = data["match_data"] as List <object>;
                    if (match_data == null)
                    {
                        match_data = new List <object>();
                        match_data.Add(data["match_data"]);
                    }
                    for (int i = 0; i < match_data.Count; ++i)
                    {
                        string json_string;
                        if (match_data[i] is string)
                        {
                            json_string = match_data[i] as string;
                        }
                        else
                        {
                            json_string = json_helper_.Serialize(match_data[i]);
                        }

                        if (json_string.Length > 0)
                        {
                            if (match_data_ != json_string)
                            {
                                match_data_ = json_string;

                                if (MatchDataCallback != null)
                                {
                                    MatchDataCallback(json_string);
                                }
                            }
                        }
                    }
                }
            }

            if (data.ContainsKey("users"))
            {
                lock (lock_user_data_)
                {
                    List <object> users = data["users"] as List <object>;

                    List <object> user_data = null;
                    if (data.ContainsKey("user_data"))
                    {
                        user_data = data["user_data"] as List <object>;
                    }

                    for (int i = 0; i < users.Count; ++i)
                    {
                        Dictionary <string, object> user = users[i] as Dictionary <string, object>;

                        string uid   = "";
                        string token = "";

                        if (user.ContainsKey("uid"))
                        {
                            uid = user["uid"] as string;
                        }

                        if (user.ContainsKey("token"))
                        {
                            token = user["token"] as string;
                        }

                        FunDebug.Log("Update user info - uid:{0} token:{1}", uid, token);

                        if (uid.Length > 0 && token.Length > 0)
                        {
                            users_.Add(uid, token);
                        }

                        if (user_data != null && i < user_data.Count)
                        {
                            string json_string;
                            if (user_data[i] is string)
                            {
                                json_string = user_data[i] as string;
                            }
                            else
                            {
                                json_string = json_helper_.Serialize(user_data[i]);
                            }

                            if (uid.Length > 0 && json_string.Length > 0)
                            {
                                if (!user_data_.ContainsKey(uid) || json_string != user_data_[uid])
                                {
                                    user_data_[uid] = json_string;

                                    if (UserDataCallback != null)
                                    {
                                        UserDataCallback(uid, json_string);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 22
0
        // Callback function for list of files
        void downloadDataCompleteCb(object sender, DownloadDataCompletedEventArgs ar)
        {
            mutex_.WaitOne();

            bool failed = false;

            try
            {
                if (ar.Error != null)
                {
                    FunDebug.Log("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.Log("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.Log("Failure in downloadDataCompleteCb: {0}", e.ToString());
                failed = true;
            }
            finally
            {
                mutex_.ReleaseMutex();
            }

            if (failed)
            {
                Stop();
            }
        }
Exemplo n.º 23
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.º 24
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.Log("Exception Error: {0}", ar.Error);
                    failed = true;
                }
                else
                {
                    var info = (DownloadFileInfo)ar.UserState;
                    if (info == null)
                    {
                        FunDebug.Log("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.Log("Failure in 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.º 25
0
        public static void LoadRootCertificates()
        {
            if (trustedCerificates != null)
            {
                return;
            }

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

                trustedCerificates = new X509Certificate2Collection();

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

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

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

                                FunDebug.Log("{0} Root certificates loaded.", trustedCerificates.Count);
                            }
                        }
                        zipInputStream.Close();
                    }
                }
            }
            catch (Exception e)
            {
                FunDebug.LogError("Load certificates file failed. {0}", e.Message);
            }
        }
Exemplo n.º 26
0
 void logInfo(string format, params object[] args)
 {
     FunDebug.Log(makeLogText(format, args));
 }
Exemplo n.º 27
0
        void onReceived(string msg_type, object body)
        {
            FunDebug.Assert(msg_type == kMulticastMsgType);

            string channel_id = "";
            string sender     = "";
            bool   join       = false;
            bool   leave      = false;
            int    error_code = 0;

            if (encoding_ == FunEncoding.kJson)
            {
                if (json_helper_.HasField(body, kChannelId))
                {
                    channel_id = json_helper_.GetStringField(body, kChannelId);
                }

                if (json_helper_.HasField(body, kSender))
                {
                    sender = json_helper_.GetStringField(body, kSender);
                }

                if (json_helper_.HasField(body, kErrorCode))
                {
                    error_code = (int)json_helper_.GetIntegerField(body, kErrorCode);
                }

                if (json_helper_.HasField(body, kChannelList))
                {
                    if (ChannelListCallback != null)
                    {
                        object list = json_helper_.GetObject(body, kChannelList);
                        ChannelListCallback(list);
                    }
                    return;
                }
                else if (json_helper_.HasField(body, kJoin))
                {
                    join = json_helper_.GetBooleanField(body, kJoin);
                }
                else if (json_helper_.HasField(body, kLeave))
                {
                    leave = json_helper_.GetBooleanField(body, kLeave);
                }
            }
            else
            {
                FunMessage msg = body as FunMessage;
                object     obj = FunapiMessage.GetMessage(msg, MessageType.multicast);
                FunDebug.Assert(obj != null);

                FunMulticastMessage mcast_msg = obj as FunMulticastMessage;

                if (mcast_msg.channelSpecified)
                {
                    channel_id = mcast_msg.channel;
                }

                if (mcast_msg.senderSpecified)
                {
                    sender = mcast_msg.sender;
                }

                if (mcast_msg.error_codeSpecified)
                {
                    error_code = (int)mcast_msg.error_code;
                }

                if (mcast_msg.channels.Count > 0 || (channel_id == "" && sender == ""))
                {
                    if (ChannelListCallback != null)
                    {
                        ChannelListCallback(mcast_msg.channels);
                    }
                    return;
                }
                else if (mcast_msg.joinSpecified)
                {
                    join = mcast_msg.join;
                }
                else if (mcast_msg.leaveSpecified)
                {
                    leave = mcast_msg.leave;
                }

                body = mcast_msg;
            }

            if (error_code != 0)
            {
                FunMulticastMessage.ErrorCode code = (FunMulticastMessage.ErrorCode)error_code;
                FunDebug.LogWarning("Multicast error - channel: {0} code: {1}", channel_id, code);

                if (code == FunMulticastMessage.ErrorCode.EC_FULL_MEMBER ||
                    code == FunMulticastMessage.ErrorCode.EC_ALREADY_LEFT ||
                    code == FunMulticastMessage.ErrorCode.EC_CLOSED)
                {
                    lock (channel_lock_)
                    {
                        if (channels_.ContainsKey(channel_id))
                        {
                            channels_.Remove(channel_id);
                        }
                    }
                }

                if (ErrorCallback != null)
                {
                    ErrorCallback(channel_id, code);
                }

                return;
            }

            lock (channel_lock_)
            {
                if (!channels_.ContainsKey(channel_id))
                {
                    FunDebug.Log("You are not in the channel: {0}", channel_id);
                    return;
                }
            }

            if (join)
            {
                onUserJoined(channel_id, sender);
            }
            else if (leave)
            {
                onUserLeft(channel_id, sender);
            }
            else
            {
                lock (channel_lock_)
                {
                    if (channels_.ContainsKey(channel_id))
                    {
                        channels_[channel_id](channel_id, sender, body);
                    }
                }
            }
        }