Пример #1
0
        public static Todo ParseJson(JToken json)
        {
            Todo   todo = new Todo();
            string id   = Json.TryGetJsonProperty(json, "id");

            string created = Json.TryGetJsonProperty(json, "createdAt");

            if (created != null)
            {
                DateTime dtc = UnixDate.ToDateTime(created);
                //t.CreatedDateTime = dtc;
                todo.Created = Checkin.GetDateString(dtc);
            }

            var tipJson = json["tip"];

            if (tipJson != null)
            {
                var tip = Tip.ParseJson(tipJson);
                if (tip != null)
                {
                    if (todo.Created != null)
                    {
                        tip.OverrideAddedText = "added " + todo.Created + (
                            tip.User != null ? (" (via " + tip.User.ToString() + ")") : string.Empty);
                    }

                    todo.Tip = tip;
                }
            }

            todo.TodoId = id;

            return(todo);
        }
Пример #2
0
        public static Comment ParseJson(JToken json)
        {
            var comment = new Comment();

            comment.Id = Json.TryGetJsonProperty(json, "id");
            Debug.Assert(comment.Id != null);

            comment.User = CompactUser.ParseJson(json["user"]);

            comment.Text = Json.TryGetJsonProperty(json, "text");

            if (comment.User != null)
            {
                comment.IsSelf = comment.User.Relationship == FriendStatus.Self;
            }

            string created = Json.TryGetJsonProperty(json, "createdAt");

            if (created != null)
            {
                DateTime dtc = UnixDate.ToDateTime(created);
                comment.CreatedDateTime = dtc;
                comment.Created         = Checkin.GetDateString(dtc);
            }

            return(comment);
        }
Пример #3
0
            protected override object DeserializeCore(JObject json, Type objectType, LoadContext context)
            {
                try
                {
                    var b = new UserCheckins(context);

                    var sets = json["checkins"];
                    if (sets != null)
                    {
                        var items = sets["items"];
                        if (items != null)
                        {
                            var list = new List <Checkin>();
                            foreach (var s in items)
                            {
                                Checkin c = Checkin.ParseJson(s);
                                list.Add(c);
                            }
                            b.Recent = list;
                        }
                    }

                    b.IsLoadComplete = true;

                    return(b);
                }
                catch (Exception e)
                {
                    throw new UserIntendedException(
                              "There was a problem trying to read the list of your recent check-ins.", e);
                }
            }
Пример #4
0
        public static Update ParseJson(JToken update)
        {
            Update u = new Update();

            string created = Json.TryGetJsonProperty(update, "createdAt");

            if (created != null)
            {
                int i;
                if (int.TryParse(created, out i))
                {
                    u.CreatedAt = i;
                }

                // FUTURE: Consider an option to NOT include people in the checkin list who have not checked in within the last month. (perf default!)
                DateTime dtc = UnixDate.ToDateTime(created);
                u.CreatedDateTime = dtc;
                u.Created         = Checkin.GetDateString(dtc);
            }

            // unread
            u.IsUnread = Json.TryGetJsonBool(update, "unread");

            // ids
            var idj = update["ids"];

            if (idj != null)
            {
                u.Ids = idj.Values <string>().ToList();
            }

            // target
            var targetJson = update["target"];

            if (targetJson != null)
            {
                u.TargetObject = TargetObject.ParseJson(targetJson);
            }

            // text
            u.Text = Json.TryGetJsonProperty(update, "text");

            // entities

            // image
            var img = update["image"];

            if (img != null)
            {
                u.FullImage = Json.TryGetUriProperty(img, "fullPath");
            }

            // imageType

            // [icon]

            return(u);
        }
Пример #5
0
        private static object HydrateCompactObject(TargetObjectType type, JToken item)
        {
            try
            {
                if (item != null)
                {
                    switch (type)
                    {
                    case TargetObjectType.Badge:
                        return(Badge.ParseJson(item));

                    case TargetObjectType.Checkin:
                        return(Checkin.ParseJson(item));

                    case TargetObjectType.Special:
                        // VenueId, if null, must be parsed out of the
                        // notification or else it will throw. FYI.
                        return(CompactSpecial.ParseJson(item, null));

                    case TargetObjectType.Tip:
                        return(Tip.ParseJson(item));

                    case TargetObjectType.Url:
                        Uri uri = Json.TryGetUriProperty(item, "url");
                        return(uri);

                    case TargetObjectType.User:
                        return(CompactUser.ParseJson(item));

                    case TargetObjectType.Venue:
                        return(CompactVenue.ParseJson(item));

                    default:
                        break;
                    }
                }
            }
            catch (Exception)
            {
            }

            return(null);
        }
        // TODO: Scores and total from this entry... see how official app does it.


        public LeaderboardNotification(JToken item)
        {
            Message = Checkin.SanitizeString(Json.TryGetJsonProperty(item, "message"));

            var leaders = new List <LeaderboardItem>();
            var lj      = item["leaderboard"];

            if (lj != null)
            {
                foreach (var victor in lj)
                {
                    var wolverine = LeaderboardItem.ParseJson(victor);
                    if (wolverine != null)
                    {
                        leaders.Add(wolverine);
                    }
                }
            }

            Leaderboard = leaders;
        }
Пример #7
0
            protected override object DeserializeCore(JObject json, Type objectType, LoadContext context)
            {
                try
                {
                    var u = new User(context);
                    u.IgnoreRaisingPropertyChanges = true;

                    var user = json["user"];

                    string uid = Json.TryGetJsonProperty(user, "id");
                    u.UserId = uid;

                    u.First = Json.TryGetJsonProperty(user, "firstName");
                    u.Last  = Json.TryGetJsonProperty(user, "lastName");
#if DEMO
                    if (u.Last != null && u.Last.Length > 0)
                    {
                        u.Last = u.Last.Substring(0, 1);
                    }
#endif
                    u.Pings = Json.TryGetJsonBool(user, "pings");

                    u.HomeCity = Json.TryGetJsonProperty(user, "homeCity");

                    var contact = user["contact"];
                    if (contact != null)
                    {
                        u.Phone    = FormatSimpleUnitedStatesPhoneNumberMaybe(Json.TryGetJsonProperty(contact, "phone"));
                        u.Email    = Json.TryGetJsonProperty(contact, "email");
                        u.Twitter  = Json.TryGetJsonProperty(contact, "twitter");
                        u.Facebook = Json.TryGetJsonProperty(contact, "facebook");
#if DEMO
                        if (!string.IsNullOrEmpty(u.Phone))
                        {
                            u.Phone = "(206) 555-1212";
                        }
                        if (!string.IsNullOrEmpty(u.Email))
                        {
                            u.Email = "*****@*****.**";
                        }
#endif
                    }

                    u.FriendStatus = GetFriendStatus(Json.TryGetJsonProperty(user, "relationship"));

                    u.MayorshipsLocalUri     = new Uri(string.Format(CultureInfo.InvariantCulture, "/JeffWilcox.FourthAndMayor.Profile;component/ProfileMayorships.xaml?id={0}", uid), UriKind.Relative);
                    u.BadgesLocalUri         = new Uri(string.Format(CultureInfo.InvariantCulture, "/JeffWilcox.FourthAndMayor.Profile;component/ProfileBadges.xaml?id={0}", uid), UriKind.Relative);
                    u.TipsLocalUri           = new Uri(string.Format(CultureInfo.InvariantCulture, "/JeffWilcox.FourthAndMayor.Profile;component/ProfileTips.xaml?id={0}", uid), UriKind.Relative);
                    u.RecentCheckinsLocalUri = new Uri(string.Format(CultureInfo.InvariantCulture, "/JeffWilcox.FourthAndMayor.Profile;component/ProfileCheckins.xaml?id={0}", uid), UriKind.Relative);
                    u.TopCategoriesLocalUri  = new Uri(string.Format(CultureInfo.InvariantCulture, "/JeffWilcox.FourthAndMayor.Profile;component/ProfileMostExploredCategories.xaml?id={0}", uid), UriKind.Relative);
                    u.TopPlacesLocalUri      = new Uri(string.Format(CultureInfo.InvariantCulture, "/JeffWilcox.FourthAndMayor.Profile;component/ProfileTopPlaces.xaml?id={0}", uid), UriKind.Relative);
                    u.FriendListLocalUri     = new Uri(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "/JeffWilcox.FourthAndMayor.Profile;component/ProfileFriends.xaml?id={0}&self={1}",
                            uid,
                            u.FriendStatus == FriendStatus.Self ? "1" : string.Empty
                            ),
                        UriKind.Relative);

                    u.FriendRequestsLocalUri = new Uri(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "/JeffWilcox.FourthAndMayor.Profile;component/ProfileFriends.xaml?id={0}&requests=please&self={1}",
                            uid,
                            u.FriendStatus == FriendStatus.Self ? "1" : string.Empty
                            ),
                        UriKind.Relative);

                    string uri = Json.TryGetJsonProperty(user, "photo");
                    if (uri != null)
                    {
                        if (!uri.Contains(".gif"))
                        {
                            u.Photo = new Uri(uri);
                        }
                    }

                    string gender = Json.TryGetJsonProperty(user, "gender");
                    if (gender != null)
                    {
                        u.Gender = gender == "female" ? Model.Gender.Female : Model.Gender.Male;
                    }

                    var scores = user["scores"];
                    if (scores != null)
                    {
                        u.Scores = LeaderboardItemScores.ParseJson(scores);
                    }

                    var checkins = user["checkins"];
                    if (checkins != null)
                    {
                        string totalCheckinCount = Json.TryGetJsonProperty(checkins, "count");
                        int    i;
                        if (int.TryParse(totalCheckinCount, out i))
                        {
                            if (i > 0)
                            {
                                u.TotalCheckins =
                                    Json.GetPrettyInt(i)
                                    + " "
                                    + "check-in"
                                    + (i == 1 ? string.Empty : "s");
                            }
                        }

                        if (u.TotalCheckins == null)
                        {
                            u.TotalCheckins = "No check-ins";
                        }

                        // recent checkins
                        var items = checkins["items"];
                        if (items != null)
                        {
                            foreach (var item in items)
                            {
                                // Just grabbing the first one.
                                u.RecentCheckin = Checkin.ParseJson(item);

                                break;
                            }
                        }
                    }

                    /*
                     *           "requests": {
                     * "count": 0
                     * },
                     * "tips": {
                     * "count": 2
                     * },
                     * "todos": {
                     * "count": 0
                     * }
                     * */

                    var tips = user["tips"];
                    if (tips != null)
                    {
                        string tipsNumber = Json.TryGetJsonProperty(tips, "count");
                        int    tc;
                        if (int.TryParse(tipsNumber, out tc))
                        {
                            if (tc <= 0)
                            {
                                u.TipsCount = "No tips";
                            }
                            else if (tc == 1)
                            {
                                u.TipsCount = "1 tip";
                            }
                            else
                            {
                                u.TipsCount = tc.ToString(CultureInfo.InvariantCulture) + " tips";
                            }
                        }
                    }

                    // TODO: V2: TIPS COUNT
                    // TODO: V2: TODOS COUNT

                    var friends = user["friends"];
                    if (friends != null)
                    {
                        string friendsCount = Json.TryGetJsonProperty(friends, "count");
                        if (friendsCount != null)
                        {
                            u.FriendsCount = "No friends yet";
                            int i = int.Parse(friendsCount, CultureInfo.InvariantCulture);
                            if (i == 1)
                            {
                                u.FriendsCount = "1 friend";
                            }
                            else if (i > 1)
                            {
                                u.FriendsCount = i.ToString(CultureInfo.InvariantCulture) + " friends";
                            }
                        }

                        // TODO: V2: There is a new concept of friend groups.. hmm.

                        /*
                         * "friends": {
                         * "count": 22,
                         * "groups": [
                         * {
                         *  "type": "others",
                         *  "name": "other friends",
                         *  "count": 22,
                         *  "items": [ ]
                         * }
                         * ]
                         * },
                         */
                    }

                    var requests = user["requests"];
                    if (requests != null)
                    {
                        string fr = Json.TryGetJsonProperty(requests, "count");
                        int    i;
                        // TODO: V2: VALIDATE THIS JUST TO BE SURE.
                        if (int.TryParse(fr, out i))
                        {
                            // TODO: UI: Add pending friend requests to profile.xaml
                            u.PendingFriendRequests = i;
                        }
                    }

                    //var stats = user["stats"];
                    //if (stats != null)
                    //{
                    //    // this was deprecated in v2 I believe
                    //}

                    var badges = user["badges"];
                    u.BadgeCountText = "No badges";
                    if (badges != null)
                    {
                        string count = Json.TryGetJsonProperty(badges, "count");
                        if (count != null)
                        {
                            int badgeCount = int.Parse(count, CultureInfo.InvariantCulture);
                            if (badgeCount == 1)
                            {
                                u.HasBadges      = true;
                                u.BadgeCountText = "1 badge";
                            }
                            else
                            {
                                u.HasBadges      = true;
                                u.BadgeCountText = badgeCount + " badges";
                            }
                        }
                    }

                    var mayorships = user["mayorships"];
                    u.MayorshipCountText = "No mayorships";
                    if (mayorships != null)
                    {
                        string mayorcount = Json.TryGetJsonProperty(mayorships, "count");
                        var    ml         = new List <CompactVenue>();
                        var    items      = mayorships["items"];
                        if (items != null)
                        {
                            foreach (var mayorship in items)
                            {
                                CompactVenue bv = CompactVenue.ParseJson(mayorship);
                                ml.Add(bv);
                            }
                        }

                        if (mayorcount != null)
                        {
                            int i = int.Parse(mayorcount, CultureInfo.InvariantCulture);
                            if (i == 0)
                            {
                                // u.MayorshipCountText = "No mayorships";
                            }
                            else if (i == 1)
                            {
                                u.MayorshipCountText = "1 mayorship";
                            }
                            else
                            {
                                u.MayorshipCountText = i + " mayorships";
                            }
                        }
                    }

                    u.IgnoreRaisingPropertyChanges = false;
                    u.IsLoadComplete = true;

                    return(u);
                }
                catch (Exception e)
                {
                    throw new UserIntendedException(
                              "The person's information could not be downloaded at this time, please try again later.", e);
                }
            }
Пример #8
0
        public static Checkin ParseJson(JToken checkin)
        {
            Checkin c = new Checkin();

            string created = Json.TryGetJsonProperty(checkin, "createdAt");
            if (created != null)
            {
                // FUTURE: Consider an option to NOT include people in the checkin list who have not checked in within the last month. (perf default!)
                DateTime dtc = UnixDate.ToDateTime(created);
                c.CreatedDateTime = dtc;
                c.Created = GetDateString(dtc);
            }

            // Client information.
            var source = checkin["source"];
            if (source != null)
            {
                c.ClientName = Json.TryGetJsonProperty(source, "name");
               
                // TODO: Create a crashless URI helper.
                try
                {
                    string url = Json.TryGetJsonProperty(source, "url");
                    if (!string.IsNullOrEmpty(url))
                    {
                        if (url.StartsWith("www"))
                        {
                            url = "http://" + url;
                        }
                        c.ClientWebUri = new Uri(url, UriKind.Absolute);
                    }
                }
                catch 
                {
                }
            }

            string type = Json.TryGetJsonProperty(checkin, "type");
            // Only if present. Won't show up in badge winnings, for instance.
            if (type != null)
            {
                Debug.Assert(type == "checkin" || type == "shout" || type == "venueless");
            }
            c.CheckinType = type;

            c.CheckinId = Json.TryGetJsonProperty(checkin, "id");
            // badge mode actually won't have this Debug.Assert(c.CheckinId != null);

            if (!string.IsNullOrEmpty(c.CheckinId))
            {
                c.LocalCommentsUri = new Uri(string.Format(CultureInfo.InvariantCulture, "/Views/Comments.xaml?checkin={0}", c.CheckinId),UriKind.Relative);
            }

            var location = checkin["location"];
            if (location != null && type == "venueless") // consider if that's right
            {
                // if shout or venueless, will provide...
                // lat, lng pair and/or a name
                string venuelessName = Json.TryGetJsonProperty(location, "name");
                c.VenuelessName = venuelessName;
            }

            var user = checkin["user"];
            if (user != null)
            {
                CompactUser bu = CompactUser.ParseJson(user);
                c.User = bu;
            }

            var venue = checkin["venue"];
            if (venue != null)
            {
                CompactVenue bv = CompactVenue.ParseJson(venue);
                if (bv != null)
                {
                    c.DisplayAddressLine = bv.AddressLine;
                }
                c.Venue = bv;
            }

            // Show venueless name at least.
            if (c.Venue == null && !string.IsNullOrEmpty(c.VenuelessName))
            {
                c.Venue = CompactVenue.CreateVenueless(c.VenuelessName);
            }

            c.Shout = Json.TryGetJsonProperty(checkin, "shout");

            string ismayor = Json.TryGetJsonProperty(checkin, "isMayor");
            if (ismayor != null && ismayor.ToLowerInvariant() == "true")
            {
                c.IsMayor = true;
            }
            
            string dist = Json.TryGetJsonProperty(checkin, "distance");
            if (dist == null)
            {
                c.Meters = double.NaN;
            }
            else
            {
                c.Meters = double.Parse(dist, CultureInfo.InvariantCulture);

                // Doing this here to centralize it somewhere at least.
                if (c.Meters > 40000) // NOTE: This is a random value, What value should define a different city?
                {
                    c.IsInAnotherCity = true;
                    if (c.Venue != null)
                    {
                        string s = c.Venue.City ?? string.Empty;
                        if (!string.IsNullOrEmpty(c.Venue.State))
                        {
                            s += ", ";
                        }
                        if (c.Venue.State != null)
                        {
                            s += c.Venue.State;
                        }

                        c.DisplayAddressLine = s;
                    }
                }
            }

            if (c.User != null)
            {
                c.DisplayUser = c.User.ShortName;
                c.UserUri = c.User.UserUri;
            }
            if (c.Venue != null)
            {
                c.DisplayBetween = null; // WAS:  "@";
                c.DisplayVenue = c.Venue.Name;
                c.VenueUri = c.Venue.VenueUri;
            }
            else
            {
                if (type == "shout")
                {
                    //c.DisplayBetween = "shouted:";
                }
                else if (type == "venueless")
                {
                    c.DisplayBetween = c.VenuelessName;
                }
                else
                {
                    c.DisplayBetween = "[off-the-grid]"; // @ 
                }
            }

            // Photo and Comment information
            c.CommentsCount = GetNodeCount(checkin, "comments");
            c.PhotosCount = GetNodeCount(checkin, "photos");

            c.HasComments = c.CommentsCount > 0;
            c.HasPhotos = c.PhotosCount > 0;
            c.HasPhotosOrComments = c.HasComments || c.HasPhotos;

            if (c.HasPhotos)
            {
                List<Photo> photos = new List<Photo>();
                var pl = checkin["photos"];
                if (pl != null)
                {
                    var pll = pl["items"];
                    if (pll != null)
                    {
                        foreach (var photo in pll)
                        {
                            var po = Photo.ParseJson(photo);
                            if (po != null)
                            {
                                photos.Add(po);
                            }
                        }
                    }
                }
                c.Photos = photos;

                if (photos.Count > 0)
                {
                    c.FirstCheckinPhoto = photos[0];
                }
            }

            int activityCount = c.CommentsCount; // +c.PhotosCount;
            c.CommentsAndPhotosOrAdd = activityCount > 0 ? activityCount.ToString(CultureInfo.InvariantCulture) : "+";

            if (c.User != null && c.User.Relationship == FriendStatus.Self)
            {
                c.CanAddPhotos = true;
            }

            return c;
        }
Пример #9
0
        public static Tip ParseJson(JToken tip, Type parentType, string parentIdentifier)
        {
            var t = new Tip();

            t.ParentType       = parentType;
            t.ParentIdentifier = parentIdentifier;

            t.TipId = Json.TryGetJsonProperty(tip, "id");
            Debug.Assert(t.TipId != null);

            string txt = Checkin.SanitizeString(Json.TryGetJsonProperty(tip, "text"));

            if (!string.IsNullOrEmpty(txt))
            {
                t.Text = txt;
            }

            var user = tip["user"];

            if (user != null)
            {
                t.User = CompactUser.ParseJson(user);
            }

            string created = Json.TryGetJsonProperty(tip, "createdAt");

            if (created != null)
            {
                DateTime dtc = UnixDate.ToDateTime(created);
                t.CreatedDateTime = dtc;
                t.Created         = Checkin.GetDateString(dtc);
            }

            // NOTE: Consider getting tip group details. Only available in the
            // request. Would be a nice future release update probably.

            var todoCount = tip["todo"];

            if (todoCount != null)
            {
                string cc = Json.TryGetJsonProperty(todoCount, "count");
                int    i;
                if (int.TryParse(cc, out i))
                {
                    t.TodoCount = i;
                }
            }

            var doneCount = tip["done"];

            if (doneCount != null)
            {
                string cc = Json.TryGetJsonProperty(doneCount, "count");
                int    i;
                if (int.TryParse(cc, out i))
                {
                    t.DoneCount = i;
                }
            }

            if (t.DoneCount <= 0)
            {
                t.DoneText = "No one has done this.";
            }
            else if (t.DoneCount == 1)
            {
                t.DoneText = "1 person has done this.";
            }
            else
            {
                t.DoneText = t.DoneCount.ToString(CultureInfo.InvariantCulture) + " people have done this.";
            }

            var photo = tip["photo"];

            if (photo != null)
            {
                var pht = Model.Photo.ParseJson(photo);
                if (pht != null)
                {
                    t.Photo = pht;
                }
            }

            string status = Json.TryGetJsonProperty(tip, "status");

            //Debug.WriteLine("tip status read as (temp): " + status);
            t.Status = TipStatus.None;
            if (status != null)
            {
                if (status == "done")
                {
                    t.Status     = TipStatus.Done;
                    t.StatusText = "You've done this!";
                }
                else if (status == "todo")
                {
                    t.Status     = TipStatus.Todo;
                    t.StatusText = "You need to do this!";

                    // Don't tell the user nobody has done this if it's just them.
                    if (t.DoneCount <= 0)
                    {
                        t.DoneText = null;
                    }
                }
            }

            var compactVenue = tip["venue"];

            if (compactVenue != null)
            {
                t.Venue = CompactVenue.ParseJson(compactVenue);
            }

            string parentTypeText = t.ParentType == typeof(Model.Venue) ? "venue" : null;

            if (parentTypeText == null)
            {
                if (t.ParentType == typeof(Model.UserTips))
                {
                    parentTypeText = "usertips";
                }
                else if (t.ParentType == typeof(RecommendedTipNotification) || t.ParentType == typeof(DetailedTip))
                {
                    parentTypeText = "direct";
                }
                else
                {
                    parentTypeText = "unknown";
                }
            }

            Uri tipUri = new Uri(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "/JeffWilcox.FourthAndMayor.Lists;component/ListItem.xaml?id={0}&tipId={0}",
                    Uri.EscapeDataString(t.TipId))
                , UriKind.Relative);

            t.TipUri = tipUri;

            // TODO: This supports todo w/count, done w/count, ...

            return(t);
        }
        public MayorshipNotification(JToken item)
        {
            string cks = Json.TryGetJsonProperty(item, "checkins");
            int    checkins;

            if (int.TryParse(cks, out checkins))
            {
                Checkins = checkins;
            }

            string bhd = Json.TryGetJsonProperty(item, "daysBehind");

            if (bhd != null)
            {
                int bh;
                if (int.TryParse(bhd, out bh))
                {
                    DaysBehindTheMayor = bh;
                    // hardcoded for now
                    DaysBehindTheMayorText = string.Format(
                        CultureInfo.InvariantCulture,
                        "You are now {0} day{1} away from becoming the Mayor!",
                        bh.ToString(),
                        bh < 2 ? "" : "s");

                    if (bh > 10)
                    {
                        DaysBehindTheMayorText = null; // don't show
                    }

                    if (bh == 1)
                    {
                        ExtraText = "You must have a profile photo setup on foursquare.com to become the mayor.";
                    }
                }
            }

            Message = Checkin.SanitizeString(Json.TryGetJsonProperty(item, "message"));

            var user = item["user"];

            if (user != null)
            {
                User = CompactUser.ParseJson(user);
            }

            string imageUri = Json.TryGetJsonProperty(item, "image");

            try
            {
                Image = new Uri(imageUri, UriKind.Absolute);
            }
            catch (Exception)
            {
                // note: Might be relative, silent watson.
            }

            string tt = Json.TryGetJsonProperty(item, "type");

            switch (tt)
            {
            case "nochange":
                Type = MayorshipNotificationType.NoChange;
                break;

            case "new":
                Type = MayorshipNotificationType.New;
                break;

            case "stolen":
                Type = MayorshipNotificationType.Stolen;
                break;

            default:
                // todo: sometehing for default, silent report?
                break;
            }
        }
Пример #11
0
        public static Photo ParseJson(JToken json)
        {
            Photo p = new Photo();

            p.Id = Json.TryGetJsonProperty(json, "id");
            //Debug.Assert(p.Id != null);

            string created = Json.TryGetJsonProperty(json, "createdAt");

            if (created != null)
            {
                DateTime dtc = UnixDate.ToDateTime(created);
                p.CreatedDateTime = dtc;
                p.Created         = Checkin.GetDateString(dtc);
            }

            string primaryUri = Json.TryGetJsonProperty(json, "url");

            if (primaryUri != null)
            {
                p.Uri = new Uri(primaryUri, UriKind.Absolute);
            }

            var userJson = json["user"];

            if (userJson != null)
            {
                p.User = CompactUser.ParseJson(userJson);
                if (p.User != null)
                {
                    p.IsSelf = p.User.Relationship == FriendStatus.Self;
                }
            }

            var sizes = json["sizes"];

            if (sizes != null)
            {
                var items = sizes["items"];
                List <UriWidthHeight> sz = new List <UriWidthHeight>();
                foreach (var item in items)
                {
                    sz.Add(new UriWidthHeight
                    {
                        Uri    = new Uri(Json.TryGetJsonProperty(item, "url"), UriKind.Absolute),
                        Width  = double.Parse(Json.TryGetJsonProperty(item, "width"), CultureInfo.InvariantCulture),
                        Height = double.Parse(Json.TryGetJsonProperty(item, "height"), CultureInfo.InvariantCulture),
                    });
                }
                if (sz.Count > 0)
                {
                    p.SmallestUri = sz[sz.Count - 1].Uri;
                    p.MediumUri   = sz[sz.Count > 2 ? sz.Count - 2 : sz.Count - 1].Uri;
                    p.LargerUri   = sz[1].Uri;
                }
            }

            Uri pu = new Uri(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "/Views/PhotoViewer.xaml?photoUri={0}&isSelf={1}&id={2}",

                    Uri.EscapeDataString(p.Uri.ToString()),
                    p.IsSelf ? "true" : "false",
                    p.Id
                    )
                , UriKind.Relative);

            p.LocalPhotoViewerUri = pu;

            return(p);
        }
 public MessageNotification(JToken item)
 {
     Message = Checkin.SanitizeString(Json.TryGetJsonProperty(item, "message"));
 }
Пример #13
0
        public static Checkin ParseJson(JToken checkin)
        {
            Checkin c = new Checkin();

            string created = Json.TryGetJsonProperty(checkin, "createdAt");

            if (created != null)
            {
                // FUTURE: Consider an option to NOT include people in the checkin list who have not checked in within the last month. (perf default!)
                DateTime dtc = UnixDate.ToDateTime(created);
                c.CreatedDateTime = dtc;
                c.Created         = GetDateString(dtc);
            }

            // Client information.
            var source = checkin["source"];

            if (source != null)
            {
                c.ClientName = Json.TryGetJsonProperty(source, "name");

                // TODO: Create a crashless URI helper.
                try
                {
                    string url = Json.TryGetJsonProperty(source, "url");
                    if (!string.IsNullOrEmpty(url))
                    {
                        if (url.StartsWith("www"))
                        {
                            url = "http://" + url;
                        }
                        c.ClientWebUri = new Uri(url, UriKind.Absolute);
                    }
                }
                catch
                {
                }
            }

            string type = Json.TryGetJsonProperty(checkin, "type");

            // Only if present. Won't show up in badge winnings, for instance.
            if (type != null)
            {
                Debug.Assert(type == "checkin" || type == "shout" || type == "venueless");
            }
            c.CheckinType = type;

            c.CheckinId = Json.TryGetJsonProperty(checkin, "id");
            // badge mode actually won't have this Debug.Assert(c.CheckinId != null);

            if (!string.IsNullOrEmpty(c.CheckinId))
            {
                c.LocalCommentsUri = new Uri(string.Format(CultureInfo.InvariantCulture, "/Views/Comments.xaml?checkin={0}", c.CheckinId), UriKind.Relative);
            }

            var location = checkin["location"];

            if (location != null && type == "venueless") // consider if that's right
            {
                // if shout or venueless, will provide...
                // lat, lng pair and/or a name
                string venuelessName = Json.TryGetJsonProperty(location, "name");
                c.VenuelessName = venuelessName;
            }

            var user = checkin["user"];

            if (user != null)
            {
                CompactUser bu = CompactUser.ParseJson(user);
                c.User = bu;
            }

            var venue = checkin["venue"];

            if (venue != null)
            {
                CompactVenue bv = CompactVenue.ParseJson(venue);
                if (bv != null)
                {
                    c.DisplayAddressLine = bv.AddressLine;
                }
                c.Venue = bv;
            }

            // Show venueless name at least.
            if (c.Venue == null && !string.IsNullOrEmpty(c.VenuelessName))
            {
                c.Venue = CompactVenue.CreateVenueless(c.VenuelessName);
            }

            c.Shout = Json.TryGetJsonProperty(checkin, "shout");

            string ismayor = Json.TryGetJsonProperty(checkin, "isMayor");

            if (ismayor != null && ismayor.ToLowerInvariant() == "true")
            {
                c.IsMayor = true;
            }

            string dist = Json.TryGetJsonProperty(checkin, "distance");

            if (dist == null)
            {
                c.Meters = double.NaN;
            }
            else
            {
                c.Meters = double.Parse(dist, CultureInfo.InvariantCulture);

                // Doing this here to centralize it somewhere at least.
                if (c.Meters > 40000) // NOTE: This is a random value, What value should define a different city?
                {
                    c.IsInAnotherCity = true;
                    if (c.Venue != null)
                    {
                        string s = c.Venue.City ?? string.Empty;
                        if (!string.IsNullOrEmpty(c.Venue.State))
                        {
                            s += ", ";
                        }
                        if (c.Venue.State != null)
                        {
                            s += c.Venue.State;
                        }

                        c.DisplayAddressLine = s;
                    }
                }
            }

            if (c.User != null)
            {
                c.DisplayUser = c.User.ShortName;
                c.UserUri     = c.User.UserUri;
            }
            if (c.Venue != null)
            {
                c.DisplayBetween = null; // WAS:  "@";
                c.DisplayVenue   = c.Venue.Name;
                c.VenueUri       = c.Venue.VenueUri;
            }
            else
            {
                if (type == "shout")
                {
                    //c.DisplayBetween = "shouted:";
                }
                else if (type == "venueless")
                {
                    c.DisplayBetween = c.VenuelessName;
                }
                else
                {
                    c.DisplayBetween = "[off-the-grid]"; // @
                }
            }

            // Photo and Comment information
            c.CommentsCount = GetNodeCount(checkin, "comments");
            c.PhotosCount   = GetNodeCount(checkin, "photos");

            c.HasComments         = c.CommentsCount > 0;
            c.HasPhotos           = c.PhotosCount > 0;
            c.HasPhotosOrComments = c.HasComments || c.HasPhotos;

            if (c.HasPhotos)
            {
                List <Photo> photos = new List <Photo>();
                var          pl     = checkin["photos"];
                if (pl != null)
                {
                    var pll = pl["items"];
                    if (pll != null)
                    {
                        foreach (var photo in pll)
                        {
                            var po = Photo.ParseJson(photo);
                            if (po != null)
                            {
                                photos.Add(po);
                            }
                        }
                    }
                }
                c.Photos = photos;

                if (photos.Count > 0)
                {
                    c.FirstCheckinPhoto = photos[0];
                }
            }

            int activityCount = c.CommentsCount; // +c.PhotosCount;

            c.CommentsAndPhotosOrAdd = activityCount > 0 ? activityCount.ToString(CultureInfo.InvariantCulture) : "+";

            if (c.User != null && c.User.Relationship == FriendStatus.Self)
            {
                c.CanAddPhotos = true;
            }

            return(c);
        }
Пример #14
0
            protected override object DeserializeCore(JObject json, Type objectType, LoadContext context)
            {
                try
                {
                    var u = new DetailedCheckin(context);
                    //u.IgnoreRaisingPropertyChanges = true;

                    var jcheckin = json["checkin"];
                    if (jcheckin != null)
                    {
                        Checkin compactCheckin = Checkin.ParseJson(jcheckin);

                        // So links are not displayed, etc.
                        if (compactCheckin != null)
                        {
                            compactCheckin.ReduceFunctionality      = true;
                            compactCheckin.ReduceFunctionalityVis   = System.Windows.Visibility.Visible;
                            compactCheckin.CompleteFunctionalityVis = System.Windows.Visibility.Collapsed;
                        }

                        u.CompactCheckin = compactCheckin;

                        List <Photo> photos = new List <Photo>();
                        var          pl     = jcheckin["photos"];
                        if (pl != null)
                        {
                            var pll = pl["items"];
                            if (pll != null)
                            {
                                foreach (var photo in pll)
                                {
                                    var po = Photo.ParseJson(photo);
                                    if (po != null)
                                    {
                                        photos.Add(po);
                                    }
                                }
                            }
                        }

                        List <Comment> comments = new List <Comment>();
                        var            cl       = jcheckin["comments"];
                        if (cl != null)
                        {
                            var cll = cl["items"];
                            if (cll != null)
                            {
                                foreach (var comment in cll)
                                {
                                    var co = Comment.ParseJson(comment);
                                    if (co != null)
                                    {
                                        comments.Add(co);
                                    }
                                }
                            }
                        }

                        //var list = combined.OrderBy(w => w.CreatedDateTime).ToList();
                        //cap.AddRange(list);

                        List <object> both = new List <object>(photos.Cast <object>());
                        both.AddRange(comments.Cast <object>());

                        //List<CommentsList> lcl = null;
                        //if (cap.Count > 0)
                        //{
                        //    lcl = new List<CommentsList>();
                        //    lcl.Add(cap);
                        //}

                        u.CommentsAndPhotos = both;
                    }

                    u.IgnoreRaisingPropertyChanges = false;
                    u.IsLoadComplete = true;

                    return(u);
                }
                catch (Exception e)
                {
                    throw new UserIntendedException(
                              "There was a problem trying to read information about the checkin.", e);
                }
            }
Пример #15
0
            protected override object DeserializeCore(JObject json, Type objectType, LoadContext context)
            {
                try
                {
                    var nv = new Checkins(context);
                    nv.IgnoreRaisingPropertyChanges = true;
                    var checkins = (JArray)json["recent"];

                    var groups = new List <CheckinsGroup>();

                    var otherCities = new CheckinsGroup {
                        Name = "Friends in other cities"
                    };
                    var older = new CheckinsGroup {
                        Name = "Older"
                    };
                    var yesterday = new CheckinsGroup {
                        Name = "Yesterday"
                    };
                    var today = new CheckinsGroup {
                        Name = "Today"
                    };
                    var last3 = new CheckinsGroup {
                        Name = "Last 3 Hours"
                    };
                    var gps = new CheckinsGroup[]
                    {
                        last3,
                        today,
                        yesterday,
                        older,
                        otherCities,
                    };

                    var      now        = DateTime.UtcNow;
                    var      nowAsLocal = now.ToLocalTime();
                    DateTime d3         = now - TimeSpan.FromHours(3);
                    DateTime dt         = new DateTime(nowAsLocal.Year, nowAsLocal.Month, nowAsLocal.Day, 0, 0, 0, DateTimeKind.Local);
                    DateTime ydraw      = nowAsLocal - TimeSpan.FromDays(1);
                    DateTime dy         = new DateTime(ydraw.Year, ydraw.Month, ydraw.Day, 0, 0, 0, DateTimeKind.Local);
                    DateTime dTooMany   = nowAsLocal - MaxCheckinAge;

                    foreach (JToken checkin in checkins)
                    {
                        Checkin c = Checkin.ParseJson(checkin);
                        var     k = c.CreatedDateTime;

                        var kLocal = k.ToLocalTime();

                        string temp = c.Created;

                        var ku = k.ToUniversalTime();
                        System.Diagnostics.Debug.Assert(ku == k);

                        CheckinsGroup g = older;
                        if (c.IsInAnotherCity)
                        {
                            g = otherCities;
                        }
                        else if (k >= d3.ToUniversalTime())
                        {
                            g = last3;
                        }
                        else if (kLocal >= dt)
                        {
                            g = today;
                        }
                        else if (kLocal >= dy)
                        {
                            g = yesterday;
                        }

                        // If they have not checked in in a while.
                        if (kLocal < dTooMany)
                        {
                            continue;
                        }

                        g.Add(c);
                    }

                    foreach (var gp in gps)
                    {
                        if (gp.Count > 0)
                        {
                            groups.Add(gp);
                        }
                    }

                    nv.Groups = groups;

                    nv.IgnoreRaisingPropertyChanges = false;
                    nv.IsLoadComplete = true;
                    return(nv);
                }
                catch (Exception e)
                {
                    throw new UserIntendedException(
                              "There was a problem trying to read information about recent checkins.", e);
                }
            }
Пример #16
0
            protected override object DeserializeCore(JObject json, Type objectType, LoadContext context)
            {
                var v = new Venue(context);

                try
                {
                    var venue = json["venue"];

                    CompactVenue bv = CompactVenue.ParseJson(venue);
                    v.VenueId = bv.VenueId;
                    Debug.Assert(v.VenueId != null);

                    // TODO: Consider architecture.
                    v.Location    = bv.Location;
                    v.Address     = bv.Address;
                    v.City        = bv.City;
                    v.CrossStreet = bv.CrossStreet;
                    v.State       = bv.State;
                    v.Zip         = bv.Zip;
                    v.Name        = bv.Name;

                    var menuEntry = venue["menu"];
                    if (menuEntry != null)
                    {
                        string mobileMenu = Json.TryGetJsonProperty(menuEntry, "mobileUrl");
                        if (!string.IsNullOrEmpty(mobileMenu))
                        {
                            v.HasMenu = true;
                        }
                    }

                    string desc = Checkin.SanitizeString(Json.TryGetJsonProperty(venue, "description"));
                    if (desc != null)
                    {
                        v.Description = desc;
                    }

                    // TODO: V2: timeZone // timeZone: "America/New_York"

                    string swu = Json.TryGetJsonProperty(venue, "shortUrl");
                    if (swu != null)
                    {
                        v.ShortWebUri = new Uri(swu);
                    }

                    string verif = Json.TryGetJsonProperty(venue, "verified");
                    if (verif != null && verif.ToLowerInvariant() == "true")
                    {
                        v.IsVerified = true;
                    }

                    // older code.
                    string phone = Json.TryGetJsonProperty(venue, "phone");
                    if (phone != null)
                    {
                        v.Phone = phone; // User.FormatSimpleUnitedStatesPhoneNumberMaybe(phone);
                    }

                    // newer code for contact stuff.
                    var contact = venue["contact"];
                    if (contact != null)
                    {
                        v.Twitter = Json.TryGetJsonProperty(contact, "twitter");

                        string newerPhone = Json.TryGetJsonProperty(contact, "phone");
                        if (newerPhone != null)
                        {
                            v.Phone = newerPhone;
                        }

                        string bestPhone = Json.TryGetJsonProperty(contact, "formattedPhone");
                        if (bestPhone != null)
                        {
                            v.FormattedPhone = bestPhone;
                        }

                        // fallback.
                        if (v.FormattedPhone == null && !string.IsNullOrEmpty(v.Phone))
                        {
                            v.FormattedPhone = User.FormatSimpleUnitedStatesPhoneNumberMaybe(v.Phone);
                        }
                    }

                    string homepage = Json.TryGetJsonProperty(venue, "url");
                    if (!string.IsNullOrEmpty(homepage))
                    {
                        v.Homepage = new Uri(homepage, UriKind.Absolute);
                    }

                    var todos = venue["todos"];
                    if (todos != null)
                    {
                        var items = todos["items"];
                        if (items != null)
                        {
                            var todosList = new List <Todo>();
                            foreach (var todo in items)
                            {
                                var td = Todo.ParseJson(todo);
                                if (td != null)
                                {
                                    todosList.Add(td);
                                }
                            }
                            v.Todos = todosList;
                        }
                    }

                    var events = venue["events"];
                    if (events != null)
                    {
                        string pct = Json.TryGetJsonProperty(events, "count");
                        int    pcti;
                        if (int.TryParse(pct, out pcti))
                        {
                            v.EventsCount = pcti;

                            if (pcti > 0)
                            {
                                v.EventsSummary = Json.TryGetJsonProperty(events, "summary");
                            }

                            if (v.HasEvents)
                            {
                                // ? will this work ?
                                v.Events = DataManager.Current.Load <VenueEvents>(
                                    new LoadContext(
                                        v.LoadContext.Identity
                                        )
                                    );
                            }
                        }
                    }

                    var photos = venue["photos"];
                    if (photos != null)
                    {
                        string pct = Json.TryGetJsonProperty(photos, "count");
                        int    pcti;
                        if (int.TryParse(pct, out pcti))
                        {
                            if (pcti == 1)
                            {
                                v.PhotosCount = "1 photo";
                            }
                            else if (pcti > 1)
                            {
                                v.PhotosCount = pcti.ToString() + " photos";
                            }

                            // get the grounds
                            if (pcti > 0)
                            {
                                var groups = photos["groups"];
                                if (groups != null)
                                {
                                    var pg = new List <PhotoGroup>();
                                    foreach (var item in groups)
                                    {
                                        string name  = Json.TryGetJsonProperty(item, "name");
                                        var    items = item["items"];
                                        var    group = new PhotoGroup();
                                        group.Name = name;
                                        foreach (var it in items)
                                        {
                                            Photo p = Photo.ParseJson(it);
                                            if (p != null)
                                            {
                                                group.Add(p);
                                            }
                                        }
                                        if (group.Count > 0)
                                        {
                                            pg.Add(group);
                                        }
                                    }
                                    if (pg.Count > 0)
                                    {
                                        v.PhotoGroups = pg;
                                    }
                                }
                            }
                        }
                    }
                    // Allowing the GIC to show the empty template.
                    if (v.PhotoGroups == null)
                    {
                        v.PhotoGroups = new List <PhotoGroup>();
                    }

                    string htodo = Json.TryGetJsonProperty(venue, "hasTodo"); // checkin mode only
                    if (htodo != null && htodo.ToLowerInvariant() == "true")
                    {
                        v.HasToDo = true;
                    }

                    v.HereNow = "Nobody";
                    bool hereNow = false;
                    var  herenow = venue["hereNow"];
                    if (herenow != null)
                    {
                        bool isSelfHere = false;

                        string summary = Json.TryGetJsonProperty(herenow, "summary");
                        if (summary != null)
                        {
                            v.HereNow = summary;
                        }

                        var    groups = herenow["groups"];
                        string hn     = Json.TryGetJsonProperty(herenow, "count");
                        if (/*!string.IsNullOrEmpty(hn) &&*/ groups != null) // I still want to compute this anyway.
                        {
                            int totalCount     = int.Parse(hn, CultureInfo.InvariantCulture);
                            int remainingCount = totalCount;

                            var hereNowGroups = new List <CheckinsGroup>();
                            foreach (var group in groups)
                            {
                                string type  = Json.TryGetJsonProperty(group, "type");  // friends, others
                                string name  = Json.TryGetJsonProperty(group, "name");  // "friends here", "other people here"
                                string count = Json.TryGetJsonProperty(group, "count"); // the count, an int
                                var    items = group["items"];

                                if (items != null)
                                {
                                    var cg = new CheckinsGroup {
                                        Name = name
                                    };

                                    foreach (var item in items)
                                    {
                                        Checkin cc = Checkin.ParseJson(item);
                                        remainingCount--;
                                        if (cc.User != null && cc.User.Relationship == FriendStatus.Self)
                                        {
                                            // Self!
                                            var selfGroup = new CheckinsGroup {
                                                Name = "you're here!"
                                            };
                                            isSelfHere = true;
                                            selfGroup.Add(cc);
                                            hereNowGroups.Add(selfGroup);
                                        }
                                        else
                                        {
                                            cg.Add(cc);
                                        }
                                    }

                                    if (cg.Count > 0)
                                    {
                                        hereNowGroups.Add(cg);
                                    }
                                }
                            }

                            // Special last item with the remainder count.
                            if (remainingCount > 0 && hereNowGroups.Count > 0)
                            {
                                var lastGroup = hereNowGroups[hereNowGroups.Count - 1];
                                var hnr       = new Checkin
                                {
                                    HereNowRemainderText =
                                        remainingCount == 1
                                            ? "... plus 1 person"
                                            : "... plus " + remainingCount.ToString() + " people",
                                };
                                lastGroup.Add(hnr);
                            }

                            v.HereNowGroups = hereNowGroups;

                            // subtract one for self
                            if (isSelfHere)
                            {
                                totalCount--;
                            }
                            string prefix = (isSelfHere ? "You and " : string.Empty);
                            if (string.IsNullOrEmpty(summary))
                            {
                                if (totalCount > 1)
                                {
                                    v.HereNow = prefix + Json.GetPrettyInt(totalCount) + " " + (isSelfHere ? "other " : "") + "people";
                                }
                                else if (totalCount == 1)
                                {
                                    v.HereNow = prefix + "1 " + (isSelfHere ? "other " : "") + "person";
                                }
                                else if (totalCount == 0 && isSelfHere)
                                {
                                    v.HereNow = "You are here";
                                }
                            }

                            if (totalCount > 0)
                            {
                                hereNow = true;
                            }
                        }
                    }

                    v.HasHereNow = hereNow;

                    var stats = venue["stats"];
                    if (stats != null)
                    {
                        string checkins = Json.TryGetJsonProperty(stats, "checkinsCount");
                        if (checkins != null)
                        {
                            int i;
                            if (int.TryParse(checkins, out i))
                            {
                                v.Checkins = i;
                            }
                        }

                        checkins = Json.TryGetJsonProperty(stats, "usersCount");
                        if (checkins != null)
                        {
                            int i;
                            if (int.TryParse(checkins, out i))
                            {
                                v.TotalPeople = i;
                            }
                        }
                    }

                    var mayor = venue["mayor"];
                    if (mayor != null)
                    {
                        string mayorCheckinCount = Json.TryGetJsonProperty(mayor, "count");

                        var user = mayor["user"];
                        if (user != null)
                        {
                            v.Mayor = CompactUser.ParseJson(user);
                        }

                        // Note there is a mayor.count property, it is the num
                        // of checkins in the last 60 days.
                    }

                    var beenHere = venue["beenHere"];
                    if (beenHere != null)
                    {
                        string c = Json.TryGetJsonProperty(beenHere, "count");
                        if (c != null)
                        {
                            int i;
                            if (int.TryParse(c, out i))
                            {
                                v.BeenHere = i;
                            }
                        }
                    }

                    var tips = venue["tips"];
                    if (tips != null)
                    {
                        string tipsCountStr = Json.TryGetJsonProperty(tips, "count");
                        if (tipsCountStr != null)
                        {
                            int tc;
                            if (int.TryParse(tipsCountStr, out tc))
                            {
                                if (tc <= 0)
                                {
                                    tipsCountStr = "No tips";
                                }
                                else if (tc == 1)
                                {
                                    tipsCountStr = "1 tip";
                                }
                                else
                                {
                                    tipsCountStr = tc.ToString() + " tips";
                                }
                            }
                        }
                        else
                        {
                            tipsCountStr = "No tips";
                        }
                        v.TipsCountText = tipsCountStr;

                        var ml        = new List <TipGroup>();
                        var tipGroups = tips["groups"];
                        if (tipGroups != null)
                        {
                            foreach (var tipGroup in tipGroups)
                            {
                                //string groupType = Json.TryGetJsonProperty(tipGroup, "type"); // others, ???v2
                                string groupName = Json.TryGetJsonProperty(tipGroup, "name"); // tips from others
                                //string countStr = Json.TryGetJsonProperty(tipGroup, "count");

                                var tipSet = tipGroup["items"];
                                if (tipSet != null)
                                {
                                    TipGroup tg = new TipGroup {
                                        Name = groupName
                                    };
                                    foreach (var tip in tipSet)
                                    {
                                        Tip t = Tip.ParseJson(tip, typeof(Model.Venue), (string)context.Identity);
                                        if (t != null)
                                        {
                                            tg.Add(t);
                                        }
                                    }
                                    if (tg.Count > 0)
                                    {
                                        ml.Add(tg);
                                    }
                                }
                            }
                        }
                        v.TipGroups = ml;
                    }

                    var specials     = venue["specials"];
                    var specialsList = new SpecialGroup {
                        Name = "specials here"
                    };
                    if (specials != null)
                    {
                        try
                        {
                            var items = specials["items"];
                            if (items != null)
                            {
                                foreach (var s in items)
                                {
                                    CompactSpecial cs = CompactSpecial.ParseJson(s, v.VenueId);
                                    if (cs != null)
                                    {
                                        specialsList.Add(cs);

                                        if (cs.IsUnlocked)
                                        {
                                            v.SpecialUnlocked = true;
                                        }
                                    }
                                }
                                if (specialsList.Count == 1)
                                {
                                    specialsList.Name = "special here";
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // 3.4 moves to a new Foursquare API version and so
                            // we don't want old cached data to throw here.
                        }
                    }
                    v.Specials = specialsList;

                    var nearby             = venue["specialsNearby"];
                    var nearbySpecialsList = new SpecialGroup {
                        Name = "specials nearby"
                    };
                    if (nearby != null)
                    {
                        foreach (var s in nearby)
                        {
                            CompactSpecial cs = CompactSpecial.ParseJson(s, null);
                            if (cs != null)
                            {
                                nearbySpecialsList.Add(cs);
                            }
                        }
                        if (nearbySpecialsList.Count == 1)
                        {
                            nearbySpecialsList.Name = "special nearby";
                        }
                    }
                    v.NearbySpecials = nearbySpecialsList;

                    var cmb = new List <SpecialGroup>(2);
                    if (specialsList.Count > 0)
                    {
                        cmb.Add(specialsList);
                    }
                    if (nearbySpecialsList.Count > 0)
                    {
                        cmb.Add(nearbySpecialsList);
                    }
                    v.CombinedSpecials = cmb;

                    var categories = venue["categories"];
                    if (categories != null)
                    {
                        foreach (var cat in categories)
                        {
                            var cc = Category.ParseJson(cat);
                            if (cc != null && cc.IsPrimary)
                            {
                                v.PrimaryCategory = cc;
                                break;
                            }
                            // Just the first actually!
                            break;
                        }
                    }

                    // stats
                    // .herenow
                    // .checkins
                    // beenhere: me:true;

                    // specials

                    var tags = venue["tags"];
                    if (tags != null)
                    {
                        List <string> tl = new List <string>();
                        foreach (string tag in tags)
                        {
                            tl.Add(tag);
                        }

                        if (tl.Count > 0)
                        {
                            v.Tags = tl;

                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < tl.Count; i++)
                            {
                                if (i > 0)
                                {
                                    sb.Append(", ");
                                }

                                sb.Append(tl[i]);
                            }

                            v.TagsString = sb.ToString();
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new UserIntendedException(
                              "There was a problem trying to read the venue information.", e);
                }

                v.IsLoadComplete = true;

                return(v);
            }
        private bool IsNearby(Checkin c)
        {
            if (_map != null && _map.BoundingRectangle != null && c.Venue != null && c.Venue.Location != null)
            {
                return _map.BoundingRectangle.Intersects(
                    new LocationRect(
                        c.Venue.Location.AsGeoCoordinate(), 
                        
                        // Using the actual size of the map to get "nearby"
                        // locations that the user might quickly pan to as
                        // well.
                        _map.BoundingRectangle.Width, 
                        _map.BoundingRectangle.Height)
                    );
            }

            return false;
        }
Пример #18
0
        public static Badge ParseJson(JToken badge)
        {
            Badge b = new Badge();

            b.Id      = Json.TryGetJsonProperty(badge, "id");
            b.BadgeId = Json.TryGetJsonProperty(badge, "badgeId");

            b.Name        = Json.TryGetJsonProperty(badge, "name");
            b.Hint        = Json.TryGetJsonProperty(badge, "hint");
            b.Description = Json.TryGetJsonProperty(badge, "description");

            var image = badge["image"];

            if (image != null)
            {
                try
                {
                    // TODO: Move to using MultiResolutionImage!
                    b.MultiResolutionIcon = MultiResolutionImage.ParseJson(image);

                    string prefix    = Json.TryGetJsonProperty(image, "prefix");
                    string imageName = Json.TryGetJsonProperty(image, "name");
                    var    sizes     = image["sizes"];
                    if (sizes != null)
                    {
                        List <int> szz = sizes.Select(size => int.Parse(size.ToString(), CultureInfo.InvariantCulture)).ToList();
                        b.Sizes = szz;
                        if (szz.Count > 0)
                        {
                            b.IconUri      = new Uri(prefix + szz[0] + imageName, UriKind.Absolute);
                            b.IconLargeUri = new Uri(prefix + szz[szz.Count - 1] + imageName, UriKind.Absolute);

                            if (szz.Count > 2)
                            {
                                b.IconMediumUri = new Uri(prefix + szz[1] + imageName, UriKind.Absolute);
                            }
                            else
                            {
                                // No medium-sized icon available.
                                b.IconMediumUri = b.IconUri;
                            }
                        }
                        b.ImagePrefix  = prefix;
                        b.ImagePostfix = imageName;
                    }
                }
                catch (Exception)
                {
                }
            }

            var unlocks = badge["unlocks"];

            if (unlocks != null)
            {
                List <Checkin> lc = new List <Checkin>();
                foreach (var unlock in unlocks)
                {
                    try
                    {
                        Checkin c = Checkin.ParseJson(unlock);
                        lc.Add(c);
                    }
                    catch (Exception)
                    {
                        // note: silent watchson?
                    }
                }
                b.Unlocks = lc;
            }

            return(b);
        }
Пример #19
0
        public static CompactListItem ParseJson(JToken json)
        {
            CompactListItem c = new CompactListItem();

            c.Id = Json.TryGetJsonProperty(json, "id");

            string created = Json.TryGetJsonProperty(json, "createdAt");

            if (created != null)
            {
                DateTime dtc = UnixDate.ToDateTime(created);
                c.CreatedAt = Checkin.GetDateString(dtc);
                c.Created   = dtc;
            }

            var user = json["user"];

            if (user != null)
            {
                c.User = CompactUser.ParseJson(user);
            }

            var photo = json["photo"];

            if (photo != null)
            {
                c.Photo = Photo.ParseJson(photo);
            }

            var venue = json["venue"];

            if (venue != null)
            {
                c.Venue = CompactVenue.ParseJson(venue);
            }

            var tip = json["tip"];

            if (tip != null)
            {
                c.Tip = Tip.ParseJson(tip);
            }

            var note = json["note"];

            if (note != null)
            {
                c.Note = Json.TryGetJsonProperty(note, "text");
            }

            c.Todo   = Json.TryGetJsonBool(json, "todo");
            c.IsDone = Json.TryGetJsonBool(json, "done");

            string s = Json.TryGetJsonProperty(json, "visitedCount");

            if (s != null)
            {
                int i;
                if (int.TryParse(s, out i))
                {
                    c.VisitedCount = i;
                }
            }

            // TODO: V4: "listed" list of compact venues where the item appears on.

            return(c);
        }
Пример #20
0
        public static CompactVenue ParseJson(JToken venue)
        {
            var b = new CompactVenue();

            b.VenueId = Json.TryGetJsonProperty(venue, "id");
            Debug.Assert(b.VenueId != null);

            // FUTURE: Centralize handling of location.
            var location = venue["location"];

            if (location != null)
            {
                b.Address = Json.TryGetJsonProperty(location, "address");

                b.City        = Json.TryGetJsonProperty(location, "city");
                b.CrossStreet = Json.TryGetJsonProperty(location, "crossStreet");
                b.State       = Json.TryGetJsonProperty(location, "state");
                b.Zip         = Json.TryGetJsonProperty(location, "postalCode");

                if (b.Address != null || b.CrossStreet != null)
                {
                    b.AddressLine = SpaceAfterIfThere(b.Address) + WrapIfThere(b.CrossStreet, "(", ")");
                }

                var gl  = location["lat"];
                var gll = location["lng"];
                // didn't work in Brazil and other place!
                //string gl = Json.TryGetJsonProperty(location, "lat");
                //string gll = Json.TryGetJsonProperty(location, "lng");
                if (gl != null && gll != null)
                {
                    try
                    {
                        b._location = new LocationPair
                        {
                            Latitude  = (double)gl,  // double.Parse(gl, CultureInfo.InvariantCulture),
                            Longitude = (double)gll, // double.Parse(gll, CultureInfo.InvariantCulture),
                        };
                    }
                    catch
                    {
                    }
                }

                string dist = Json.TryGetJsonProperty(location, "distance");
                if (dist == null)
                {
                    b.Meters = double.NaN;
                }
                else
                {
                    b.Meters = double.Parse(dist, CultureInfo.InvariantCulture);
                }
            }

            b.Name = Json.TryGetJsonProperty(venue, "name");
            if (b.Name != null)
            {
                b.Name = Checkin.SanitizeString(b.Name);
            }

            string verif = Json.TryGetJsonProperty(venue, "verified");
            // NOTE: Is this even useful to expose? (A bool property)

            var todos = venue["todos"];

            if (todos != null)
            {
                // temporary hack around lists...

                var subListOne = todos["id"];
                if (subListOne != null)
                {
                    var userSubTree = todos["user"];
                    if (userSubTree != null)
                    {
                        string userIsSelf = Json.TryGetJsonProperty(userSubTree, "relationship");
                        if (userIsSelf != null && userIsSelf == "self")
                        {
                            b.HasTodo = true;
                        }
                    }
                }

                //string htodo = Json.TryGetJsonProperty(todos, "count"); // checkin mode only
                //int i;
                //if (int.TryParse(htodo, CultureInfo.InvariantCulture);
                //if (i > 0)
                //{
                //b.HasTodo = true;
                //}
            }

            var specials = venue["specials"];

            if (specials != null)
            {
                try
                {
                    var cv            = new List <CompactSpecial>();
                    var specialsItems = specials["items"];
                    if (specialsItems != null)
                    {
                        foreach (var special in specialsItems)
                        {
                            if (special != null)
                            {
                                CompactSpecial spo = CompactSpecial.ParseJson(special, b.VenueId);
                                if (spo != null)
                                {
                                    cv.Add(spo);
                                }
                            }
                        }
                    }
                    if (cv.Count > 0)
                    {
                        b.Specials = cv;
                    }
                }
                catch (Exception)
                {
                    // As of 3.4, and a new Foursquare API version, specials
                    // returned are in dictionary format. This prevents cached
                    // data from throwing here.
                }
            }

            var stats = venue["stats"];

            if (stats != null)
            {
                // NOTE: V2: Add these properties to the POCO

                string checkinsCount = Json.TryGetJsonProperty(stats, "checkinsCount");
                int    i;
                if (int.TryParse(checkinsCount, out i))
                {
                    b.CheckinsCount = i;
                }

                string usersCount = Json.TryGetJsonProperty(stats, "usersCount");
            }

            var hereNow = venue["hereNow"];

            if (hereNow != null)
            {
                string hnc = Json.TryGetJsonProperty(hereNow, "count");
                int    hni;
                if (int.TryParse(hnc, out hni))
                {
                    if (hni > 1)
                    {
                        b.HereNow = Json.GetPrettyInt(hni) + " people";
                    }
                    else if (hni == 1)
                    {
                        b.HereNow = "1 person";
                    }
                }
            }

            var pc = venue["categories"];

            if (pc != null)
            {
                // FUTURE: A collection of all the categories.
                foreach (var category in pc)
                {
                    // NOTE: For this version, just grabbing the first categ.
                    b.PrimaryCategory = Category.ParseJson(category);
                    break;
                }
            }

            var contact = venue["contact"];

            if (contact != null)
            {
                b.Phone = Json.TryGetJsonProperty(contact, "phone");
                // NOTE: VENUE TWITTER?
            }

            b.VenueUri = new Uri(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "/Views/Venue.xaml?id={0}&name={1}",
                    Uri.EscapeDataString(b.VenueId),
                    Uri.EscapeDataString(b.Name)), UriKind.Relative);

            return(b);
        }