/// <summary> /// Loads data fields of this instance from the given json object /// </summary> internal override void LoadData(JsonObject data) { base.LoadData(data); Subject = Convert.ToString(data["subject"]); Message = GetHtmlContent(Convert.ToString(data["message"])); }
public Story(JsonObject jsonIn) { this.StoryId = GetJsonValueIfExists(jsonIn, "id") as string; this.FromId = GetJsonValueIfExists((JsonObject)GetJsonValueIfExists(jsonIn, "from"), "id") as string; this.FromName = GetJsonValueIfExists((JsonObject)GetJsonValueIfExists(jsonIn, "from"), "name") as string; this.StoryProperty = GetJsonValueIfExists(jsonIn, "story") as string; this.Type = GetJsonValueIfExists(jsonIn, "type") as string; this.Message = GetJsonValueIfExists(jsonIn, "message") as string; this.PictureUrl = GetJsonValueIfExists(jsonIn, "picture") as string; this.Link = GetJsonValueIfExists(jsonIn, "link") as string; this.LinkName = GetJsonValueIfExists(jsonIn, "name") as string; this.LinkCaption = GetJsonValueIfExists(jsonIn, "caption") as string; this.LinkDescription = GetJsonValueIfExists(jsonIn, "description") as string; JsonObject likes = GetJsonValueIfExists(jsonIn, "likes") as JsonObject; if (likes != null) { this.LikeCount = Convert.ToInt32(GetJsonValueIfExists(likes, "count")); } string timeString = GetJsonValueIfExists(jsonIn, "created_time") as string; if (timeString != null) { this.CreateTime = DateTime.Parse(timeString); } timeString = GetJsonValueIfExists(jsonIn, "update_time") as string; if (timeString != null) { this.UpdateTime = DateTime.Parse(timeString); } }
/// <summary> /// Loads data fields of this instance from the given json object /// </summary> internal override void LoadData(JsonObject data) { base.LoadData(data); // details Message = Convert.ToString(data.TryGet("story") ?? data.TryGet("message")); Link = Convert.ToString(data.TryGet("link") ?? ""); LinkName = Convert.ToString(data.TryGet("name") ?? "Link"); Description = new[] { data.TryGet("caption"), data.TryGet("description") }.Where(a => a != null).Select(a => Convert.ToString(a)).ToString(Environment.NewLine); // from? var fromdata = data["from"] as JsonObject; From = Convert.ToString(fromdata["name"]); From_Id = Convert.ToString(fromdata["id"]); // like # var likesdata = data.TryGet("likes") as JsonObject; if (likesdata != null) { LikeCount = Convert.ToInt32(likesdata.TryGet("count") ?? 0); } // comment # var commentsdata = data.TryGet("comments") as JsonObject; if (commentsdata != null) { CommentCount = Convert.ToInt32(commentsdata.TryGet("count") ?? 0); } }
/// <summary> /// Loads data fields of this instance from the given json object /// </summary> internal override void LoadData(JsonObject data) { base.LoadData(data); Name = Convert.ToString(data.TryGet("name") ?? "untitled"); Location = Convert.ToString(data.TryGet("location") ?? ""); Description = Convert.ToString(data.TryGet("description") ?? ""); Count = Convert.ToInt32(data.TryGet("count") ?? 0); }
/// <summary> /// Parse the upload response /// </summary> /// <param name="response">XML</param> /// <returns>FacebookInfo object</returns> public static FacebookInfo FromUploadResponse(JsonObject response) { LOG.DebugFormat("Id: {0} - Post Id: {1}", response["id"], response["post_id"]); FacebookInfo FacebookInfo = new FacebookInfo { Page = string.Format("https://www.facebook.com/photo.php?fbid={0}", response["id"]) }; return FacebookInfo; }
/// <summary> /// Loads data fields of this instance from the given json object /// </summary> internal override void LoadData(JsonObject data) { //base.LoadData(data); // some randome id (will never be used) // need it otherwise the item will be treated as invalid Id = Guid.NewGuid().ToString(); From = Convert.ToString(data["name"]); From_Id = Convert.ToString(data["id"]); }
/// <summary> /// Loads data fields of this instance from the given json object /// </summary> internal override void LoadData(JsonObject data) { base.LoadData(data); Story = Convert.ToString(data["message"]); var fromdata = data["from"] as JsonObject; From = Convert.ToString(fromdata["name"]); From_Id = Convert.ToString(fromdata["id"]); LikeCount = Convert.ToInt32(data.TryGet("likes") ?? 0); }
/// <summary> /// Loads data fields of this instance from the given json object /// </summary> internal override void LoadData(JsonObject data) { base.LoadData(data); Title = Convert.ToString(data["title"]); var fromdata = data["from"] as JsonObject; From = Convert.ToString(fromdata["name"]); From_Id = Convert.ToString(fromdata["id"]); Link = Convert.ToString(data.TryGet("link") ?? ""); Unread = Convert.ToBoolean(data.TryGet("unread") ?? "false"); }
private async void GetUserData(Dictionary <string, string> param) { if (busy) { sendBusyEvent(); } busy = true; try { string path = "/me"; dynamic parameters = new ExpandoObject(); //if (param.Keys.Contains<string>("name")) { parameters.name = param["name"]; } //if (param.Keys.Contains<string>("caption")) { parameters.caption = param["caption"]; } //if (param.Keys.Contains<string>("link")) { parameters.link = param["link"]; } //if (param.Keys.Contains<string>("picture")) { parameters.picture = param["picture"]; } if (param.Keys.Contains <string>("path")) { path = param["path"]; } Facebook.JsonObject result = await _fb.GetTaskAsync(path, parameters); string js = "javascript: var e = document.createEvent('Events');e.initEvent('appMobi.facebook.request.response',true,true);e.success=true;e.raw='" + result.ToString() + "';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}e.error='';document.dispatchEvent(e);"; InjectJS(js); } catch (FacebookApiException ex) { // handle error message if (ex.ErrorCode == 2500) { // user not logged in. ScriptResponse sr = ErrorHandler.setupErrorResponse(ErrorsEnum.E000203); //string js = "(function(){ AppMobi.facebook.internal.handleResponse('request.response',false," + sr.ToJson() + ")})();"; string js = string.Format("javascript: var e = document.createEvent('Events');e.initEvent('appMobi.facebook.request.response',true,true);e.success=false;e.error='{0}';e.raw='';e.data={{}};document.dispatchEvent(e);", sr.Message); InjectJS(js); } else { // user not logged in. ScriptResponse sr = ErrorHandler.setupErrorResponse(ErrorsEnum.E000202); //string js = "(function(){ AppMobi.facebook.internal.handleResponse('request.response',false," + sr.ToJson() + ")})();"; string js = string.Format("javascript: var e = document.createEvent('Events');e.initEvent('appMobi.facebook.request.response',true,true);e.success=false;e.error='{0}';e.raw='';e.data={{}};document.dispatchEvent(e);", sr.Message); InjectJS(js); } } finally { busy = false; } }
public async Task <HttpResponseMessage> SignInWithFacebook(FacebookSignIn model) { if (model == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "No Data")); } if (ModelState.IsValid) { var client = new FacebookClient(model.AccessToken); Facebook.JsonObject me = (Facebook.JsonObject)client.Get("/me?fields=name,first_name,last_name,id,email"); ApplicationUser user = db.Users.Where(x => x.FacebookId == model.UserID).FirstOrDefault(); if (user != null) { user.FacebookToken = model.AccessToken; await db.SaveChangesAsync(); // if (user.FacebookToken == model.AccessToken) { await SignInHelper.SignInAsync(user, true, true); var account = new UserDetail(); account.UserName = user.UserName; account.FirstName = me["first_name"].ToString(); // user.FirstName; account.LastName = user.LastName; account.FacebookId = user.FacebookId; account.isAuthenticated = true; account.Route = user.Route; var rolesForUser = users.GetRoles(user.Id); account.isAdmin = rolesForUser.Contains("Admin"); return(Request.CreateResponse(account)); /* * } else { * return Request.CreateErrorResponse(HttpStatusCode.MethodNotAllowed, "Facebook token differs"); * } * */ } else { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Facebook id not found")); } } return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); }
public object this[string name, Type type] { get { Facebook.JsonObject asJsonObject = (Facebook.JsonObject)(CurrentNode.Current); if (asJsonObject.ContainsKey(name)) { if (type == null) { return(asJsonObject[name]); } return(ConvertPropertyFromJson(name, asJsonObject[name], type)); } else { return(null); } } }
public ProfileInfo(JsonObject ProfileData) { if (ProfileData != null) { if (Verifier.Verify(ProfileData, "picture")) this.PictureUrl = ProfileData["picture"] as String; if (Verifier.Verify(ProfileData, "name")) this.Name = ProfileData["name"] as String; if (Verifier.Verify(ProfileData, "id")) this.ID = ProfileData["id"] as String; if (Verifier.Verify(ProfileData, "first_name")) this.FirstName = ProfileData["first_name"] as String; if (Verifier.Verify(ProfileData, "last_name")) this.LastName = ProfileData["last_name"] as String; //if (Verifier.Verify(ProfileData, "link")) // this.PLink = ProfileData["link"] as String; //if (Verifier.Verify(ProfileData, "gender")) // this.PGender = ProfileData["gender"] as String; //if (Verifier.Verify(ProfileData, "username")) // this.PUsername = ProfileData["username"] as String; //if (Verifier.Verify(ProfileData, "updated_time")) // this.PUpdatedTime = ProfileData["updated_time"] as String; //if (Verifier.Verify(ProfileData, "bio")) // this.PBio = ProfileData["bio"] as String; //if (Verifier.Verify(ProfileData, "birthday")) // this.PBirthday = ProfileData["birthday"] as String; ////this.PAbout = ProfileData["about"] as String; //if (Verifier.Verify(ProfileData, "religion")) // this.PReligion = ProfileData["religion"] as String; //if (PID != null) // PImage = Downloader.FetchImage(PID); //this.PHometown = ProfileData.hometown; //this.PEducation = ProfileData.education; //this.PInterestedIn = ProfileData.interested_in; //this.PLocation = ProfileData.location; //this.PPicture = ProfileData.id; } }
/// <summary> /// Loads data fields of this instance from the given json object /// </summary> internal override void LoadData(JsonObject data) { base.LoadData(data); // from? var fromdata = data["from"] as JsonObject; From = Convert.ToString(fromdata["name"]); From_Id = Convert.ToString(fromdata["id"]); Name = Convert.ToString(data.TryGet("name") ?? "untitled"); ImageHeight = Convert.ToInt32(data["height"]); ImageWidth = Convert.ToInt32(data["width"]); // tags var tagsdata = data.TryGet("tags") as JsonObject; if (tagsdata != null) { TaggedUsers = (tagsdata["data"] as List<object>).Select(o => FBEntity.Parse<User>(o as JsonObject)).ToList(); } else { TaggedUsers = new List<User>(); } }
public async Task <HttpResponseMessage> SignOut() { try { var user = await users.FindByNameAsync(User.Identity.Name); if (user != null) { try { var client = new FacebookClient(user.FacebookToken); Facebook.JsonObject response = (Facebook.JsonObject)client.Delete("/me/permissions"); } catch (Exception ex) { // null } } AuthenticationManager.SignOut(); var account = new UserDetail(); account.isAuthenticated = false; return(Request.CreateResponse(account)); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } }
private static void RecursiveObjectToString(JsonObject obj, StringBuilder sb, int level) { if (obj.IsDictionary) { sb.AppendLine(); RecursiveDictionaryToString(obj, sb, level + 1); } else if (obj.IsArray) { foreach (JsonObject o in obj.Array) { RecursiveObjectToString(o, sb, level); sb.AppendLine(); } } else // some sort of scalar value { sb.Append(obj.String); } }
/// <summary> /// Recursively constructs this JSONObject /// </summary> internal static JsonObject Create(object o, CultureInfo ci) { var obj = new JsonObject(ci); object[] objArray; Dictionary<string, object> dict; Dictionary<string, string> sdict; NameValueCollection nvc; if ((objArray = o as object[]) != null) { obj._arrayData = new JsonObject[objArray.Length]; for (int i = 0; i < obj._arrayData.Length; ++i) { obj._arrayData[i] = Create(objArray[i], ci); } } else if ((dict = o as Dictionary<string, object>) != null) { obj._dictData = new Dictionary<string, JsonObject>(dict.Count); foreach (string key in dict.Keys) { obj._dictData[key] = Create(dict[key], ci); } } else if ((sdict = o as Dictionary<string, string>) != null) { obj._dictData = new Dictionary<string, JsonObject>(sdict.Count); foreach (string key in sdict.Keys) { obj._dictData[key] = new JsonObject(ci) { _stringData = sdict[key] }; } } else if ((nvc = o as NameValueCollection) != null) { obj._dictData = new Dictionary<string, JsonObject>(nvc.Count); foreach (string key in nvc) { obj._dictData[key] = new JsonObject(ci) { _stringData = nvc[key] }; } } else if (o != null) // o is a scalar { obj._stringData = o.ToString(); } return obj; }
public CanvasModule(IFacebookApplication fbApp, FacebookClient fb) { this.HandleFacebookOAuthDialogError(fbApp.AppId, scope: "user_about_me,read_stream"); this.DropFacebookQueryStrings(); Post["/"] = _ => { var canvasPageUrl = Context.FacebookCanvasPageUrl(fbApp.CanvasPage); return View["index", canvasPageUrl]; }; Post["/feed"] = _ => { var perms = Context.FacebooPermissions(); if (!perms.Intersect(new[] { "user_about_me", "read_stream" }).Any()) return Response.AsFacebookLogin(fbApp.AppId, scope: "user_about_me,read_stream"); dynamic model = new JsonObject(); model.canvasPageUrl = Context.FacebookCanvasPageUrl(fbApp.CanvasPage); model.facebookLoginUrl = Context.FacebookLoginUrl(fbApp.AppId, scope: "user_about_me,read_stream"); if (perms.Contains("user_about_me")) { dynamic result = fb.Get("me?fields=picture,name"); model.name = result.name; model.picture = result.picture; } if (perms.Contains("read_stream")) { dynamic result = fb.Get("me/feed"); model.feeds = result; } return View["Feed", model]; }; Post["/feed/batch"] = _ => { var perms = Context.FacebooPermissions(); if (!perms.Intersect(new[] { "user_about_me", "read_stream" }).Any()) return Response.AsFacebookLogin(fbApp.AppId, scope: "user_about_me,read_stream"); dynamic model = new JsonObject(); model.canvasPageUrl = Context.FacebookCanvasPageUrl(fbApp.CanvasPage); model.facebookLoginUrl = Context.FacebookLoginUrl(fbApp.AppId, scope: "user_about_me,read_stream"); var bp = new Dictionary<string, Tuple<int, FacebookBatchParameter>>(); int bpi = 0; if (perms.Contains("user_about_me")) bp.Add("me", new Tuple<int, FacebookBatchParameter>(bpi++, new FacebookBatchParameter("me?fields=picture,name"))); if (perms.Contains("read_stream")) bp.Add("feeds", new Tuple<int, FacebookBatchParameter>(bpi++, new FacebookBatchParameter("me/feed"))); dynamic result = fb.Batch(bp.Values.Select(t => t.Item2).ToArray()); if (bp.ContainsKey("me")) { dynamic me = result[bp["me"].Item1]; if (!(me is Exception)) { model.name = me.name; model.picture = me.picture; } } if (bp.ContainsKey("feeds")) { dynamic feeds = result[bp["feeds"].Item1]; if (!(feeds is Exception)) model.feeds = feeds; } return View["Feed", model]; }; }
/// <summary> /// Parse the signed request string. /// </summary> /// <param name="secret"> /// The secret. /// </param> /// <param name="signedRequestValue"> /// The signed request value. /// </param> /// <param name="maxAge"> /// The max age. /// </param> /// <param name="currentTime"> /// The current time. /// </param> /// <param name="throws"> /// The throws. /// </param> /// <returns> /// The FacebookSignedRequest. /// </returns> internal static IDictionary<string, object> TryParse(string secret, string signedRequestValue, int maxAge, double currentTime, bool throws) { Contract.Requires(!String.IsNullOrEmpty(signedRequestValue)); Contract.Requires(!String.IsNullOrEmpty(secret)); Contract.Requires(maxAge >= 0); Contract.Requires(currentTime >= 0); Contract.Requires(signedRequestValue.Contains("."), Properties.Resources.InvalidSignedRequest); try { // NOTE: currentTime added to parameters to make it unit testable. string[] split = signedRequestValue.Split('.'); if (split.Length != 2) { // need to have exactly 2 parts throw new InvalidOperationException(Properties.Resources.InvalidSignedRequest); } string encodedSignature = split[0]; string encodedEnvelope = split[1]; if (string.IsNullOrEmpty(encodedSignature)) { throw new InvalidOperationException(Properties.Resources.InvalidSignedRequest); } if (string.IsNullOrEmpty(encodedEnvelope)) { throw new InvalidOperationException(Properties.Resources.InvalidSignedRequest); } var envelope = (IDictionary<string, object>)JsonSerializer.Current.DeserializeObject(Encoding.UTF8.GetString(FacebookUtils.Base64UrlDecode(encodedEnvelope))); string algorithm = (string)envelope["algorithm"]; if (!algorithm.Equals("AES-256-CBC HMAC-SHA256") && !algorithm.Equals("HMAC-SHA256")) { // TODO: test throw new InvalidOperationException("Invalid signed request. (Unsupported algorithm)"); } byte[] key = Encoding.UTF8.GetBytes(secret); byte[] digest = FacebookUtils.ComputeHmacSha256Hash(Encoding.UTF8.GetBytes(encodedEnvelope), key); if (!digest.SequenceEqual(FacebookUtils.Base64UrlDecode(encodedSignature))) { throw new InvalidOperationException(Facebook.Web.Properties.Resources.InvalidSignedRequestSignature); } IDictionary<string, object> result; if (algorithm.Equals("HMAC-SHA256")) { // for requests that are signed, but not encrypted, we're done result = envelope; } else { result = new JsonObject(); result["algorithm"] = algorithm; long issuedAt = (long)envelope["issued_at"]; if (issuedAt < currentTime) { throw new InvalidOperationException(Web.Properties.Resources.OldSignedRequest); } result["issued_at"] = issuedAt; // otherwise, decrypt the payload byte[] iv = FacebookUtils.Base64UrlDecode((string)envelope["iv"]); byte[] rawCipherText = FacebookUtils.Base64UrlDecode((string)envelope["payload"]); var plainText = FacebookUtils.DecryptAes256CBCNoPadding(rawCipherText, key, iv); var payload = (IDictionary<string, object>)JsonSerializer.Current.DeserializeObject(plainText); result["payload"] = payload; } return result; } catch { if (throws) { throw; } return null; } }
private Message CreateVideoMessage(JsonObject jsonData) { FacebookMessage msg = new FacebookMessage(); string text = "<br />"; if (jsonData.ContainsKey("message")) { text += HttpUtility.HtmlEncode((string)jsonData["message"]); text += "<br /><br />"; } text += String.Format("<a href='{0}' target='_blank'><img src='{1}' /></a><br /><br />", jsonData["link"].ToString(), jsonData["picture"].ToString()); msg.Text = text; msg.PostedOn = Convert.ToDateTime(jsonData["updated_time"].ToString()); msg.Source = SocialNetworks.Facebook; JsonObject jsonUser = (JsonObject)(jsonData["from"]); msg.UserName = jsonUser["name"].ToString(); msg.UserImageUrl = String.Format("http://graph.facebook.com/{0}/picture?type=small", jsonUser["id"]); return msg; }
internal static void ThrowIfError(JsonObject obj) { if (obj.Dictionary.ContainsKey("error")) throw new FacebookApiException( obj.Dictionary["error"].Dictionary["type"].String, obj.Dictionary["error"].Dictionary["message"].String); if (obj.Dictionary.ContainsKey("error_code")) throw new FacebookApiException( obj.Dictionary["error_code"].String, obj.Dictionary["error_msg"].String); }
/// <summary> /// Loads data fields of this instance from the given json object /// </summary> internal override void LoadData(JsonObject data) { base.LoadData(data); Name = Convert.ToString(data["name"]); }
Session ValidateSession(JsonObject data) { if (!data.IsDictionary) throw new ArgumentException("Should be a dictionary", "data"); Session session = null; if (data.IsDictionary && data.Dictionary.ContainsKey("uid") && data.Dictionary.ContainsKey("access_token") && data.Dictionary.ContainsKey("sig")) { string expectedSignature = GenerateSignature(data); if (expectedSignature != data.Dictionary["sig"].String) throw new FacebookApiException("Canvas", "Unexpected signature"); return Session.FromJsonObject(data); } return session; }
public ICollection <string> GetCurrentKeys() { Facebook.JsonObject asJsonObject = (Facebook.JsonObject)(CurrentNode.Current); return(asJsonObject.Keys); }
protected virtual void ApiAsync(HttpMethod httpMethod, string path, object parameters, Type resultType, object userState) { Stream input; bool containsEtag; IList<int> batchEtags = null; var httpHelper = PrepareRequest(httpMethod, path, parameters, resultType, out input, out containsEtag, out batchEtags); _httpWebRequest = httpHelper.HttpWebRequest; #if FLUENTHTTP_CORE_TPL if (HttpWebRequestWrapperCreated != null) HttpWebRequestWrapperCreated(this, new HttpWebRequestCreatedEventArgs(userState, httpHelper.HttpWebRequest)); #endif var uploadProgressChanged = UploadProgressChanged; bool notifyUploadProgressChanged = uploadProgressChanged != null && httpHelper.HttpWebRequest.Method == "POST"; httpHelper.OpenReadCompleted += (o, e) => { FacebookApiEventArgs args; if (e.Cancelled) { args = new FacebookApiEventArgs(e.Error, true, userState, null); } else if (e.Error == null) { string responseString = null; try { using (var stream = e.Result) { #if NETFX_CORE bool compressed = false; var contentEncoding = httpHelper.HttpWebResponse.Headers.AllKeys.Contains("Content-Encoding") ? httpHelper.HttpWebResponse.Headers["Content-Encoding"] : null; if (contentEncoding != null) { if (contentEncoding.IndexOf("gzip") != -1) { using (var uncompressedStream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress)) { using (var reader = new StreamReader(uncompressedStream)) { responseString = reader.ReadToEnd(); } } compressed = true; } else if (contentEncoding.IndexOf("deflate") != -1) { using (var uncompressedStream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress)) { using (var reader = new StreamReader(uncompressedStream)) { responseString = reader.ReadToEnd(); } } compressed = true; } } if (!compressed) { using (var reader = new StreamReader(stream)) { responseString = reader.ReadToEnd(); } } #else var response = httpHelper.HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.NotModified) { var jsonObject = new JsonObject(); var headers = new JsonObject(); foreach (var headerName in response.Headers.AllKeys) headers[headerName] = response.Headers[headerName]; jsonObject["headers"] = headers; args = new FacebookApiEventArgs(null, false, userState, jsonObject); OnCompleted(httpMethod, args); return; } using (var reader = new StreamReader(stream)) { responseString = reader.ReadToEnd(); } #endif } try { object result = ProcessResponse(httpHelper, responseString, resultType, containsEtag, batchEtags); args = new FacebookApiEventArgs(null, false, userState, result); } catch (Exception ex) { args = new FacebookApiEventArgs(ex, false, userState, null); } } catch (Exception ex) { args = httpHelper.HttpWebRequest.IsCancelled ? new FacebookApiEventArgs(ex, true, userState, null) : new FacebookApiEventArgs(ex, false, userState, null); } } else { var webEx = e.Error as WebExceptionWrapper; if (webEx == null) { args = new FacebookApiEventArgs(e.Error, httpHelper.HttpWebRequest.IsCancelled, userState, null); } else { if (webEx.GetResponse() == null) { args = new FacebookApiEventArgs(webEx, false, userState, null); } else { var response = httpHelper.HttpWebResponse; if (response.StatusCode == HttpStatusCode.NotModified) { var jsonObject = new JsonObject(); var headers = new JsonObject(); foreach (var headerName in response.Headers.AllKeys) headers[headerName] = response.Headers[headerName]; jsonObject["headers"] = headers; args = new FacebookApiEventArgs(null, false, userState, jsonObject); } else { httpHelper.OpenReadAsync(); return; } } } } OnCompleted(httpMethod, args); }; if (input == null) { httpHelper.OpenReadAsync(); } else { // we have a request body so write httpHelper.OpenWriteCompleted += (o, e) => { FacebookApiEventArgs args; if (e.Cancelled) { input.Dispose(); args = new FacebookApiEventArgs(e.Error, true, userState, null); } else if (e.Error == null) { try { using (var stream = e.Result) { // write input to requestStream var buffer = new byte[BufferSize]; int nread; if (notifyUploadProgressChanged) { long totalBytesToSend = input.Length; long bytesSent = 0; while ((nread = input.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, nread); stream.Flush(); // notify upload progress changed bytesSent += nread; OnUploadProgressChanged(new FacebookUploadProgressChangedEventArgs(0, 0, bytesSent, totalBytesToSend, ((int)(bytesSent * 100 / totalBytesToSend)), userState)); } } else { while ((nread = input.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, nread); stream.Flush(); } } } httpHelper.OpenReadAsync(); return; } catch (Exception ex) { args = new FacebookApiEventArgs(ex, httpHelper.HttpWebRequest.IsCancelled, userState, null); } finally { input.Dispose(); } } else { input.Dispose(); var webExceptionWrapper = e.Error as WebExceptionWrapper; if (webExceptionWrapper != null) { var ex = webExceptionWrapper; if (ex.GetResponse() != null) { httpHelper.OpenReadAsync(); return; } } args = new FacebookApiEventArgs(e.Error, false, userState, null); } OnCompleted(httpMethod, args); }; httpHelper.OpenWriteAsync(); } }
private Message CreateStatusMessage(JsonObject jsonData) { FacebookMessage msg = new FacebookMessage(); msg.Text = HttpUtility.HtmlEncode((string)jsonData["message"]); msg.PostedOn = Convert.ToDateTime(jsonData["updated_time"].ToString()); msg.Source = SocialNetworks.Facebook; JsonObject jsonUser = (JsonObject)(jsonData["from"]); msg.UserName = jsonUser["name"].ToString(); msg.UserImageUrl = String.Format("http://graph.facebook.com/{0}/picture?type=small", jsonUser["id"]); return msg; }
private static void RecursiveDictionaryToString(JsonObject obj, StringBuilder sb, int level) { foreach (KeyValuePair<string, JsonObject> kvp in obj.Dictionary) { sb.Append(' ', level * 2); sb.Append(kvp.Key); sb.Append(" => "); RecursiveObjectToString(kvp.Value, sb, level); sb.AppendLine(); } }
/// <summary> /// Makes a request to the Facebook server. /// </summary> /// <param name="httpMethod">Http method. (GET/POST/DELETE)</param> /// <param name="path">The resource path or the resource url.</param> /// <param name="parameters">The parameters.</param> /// <param name="resultType">The type of deserialize object into.</param> /// <returns>The json result.</returns> protected virtual object Api(HttpMethod httpMethod, string path, object parameters, Type resultType) { Stream input; bool containsEtag; IList<int> batchEtags; var httpHelper = PrepareRequest(httpMethod, path, parameters, resultType, out input, out containsEtag, out batchEtags); if (input != null) { try { using (var stream = httpHelper.OpenWrite()) { // write input to requestStream var buffer = new byte[BufferSize]; while (true) { int bytesRead = input.Read(buffer, 0, buffer.Length); input.Flush(); if (bytesRead <= 0) break; stream.Write(buffer, 0, bytesRead); stream.Flush(); } } } catch (WebExceptionWrapper ex) { if (ex.GetResponse() == null) throw; } finally { input.Dispose(); } } Stream responseStream = null; object result = null; bool read = false; try { responseStream = httpHelper.OpenRead(); read = true; } catch (WebExceptionWrapper ex) { var response = ex.GetResponse(); if (response == null) throw; if (response.StatusCode == HttpStatusCode.NotModified) { var jsonObject = new JsonObject(); var headers = new JsonObject(); foreach (var headerName in response.Headers.AllKeys) headers[headerName] = response.Headers[headerName]; jsonObject["headers"] = headers; result = jsonObject; } else { responseStream = httpHelper.OpenRead(); read = true; } } finally { if (read) { string responseString; using (var stream = responseStream) { using (var reader = new StreamReader(stream)) { responseString = reader.ReadToEnd(); } } result = ProcessResponse(httpHelper, responseString, resultType, containsEtag, batchEtags); } } return result; }
private object ProcessResponse(HttpHelper httpHelper, string responseString, Type resultType, bool containsEtag, IList<int> batchEtags) { try { object result = null; if (httpHelper == null) { // batch row result = DeserializeJson(responseString, resultType); } else { var response = httpHelper.HttpWebResponse; if (response == null) throw new InvalidOperationException(UnknownResponse); if (response.ContentType.Contains("text/javascript") || response.ContentType.Contains("application/json")) { result = DeserializeJson(responseString, resultType); } else if (response.StatusCode == HttpStatusCode.OK && response.ContentType.Contains("text/plain")) { if (response.ResponseUri.AbsolutePath == "/oauth/access_token") { var body = new JsonObject(); foreach (var kvp in responseString.Split('&')) { var split = kvp.Split('='); if (split.Length == 2) body[split[0]] = split[1]; } if (body.ContainsKey("expires")) body["expires"] = Convert.ToInt64(body["expires"]); result = resultType == null ? body : DeserializeJson(body.ToString(), resultType); return result; } else { throw new InvalidOperationException(UnknownResponse); } } else { throw new InvalidOperationException(UnknownResponse); } } var exception = GetException(httpHelper, result); if (exception == null) { if (containsEtag && httpHelper != null) { var json = new JsonObject(); var response = httpHelper.HttpWebResponse; var headers = new JsonObject(); foreach (var headerName in response.Headers.AllKeys) headers[headerName] = response.Headers[headerName]; json["headers"] = headers; json["body"] = result; return json; } return batchEtags == null ? result : ProcessBatchResponse(result, batchEtags); } throw exception; } catch (FacebookApiException) { throw; } catch (Exception) { if (httpHelper != null && httpHelper.InnerException != null) throw httpHelper.InnerException; throw; } }
private static void LoginNavigationStarted(Uri url, object state) { FacebookOAuthResult result; // Check if we're waiting for user input or if login is complete if (_client.TryParseOAuthCallbackUrl(url, out result)) { // Login complete if (result.IsSuccess) { AccessToken = result.AccessToken; Expires = result.Expires; _client.AccessToken = AccessToken; Settings.Set(TOKEN_KEY, EncryptionProvider.Encrypt(AccessToken, AppId)); Settings.Set(EXPIRY_DATE_BIN, Expires.ToBinary()); } _web.Finish(); if (_onHideUnity != null) { _onHideUnity(false); } API("/me?fields=id,name", HttpMethod.GET, fbResult => { if (IsLoggedIn) { UserId = fbResult.Json["id"] as string; UserName = fbResult.Json["name"] as string; Settings.Set(FBID_KEY, UserId); Settings.Set(FBNAME_KEY, UserName); } if (state is FacebookDelegate) { JsonObject jResult = new JsonObject(); jResult.Add(new KeyValuePair<string, object>("authToken", AccessToken)); jResult.Add(new KeyValuePair<string, object>("authTokenExpiry", Expires.ToString())); ((FacebookDelegate)state)(new FBResult() { Json = jResult, Text = jResult.ToString() }); } }); } }
/// <exception cref="FacebookApiException"></exception> JsonObject GetSignedRequest(NameValueCollection request) { if (_signedRequest != null) return _signedRequest; String srStr = request["signed_request"]; if (String.IsNullOrEmpty(srStr)) return null; return _signedRequest = ParseSignedRequest(srStr); }
private List<Message> MapMessage(JsonObject jsonData) { List<Message> messages = new List<Message>(); JsonArray data = (JsonArray)jsonData["data"]; foreach (JsonObject jsonMsg in data) { string messageType = (string)jsonMsg["type"]; switch (messageType) { case Status: messages.Add(CreateStatusMessage(jsonMsg)); break; case Link: messages.Add(CreateLinkMessage(jsonMsg)); break; case Photo: messages.Add(CreatePhotoMessage(jsonMsg)); break; case Video: messages.Add(CreateVideoMessage(jsonMsg)); break; default: break; } } return messages; }
Session ToFacebookSession(JsonObject data) { if (!data.Dictionary.ContainsKey("oauth_token")) return null; var expires = data.Dictionary["expires"].Integer; var sess = new Session { UserId = data.Dictionary["user_id"].Integer, OAuthToken = data.Dictionary["oauth_token"].String, // if user granted 'offline_access' permission, the 'expires' value is 0. Expires = expires == 0 ? DateTime.MaxValue : s_unixStart.AddSeconds(expires), }; sess.Signature = GenerateSignature(sess.ToJsonObject()); return sess; }
/// <summary> /// Returns a <see cref="FacebookBatchParameter"/> representing FQL multi-query. /// </summary> /// <param name="fql"> /// The fql queries. /// </param> /// <returns> /// The <see cref="FacebookBatchParameter"/>. /// </returns> public FacebookBatchParameter Query(params string[] fql) { Contract.Requires(fql != null); var queryDict = new JsonObject(); for (int i = 0; i < fql.Length; i++) { queryDict.Add(string.Concat("query", i), fql[i]); } HttpMethod = HttpMethod.Get; Path = "/method/fql.multiquery"; Parameters = new JsonObject { { "queries", queryDict } }; return this; }
//public void getPageImpresion(string pageId, Guid UserId, int days) //{ // try // { // string strAge = "https://graph.facebook.com/" + pageId + "/insights/page_impressions/day"; // FacebookClient fb = new FacebookClient(); // FacebookAccountRepository fbAccRepo = new FacebookAccountRepository(); // FacebookAccount acc = fbAccRepo.getUserDetails(pageId); // fb.AccessToken = acc.AccessToken; // JsonObject outputreg = (JsonObject)fb.Get(strAge); // JArray data = (JArray)JsonConvert.DeserializeObject(outputreg["data"].ToString()); // FacebookInsightStats objFbi = new FacebookInsightStats(); // FacebookInsightStatsRepository objfbiRepo = new FacebookInsightStatsRepository(); // foreach (var item in data) // { // var values = item["values"]; // foreach (var age in values) // { // objFbi.EntryDate = DateTime.Now; // objFbi.FbUserId = pageId; // objFbi.Id = Guid.NewGuid(); // objFbi.PageImpressionCount = int.Parse(age["value"].ToString()); // objFbi.UserId = UserId; // objFbi.CountDate = age["end_time"].ToString(); // if (!objfbiRepo.checkFbIPageImprStatsExists(pageId, UserId, age["end_time"].ToString())) // objfbiRepo.addFacebookInsightStats(objFbi); // else // objfbiRepo.updateFacebookInsightStats(objFbi); // } // } // } // catch (Exception Err) // { // Console.Write(Err.StackTrace); // } //} public void getPageImpresion(string pageId, Guid UserId, int days) { JsonObject outputreg = new JsonObject(); try { int count = 0; string nextpage = string.Empty; string prevpage = string.Empty; string strAge = string.Empty; if (count == 0) { strAge = "https://graph.facebook.com/" + pageId + "/insights/page_impressions/day"; } else { strAge = prevpage; } FacebookClient fb = new FacebookClient(); FacebookAccountRepository fbAccRepo = new FacebookAccountRepository(); for (int i = 0; i < 11; i++) { if (count > 0) { strAge = prevpage; } FacebookAccount acc = fbAccRepo.getUserDetails(pageId); fb.AccessToken = acc.AccessToken; outputreg = (JsonObject)fb.Get(strAge); JArray data = (JArray)JsonConvert.DeserializeObject(outputreg["data"].ToString()); //code written by abhay JObject data1 = (JObject)JsonConvert.DeserializeObject(outputreg["paging"].ToString()); if (count == 0) { prevpage = data1["previous"].ToString(); nextpage = data1["next"].ToString(); //End of block FacebookInsightStats objFbi = new FacebookInsightStats(); FacebookInsightStatsRepository objfbiRepo = new FacebookInsightStatsRepository(); foreach (var item in data) { var values = item["values"]; foreach (var age in values) { //objFbi.EntryDate = DateTime.Now; objFbi.EntryDate = Convert.ToDateTime(age["end_time"].ToString()); objFbi.FbUserId = pageId; objFbi.Id = Guid.NewGuid(); objFbi.PageImpressionCount = int.Parse(age["value"].ToString()); objFbi.UserId = UserId; objFbi.CountDate = age["end_time"].ToString(); if (!objfbiRepo.checkFbIPageImprStatsExists(pageId, UserId, age["end_time"].ToString())) objfbiRepo.addFacebookInsightStats(objFbi); else objfbiRepo.updateFacebookInsightStats(objFbi); } } count++; } else { count++; prevpage = data1["previous"].ToString(); // nextpage = data1["next"].ToString(); //End of block FacebookInsightStats objFbi = new FacebookInsightStats(); FacebookInsightStatsRepository objfbiRepo = new FacebookInsightStatsRepository(); foreach (var item in data) { var values = item["values"]; foreach (var age in values) { //objFbi.EntryDate = DateTime.Now; objFbi.EntryDate = Convert.ToDateTime(age["end_time"].ToString()); objFbi.FbUserId = pageId; objFbi.Id = Guid.NewGuid(); objFbi.PageImpressionCount = int.Parse(age["value"].ToString()); objFbi.UserId = UserId; objFbi.CountDate = age["end_time"].ToString(); if (!objfbiRepo.checkFbIPageImprStatsExists(pageId, UserId, age["end_time"].ToString())) objfbiRepo.addFacebookInsightStats(objFbi); else objfbiRepo.updateFacebookInsightStats(objFbi); } } } } outputreg = (JsonObject)fb.Get(nextpage); JArray newdata = (JArray)JsonConvert.DeserializeObject(outputreg["data"].ToString()); JObject newdata1 = (JObject)JsonConvert.DeserializeObject(outputreg["paging"].ToString()); FacebookInsightStats objFbi1 = new FacebookInsightStats(); FacebookInsightStatsRepository objfbiRepo1 = new FacebookInsightStatsRepository(); foreach (var item in newdata) { var values = item["values"]; foreach (var age in values) { //objFbi1.EntryDate = DateTime.Now; objFbi1.EntryDate = Convert.ToDateTime(age["end_time"].ToString()); objFbi1.FbUserId = pageId; objFbi1.Id = Guid.NewGuid(); objFbi1.PageImpressionCount = int.Parse(age["value"].ToString()); objFbi1.UserId = UserId; objFbi1.CountDate = age["end_time"].ToString(); if (Convert.ToDateTime(age["end_time"].ToString()) > DateTime.Now) break; if (!objfbiRepo1.checkFbIPageImprStatsExists(pageId, UserId, age["end_time"].ToString())) objfbiRepo1.addFacebookInsightStats(objFbi1); else objfbiRepo1.updateFacebookInsightStats(objFbi1); } } } catch (Exception Err) { Console.Write(Err.StackTrace); } }
/// <summary> /// Returns a <see cref="FacebookBatchParameter"/> representing FQL query. /// </summary> /// <param name="fql"> /// The fql query. /// </param> /// <returns> /// The <see cref="FacebookBatchParameter"/>. /// </returns> public FacebookBatchParameter Query(string fql) { Contract.Requires(!string.IsNullOrEmpty(fql)); HttpMethod = HttpMethod.Get; Path = "/method/fql.query"; Parameters = new JsonObject { { "query", fql } }; return this; }