Esempio n. 1
0
        private async void menuFlyoutItemMediaFromClipboard_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var image = await Clipboard.GetContent().GetBitmapAsync();

                var stream = await image.OpenReadAsync();

                var    size   = stream.Size;
                byte[] bytes  = new byte[size];
                var    reader = new DataReader(stream.GetInputStreamAt(0));
                await reader.LoadAsync((uint)size);

                reader.ReadBytes(bytes);



                var media = new PostMedia();
                media.Data     = bytes;
                media.FileName = DateTime.Now.ToString("yyyyMMddhhmmss");

                viewModel.SetPostImageCommand.Execute(media);
            }
            catch (Exception)
            {
                ToastText text = new ToastText("クリップボードの取得に失敗しました", ToastTemplateType.ToastText01);
                text.Show();
            }
        }
        public async Task AddAsync(PostMedia entity)
        {
            await DbContextManager.BeginTransactionAsync();

            var spParameters = new SqlParameter[2];

            spParameters[0] = new SqlParameter()
            {
                ParameterName = "userid", Value = entity.UserId
            };
            spParameters[1] = new SqlParameter()
            {
                ParameterName = "post", Value = entity.Media
            };

            await DbContextManager.StoreProc <StoreProcResult>("[dbo].spInsertPostMedias", spParameters);

            try
            {
                await DbContextManager.CommitAsync();
            }
            catch (Exception)
            {
                DbContextManager.RollbackTransaction();
            }
        }
Esempio n. 3
0
        /* NOT TESTED YET
         * public async Task DeletePostAsync(int id)
         * {
         *  var post = await _blogContext.Posts
         *      .AsNoTracking()
         *      .FirstOrDefaultAsync(x => x.Id == id);
         * }*/


        //  Helper methods

        private string SetPostMediaName(PostMedia media)
        {
            var ext      = Path.GetExtension(media.MedialUrl);
            var name     = Path.GetFileNameWithoutExtension(media.MedialUrl);
            var fileName = name + ext;

            return(fileName);
        }
Esempio n. 4
0
        private Task DeletePostFileAsync(PostMedia media)
        {
            var fileName = SetPostMediaName(media);
            var filePath = GetPostMediaFilePath(fileName);

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            return(Task.CompletedTask);
        }
Esempio n. 5
0
        public TwitterUIComponent()
        {
            suggestList = new ObservableCollection <string>();
            mentionSuggestSourceList = new ObservableCollection <string>();
            hashSuggestSourceList    = new ObservableCollection <string>();

            postText        = "";
            isHashTagLock   = false;
            isPostWithMedia = false;
            PostMedia       = new PostMedia();
            InReplyToStatus = Tweet.ZeroTweet;
        }
Esempio n. 6
0
        public IActionResult Delete(int id)
        {
            int    resHttpStatusCode = 400;
            string resMsg            = "Bad request";

            try
            {
                using (var ctx = new ConclaveDbContext())
                {
                    var itemToRemove = ctx.Post.SingleOrDefault(x => x.Id == id);
                    if (itemToRemove != null)
                    {
                        if (itemToRemove.Media == "Y")
                        {
                            var q = (from item in ctx.PostMedia where item.PostId == id select new { id = item.Id }).ToList();
                            foreach (var item in q)
                            {
                                PostMedia pm = new PostMedia()
                                {
                                    Id = item.id
                                };
                                ctx.PostMedia.Attach(pm);
                                ctx.PostMedia.Remove(pm);
                            }
                            ctx.SaveChanges();
                        }
                        ctx.Post.Attach(itemToRemove);
                        ctx.Post.Remove(itemToRemove);
                        ctx.SaveChanges();
                        _cache.StringSet("posts-get-all-isnew", "y");
                        resHttpStatusCode = 200;
                    }
                }
            }
            catch (Exception e)
            {
                CLogger.Log(e);
                resHttpStatusCode = 500;
            }

            HttpContext.Response.StatusCode = resHttpStatusCode;
            return(new JsonResult(new
            {
                success = (resHttpStatusCode == 200 ? "true" : "false"),
                msg = resMsg
            }));
        }
Esempio n. 7
0
        private async Task SetPostImageAsync(StorageFile file)
        {
            var stream = await file.OpenAsync(FileAccessMode.Read);

            var size = stream.Size;

            byte[] bytes  = new byte[size];
            var    reader = new DataReader(stream.GetInputStreamAt(0));
            await reader.LoadAsync((uint)size);

            reader.ReadBytes(bytes);
            var media = new PostMedia();

            media.Data     = bytes;
            media.FileName = DateTime.Now.ToString("yyyyMMddhhmmss");

            viewModel.SetPostImageCommand.Execute(media);
        }
Esempio n. 8
0
            /// <summary>
            /// 上传媒体文件
            /// </summary>
            /// <param name="media"></param>
            /// <param name="url"></param>
            /// <returns></returns>
            public static string GetMediaResult(string url, PostMedia media)
            {
                Encoding encoding = Encoding.GetEncoding(REQUESTENCODING);

                byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + BOUNDARY + "\r\n");
                byte[] endbytes      = Encoding.ASCII.GetBytes("\r\n--" + BOUNDARY + "--\r\n");

                // content-type前不能有空格
                string format = "content-disposition: form-data; name=\"{0}\"; filename=\"{1}\";filelegth=\"{2}\"\r\ncontent-type: application/octet-stream\r\n\r\n";

                byte[] headerbytes = encoding.GetBytes(string.Format(format, "media", media.FullName, media.ByteData.Length));
                byte[] buffer;
                using (var stream = new MemoryStream())
                {
                    stream.Write(boundarybytes, 0, boundarybytes.Length);
                    stream.Write(headerbytes, 0, headerbytes.Length);
                    stream.Write(media.ByteData, 0, media.ByteData.Length);
                    stream.Write(endbytes, 0, endbytes.Length);//1.3 form end
                    buffer = stream.GetBuffer();
                }

                return(GetFileResult(url, buffer));
            }
Esempio n. 9
0
        /// <summary>
        /// Updates post media files <see cref="PostMedia"/>
        /// </summary>
        /// <param name="post"></param>
        /// <param name="oldMedia"></param>
        /// <returns></returns>
        public async Task <(List <PostMedia> newMedia, List <PostMedia> oldMedia)> UpdatePostMediaAsync(Post post, IReadOnlyCollection <PostMedia> oldMedia)
        {
            var deleteList   = new List <PostMedia>();
            var imgRegex     = new Regex("<img[^>].+ />", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            var newPostMedia = new List <PostMedia>();

            var oldMediaFiles = new List <PostMedia>();

            if (oldMedia != null)
            {
                oldMediaFiles.AddRange(oldMedia);
            }

            post.Media.Clear();

            foreach (Match match in imgRegex.Matches(post.Content))
            {
                var doc = new XmlDocument();
                doc.LoadXml("<root>" + match.Value + "</root>");

                var assetArray    = doc.FirstChild.FirstChild.Attributes;
                var imageUrl      = assetArray[0].InnerText;
                var imageFilename = assetArray[1].InnerText;


                if (string.IsNullOrEmpty(imageFilename) || string.IsNullOrEmpty(imageUrl))
                {
                    continue;
                }
                var media = new PostMedia
                {
                    PostId    = post.Id,
                    FileName  = imageFilename,
                    MedialUrl = imageUrl
                };
                //  set fileName
                media.FileName = SetPostMediaName(media);
                newPostMedia.Add(media);
            }

            //  has old photos? delete them
            var anyOldPhotos = oldMediaFiles.Any();

            if (anyOldPhotos)
            {
                //deleteList.AddRange(from itm in oldMedia let itemFound = post.Media.Any(x => x.FileName == itm.FileName) where itemFound == false select itm);
                foreach (var itm in oldMediaFiles)
                {
                    // item in post.Media? true else add for delete(deleteList)
                    var found = post.Media.Any(x => x.FileName == itm.FileName); // ok
                    if (!found)
                    {
                        deleteList.Add(itm);// not found so add it to removal list for deletion
                    }
                }
            }

            if (!deleteList.Any())
            {
                return(newPostMedia, oldMediaFiles);
            }
            {
                //  delete each item from serve
                foreach (var itm in deleteList)
                {
                    await DeletePostFileAsync(itm);
                }
            }

            return(newPostMedia, oldMediaFiles);
        }
 public Task DeleteAsync(PostMedia parameters)
 {
     throw new NotImplementedException();
 }
 public HashSet <string> DeleteValidation(PostMedia parameters)
 {
     return(ValidationMessages);
 }
        public async Task UpdateAsync(PostMedia entity)
        {
            await Uow.RegisterDirtyAsync(entity);

            await Uow.CommitAsync();
        }
 public Task <object> GetBy(PostMedia parameters)
 {
     throw new NotImplementedException();
 }
Esempio n. 14
0
 public void SetPostImage(PostMedia media)
 {
     TwitterUIComponent.SetPostMedia(media);
 }
Esempio n. 15
0
 public void SetPostMedia(PostMedia media)
 {
     this.PostMedia = media;
     IsAcceptMedia  = true;
 }
 public HashSet <string> UpdateValidation(PostMedia entity)
 {
     return(ValidationMessages);
 }
Esempio n. 17
0
        /// <summary>
        /// 设置客服帐号的头像
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="kf_account"></param>
        /// <param name="media"></param>
        /// <returns></returns>
        public JsonResult UploadHeadImg(string access_token, string kf_account, PostMedia media)
        {
            string url = string.Format("{0}cgi-bin/customservice/kfaccount/uploadheadimg?access_token={1}&kf_account={2}", baseUrl, access_token, kf_account);

            return(JsonHelper.Decode <JsonResult>(HttpHelper.HttpPost.GetMediaResult(url, media)));
        }
Esempio n. 18
0
        public async Task <IActionResult> Post()
        {
            int    resHttpStatusCode = 400;
            string resMsg            = "Bad request";

            try
            {
                var uploadPath = _config["AppConfig:Storage:Uploads"];
                if (!string.IsNullOrEmpty(Request.Form["text"].ToString()))
                {
                    Post post = new Post();
                    post.UserSocialId = AuthToken.GetUserSocialId(HttpContext.Request.Headers["Authorization"].ToString().Split(" ")[1]);
                    post.Text         = Request.Form["text"].ToString();

                    List <Tuple <string, string> > attachmentList = new List <Tuple <string, string> >();
                    foreach (var formFile in Request.Form.Files)
                    {
                        if (formFile.Length > 0)
                        {
                            var filetype = formFile.ContentType.Split("/")[0];
                            var filename = Guid.NewGuid().ToString() + DateTime.UtcNow.ToString("yyyyMMddHHmmsss") + formFile.FileName.Substring(formFile.FileName.LastIndexOf(".", System.StringComparison.Ordinal));
                            var filePath = Path.Combine(uploadPath, filename);

                            using (var stream = System.IO.File.Create(filePath))
                            {
                                await formFile.CopyToAsync(stream).ConfigureAwait(false);

                                attachmentList.Add(Tuple.Create(filetype, "/" + uploadPath + filename));
                            }
                        }
                    }
                    post.Media = attachmentList.Count() > 0 ? "Y" : "N";
                    using (var ctx = new ConclaveDbContext())
                    {
                        ctx.Post.Add(post);
                        ctx.SaveChanges();
                        var postid = post.Id;
                        foreach (var(filetype, filepath) in attachmentList)
                        {
                            PostMedia pm = new PostMedia();
                            pm.PostId   = postid;
                            pm.Path     = filepath;
                            pm.Filetype = filetype;
                            ctx.PostMedia.Add(pm);
                            ctx.SaveChanges();
                        }
                    }
                    _cache.StringSet("posts-get-all-isnew", "y");
                    resHttpStatusCode = 200;
                    resMsg            = "Post addedd successfully";
                }
            }
            catch (Exception e)
            {
                resHttpStatusCode = 500;
                resMsg            = "An internal error has occurred";
                CLogger.Log(e);
            }
            HttpContext.Response.StatusCode = resHttpStatusCode;
            return(new JsonResult(new
            {
                success = (resHttpStatusCode == 200 ? "true" : "false"),
                msg = resMsg
            }));;
        }