void Awake()
    {
        CloudSaveInitializer.AttachToGameObject(gameObject);
        gameObject.AddComponent <GameManager>();
        dataset = GameManager.Instance.CurrentDataset;
        datasetNameLabel.text = dataset.Name;
        syncCountLabel.text   = SdkUtils.ConvertSyncRevisionToString(dataset.GetLastSyncRevision());

        _dialogController   = GetComponent <DialogController>();
        _conflictController = GetComponent <ConflictController>();

        List <Dropdown.OptionData> options = new List <Dropdown.OptionData>();

        foreach (KeyValuePair <string, string> entry in GameManager.Instance.EndPoints)
        {
            options.Add(new Dropdown.OptionData(entry.Key));
        }

        _dropdown.AddOptions(options);

        for (int i = 0; i < options.Count; i++)
        {
            var option = options[i];
            if (option.text.Equals(GameManager.Instance._endpoint))
            {
                _dropdown.value = i;
                break;
            }
        }
    }
示例#2
0
        private void SendImage()
        {
            if (conn.ConnectionState != agsXMPP.XmppConnectionState.Connected &&
                conn.ConnectionState != agsXMPP.XmppConnectionState.SessionStarted)
            {
                MessageBox.Show("请连接后再上传文件");
                return;
            }
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            // Path : /{org_name}/{app_name}/chatfiles
            string path = conn.GetUrl("chatfiles");

            PostedFileResp resp  = PostedFileManager.PostFile(path, conn.TokenData.access_token, openFileDialog1.FileName);
            string         title = BuildMsgTitle(conn.UserName);

            //edChat.AppendHtml(title, Color.Blue);
            //edChat.AppendNewLine();

            byte[] bytes = SdkUtils.DownloadThumbnail(resp.uri + "/" + resp.entities[0].uuid, resp.entities[0].share_secret, conn.TokenData.access_token);

            //edChat.AppendImageBytes(bytes);
            //edChat.AppendNewLine(2);
            conn.SendFile(toUserName, resp);
        }
        public IList <SyncRevision> GetLastSyncRevision(string identityId, string datasetName)
        {
            const string query = "SELECT SyncRevisions " +
                                 "FROM Datasets " +
                                 "WHERE IdentityId = @IdentityId AND Name = @Name";

            using (var connection = new SqliteConnection(_filePath))
            {
                connection.Open();

                using (var command = new SqliteCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@IdentityId", identityId);
                    command.Parameters.AddWithValue("@Name", datasetName);
                    using (var reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            var syncRevisionsStr = reader.IsDBNull(0) ? string.Empty : reader.GetString(0);
                            return(SdkUtils.ConvertStringToSyncRevision(syncRevisionsStr));
                        }

                        return(null);
                    }
                }
            }
        }
示例#4
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url">上传的URL地址</param>
        /// <param name="token">上传需要的 token</param>
        /// <param name="fileBytes">文件字节</param>
        /// <param name="filePath">要上传的文件本地路径</param>
        /// <returns></returns>
        public static PostedFileResp PostFile(string url, string token, byte[] fileBytes, string filePath)
        {
            string responseText = "";

            HttpRequestClient httpRequestClient = new HttpRequestClient();

            httpRequestClient.SetFieldValue("file", filePath, "application/octet-stream", fileBytes);

            // 开始上传文件
            httpRequestClient.Upload(url, token, out responseText);

            // 上传返回的参数
            PostedFileResp resp = JsonConvert.DeserializeObject <PostedFileResp>(responseText);

            if (resp.entities == null || resp.entities.Length == 0)
            {
                // 可能上传失败,原因是?????
                throw new ApplicationException("上传失败,原因是?????");
            }

            // 传入本地文件路径到 PostedFileResp.entities; entities[0]为第一文件,目前只支持1个文件的上传
            resp.entities[0].filename = Path.GetFileName(filePath);

            string fileType = SdkUtils.GetFileType(resp.entities[0].filename);

            // 如果文件为图片,则获取图片的大小,并传入到PostedFileResp.entities
            if ("img".Equals(fileType))
            {
                Image img = Bitmap.FromFile(filePath);
                resp.entities[0].imageSize = new Size(img.Width, img.Height);
                img.Dispose();
            }
            return(resp);
        }
示例#5
0
        public T Execute <T>(IRequest <T> request, string session, string appAuthToken) where T : IResponse
        {
            // 构造请求参数
            ParamDictionary requestParams = buildRequestParams(request, session, appAuthToken);

            // 字典排序
            IDictionary <string, string> sortedParams = new SortedDictionary <string, string>(requestParams);
            ParamDictionary sortedDic = new ParamDictionary(sortedParams);

            // 参数签名
            string charset = string.IsNullOrEmpty(this.charset) ? "utf-8" : this.charset;
            //string signResult = Signature.RSASign(sortedDic, privateKeyPem, charset, this.keyFromFile, this.signType);
            //// 添加签名结果参数
            //sortedDic.Add(SIGN, signResult);

            // 参数拼接
            string signedResult = WebUtils.BuildQuery(sortedDic, charset);
            var    txtParams    = sortedDic;


            // 是否需要上传文件
            string body;
            string requestBody = null;
            string url         = "";                                // this.serverUrl + "?" + CHARSET + "=" + this.charset;

            url = GetFullUrl(this.serverUrl, request.GetApiName()); // + "?" + CHARSET + "=" + this.charset;
            if (request is IUploadRequest <T> )
            {
                IUploadRequest <T>             uRequest   = (IUploadRequest <T>)request;
                IDictionary <string, FileItem> fileParams = SdkUtils.CleanupDictionary(uRequest.GetFileParameters());
                body = webUtils.DoPost(url, txtParams, fileParams, this.charset, out requestBody);
            }
            else
            {
                body = webUtils.DoPost(url, txtParams, this.charset, out requestBody);
            }

            T           rsp    = null;
            IParser <T> parser = null;

            if ("xml".Equals(format))
            {
                parser = new XmlParser <T>();
                rsp    = parser.Parse(body, charset);
            }
            else
            {
                parser = new JsonParser <T>();
                rsp    = parser.Parse(body, charset);
            }

            ResponseParseItem item = parseRespItem(request, body, parser, this.encyptKey, this.encyptType, charset);

            rsp             = parser.Parse(item.realContent, charset);
            rsp.RequestBody = requestBody;

            CheckResponseSign(request, item.respContent, rsp.IsError, parser, this.publicKey, this.charset, signType, this.keyFromFile);

            return(rsp);
        }
        public void UpdateLastSyncRevision(string identityId, string name, IList <SyncRevision> syncRevisionList)
        {
            var localSyncRevision = GetLastSyncRevision(identityId, name);
            var syncRevisionsStr  = SdkUtils.ConvertSyncRevisionToString(syncRevisionList);

            if (localSyncRevision == null)
            {
                const string query = @"INSERT INTO Datasets
                               (IdentityId, Name, SyncRevisions)
                               VALUES (@IdentityId, @Name, @SyncRevisions)";

                using (var connection = new SqliteConnection(_filePath))
                {
                    connection.Open();

                    using (var trx = connection.BeginTransaction())
                    {
                        using (var command = new SqliteCommand(query, connection))
                        {
                            command.Parameters.AddWithValue("@IdentityId", identityId);
                            command.Parameters.AddWithValue("@Name", name);
                            command.Parameters.AddWithValue("@SyncRevisions", syncRevisionsStr);
                            command.ExecuteNonQuery();
                        }

                        trx.Commit();
                    }
                }
            }
            else
            {
                const string query =
                    @"UPDATE Datasets SET SyncRevisions = @SyncRevisions
                        WHERE IdentityId = @IdentityId AND Name = @Name";

                using (var connection = new SqliteConnection(_filePath))
                {
                    connection.Open();

                    using (var trx = connection.BeginTransaction())
                    {
                        using (var command = new SqliteCommand(query, connection))
                        {
                            command.Parameters.AddWithValue("@SyncRevisions", syncRevisionsStr);
                            command.Parameters.AddWithValue("@IdentityId", identityId);
                            command.Parameters.AddWithValue("@Name", name);
                            command.ExecuteNonQuery();
                        }

                        trx.Commit();
                    }
                }
            }
        }
        private static RecordPatch RecordToPatch(Record record)
        {
            var patch = new RecordPatch
            {
                deviceLastModifiedDate = SdkUtils.ConvertToUnixEpochMilliSeconds(record.DeviceLastModifiedDate),
                key   = record.Key,
                value = record.Value
            };

            return(patch);
        }
示例#8
0
        public void EncodeParamTest()
        {
            // TODO figure out the always painful DateTime conversions
            // var date = DateTime.Parse("2020-01-01T14:48:00.00Z");
            // Assert.Equal("2020-01-01T14%3A48%3A00.000Z", Transport.EncodeParam(date));
            Assert.Equal("foo%2Fbar", SdkUtils.EncodeParam("foo%2Fbar"));
            Assert.Equal("foo%2Fbar", SdkUtils.EncodeParam("foo/bar"));
            var actual = SdkUtils.EncodeParam(true);

            Assert.Equal("true", actual);
            actual = SdkUtils.EncodeParam(2.3);
            Assert.Equal("2.3", actual);
        }
        public void PutRecordsAsync(string identityId, string datasetName, string syncRevisions, string syncSessionToken,
                                    IList <Record> records, CloudSaveCallback <DatasetPutResult> callback)
        {
            var request = new PushRecordsRequest
            {
                identityId  = identityId,
                syncCount   = syncRevisions,
                DatasetName = datasetName,
                deviceId    = SystemInfo.deviceUniqueIdentifier,
                // TODO: disable syncSession for now.
//                syncSessionToken = syncSessionToken,
            };

            var patches = new List <RecordPatch>();

            foreach (var record in records)
            {
                patches.Add(RecordToPatch(record));
            }

            request.recordPatches = patches.ToArray();

            _client.PushRecordsAsync(request, (err, result) =>
            {
                if (err != null)
                {
                    callback(err, null);
                    return;
                }

                var datasetRecords = new List <Record>();
                foreach (var record in result.records)
                {
                    datasetRecords.Add(new Record.Builder(record.key)
                                       .Value(record.value)
                                       .SyncCount(record.syncCount)
                                       .SyncRegion(record.lastModifiedRegion)
                                       .LastModifiedBy(record.lastModifiedBy)
                                       .LastModifiedDate(SdkUtils.ConvertFromUnixEpochSeconds(record.lastModifiedDate))
                                       .Build()
                                       );
                }

                callback(null, new DatasetPutResult
                {
                    Records       = datasetRecords,
                    SyncRevisions = SdkUtils.ConvertStringToSyncRevision(result.syncCount)
                });
            });
        }
        internal void PutValueInternal(SqliteConnection conn, string identityId, string datasetName, string key, string value)
        {
            Record record = GetRecord(identityId, datasetName, key);

            if (record != null && string.Equals(record.Value, value))
            {
                return;
            }

            bool recordFound = record != null;

            if (recordFound)
            {
                const string updateRecordQuery =
                    @"UPDATE Records SET Value = @Value, DeviceLastModifiedDate = @DeviceLastModifiedDate, IsDirty = @IsDirty
                    WHERE IdentityId = @IdentityId AND Name = @Name AND Key = @Key";

                using (var command = new SqliteCommand(updateRecordQuery, conn))
                {
                    command.Parameters.AddWithValue("@Value", value);
                    command.Parameters.AddWithValue("@DeviceLastModifiedDate", SdkUtils.ConvertDateTimeToTicks(DateTime.Now));
                    command.Parameters.AddWithValue("@IsDirty", 1);
                    command.Parameters.AddWithValue("@IdentityId", identityId);
                    command.Parameters.AddWithValue("@Name", datasetName);
                    command.Parameters.AddWithValue("@Key", key);
                    command.ExecuteNonQuery();
                }
            }
            else
            {
                const string insertQuery =
                    @"INSERT INTO Records (IdentityId, Name, Key, Value, SyncCount, SyncRegion,
                                     DeviceLastModifiedDate, LastModifiedBy, IsDirty) VALUES (@IdentityId, @Name,
                                     @Key, @Value, @SyncCount, @SyncRegion, @DeviceLastModifiedDate, @LastModifiedBy, @IsDirty)";
                using (var command = new SqliteCommand(insertQuery, conn))
                {
                    command.Parameters.AddWithValue("@IdentityId", identityId);
                    command.Parameters.AddWithValue("@Name", datasetName);
                    command.Parameters.AddWithValue("@Key", key);
                    command.Parameters.AddWithValue("@Value", value);
                    command.Parameters.AddWithValue("@SyncCount", 0);
                    command.Parameters.AddWithValue("@SyncRegion", "Unknown");
                    command.Parameters.AddWithValue("@DeviceLastModifiedDate", SdkUtils.ConvertDateTimeToTicks(DateTime.Now));
                    command.Parameters.AddWithValue("@LastModifiedBy", string.Empty);
                    command.Parameters.AddWithValue("@IsDirty", 1);
                    command.ExecuteNonQuery();
                }
            }
        }
示例#11
0
        private void SendAudio(string audioFileName)
        {
            string path = conn.GetUrl("chatfiles");

            PostedFileResp resp  = PostedFileManager.PostFile(path, conn.TokenData.access_token, audioFileName);
            string         title = BuildMsgTitle(conn.UserName);

            //edChat.AppendHtml(title, Color.Blue);
            //edChat.AppendNewLine();

            byte[] bytes = SdkUtils.DownloadThumbnail(resp.uri + "/" + resp.entities[0].uuid, resp.entities[0].share_secret, conn.TokenData.access_token);

            AppendAudioTag("我的语音");

            conn.SendFile(toUserName, resp);
        }
示例#12
0
        public void BinaryModeTest()
        {
            var contents = _contentTypes["binary"];

            Assert.NotNull(contents);
            foreach (var content in contents)
            {
                var s      = Convert.ToString(content);
                var actual = SdkUtils.ResponseMode(s);
                if (actual != ResponseMode.Binary)
                {
                    _testOutputHelper.WriteLine($"{s} is not binary");
                }
                Assert.Equal(ResponseMode.Binary, actual);
            }
        }
        public void ListUpdatesAsync(string identityId, string datasetName, IList <SyncRevision> syncRevisions,
                                     CloudSaveCallback <DatasetUpdates> callback)
        {
            var lastSyncRevisionStr = SdkUtils.ConvertSyncRevisionToString(syncRevisions);
            var request             = new PullRecordsRequest
            {
                IdentityId       = identityId,
                DatasetName      = datasetName,
                OldSyncRevisions = lastSyncRevisionStr,
            };

            _client.PullRecordsAsync(request, (err, pullRecordsResponse) =>
            {
                if (err != null)
                {
                    callback(err, null);
                    return;
                }

                var records        = pullRecordsResponse.Records;
                var datasetRecords = new List <Record>();
                if (records.Count > 0)
                {
                    foreach (var remoteRecord in records)
                    {
                        datasetRecords.Add(new Record.Builder(remoteRecord.key)
                                           .Value(remoteRecord.value)
                                           .SyncRegion(remoteRecord.lastModifiedRegion)
                                           .SyncCount(remoteRecord.syncCount)
                                           .LastModifiedBy(remoteRecord.lastModifiedBy)
                                           .LastModifiedDate(SdkUtils.ConvertFromUnixEpochSeconds(remoteRecord.lastModifiedDate))
                                           .DeviceLastModifiedDate(SdkUtils.ConvertFromUnixEpochSeconds(remoteRecord.deviceLastModifiedDate))
                                           .Build()
                                           );
                    }
                }
                callback(null, new DatasetUpdates
                {
                    IdentityId       = pullRecordsResponse.identityId,
                    DatasetName      = pullRecordsResponse.name,
                    SyncSessionToken = pullRecordsResponse.syncSessionToken,
                    SyncRevisions    = SdkUtils.ConvertStringToSyncRevision(pullRecordsResponse.syncCount),
                    Records          = datasetRecords
                });
            });
        }
 public void SaveToLocal()
 {
     if (string.IsNullOrEmpty(keyText))
     {
         _dialogController.Show("Key should not be null");
         return;
     }
     try
     {
         dataset.Put(keyText, valueText);
         syncCountLabel.text = SdkUtils.ConvertSyncRevisionToString(dataset.GetLastSyncRevision());
     }
     catch (Exception e)
     {
         _dialogController.Show("Failed to save data to Local: " + e.Message);
         return;
     }
     _dialogController.Show("Success to save data to Local");
 }
示例#15
0
        private void RecieveAudioMessage(AudioBody body)
        {
            byte[] bytes = SdkUtils.DownloadThumbnail(body.url, body.secret, conn.TokenData.access_token);

            string fileTempDir = SdkUtils.GetRevFileTempDir();

            File.WriteAllBytes(fileTempDir + "\\" + body.filename, bytes);

            string wavFile = AudioConverter.ConvertToWave(fileTempDir, body.filename, Path.GetFileNameWithoutExtension(body.filename) + ".wav");

            if (!File.Exists(wavFile))
            {
                return;
            }

            chatBrower.AppendLeftHtml(toUserName, "收到音频");

            //AppendAudioTag(null);

            PlayAudio(wavFile);
        }
        public Record GetRecord(string identityId, string datasetName, string key)
        {
            Record record = null;

            const string query = @"SELECT Key, Value, SyncCount, SyncRegion, LastModifiedDate, DeviceLastModifiedDate,
                           LastModifiedBy, IsDirty FROM Records
                           WHERE IdentityId = @IdentityId
                           AND Name = @Name
                           AND Key = @Key";

            using (var connection = new SqliteConnection(_filePath))
            {
                connection.Open();

                using (var command = new SqliteCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@IdentityId", identityId);
                    command.Parameters.AddWithValue("@Name", datasetName);
                    command.Parameters.AddWithValue("@Key", key);

                    using (var reader = command.ExecuteReader())
                    {
                        if (reader.HasRows && reader.Read())
                        {
                            record = new Record.Builder(reader.GetString(0))
                                     .Value(reader.IsDBNull(1) ? string.Empty : reader.GetString(1))
                                     .SyncCount(reader.GetInt64(2))
                                     .SyncRegion(reader.GetString(3))
                                     .LastModifiedDate(SdkUtils.ConvertTicksToDateTime(reader.GetString(4)))
                                     .DeviceLastModifiedDate(SdkUtils.ConvertTicksToDateTime(reader.GetString(5)))
                                     .LastModifiedBy(reader.GetString(6))
                                     .IsDirty(reader.GetInt32(7) == 1)
                                     .Build();
                        }
                    }
                }
            }

            return(record);
        }
示例#17
0
        /// <summary>
        /// 接收图片消息
        /// </summary>
        /// <param name="imgBody"></param>
        private void RecieveImageMessage(ImageBody imgBody)
        {
            /*
             * [{"type":"img","url":"https://a1.easemob.com/easemob-demo/chatdemoui/chatfiles/cd6f8050-81f7-11e5-a16a-05187e341cb0",
             * "secret":"zW-AWoH3EeWmJevV5n4Fpkxnnu3e5okMLIhENE0QHaZbvqg5",
             * "filename":"原生+自定义.jpg",
             * "thumb":"https://a1.easemob.com/easemob-demo/chatdemoui/chatfiles/cd6f8050-81f7-11e5-a16a-05187e341cb0",
             * "thumb_secret":"","size":{"width":952,"height":671}}]
             */

            string url          = imgBody.url;
            string secret       = imgBody.secret;
            string filename     = imgBody.filename;
            string thumb        = imgBody.thumb;
            string thumb_secret = imgBody.thumb_secret;
            int    width        = 0;
            int    height       = 0;

            byte[] bytes = null;
            if (!string.IsNullOrEmpty(thumb))
            {
                width  = imgBody.size.width;
                height = imgBody.size.height;

                bytes = SdkUtils.DownloadThumbnail(thumb, secret, conn.TokenData.access_token);
            }


            if (bytes == null || bytes.Length == 0)
            {
            }
            else
            {
                //edChat.AppendImageBytes(bytes);
            }
            // edChat.AppendNewLine(2);
            chatBrower.AppendLeftImage(toUserName, thumb);
        }
        private void btnRecord_MouseUp(object sender, MouseEventArgs e)
        {
            DateTime now = DateTime.Now;

            string fileTempDir = SdkUtils.GetRevFileTempDir();
            string filename    = String.Format("{0}_{1}", FileNamePrefix, now.ToString("MMddHHmmss"));
            string wavFile     = filename + ".wav";
            string amrFile     = filename + ".amr";
            string wavFilePath = Path.Combine(fileTempDir, wavFile);

            // 保存为wav格式
            recorder.EndRecordSound(wavFilePath);

            if (File.Exists(wavFilePath))
            {
                AudioConverter.ConvertToAmr(fileTempDir, wavFile, amrFile);
                AudioFileName = Path.Combine(fileTempDir, amrFile);
                this.Close();
            }
            else
            {
                //错误
            }
        }
        public void UpdateDatasetAfterSync(string identityId, string datasetName, IList <SyncRevision> syncRevisionList)
        {
            const string query =
                @"UPDATE Datasets SET SyncRevisions = @SyncRevisions, WHERE IdentityId = @IdentityId AND Name = @Name";

            using (var connection = new SqliteConnection(_filePath))
            {
                connection.Open();

                using (var trx = connection.BeginTransaction())
                {
                    using (var command = new SqliteCommand(query, connection))
                    {
                        var syncRevisionsStr = SdkUtils.ConvertSyncRevisionToString(syncRevisionList);
                        command.Parameters.AddWithValue("@SyncRevisions", syncRevisionsStr);
                        command.Parameters.AddWithValue("@IdentityId", identityId);
                        command.Parameters.AddWithValue("@Name", datasetName);
                        command.ExecuteNonQuery();
                    }

                    trx.Commit();
                }
            }
        }
        public IList <Record> GetDirtyRecords(string identityId, string datasetName)
        {
            var syncRevisions = GetLastSyncRevision(identityId, datasetName);

            var records = new List <Record>();

            if (syncRevisions == null)
            {
                return(records);
            }

            const string queryTrueDirty =
                @"SELECT Key, Value, SyncCount, SyncRegion, LastModifiedDate, DeviceLastModifiedDate,
                         LastModifiedBy, IsDirty FROM Records
                         WHERE IdentityId = @IdentityId AND Name = @Name AND IsDirty = @IsDirty";

            using (var connection = new SqliteConnection(_filePath))
            {
                connection.Open();

                using (var command = new SqliteCommand(queryTrueDirty, connection))
                {
                    command.Parameters.AddWithValue("@IdentityId", identityId);
                    command.Parameters.AddWithValue("@Name", datasetName);
                    command.Parameters.AddWithValue("@IsDirty", 1);
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.HasRows && reader.Read())
                        {
                            records.Add(
                                new Record.Builder(reader.GetString(0))
                                .Value(reader.IsDBNull(1) ? string.Empty : reader.GetString(1))
                                .SyncCount(reader.GetInt64(2))
                                .SyncRegion(reader.GetString(3))
                                .LastModifiedDate(SdkUtils.ConvertTicksToDateTime(reader.GetString(4)))
                                .DeviceLastModifiedDate(SdkUtils.ConvertTicksToDateTime(reader.GetString(5)))
                                .LastModifiedBy(reader.GetString(6))
                                .IsDirty(reader.GetInt32(7) == 1)
                                .Build()
                                );
                        }
                    }
                }
            }

            foreach (var syncRevision in syncRevisions)
            {
                var          datasetSyncCount  = syncRevision.SyncCount;
                var          datasetSyncRegion = syncRevision.SyncRegion;
                const string query             =
                    @"SELECT Key, Value, SyncCount, SyncRegion, LastModifiedDate, DeviceLastModifiedDate,
                            LastModifiedBy, IsDirty FROM Records
                            WHERE IdentityId = @IdentityId
                            AND Name = @Name
                            AND IsDirty = @IsDirty
                            AND SyncRegion = @datasetSyncRegion AND SyncCount > @datasetSyncCount";

                using (var connection = new SqliteConnection(_filePath))
                {
                    connection.Open();

                    using (var command = new SqliteCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@IdentityId", identityId);
                        command.Parameters.AddWithValue("@Name", datasetName);
                        command.Parameters.AddWithValue("@IsDirty", 0);
                        command.Parameters.AddWithValue("@datasetSyncCount", datasetSyncCount);
                        command.Parameters.AddWithValue("@datasetSyncRegion", datasetSyncRegion);
                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.HasRows && reader.Read())
                            {
                                records.Add(
                                    new Record.Builder(reader.GetString(0))
                                    .Value(reader.IsDBNull(1) ? string.Empty : reader.GetString(1))
                                    .SyncCount(reader.GetInt64(2))
                                    .SyncRegion(reader.GetString(3))
                                    .LastModifiedDate(SdkUtils.ConvertTicksToDateTime(reader.GetString(4)))
                                    .DeviceLastModifiedDate(SdkUtils.ConvertTicksToDateTime(reader.GetString(5)))
                                    .LastModifiedBy(reader.GetString(6))
                                    .IsDirty(reader.GetInt32(7) == 1)
                                    .Build()
                                    );
                            }
                        }
                    }
                }
            }

            return(records);
        }
示例#21
0
        /// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="toUser">发给谁</param>
        /// <param name="postedfile">已经上传的文件返回信息</param>
        public void SendFile(string toUser, PostedFileResp postedfile)
        {
            Jid to   = new Jid(BuildJid(toUser));
            Jid from = new Jid(BuildJid(UserName));

            BodyBase[] bodies = new BodyBase[postedfile.entities.Length];
            // 构建发送文件的 message 消息
            for (int i = 0; i < postedfile.entities.Length; i++)
            {
                PostFileEntity entity = postedfile.entities[i];
                // 文件类型 img audio
                string otype = SdkUtils.GetFileType(entity.filename);
                // 文件的url
                string ourl      = postedfile.uri + "/" + entity.uuid;
                string osecret   = entity.share_secret;
                string ofilename = entity.filename;

                /*
                 * 传图片
                 * ReceivedData:
                 * <message xmlns='jabber:client' from='easemob-demo#[email protected]/webim'
                 * to='easemob-demo#[email protected]' id='124420481838219668' type='chat'>
                 * <body>
                 * {"from":"weigang75","to":"march3","bodies":
                 * [{"type":"img","url":"https://a1.easemob.com/easemob-demo/chatdemoui/chatfiles/cd6f8050-81f7-11e5-a16a-05187e341cb0",
                 * "secret":"zW-AWoH3EeWmJevV5n4Fpkxnnu3e5okMLIhENE0QHaZbvqg5",
                 * "filename":"原生+自定义.jpg",
                 * "thumb":"https://a1.easemob.com/easemob-demo/chatdemoui/chatfiles/cd6f8050-81f7-11e5-a16a-05187e341cb0",
                 * "thumb_secret":"","size":{"width":952,"height":671}}],"ext":{}}</body></message>
                 *
                 * 传语音
                 * ReceivedData:
                 * <message xmlns='jabber:client' from='easemob-demo#[email protected]/webim'
                 * to='easemob-demo#[email protected]' id='124421298246910356' type='chat'>
                 * <body>
                 * {"from":"weigang75","to":"march3","bodies":
                 * [{"type":"audio",
                 * "url":"https://a1.easemob.com/easemob-demo/chatdemoui/chatfiles/3ec2bb50-81f8-11e5-8e7c-1fa6315dec2d",
                 * "secret":"PsK7WoH4EeWwmIkeyVsexnkK-Rmqu2X_N2qqK9FQYmUkko8W",
                 * "filename":"环信通讯 - 副本.mp3",
                 * "length":3}],"ext":{}}</body></message>
                 *
                 */

                // 如果是文件,需要多一些字段 thumb、thumb_secret、size
                if ("img".Equals(otype))
                {
                    bodies[i] = new ImageBody
                    {
                        type         = otype,
                        url          = ourl,
                        secret       = osecret,
                        filename     = ofilename,
                        thumb        = ourl,
                        thumb_secret = "",
                        size         = new ImageSize
                        {
                            width  = entity.imageSize.Width,
                            height = entity.imageSize.Height
                        }
                    };
                }
                else if ("audio".Equals(otype))
                {
                    bodies[i] = new AudioBody
                    {
                        type     = otype,
                        url      = ourl,
                        secret   = osecret,
                        filename = ofilename
                    };
                }
                else
                {
                    bodies[i] = new FileBody
                    {
                        type     = otype,
                        url      = ourl,
                        secret   = osecret,
                        filename = ofilename
                    };
                }
            }

            MsgData data = new MsgData()
            {
                from = UserName, to = toUser, bodies = bodies, ext = new { }
            };

            WSMessage msgNode = new WSMessage(to, from);

            msgNode.Type = MessageType.chat;
            msgNode.SetBodyData(data);

            Send(msgNode);
        }
        private void SynchronizeInternalAsync(ISyncCallback callback, long syncSequenceId, int retry)
        {
            if (retry < 0)
            {
                var e = new SyncConflictingException();

                if (Logger.LoggingConfig.LogInnerMostError)
                {
                    _logger.Error(e, "Sync failed due to retry less than 0");
                }

                callback.OnError(this, new SyncConflictingException());
                return;
            }

            // pull from remote

            var lastSyncRevisions = _local.GetLastSyncRevision(IdentityId, Name);

            _remote.ListUpdatesAsync(IdentityId, Name, lastSyncRevisions,
                                     (listUpdatesErr, datasetUpdates) =>
            {
                if (syncSequenceId != _currentSyncSequenceId)
                {
                    var e = new SyncCanceledException();
                    callback.OnError(this, e);

                    if (Logger.LoggingConfig.LogInnerMostError)
                    {
                        _logger.Error(e, "INTERNAL LOG - Sync Failed due to inconsistent syncSequenceId.");
                    }

                    return;
                }

                if (listUpdatesErr != null)
                {
                    var e = new SyncNetworkException("Failed to pull from remote", listUpdatesErr);

                    if (Logger.LoggingConfig.LogInnerMostError)
                    {
                        _logger.Error(e, "INTERNAL LOG - Failed to pull from remote");
                    }

                    callback.OnError(this, e);
                    return;
                }

                if (!MergeRemoteRecords(callback, datasetUpdates))
                {
                    return;
                }

                // push to remote.
                // includes the records whose region is different.
                var localChanges = _local.GetDirtyRecords(IdentityId, Name);

                if (localChanges.Count == 0)
                {
                    callback.OnSuccess(this);
                    return;
                }

                _remote.PutRecordsAsync(IdentityId, Name,
                                        SdkUtils.ConvertSyncRevisionToString(datasetUpdates.SyncRevisions),
                                        datasetUpdates.SyncSessionToken, localChanges, (putErr, putResult) =>
                {
                    if (syncSequenceId != _currentSyncSequenceId)
                    {
                        var e = new SyncCanceledException();

                        if (Logger.LoggingConfig.LogInnerMostError)
                        {
                            _logger.Error(e, "INTERNAL LOG - Sync failed due to inconsistency of syncSequenceId");
                        }

                        callback.OnError(this, e);
                        return;
                    }

                    if (putErr != null)
                    {
                        if (Logger.LoggingConfig.LogInnerMostError)
                        {
                            _logger.Error(putErr, "INTERNAL LOG - Failed to push to remote: {0}", putErr.Message);
                        }

                        if (ErrorResponseException.IsDatasetConflict(putErr))
                        {
                            SynchronizeInternalAsync(callback, syncSequenceId, --retry);
                            return;
                        }

                        callback.OnError(this, new SyncNetworkException("Failed to push to remote", putErr));
                        return;
                    }

                    _local.ConditionallyPutRecords(IdentityId, Name, putResult.Records, localChanges);
                    _local.UpdateLastSyncRevision(IdentityId, Name, putResult.SyncRevisions);

                    callback.OnSuccess(this);
                });
            });
        }
        private bool MergeRemoteRecords(ISyncCallback callback, DatasetUpdates datasetUpdates)
        {
            var conflicts     = new List <SyncConflict>();
            var remoteUpdates = new List <Record>();

            foreach (var remoteRecord in datasetUpdates.Records)
            {
                var localRecord = _local.GetRecord(IdentityId, Name, remoteRecord.Key);
                if (localRecord == null)
                {
                    remoteUpdates.Add(remoteRecord);
                    continue;
                }

                if (remoteRecord.SyncRegion != localRecord.SyncRegion) // always a conflict if region is different.
                {
                    conflicts.Add(new SyncConflict(remoteRecord, localRecord));
                    continue;
                }

                if (remoteRecord.SyncCount <= localRecord.SyncCount)
                {
                    // ignore remote record if we know for sure remote record is older.
                    continue;
                }

                if (localRecord.IsDirty)
                {
                    conflicts.Add(new SyncConflict(remoteRecord, localRecord));
                }
                else
                {
                    remoteUpdates.Add(remoteRecord);
                }
            }

            _logger.DebugFormat("INTERNAL LOG - {0} records in conflict", conflicts.Count);
            if (conflicts.Count != 0 && !callback.OnConflict(this, conflicts))
            {
                var e = new SyncConflictingException();

                if (Logger.LoggingConfig.LogInnerMostError)
                {
                    _logger.Error(e, "INTERNAL LOG - Conflict resolution failed/cancelled.");
                }

                callback.OnError(this, e);
                return(false);
            }

            if (remoteUpdates.Count != 0)
            {
                _logger.DebugFormat("INTERNAL LOG - Save {0} records to local", remoteUpdates.Count);
                _local.PutRecords(IdentityId, Name, remoteUpdates);
            }

            _local.UpdateLastSyncRevision(IdentityId, Name, datasetUpdates.SyncRevisions);

            _logger.DebugFormat("INTERNAL LOG - Update SyncRevision of Dataset to {0}", SdkUtils.ConvertSyncRevisionToString(datasetUpdates.SyncRevisions));
            return(true);
        }
 public void SwitchDataset()
 {
     dataset = GameManager.Instance.CurrentDataset;
     datasetNameLabel.text = dataset.Name;
     syncCountLabel.text   = SdkUtils.ConvertSyncRevisionToString(dataset.GetLastSyncRevision());
 }
 public void OnSuccess(IDataset dataset)
 {
     _dialogController.Show("Sync success");
     syncCountLabel.text = SdkUtils.ConvertSyncRevisionToString(dataset.GetLastSyncRevision());
 }
        internal void UpdateOrInsertRecord(SqliteConnection conn, string identityId, string datasetName, Record record)
        {
            const string checkRecordquery = @"SELECT COUNT(*) FROM Records WHERE
                                        IdentityId = @IdentityId AND
                                        Name = @Name AND
                                        Key = @Key";

            bool recordFound = false;

            using (var command = new SqliteCommand(checkRecordquery, conn))
            {
                command.Parameters.AddWithValue("@IdentityId", identityId);
                command.Parameters.AddWithValue("@Name", datasetName);
                command.Parameters.AddWithValue("@Key", record.Key);

                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        recordFound = reader.GetInt32(0) > 0;
                    }
                }
            }

            if (recordFound)
            {
                const string updateRecordQuery =
                    @"UPDATE Records SET Value = @Value, SyncCount = @SyncCount, SyncRegion = @SyncRegion,
                                           LastModifiedDate = @LastModifiedDate, DeviceLastModifiedDate = @DeviceLastModifiedDate,
                                           LastModifiedBy = @LastModifiedBy, IsDirty = @IsDirty WHERE IdentityId = @IdentityId AND
                                           Name = @Name AND Key = @Key";

                using (var command = new SqliteCommand(updateRecordQuery, conn))
                {
                    command.Parameters.AddWithValue("@Value", record.Value);
                    command.Parameters.AddWithValue("@SyncCount", record.SyncCount);
                    command.Parameters.AddWithValue("@SyncRegion", record.SyncRegion);
                    var date = record.LastModifiedDate.HasValue
                        ? SdkUtils.ConvertDateTimeToTicks(record.LastModifiedDate.Value)
                        : SdkUtils.ConvertDateTimeToTicks(DateTime.Now);
                    command.Parameters.AddWithValue("@LastModifiedDate", date);
                    command.Parameters.AddWithValue("@DeviceLastModifiedDate",
                                                    SdkUtils.ConvertDateTimeToTicks(DateTime.Now));
                    command.Parameters.AddWithValue("@LastModifiedBy", record.LastModifiedBy);
                    command.Parameters.AddWithValue("@IsDirty", record.IsDirty ? 1 : 0);
                    command.Parameters.AddWithValue("@IdentityId", identityId);
                    command.Parameters.AddWithValue("@Name", datasetName);
                    command.Parameters.AddWithValue("@Key", record.Key);
                    command.ExecuteNonQuery();
                }
            }
            else
            {
                const string insertQuery =
                    @"INSERT INTO Records (IdentityId, Name, Key, Value, SyncCount, SyncRegion,
                                     LastModifiedDate, DeviceLastModifiedDate, LastModifiedBy, IsDirty)
                                     VALUES (@IdentityId, @Name, @Key, @Value,
                                     @SyncCount, @SyncRegion, @LastModifiedDate, @DeviceLastModifiedDate, @LastModifiedBy, @IsDirty)";

                using (var command = new SqliteCommand(insertQuery, conn))
                {
                    command.Parameters.AddWithValue("@IdentityId", identityId);
                    command.Parameters.AddWithValue("@Name", datasetName);
                    command.Parameters.AddWithValue("@Key", record.Key);
                    command.Parameters.AddWithValue("@Value", record.Value);
                    command.Parameters.AddWithValue("@SyncCount", record.SyncCount);
                    command.Parameters.AddWithValue("@SyncRegion", record.SyncRegion);
                    var date = record.LastModifiedDate.HasValue
                        ? SdkUtils.ConvertDateTimeToTicks(record.LastModifiedDate.Value)
                        : SdkUtils.ConvertDateTimeToTicks(DateTime.Now);
                    command.Parameters.AddWithValue("@LastModifiedDate", date);
                    command.Parameters.AddWithValue("@DeviceLastModifiedDate",
                                                    SdkUtils.ConvertDateTimeToTicks(DateTime.Now));
                    command.Parameters.AddWithValue("@LastModifiedBy", record.LastModifiedBy);
                    command.Parameters.AddWithValue("@IsDirty", record.IsDirty ? 1 : 0);
                    command.ExecuteNonQuery();
                }
            }
        }