internal static LCRanking Parse(IDictionary <string, object> data) { LCRanking ranking = new LCRanking(); if (data.TryGetValue("rank", out object rank)) { ranking.Rank = Convert.ToInt32(rank); } if (data.TryGetValue("user", out object user)) { LCObjectData objectData = LCObjectData.Decode(user as System.Collections.IDictionary); ranking.User = LCUser.GenerateUser(objectData); } if (data.TryGetValue("statisticName", out object statisticName)) { ranking.StatisticName = statisticName as string; } if (data.TryGetValue("statisticValue", out object value)) { ranking.Value = Convert.ToDouble(value); } if (data.TryGetValue("statistics", out object statistics) && statistics is List <object> list) { List <LCStatistic> statisticList = new List <LCStatistic>(); foreach (object item in list) { LCStatistic statistic = LCStatistic.Parse(item as IDictionary <string, object>); statisticList.Add(statistic); } ranking.IncludedStatistics = statisticList.AsReadOnly(); } return(ranking); }
static async Task SaveBatches(Stack <LCBatch> batches) { while (batches.Count > 0) { LCBatch batch = batches.Pop(); // 特殊处理 File 依赖 IEnumerable <LCFile> dirtyFiles = batch.objects.Where(item => (item is LCFile) && item.IsDirty) .Cast <LCFile>(); foreach (LCFile file in dirtyFiles) { await file.Save(); } List <LCObject> dirtyObjects = batch.objects.Where(item => item.IsDirty) .ToList(); if (dirtyObjects.Count == 0) { continue; } List <Dictionary <string, object> > requestList = dirtyObjects.Select(item => { string path = item.ObjectId == null ? $"/1.1/classes/{item.ClassName}" : $"/1.1/classes/{item.ClassName}/{item.ClassName}"; string method = item.ObjectId == null ? "POST" : "PUT"; Dictionary <string, object> body = LCEncoder.Encode(item.operationDict) as Dictionary <string, object>; return(new Dictionary <string, object> { { "path", path }, { "method", method }, { "body", body } }); }).ToList(); Dictionary <string, object> data = new Dictionary <string, object> { { "requests", LCEncoder.Encode(requestList) } }; List <Dictionary <string, object> > results = await LCCore.HttpClient.Post <List <Dictionary <string, object> > >("batch", data : data); List <LCObjectData> resultList = results.Select(item => { if (item.TryGetValue("error", out object error)) { Dictionary <string, object> err = error as Dictionary <string, object>; int code = (int)err["code"]; string message = (string)err["error"]; throw new LCException(code, message as string); } return(LCObjectData.Decode(item["success"] as IDictionary)); }).ToList(); for (int i = 0; i < dirtyObjects.Count; i++) { LCObject obj = dirtyObjects[i]; LCObjectData objData = resultList[i]; obj.Merge(objData); } } }
public static LCFile DecodeFile(IDictionary dict) { LCFile file = new LCFile(); LCObjectData objectData = LCObjectData.Decode(dict as Dictionary <string, object>); file.Merge(objectData); return(file); }
/// <summary> /// Deserializes a JSON string to a LCObject. /// </summary> /// <param name="json"></param> /// <returns></returns> public static LCObject ParseObject(string json) { LCObjectData objectData = LCObjectData.Decode(JsonConvert.DeserializeObject <Dictionary <string, object> >(json)); LCObject obj = Create(objectData.ClassName); obj.Merge(objectData); return(obj); }
static async Task <LCUser> Login(Dictionary <string, object> data) { Dictionary <string, object> response = await LeanCloud.HttpClient.Post <Dictionary <string, object> >("login", data : data); LCObjectData objectData = LCObjectData.Decode(response); currentUser = new LCUser(objectData); return(currentUser); }
static LCObject DecodeObject(IDictionary dict) { string className = dict["className"].ToString(); LCObject obj = LCObject.Create(className); LCObjectData objectData = LCObjectData.Decode(dict as Dictionary <string, object>); obj.Merge(objectData); return(obj); }
private static void OnLoginNotification(Dictionary <string, object> data) { if (TryGetLiveQuery(data, out LCLiveQuery liveQuery) && data.TryGetValue("object", out object obj) && obj is Dictionary <string, object> dict) { LCObjectData objectData = LCObjectData.Decode(dict); LCUser user = LCUser.GenerateUser(objectData); liveQuery.OnLogin?.Invoke(user); } }
public async Task <LCSearchResponse <T> > Find() { string path = "search/select"; Dictionary <string, object> queryParams = new Dictionary <string, object> { { "clazz", className }, { "limit", limit }, { "skip", skip } }; if (queryString != null) { queryParams["q"] = queryString; } if (highlights != null && highlights.Count() > 0) { queryParams["highlights"] = string.Join(",", highlights); } if (includeKeys != null && includeKeys.Count() > 0) { queryParams["include"] = string.Join(",", includeKeys); } if (!string.IsNullOrEmpty(sid)) { queryParams["sid"] = sid; } if (orders != null && orders.Count() > 0) { queryParams["order"] = string.Join(",", orders); } if (sortBuilder != null) { queryParams["sort"] = sortBuilder.Build(); } Dictionary <string, object> response = await LCCore.HttpClient.Get <Dictionary <string, object> >(path, queryParams : queryParams); LCSearchResponse <T> ret = new LCSearchResponse <T>(); ret.Hits = (int)response["hits"]; ret.Sid = (string)response["sid"]; List <object> results = response["results"] as List <object>; List <T> list = new List <T>(); foreach (object data in results) { LCObjectData objectData = LCObjectData.Decode(data as Dictionary <string, object>); T obj = LCObject.Create(className) as T; obj.Merge(objectData); list.Add(obj); } ret.Results = list.AsReadOnly(); return(ret); }
static async Task <LCUser> Login(Dictionary <string, object> data) { Dictionary <string, object> response = await LCCore.HttpClient.Post <Dictionary <string, object> >("login", data : data); LCObjectData objectData = LCObjectData.Decode(response); currentUser = GenerateUser(objectData); await SaveToLocal(); return(currentUser); }
private static async Task <object> Invoke(MethodInfo mi, Dictionary <string, object> dict) { LCObjectData objectData = LCObjectData.Decode(dict["object"] as Dictionary <string, object>); objectData.ClassName = "_User"; LCObject user = LCObject.Create("_User"); user.Merge(objectData); return(await LCEngine.Invoke(mi, new object[] { user }) as LCObject); }
public async Task <object> Hook(string className, string hookName, JsonElement body) { try { LCLogger.Debug($"Hook: {className}#{hookName}"); LCLogger.Debug(body.ToString()); LCEngine.CheckHookKey(Request); string classHookName = GetClassHookName(className, hookName); if (ClassHooks.TryGetValue(classHookName, out MethodInfo mi)) { Dictionary <string, object> data = LCEngine.Decode(body); LCObjectData objectData = LCObjectData.Decode(data["object"] as Dictionary <string, object>); objectData.ClassName = className; LCObject obj = LCObject.Create(className); obj.Merge(objectData); // 避免死循环 if (hookName.StartsWith("before")) { obj.DisableBeforeHook(); } else { obj.DisableAfterHook(); } LCEngine.InitRequestContext(Request); LCUser user = null; if (data.TryGetValue("user", out object userObj) && userObj != null) { user = new LCUser(); user.Merge(LCObjectData.Decode(userObj as Dictionary <string, object>)); LCEngineRequestContext.CurrentUser = user; } LCObject result = await LCEngine.Invoke(mi, new object[] { obj }) as LCObject; if (result != null) { return(LCCloud.Encode(result)); } } return(body); } catch (Exception e) { return(StatusCode(500, e.Message)); } }
/// <summary> /// Saves the file to LeanCloud. /// </summary> /// <param name="onProgress"></param> /// <returns></returns> public async Task <LCFile> Save(Action <long, long> onProgress = null) { if (!string.IsNullOrEmpty(Url)) { // 外链方式 await base.Save(); } else { // 上传文件 Dictionary <string, object> uploadToken = await GetUploadToken(); string uploadUrl = uploadToken["upload_url"] as string; string key = uploadToken["key"] as string; string token = uploadToken["token"] as string; string provider = uploadToken["provider"] as string; try { if (provider == "s3") { // AWS LCAWSUploader uploader = new LCAWSUploader(uploadUrl, MimeType, stream); await uploader.Upload(onProgress); } else if (provider == "qiniu") { // Qiniu LCQiniuUploader uploader = new LCQiniuUploader(uploadUrl, token, key, stream); await uploader.Upload(onProgress); } else { throw new Exception($"{provider} is not support."); } LCObjectData objectData = LCObjectData.Decode(uploadToken); Merge(objectData); _ = LCCore.HttpClient.Post <Dictionary <string, object> >("fileCallback", data: new Dictionary <string, object> { { "result", true }, { "token", token } }); } catch (Exception e) { _ = LCCore.HttpClient.Post <Dictionary <string, object> >("fileCallback", data: new Dictionary <string, object> { { "result", false }, { "token", token } }); throw e; } } return(this); }
private static bool TryGetObject(Dictionary <string, object> data, out LCObject obj) { if (!data.TryGetValue("object", out object o) || !(o is Dictionary <string, object> dict)) { obj = null; return(false); } LCObjectData objectData = LCObjectData.Decode(dict); obj = LCObject.Create(dict["className"] as string); obj.Merge(objectData); return(true); }
static async Task <LCUser> LoginWithAuthData(string authType, Dictionary <string, object> data, bool failOnNotExist) { Dictionary <string, object> authData = new Dictionary <string, object> { { authType, data } }; string path = failOnNotExist ? "users?failOnNotExist=true" : "users"; Dictionary <string, object> response = await LeanCloud.HttpClient.Post <Dictionary <string, object> >(path, data : new Dictionary <string, object> { { "authData", authData } }); LCObjectData objectData = LCObjectData.Decode(response); currentUser = new LCUser(objectData); return(currentUser); }
/// <summary> /// 设置当前用户 /// </summary> /// <param name="sessionToken"></param> /// <returns></returns> public static async Task <LCUser> BecomeWithSessionToken(string sessionToken) { if (string.IsNullOrEmpty(sessionToken)) { throw new ArgumentNullException(nameof(sessionToken)); } Dictionary <string, object> headers = new Dictionary <string, object> { { "X-LC-Session", sessionToken } }; Dictionary <string, object> response = await LeanCloud.HttpClient.Get <Dictionary <string, object> >("users/me", headers : headers); LCObjectData objectData = LCObjectData.Decode(response); currentUser = new LCUser(objectData); return(currentUser); }
public async Task <List <T> > Find() { string path = $"classes/{ClassName}"; Dictionary <string, object> parameters = BuildParams(); Dictionary <string, object> response = await LeanCloud.HttpClient.Get <Dictionary <string, object> >(path, queryParams : parameters); List <object> results = response["results"] as List <object>; List <T> list = new List <T>(); foreach (object item in results) { LCObjectData objectData = LCObjectData.Decode(item as Dictionary <string, object>); T obj = LCObject.Create(ClassName) as T; obj.Merge(objectData); list.Add(obj); } return(list); }
/// <summary> /// Fetches all of the objects in the provided list. /// </summary> /// <param name="objects">The objects for fetching.</param> /// <returns></returns> public static async Task <IEnumerable <LCObject> > FetchAll(IEnumerable <LCObject> objects) { if (objects == null || objects.Count() == 0) { throw new ArgumentNullException(nameof(objects)); } IEnumerable <LCObject> uniqueObjects = objects.Where(item => item.ObjectId != null); List <Dictionary <string, object> > requestList = uniqueObjects.Select(item => { string path = $"/{LCCore.APIVersion}/classes/{item.ClassName}/{item.ObjectId}"; return(new Dictionary <string, object> { { "path", path }, { "method", "GET" } }); }).ToList(); Dictionary <string, object> data = new Dictionary <string, object> { { "requests", LCEncoder.Encode(requestList) } }; List <Dictionary <string, object> > results = await LCCore.HttpClient.Post <List <Dictionary <string, object> > >("batch", data : data); Dictionary <string, LCObjectData> dict = new Dictionary <string, LCObjectData>(); foreach (Dictionary <string, object> item in results) { if (item.TryGetValue("error", out object error)) { int code = (int)error; string message = item["error"] as string; throw new LCException(code, message); } Dictionary <string, object> d = item["success"] as Dictionary <string, object>; string objectId = d["objectId"] as string; dict[objectId] = LCObjectData.Decode(d); } foreach (LCObject obj in objects) { LCObjectData objData = dict[obj.ObjectId]; obj.Merge(objData); } return(objects); }
/// <summary> /// Sends this status. /// </summary> /// <returns></returns> public async Task <LCStatus> Send() { LCUser user = await LCUser.GetCurrent(); if (user == null) { throw new ArgumentNullException("current user"); } Dictionary <string, object> formData = new Dictionary <string, object> { { InboxTypeKey, InboxType } }; if (Data != null) { formData["data"] = LCEncoder.Encode(Data); } if (query != null) { Dictionary <string, object> queryData = new Dictionary <string, object> { { "className", query.ClassName } }; Dictionary <string, object> ps = query.BuildParams(); if (ps.TryGetValue("where", out object whereObj) && whereObj is string where) { queryData["where"] = JsonConvert.DeserializeObject(where); } if (ps.TryGetValue("keys", out object keys)) { queryData["keys"] = keys; } formData["query"] = queryData; } Dictionary <string, object> response = await LCCore.HttpClient.Post <Dictionary <string, object> >("statuses", data : formData); LCObjectData objectData = LCObjectData.Decode(response); Merge(objectData); return(this); }
/// <summary> /// Fetches this object from the cloud. /// </summary> /// <param name="keys">The keys for fetching.</param> /// <param name="includes">The include keys for fetching.</param> /// <returns></returns> public async Task <LCObject> Fetch(IEnumerable <string> keys = null, IEnumerable <string> includes = null) { Dictionary <string, object> queryParams = new Dictionary <string, object>(); if (keys != null) { queryParams["keys"] = string.Join(",", keys); } if (includes != null) { queryParams["include"] = string.Join(",", includes); } string path = $"classes/{ClassName}/{ObjectId}"; Dictionary <string, object> response = await LCCore.HttpClient.Get <Dictionary <string, object> >(path, queryParams : queryParams); LCObjectData objectData = LCObjectData.Decode(response); Merge(objectData); return(this); }
/// <summary> /// 更新密码 /// </summary> /// <param name="oldPassword"></param> /// <param name="newPassword"></param> /// <returns></returns> public async Task UpdatePassword(string oldPassword, string newPassword) { if (string.IsNullOrEmpty(oldPassword)) { throw new ArgumentNullException(nameof(oldPassword)); } if (string.IsNullOrEmpty(newPassword)) { throw new ArgumentNullException(nameof(newPassword)); } Dictionary <string, object> data = new Dictionary <string, object> { { "old_password", oldPassword }, { "new_password", newPassword } }; Dictionary <string, object> response = await LeanCloud.HttpClient.Put <Dictionary <string, object> >( $"users/{ObjectId}/updatePassword", data : data); LCObjectData objectData = LCObjectData.Decode(response); Merge(objectData); }
/// <summary> /// 使用手机号和验证码注册或登录 /// </summary> /// <param name="mobile"></param> /// <param name="code"></param> /// <returns></returns> public static async Task <LCUser> SignUpOrLoginByMobilePhone(string mobile, string code) { if (string.IsNullOrEmpty(mobile)) { throw new ArgumentNullException(nameof(mobile)); } if (string.IsNullOrEmpty(mobile)) { throw new ArgumentNullException(nameof(code)); } Dictionary <string, object> data = new Dictionary <string, object> { { "mobilePhoneNumber", mobile }, { "smsCode", code } }; Dictionary <string, object> response = await LeanCloud.HttpClient.Post <Dictionary <string, object> >("usersByMobilePhone", data : data); LCObjectData objectData = LCObjectData.Decode(response); currentUser = new LCUser(objectData); return(currentUser); }
public async Task <LCFile> Save(Action <long, long> onProgress = null) { if (!string.IsNullOrEmpty(Url)) { // 外链方式 await base.Save(); } else { // 上传文件 Dictionary <string, object> uploadToken = await GetUploadToken(); string uploadUrl = uploadToken["upload_url"] as string; string key = uploadToken["key"] as string; string token = uploadToken["token"] as string; string provider = uploadToken["provider"] as string; if (provider == "s3") { // AWS LCAWSUploader uploader = new LCAWSUploader(uploadUrl, MimeType, data); await uploader.Upload(onProgress); } else if (provider == "qiniu") { // Qiniu LCQiniuUploader uploader = new LCQiniuUploader(uploadUrl, token, key, data); await uploader.Upload(onProgress); } else { throw new Exception($"{provider} is not support."); } LCObjectData objectData = LCObjectData.Decode(uploadToken); Merge(objectData); } return(this); }
/// <summary> /// Saves this object to the cloud. /// </summary> /// <param name="fetchWhenSave">Whether or not fetch data when saved.</param> /// <param name="query">The condition for saving.</param> /// <returns></returns> public async Task <LCObject> Save(bool fetchWhenSave = false, LCQuery <LCObject> query = null) { if (LCBatch.HasCircleReference(this, new HashSet <LCObject>())) { throw new ArgumentException("Found a circle dependency when save."); } Stack <LCBatch> batches = LCBatch.BatchObjects(new List <LCObject> { this }, false); if (batches.Count > 0) { await SaveBatches(batches); } string path = ObjectId == null ? $"classes/{ClassName}" : $"classes/{ClassName}/{ObjectId}"; Dictionary <string, object> queryParams = new Dictionary <string, object>(); if (fetchWhenSave) { queryParams["fetchWhenSave"] = true; } if (query != null) { queryParams["where"] = query.BuildWhere(); } Dictionary <string, object> response = ObjectId == null ? await LCCore.HttpClient.Post <Dictionary <string, object> >(path, data : LCEncoder.Encode(operationDict) as Dictionary <string, object>, queryParams : queryParams) : await LCCore.HttpClient.Put <Dictionary <string, object> >(path, data : LCEncoder.Encode(operationDict) as Dictionary <string, object>, queryParams : queryParams); LCObjectData data = LCObjectData.Decode(response); Merge(data); return(this); }
/// <summary> /// Retrieves a list of LCStatus that satisfy the query from the cloud. /// </summary> /// <returns></returns> public new async Task <ReadOnlyCollection <LCStatus> > Find() { LCUser user = await LCUser.GetCurrent(); if (user == null) { throw new ArgumentNullException("current user"); } Dictionary <string, object> queryParams = new Dictionary <string, object> { { LCStatus.OwnerKey, JsonConvert.SerializeObject(LCEncoder.Encode(user)) }, { LCStatus.InboxTypeKey, InboxType }, { "where", BuildWhere() }, { "sinceId", SinceId }, { "maxId", MaxId }, { "limit", Condition.Limit } }; Dictionary <string, object> response = await LCCore.HttpClient.Get <Dictionary <string, object> >("subscribe/statuses", queryParams : queryParams); List <object> results = response["results"] as List <object>; List <LCStatus> statuses = new List <LCStatus>(); foreach (object item in results) { LCObjectData objectData = LCObjectData.Decode(item as IDictionary); LCStatus status = new LCStatus(); status.Merge(objectData); status.MessageId = (int)objectData.CustomPropertyDict[LCStatus.MessageIdKey]; status.Data = objectData.CustomPropertyDict; status.InboxType = objectData.CustomPropertyDict[LCStatus.InboxTypeKey] as string; statuses.Add(status); } return(statuses.AsReadOnly()); }
/// <summary> /// Gets the followers and followees of the currently logged in user. /// </summary> /// <param name="includeFollower"></param> /// <param name="includeFollowee"></param> /// <param name="returnCount"></param> /// <returns></returns> public async Task <LCFollowersAndFollowees> GetFollowersAndFollowees(bool includeFollower = false, bool includeFollowee = false, bool returnCount = false) { Dictionary <string, object> queryParams = new Dictionary <string, object>(); if (returnCount) { queryParams["count"] = 1; } if (includeFollower || includeFollowee) { List <string> includes = new List <string>(); if (includeFollower) { includes.Add("follower"); } if (includeFollowee) { includes.Add("followee"); } queryParams["include"] = string.Join(",", includes); } string path = $"users/{ObjectId}/followersAndFollowees"; Dictionary <string, object> response = await LCCore.HttpClient.Get <Dictionary <string, object> >(path, queryParams : queryParams); LCFollowersAndFollowees result = new LCFollowersAndFollowees(); if (response.TryGetValue("followers", out object followersObj) && (followersObj is List <object> followers)) { result.Followers = new List <LCObject>(); foreach (object followerObj in followers) { LCObjectData objectData = LCObjectData.Decode(followerObj as IDictionary); LCObject follower = new LCObject("_Follower"); follower.Merge(objectData); result.Followers.Add(follower); } } if (response.TryGetValue("followees", out object followeesObj) && (followeesObj is List <object> followees)) { result.Followees = new List <LCObject>(); foreach (object followeeObj in followees) { LCObjectData objectData = LCObjectData.Decode(followeeObj as IDictionary); LCObject followee = new LCObject("_Followee"); followee.Merge(objectData); result.Followees.Add(followee); } } if (response.TryGetValue("followers_count", out object followersCountObj) && (followersCountObj is int followersCount)) { result.FollowersCount = followersCount; } if (response.TryGetValue("followees_count", out object followeesCountObj) && (followeesCountObj is int followeesCount)) { result.FolloweesCount = followeesCount; } return(result); }