예제 #1
0
        public List <InstagramPost> GetUserPostsByUsername(string username, byte[] instagramCookies)
        {
            IInstaApi instaApi = CreateInstaApi(instagramCookies, REQUEST_DELAY_MIN, REQUEST_DELAY_MAX);

            List <InstagramPost> posts = new List <InstagramPost>();

            PaginationParameters pageParams = PaginationParameters.Empty;

            Task <IResult <InstaMediaList> > mediaListTask = Task.Run(() => instaApi.UserProcessor.GetUserMediaAsync(username, pageParams));

            mediaListTask.Wait();
            IResult <InstaMediaList> mediaList = mediaListTask.Result;

            if (mediaList.Succeeded)
            {
                Parallel.ForEach(mediaList.Value, media =>
                {
                    InstagramPost post   = new InstagramPost();
                    post.CountOfComments = Convert.ToInt32(media.CommentsCount);
                    post.Commenters      = GetPostCommenters(media);
                    post.CountOfLikes    = Convert.ToInt32(media.LikesCount);
                    post.Likers          = GetPostLikers(media);
                    post.MediaFileUri    = GetUri(media);
                    posts.Add(post);
                });
            }

            return(posts);
        }
예제 #2
0
        public List <InstagramPost> GetUserPostsByUsername(string username)
        {
            if (_instaApi == null)
            {
                throw new NullReferenceException();
            }

            List <InstagramPost> posts = new List <InstagramPost>();

            Task <IResult <InstaMediaList> > mediaListTask = Task.Run(() => _instaApi.UserProcessor.GetUserMediaAsync(username, PaginationParameters.MaxPagesToLoad(MAX_PAGES_TO_LOAD)));

            mediaListTask.Wait();
            IResult <InstaMediaList> mediaList = mediaListTask.Result;

            if (mediaList.Succeeded)
            {
                Parallel.ForEach(mediaList.Value, media =>
                {
                    InstagramPost post   = new InstagramPost();
                    post.CountOfComments = Convert.ToInt32(media.CommentsCount);
                    post.Commenters      = GetPostCommenters(media);
                    post.CountOfLikes    = Convert.ToInt32(media.LikesCount);
                    post.Likers          = GetPostLikers(media);
                    post.MediaFileUri    = GetUri(media);
                    posts.Add(post);
                });
            }

            return(posts);
        }
예제 #3
0
        public async Task <List <InstagramPost> > GetUserPostsByPrimaryKeyAsync(string primaryKey)
        {
            if (_instaApi == null)
            {
                throw new NullReferenceException();
            }

            long pk = Convert.ToInt64(primaryKey);
            List <InstagramPost> posts      = new List <InstagramPost>();
            PaginationParameters pageParams = PaginationParameters.MaxPagesToLoad(MAX_PAGES_TO_LOAD);

            IResult <InstaMediaList> mediaList = await _instaApi.UserProcessor.GetUserMediaByIdAsync(pk, pageParams);

            if (mediaList.Succeeded)
            {
                Parallel.ForEach(mediaList.Value, media =>
                {
                    InstagramPost post   = new InstagramPost();
                    post.CountOfComments = Convert.ToInt32(media.CommentsCount);
                    post.Commenters      = GetPostCommenters(media);
                    post.CountOfLikes    = Convert.ToInt32(media.LikesCount);
                    post.Likers          = GetPostLikers(media);
                    post.MediaFileUri    = GetUri(media);
                    posts.Add(post);
                });
            }

            return(posts);
        }
        // POST api/values
        //public void Post([FromBody]InstagramPost instragramPost)
        public async Task GetAsync()

        {
            InstagramPost instagram = new InstagramPost();

            instagram.Login    = "******";
            instagram.Password = "******";
            instagram.UrlLink  = "http://10.10.0.193:80/Videos/2bbca089-1916-47d8-809a-23f8b400d629/video.mp4";
        }
예제 #5
0
        private static List <InstagramPost> ConvertJsonResponseInObjects(List <string> allMediaIds)
        {
            List <InstagramPost> posts = new List <InstagramPost>();

            foreach (string post in allMediaIds)
            {
                string        onePost   = GetOnePost(post);
                InstagramPost instaPost = new InstagramPost(onePost);
                posts.Add(instaPost);
            }
            return(posts);
        }
예제 #6
0
        public async Task <JsonResult> HasLikedPagePostAsync(string InstagramPostLink,
                                                             bool increasePointsIfLiked = false)
        {
            InstagramPost InstagramPost = context.InstagramPosts.SingleOrDefault(c => c.Link == InstagramPostLink);
            List <string> likers        = new List <string>();
            bool          hasLiked      = likers.Any(liker => liker == CurrentUser.Name);

            if (hasLiked && increasePointsIfLiked)
            {
                CurrentUser.Points += 10;
                await context.SaveChangesAsync();
            }
            return(Json(hasLiked, JsonRequestBehavior.AllowGet));
        }
        public async Task <List <InstagramPost> > GetPosts()
        {
            IInstaApi api = (IInstaApi)HttpContext.Current.Session["api"];

            if (api == null || !api.IsUserAuthenticated)
            {
                return(null);
            }

            List <InstagramPost> results = null;
            var user = await api.GetCurrentUserAsync();

            if (!user.Succeeded)
            {
                return(null);
            }

            var mediaCollections = await api.UserProcessor.GetUserMediaAsync(user.Value.UserName, InstagramApiSharp.PaginationParameters.MaxPagesToLoad(2));

            if (!mediaCollections.Succeeded)
            {
                return(null);
            }


            results = new List <InstagramPost>();
            for (int i = 0; i < mediaCollections.Value.Count; i++)
            {
                InstagramPost temp = new InstagramPost();
                //temp.ImageUri = mediacollections.Value[i].Images[1].Uri;
                //temp.ViewCount = mediacollections.Value[i].ViewCount;
                //temp.
                results.Add(new InstagramPost
                {
                    LikesCount    = mediaCollections.Value[i].LikesCount,
                    ViewCount     = mediaCollections.Value[i].ViewCount,
                    CommentsCount = mediaCollections.Value[i].CommentsCount,
                    ImageUriSmall = mediaCollections.Value[i].Images[1].Uri,
                    ImageUriLarge = mediaCollections.Value[i].Images[0].Uri,
                    DatePosted    = mediaCollections.Value[i].TakenAt.ToShortDateString(),
                    TimePosted    = mediaCollections.Value[i].TakenAt.ToShortTimeString(),
                    Description   = mediaCollections.Value[i].Caption.Text
                });
            }


            return(results);
        }
예제 #8
0
        private static async Task <List <InstagramPost> > GetInstagramPosts(InstagramPage instagramPage, List <string> shortcodes)
        {
            List <InstagramPost> instagramPosts = new List <InstagramPost>();

            foreach (var shortCode in shortcodes)
            {
                //Retrieve instagram post with pictures
                HttpClient    client        = new HttpClient();
                Uri           url           = new Uri(@"https://www.instagram.com/p/" + shortCode + @"/?__a=1", UriKind.Absolute);
                InstagramPost instagramPost = new InstagramPost();
                instagramPost.Pictures = new List <byte[]>();
                List <Uri> pictureUrls = new List <Uri>();
                using (var response = await client.GetAsync(url))
                {
                    using (var content = response.Content)
                    {
                        string json = await content.ReadAsStringAsync();

                        JObject jsonResult = JObject.Parse(json);
                        try
                        {
                            instagramPost.Message = (string)jsonResult.SelectToken("$.graphql.shortcode_media.edge_media_to_caption.edges[0].node.text");
                            instagramPost.Likes   = (int)jsonResult.SelectToken("$.graphql.shortcode_media.edge_media_preview_like.count");
                        }
                        catch (Exception)
                        {
                        }
                        pictureUrls = jsonResult.SelectTokens("$.graphql.shortcode_media.edge_sidecar_to_children.edges.[*].node.display_resources[0].src").Select(s => (Uri)s).ToList();

                        if (pictureUrls.Count == 0)
                        {
                            pictureUrls.Add((Uri)jsonResult.SelectToken("$.graphql.shortcode_media.display_resources[0].src"));
                        }
                    }
                }

                foreach (var pictureUrl in pictureUrls)
                {
                    byte[] picture = await client.GetByteArrayAsync(pictureUrl);

                    instagramPost.Pictures.Add(picture);
                }

                instagramPosts.Add(instagramPost);
            }
            return(instagramPosts);
        }
예제 #9
0
        public async Task <ActionResult> AddPost(InstagramPost post)
        {
            if (CurrentUser.Points - post.Points < 0)
            {
                ModelState.AddModelError("Points", "You do not have enough points, Please earn points");
            }
            if (ModelState.IsValid)
            {
                post.ApplicationUser = CurrentUser;
                lock (post.ApplicationUser)
                {
                    post.ApplicationUser.Points -= (int)post.Points;
                }
                context.InstagramPosts.Add(post);
                await context.SaveChangesAsync();

                return(RedirectToAction("Posts"));
            }
            return(View(post));
        }
예제 #10
0
        public async Task <JsonResult> GetPostLikes(string link, int numberOfPrevLikes = 0, bool increasePoints = false)
        {
            InstagramPost      post      = context.InstagramPosts.First(c => c.Link == link);
            InstagramMediaInfo mediaInfo = GetMediaInfo(post.ApplicationUser
                                                        .AccessTokens.First(a => a.Provider == "Instagram").AccessTokenValue);
            int count = mediaInfo.data.First(d => d.link == link).likes.count;

            if (increasePoints)
            {
                if (count > numberOfPrevLikes)
                {
                    lock (CurrentUser)
                    {
                        CurrentUser.Points += 10;
                    }
                    await context.SaveChangesAsync();
                }
            }
            return(Json(count,
                        JsonRequestBehavior.AllowGet));
        }
예제 #11
0
        public async Task <InstagramPost> GetPostMetadata(string postUrl)
        {
            InstagramPost post = default;

            try
            {
                await page.GoToAsync(postUrl);

                post = new InstagramPost()
                {
                    Comments         = await InstagramScrapingUtils.GetComments(page),
                    Likes            = await InstagramScrapingUtils.GetLikes(page),
                    PhotoOrVideoUrls = await InstagramScrapingUtils.GetPhotoOrVideoUrls(page)
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(post);
        }
예제 #12
0
        public override async Task ExecuteAsync(string generator, WebHookHandlerContext context)
        {
            // Get the WebHook client
            InstagramWebHookClient client = Dependencies.Client;

            // Convert the incoming data to a collection of InstagramNotifications
            var notifications = context.GetDataOrDefault <InstagramNotificationCollection>();

            foreach (var notification in notifications)
            {
                // Use WebHook client to get detailed information about the posted media
                JArray entries = await client.GetRecentGeoMedia(context.Id, notification.ObjectId);

                foreach (JToken entry in entries)
                {
                    InstagramPost post = entry.ToObject <InstagramPost>();

                    // Image information
                    if (post.Images != null)
                    {
                        InstagramMedia thumbnail = post.Images.Thumbnail;
                        InstagramMedia lowRes    = post.Images.LowResolution;
                        InstagramMedia stdRes    = post.Images.StandardResolution;
                    }

                    // Video information
                    if (post.Videos != null)
                    {
                        InstagramMedia lowBandwidth = post.Videos.LowBandwidth;
                        InstagramMedia lowRes       = post.Videos.LowResolution;
                        InstagramMedia stdRes       = post.Videos.StandardResolution;
                    }

                    // Get direct links and sizes of media
                    Uri link = post.Link;
                }
            }
        }
예제 #13
0
        private void initPosts()
        {
            var frame = (Panel as GisPanel).Frame;

            // Clear
            if (VkCurrentLayer != null)
            {
                Layers.Remove(VkCurrentLayer);
                frame.viewLayers.GisLayers.Remove(VkCurrentLayer.Layer);
            }
            if (Control.PostsVK == null || Control.PostsVK.Count == 0)
            {
                return;
            }

            // add new posts
            globePostsVK = new PointsGisLayer(Game, Control.PostsVK.Count)
            {
                ImageSizeInAtlas = new Vector2(128, 128),
                TextureAtlas     = Game.Content.Load <Texture2D>("Train/station_circle.tga")
            };
            globePostsVK.ZOrder = 1000;
            var id = 0;

            foreach (var post in Control.PostsVK.FindAll(e => e.geo != null))
            {
                var coordinate = post.geo.coordinates.Split(' ');
                globePostsVK.PointsCpu[id] = new Gis.GeoPoint
                {
                    Lon   = DMathUtil.DegreesToRadians(double.Parse(coordinate[1])),
                    Lat   = DMathUtil.DegreesToRadians(double.Parse(coordinate[0])),
                    Color = new Color(255, 217, 0, maxAlpha),
                    Tex0  = new Vector4(0, 0, 0.05f, 0.0f)
                };
                id++;
            }
            VkCurrentLayer = new GisLayerWrapper(globePostsVK);
            frame.viewLayers.GisLayers.Add(VkCurrentLayer.Layer);
            Layers.Add(VkCurrentLayer);
            globePostsVK.UpdatePointsBuffer();

            if (frames != null)
            {
                for (int i = 0; i < frames.Count; i++)
                {
                    var f = frames[i];
                    f.Parent.Remove(f);
                    f = null;
                }
                frames.Clear();
            }
            var ui = ((CustomGameInterface)Game.GameInterface).ui;
            List <InstagramPost> instPost = new List <InstagramPost>();
            int idx = 0;

            if (Control.newPostsVK == null)
            {
                return;
            }
            foreach (var po in Control.newPostsVK)
            {
                var ins = new InstagramPost()
                {
                    Likes     = po?.likes?.count > 0 ? po.likes.count.ToString() : 0.ToString(),
                    Text      = po.text,
                    TimeStamp = ConvertFromUnixTimestamp((double)po.date * 1000),
                    Url       = String.IsNullOrEmpty(po.photo_url) ? "" : po.photo_url,
                };
                instPost.Add(ins);
                var geopoint = globePostsVK.PointsCpu[globePostsVK.PointsCount - Control.newPostsVK.Count + idx];
                idx++;
                var cartesianCoor  = GeoHelper.SphericalToCartesian(new DVector2(geopoint.Lon, geopoint.Lat));
                var screenPosition = ViewLayer.GlobeCamera.CartesianToScreen(cartesianCoor);
                Console.WriteLine(screenPosition);
                if (screenPosition.X < 0 || screenPosition.Y < 0)
                {
                    continue;
                }
                var newFrame = FrameHelper.createWebPhotoFrameGeoTag(ui, (int)screenPosition.X, (int)screenPosition.Y, maxImageSize, maxImageSize, "inst_load", ins.Url, 0, instPost.ToArray(), geopoint);
                frames.Add(newFrame);
                frame.Add(newFrame);
            }

            // clear new posts
            Control.newPostsVK = null;
        }
예제 #14
0
 public async Task SaveFile(InstagramPost data, string fileName)
 {
     var _path    = Path.Combine(Directory.GetCurrentDirectory(), $"{fileName}_post.json");
     var _dataStr = JsonConvert.SerializeObject(data);
     await File.WriteAllTextAsync(_path, _dataStr);
 }
예제 #15
0
        //action on mouse
        public void onMouseClick(int mouseX, int mouseY)
        {
            foreach (var f in frames)
            {
                if (f.GlobalRectangle.Contains(mouseX, mouseY))
                {
                    return;
                }
                Console.WriteLine("click on frame");
            }

            //if (frames.Count > 1) return;
            DVector2 mousePosition;

            ViewLayer.GlobeCamera.ScreenToSpherical(mouseX, mouseY, out mousePosition);
            var posts = new List <Post>();

            Gis.GeoPoint currentpost = new Gis.GeoPoint();

            if (globePostsVK != null && globePostsVK.IsVisible)
            {
                for (int i = 0; i < Control.PostsVK.Count; i++)
                {
                    var post = globePostsVK.PointsCpu[i];
                    if (post.Color.Alpha == 0)
                    {
                        continue;
                    }
                    var distance = GeoHelper.DistanceBetweenTwoPoints(mousePosition, new DVector2(post.Lon, post.Lat));
                    if (distance < post.Tex0.Z)
                    {
                        if (!(Game.GameInterface is CustomGameInterface))
                        {
                            return;
                        }

                        posts.Add(Control.PostsVK[i]);
                        currentpost = post;
                    }
                }
            }

            Log.Message(DMathUtil.RadiansToDegrees(mousePosition.X) + "");
            Log.Message(DMathUtil.RadiansToDegrees(mousePosition.Y) + "");

            var ui = ((CustomGameInterface)Game.GameInterface).ui;

            if (posts.Count > 0)
            {
                //for (int i = 0; i < frames.Count; i++)
                //{
                //	var f = frames[i];
                //	f.Parent.Remove(f);
                //	f = null;
                //}
                //frames.Clear();
                List <InstagramPost> instPost = new List <InstagramPost>();
                foreach (var po in posts)
                {
                    var ins = new InstagramPost()
                    {
                        Likes     = po?.likes?.count > 0? po.likes.count.ToString() : 0.ToString(),
                        Text      = po.text,
                        TimeStamp = ConvertFromUnixTimestamp((double)po.date * 1000),
                        Url       = String.IsNullOrEmpty(po.photo_url) ? "" : po.photo_url,
                    };
                    instPost.Add(ins);
                }
                var frame = FrameHelper.createWebPhotoFrameGeoTag(ui, mouseX, mouseY, maxImageSize, maxImageSize, "inst_load", posts[0].photo_url, 0, instPost.ToArray(), currentpost);
                frames.Add(frame);
                var p = (Panel as GisPanel);
                p.Frame.Insert(0, frame);
            }
            else
            {
                for (int i = 0; i < frames.Count; i++)
                {
                    var f = frames[i];
                    f.Parent.Remove(f);
                    f = null;
                }
                frames.Clear();
            }
        }
예제 #16
0
        /// <summary>
        /// Creates and adds a few ItemViewModel objects into the Items collection.
        /// </summary>
        public void LoadData()
        {
            /*for (int i = 0; i < 10; i++)
            {
                Items.Add(new InstagramPost()
                {
                    Username = "******" + i.ToString(),
                    Caption = "Description" + i.ToString(),
                    Image = @"http://upload.wikimedia.org/wikipedia/en/2/28/Instagram_logo.png"

                });

            }*/

            WebClient req = new WebClient();

            req.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(
                delegate(object sender, System.Net.DownloadStringCompletedEventArgs e)
                {
                    JObject o = JObject.Parse(e.Result);
                    JArray posts = (JArray)o["data"];
                    foreach (JObject post in posts)
                    {

                        try
                        {
                            JObject captionArray = (JObject)post.SelectToken("caption");
                            InstagramPost item = new InstagramPost();

                            if (captionArray != null)
                            {

                                Items.Add(new InstagramPost()
                                {
                                    Caption = (string)captionArray.SelectToken("text"),
                                    Username = (string)captionArray.SelectToken("from").SelectToken("username"),
                                    Image = (string)post.SelectToken("images").SelectToken("standard_resolution").SelectToken("url")
                                });
                            }
                            else
                                continue;
                        }
                        catch (Exception )
                        {
                            continue;
                        }
                    }
                    this.IsDataLoaded = true;
                });

            // download the popular photos
            req.DownloadStringAsync(new Uri(@"https://api.instagram.com/v1/media/popular?client_id=5c545224bace4df68beb588b384ab80f"));
        }
예제 #17
0
        public JsonResult Save(InstagramPostViewModel model)
        {
            Response response;

            try
            {
                var      date        = DateUtility.GetDateTime(model.publishDate);
                DateTime dateTimeNow = DateTime.Today;
                if (date < dateTimeNow)
                {
                    response = new Response()
                    {
                        status  = 500,
                        message = "شما قادر به انتخاب روزهای گذشته نیستید.",
                    };
                    return(Json(response, JsonRequestBehavior.AllowGet));
                }
                int    status  = 200;
                string message = string.Empty;
                using (var db = new KiaGalleryContext())
                {
                    int userId = GetAuthenticatedUserId();
                    if (model.id != null && model.id > 0)
                    {
                        var entity = db.InstagramPost.Single(x => x.Id == model.id);
                        entity.Title             = model.title;
                        entity.Respite           = model.respite;
                        entity.DayCounter        = model.dayCounter;
                        entity.FileId            = model.fileId;
                        entity.FileName          = model.fileName;
                        entity.PublishDate       = DateUtility.GetDateTime(model.publishDate);
                        entity.InstagramPostType = model.instagramPostType;
                        entity.ModifyUserId      = userId;
                        entity.ModifyDate        = DateTime.Now;
                        entity.Ip = Request.UserHostAddress;
                        message   = "عملیات با موفقیت ویرایش شد.";
                    }
                    else
                    {
                        var entity = new InstagramPost()
                        {
                            Title             = model.title,
                            Respite           = model.respite,
                            DayCounter        = model.dayCounter,
                            FileId            = model.fileId,
                            FileName          = model.fileName,
                            PublishDate       = DateUtility.GetDateTime(model.publishDate),
                            InstagramPostType = model.instagramPostType,
                            CreateUserId      = GetAuthenticatedUserId(),
                            ModifyUserId      = GetAuthenticatedUserId(),
                            CreateDate        = DateTime.Now,
                            ModifyDate        = DateTime.Now,
                            Ip = Request.UserHostAddress,
                        };
                        db.InstagramPost.Add(entity);
                        message = "عملیت با موفقیت ایجاد شد.";
                    }
                    db.SaveChanges();
                }

                response = new Response()
                {
                    status  = status,
                    message = message
                };
            }
            catch (Exception ex)
            {
                response = Core.GetExceptionResponse(ex);
            }

            return(Json(response, JsonRequestBehavior.AllowGet));
        }
예제 #18
0
        private void CheckForUserLike(ApplicationUser observer, ObservableUser observable, User postOwner, InstagramPost firstPostState, InstagramPost secondPostState)
        {
            if (!firstPostState.Likers.Contains(observable) &&
                secondPostState.Likers.Contains(observable))
            {
                var activity = new UserActivity();
                activity.ObserverPrimaryKey   = observer.InstagramPK;
                activity.InitiatorPrimaryKey  = observable.InstagramPK;
                activity.TargetUserPrimaryKey = postOwner.InstagramPK;
                activity.LinkToMedia          = firstPostState.MediaFileUri;
                activity.EventDate            = DateTime.Now;
                activity.ActivityType         = UserActivityType.Like;

                _postIsLiked?.Invoke(null, activity);
            }
        }