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.º 2
0
        public bool JoinChannel(string channel_id, string token, OnChatMessage handler)
        {
            if (!base.JoinChannel(channel_id, token, onReceived))
            {
                return(false);
            }

            lock (chat_channel_lock_)
            {
                if (chat_channels_.ContainsKey(channel_id))
                {
                    FunDebug.LogWarning("Already joined the '{0}' channel.", channel_id);
                    return(false);
                }

                chat_channels_.Add(channel_id, handler);
            }

            return(true);
        }
Exemplo n.º 3
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();
        }
Exemplo n.º 4
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("Multicast.SendToChannel - You should set a vaild channel id.");
                return(false);
            }

            lock (channel_lock_)
            {
                if (!Connected)
                {
                    FunDebug.LogWarning("Multicast.SendToChannel - Multicast is not connected.\n" +
                                        "If you are trying to send a message in which you were, " +
                                        "connect first while preserving the session id you used for join.");
                    return(false);
                }
                if (!channels_.ContainsKey(channel_id))
                {
                    FunDebug.LogWarning("Multicast.SendToChannel - You are not in the '{0} channel.", channel_id);
                    return(false);
                }
            }

            mcast_msg.sender = sender_;

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

            session_.SendMessage(kMulticastMsgType, fun_msg);
            return(true);
        }
        void onError(string channel_id, FunMulticastMessage.ErrorCode code)
        {
            FunDebug.LogWarning("[Multicast] error occurred. channel:{0} error:{1}", channel_id, code);

            if (code == FunMulticastMessage.ErrorCode.EC_CLOSED)
            {
                // This error occurs when the server is closed.
                // If the session is connected, tries to rejoin the channel.

                if (Connected && InChannel(channel_id))
                {
                    string token = null;
                    lock (token_lock_)
                    {
                        if (tokens_.ContainsKey(channel_id))
                        {
                            token = tokens_[channel_id];
                        }
                    }

                    requestToJoin(channel_id, token);
                    return;
                }
            }

            if (code != FunMulticastMessage.ErrorCode.EC_ALREADY_JOINED)
            {
                lock (channel_lock_)
                {
                    if (channels_.ContainsKey(channel_id))
                    {
                        channels_.Remove(channel_id);
                    }
                }
            }

            if (ErrorCallback != null)
            {
                ErrorCallback(channel_id, code);
            }
        }
Exemplo n.º 6
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.º 7
0
        public static T GetMessage <T> (FunDedicatedServerRpcMessage msg, MessageType 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("FunapiDSRpcMessage.GetMessage - Failed to decode '{0}' ({1})\n{2}",
                                  type, msg_type, e.ToString());
            }

            return(default(T));
        }
Exemplo n.º 8
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.º 9
0
        protected bool encryptMessage(FunapiMessage message, EncryptionType type)
        {
            if (type == EncryptionType.kDummyEncryption)
            {
                return(true);
            }

            if (!encryptors_.ContainsKey(type))
            {
                debug.LogWarning("Encryptor.encryptMessage - Unavailable type: {0}", type);
                return(false);
            }

            Encryptor encryptor = encryptors_[type];

            if (encryptor.state != Encryptor.State.kEstablished)
            {
                debug.LogWarning("Encryptor.encryptMessage - Can't encrypt '{0}' message. " +
                                 "Encryptor state is not established. state: {1}",
                                 message.msg_type, encryptor.state);
                return(false);
            }

            if (message.body.Count > 0)
            {
                string header = "";
                Int64  nSize  = encryptor.Encrypt(message.body, message.body, ref header);
                if (nSize <= 0)
                {
                    debug.LogWarning("Encryptor.encryptMessage - Failed to encrypt.");
                    return(false);
                }

                FunDebug.Assert(nSize == message.body.Count);

                message.enc_header = header;
            }

            return(true);
        }
Exemplo n.º 10
0
        public static FunDedicatedServerRpcMessage CreateMessage(object msg, MessageType msg_type)
        {
            if (msg is Enum)
            {
                msg = (Int32)msg;
            }

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

            return(null);
        }
Exemplo n.º 11
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("Multicast.SendToChannel - You should set a vaild channel id.");
                return(false);
            }

            lock (channel_lock_)
            {
                if (!Connected)
                {
                    FunDebug.LogWarning("Multicast.SendToChannel - Multicast is not connected.\n" +
                                        "If you are trying to send a message in which you were, " +
                                        "connect first while preserving the session id you used for join.");
                    return(false);
                }
                if (!channels_.ContainsKey(channel_id))
                {
                    FunDebug.LogWarning("Multicast.SendToChannel - You are not in the '{0} channel.", channel_id);
                    return(false);
                }
            }

            json_helper_.SetStringField(json_msg, kSender, sender_);

            session_.SendMessage(kMulticastMsgType, json_msg);
            return(true);
        }
        public void UpdateList(int max_count, int page = 0, string category = "")
        {
            if (web_client_ == null || string.IsNullOrEmpty(host_url_))
            {
                FunDebug.LogWarning("Announcement.UpdateList - You must call Init() function first.");
                onResult(AnnounceResult.kNeedInitialize);
                return;
            }

            // Request a list of announcements.
            string url = host_url_ + kAnnouncementsUrl + "?count=" + max_count;

            if (page > 0)
            {
                url = url + "&page=" + page;
            }
            if (!String.IsNullOrEmpty(category))
            {
                url = url + "&kind=" + Uri.EscapeDataString(category);
            }
            web_client_.DownloadDataAsync(new Uri(url));
        }
        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.º 14
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.º 15
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.º 16
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);
            }
        }
Exemplo n.º 17
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);
            }
        }
        public bool JoinChannel(string channel_id, string token, ChannelMessage handler)
        {
            if (!Connected)
            {
                FunDebug.LogWarning("[Multicast] request to join '{0}' channel but session is not connected.", channel_id);
                return(false);
            }

            lock (channel_lock_)
            {
                if (channels_.ContainsKey(channel_id))
                {
                    FunDebug.LogWarning("[Multicast] request to join '{0}' channel but already joined that channel.", channel_id);
                    return(false);
                }

                channels_.Add(channel_id, handler);
            }

            requestToJoin(channel_id, token);

            return(true);
        }
        public void RequestChannelList()
        {
            if (!Connected)
            {
                FunDebug.LogWarning("[Multicast] request a channel list but the session is not connected.");
                return;
            }

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

                FunMessage fun_msg = FunapiMessage.CreateFunMessage(mcast, MessageType.multicast);
                session_.SendMessage(kMulticastMsgType, fun_msg, protocol_);
            }
        }
        public bool LeaveChannel(string channel_id)
        {
            lock (channel_lock_)
            {
                if (channels_.ContainsKey(channel_id))
                {
                    channels_.Remove(channel_id);
                }
                else
                {
                    FunDebug.LogWarning("[Multicast] request to leave '{0}' channel but you are not in that channel.", channel_id);
                    return(false);
                }
            }

            if (Connected)
            {
                requestToLeave(channel_id);
                onUserLeft(channel_id, sender_);
            }

            return(true);
        }
        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);
        }
Exemplo n.º 23
0
        public void RequestChannelList()
        {
            if (!Connected)
            {
                FunDebug.LogWarning("Multicast.RequestChannelList - Multicast is not connected.\n" +
                                    "Please connect first before request a channel list.");
                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);
            }
        }
Exemplo n.º 24
0
        void updateCachedList()
        {
            StringBuilder data = new StringBuilder();

            data.Append("{ \"list\": [ ");

            int index = 0;

            foreach (DownloadFileInfo info in cached_list_)
            {
                data.AppendFormat("{{ \"path\":\"{0}\", ", info.path);
                data.AppendFormat("\"size\":{0}, ", info.size);
                if (info.hash_front.Length > 0)
                {
                    data.AppendFormat("\"front\":\"{0}\", ", info.hash_front);
                }
                data.AppendFormat("\"hash\":\"{0}\" }}", info.hash);

                if (++index < cached_list_.Count)
                {
                    data.Append(", ");
                }
            }

            data.Append(" ] }");

            string       path   = target_path_ + kCachedFileName;
            FileStream   file   = File.Open(path, FileMode.Create);
            StreamWriter stream = new StreamWriter(file);

            stream.Write(data.ToString());
            stream.Flush();
            stream.Close();

            FunDebug.DebugLog("Updates cached list : {0}", cached_list_.Count);
        }
Exemplo n.º 25
0
        public static Encryptor Create(EncryptionType type)
        {
            switch (type)
            {
            case EncryptionType.kDummyEncryption:
                return(new Encryptor0());

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

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

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

            default:
                FunDebug.LogWarning("Unknown encryptor: {0}", type);
                FunDebug.Assert(false);
                return(null);
            }
        }
    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.º 27
0
        public static IEnumerator Compute(string path, DownloadFileInfo file, OnResult on_result)
        {
            if (!File.Exists(path))
            {
                FunDebug.LogWarning("MD5Async.Compute - Can't find a file.\npath: {0}", path);

                if (on_result != null)
                {
                    on_result(path, file, false);
                }

                yield break;
            }

            MD5 md5 = MD5.Create();
            int length, read_bytes;

            byte[] buffer  = new byte[kBlockSize];
            string md5hash = "";

            FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);

            if (stream.Length > 0)
            {
                if (file.hash_front.Length > 0)
                {
                    length     = (stream.Length < kBlockSize) ? (int)stream.Length : kBlockSize;
                    read_bytes = stream.Read(buffer, 0, length);
                    md5.TransformFinalBlock(buffer, 0, read_bytes);

                    md5hash = FunapiUtils.BytesToHex(md5.Hash);
                    if (md5hash != file.hash_front || length == stream.Length)
                    {
                        stream.Close();

                        if (on_result != null)
                        {
                            on_result(path, file, md5hash == file.hash_front && md5hash == file.hash);
                        }

                        yield break;
                    }

                    md5.Clear();
                    md5             = MD5.Create();
                    stream.Position = 0;

                    yield return(null);
                }

                int sleep_count = 0;
                while (stream.Position < stream.Length)
                {
                    length = kBlockSize;
                    if (stream.Position + length > stream.Length)
                    {
                        length = (int)(stream.Length - stream.Position);
                    }

                    read_bytes = stream.Read(buffer, 0, length);

                    if (stream.Position < stream.Length)
                    {
                        md5.TransformBlock(buffer, 0, read_bytes, buffer, 0);
                    }
                    else
                    {
                        md5.TransformFinalBlock(buffer, 0, read_bytes);
                        break;
                    }

                    ++sleep_count;
                    if (sleep_count >= kSleepCountMax)
                    {
                        sleep_count = 0;
                        yield return(null);
                    }
                }
            }
            else
            {
                md5.TransformFinalBlock(buffer, 0, 0);
            }

            stream.Close();

            md5hash = FunapiUtils.BytesToHex(md5.Hash);
            if (on_result != null)
            {
                on_result(path, file, md5hash == file.hash);
            }
        }
        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);
            }
        }
Exemplo n.º 29
0
 public void LogInWithPublish(List <string> perms)
 {
     FunDebug.Log("Request facebook login with publish.");
     FB.LogInWithPublishPermissions(perms, OnLoginCb);
 }
Exemplo n.º 30
0
 public void LogInWithRead(List <string> perms)
 {
     FunDebug.Log("Request facebook login with read.");
     FB.LogInWithReadPermissions(perms, OnLoginCb);
 }