Example #1
0
        public void AddTest()
        {
            Notebook notebook1 = new Notebook()
            {
                NotebookId = SnowFlake_Net.GenerateSnowFlakeID()
            };

            Notebook notebook2 = new Notebook()
            {
                NotebookId = SnowFlake_Net.GenerateSnowFlakeID()
            };

            Notebook notebook3 = new Notebook()
            {
                NotebookId = SnowFlake_Net.GenerateSnowFlakeID()
            };

            notebook2.ParentNotebookId = notebook1.NotebookId;
            notebook3.ParentNotebookId = notebook1.NotebookId;

            NotebookService.AddNotebook(notebook1);
            NotebookService.AddNotebook(notebook2);
            NotebookService.AddNotebook(notebook3);

            // Assert.Fail();
        }
Example #2
0
 public static bool LoginByPWD(String email, string pwd, out string tokenStr, out User user)
 {
     user = UserService.GetUser(email);
     if (user != null)
     {
         string temp = SHAEncrypt_Helper.Hash256Encrypt(pwd + user.Salt);
         if (temp.Equals(user.Pwd))
         {
             long  tokenid = SnowFlake_Net.GenerateSnowFlakeID();
             var   token   = TokenSerivce.GenerateToken(tokenid);
             Token myToken = new Token
             {
                 TokenId     = SnowFlake_Net.GenerateSnowFlakeID(),
                 UserId      = user.UserId,
                 Email       = user.Email,
                 TokenStr    = token,
                 Type        = 0,
                 CreatedTime = DateTime.Now
             };
             TokenSerivce.AddToken(myToken);
             tokenStr = myToken.TokenStr;
             return(true);
         }
         else
         {
             tokenStr = "";
             return(false);
         }
     }
     else
     {
         tokenStr = "";
         return(false);
     }
 }
Example #3
0
        // 添加笔记
        // 首先要判断Notebook是否是Blog, 是的话设为blog
        // [ok]
        public static Note AddNote(Note note, bool fromAPI)
        {
            if (note.NoteId == 0)
            {
                note.NoteId = SnowFlake_Net.GenerateSnowFlakeID();
            }
            // 关于创建时间, 可能是客户端发来, 此时判断时间是否有
            note.CreatedTime = Tools.FixUrlTime(note.CreatedTime);
            note.UpdatedTime = Tools.FixUrlTime(note.UpdatedTime);

            note.UrlTitle = InitServices.GetUrTitle(note.UserId, note.Title, "note", note.NoteId);
            note.Usn      = UserService.IncrUsn(note.UserId);
            long?notebookId = note.NotebookId;

            // api会传IsBlog, web不会传
            if (!fromAPI)
            {
                note.IsBlog = NotebookService.IsBlog(notebookId);
            }
            //	if note.IsBlog {
            note.PublicTime = note.UpdatedTime;
            AddNote(note);
            // tag1
            TagService.AddTags(note.UserId, note.Tags);
            // recount notebooks' notes number
            NotebookService.ReCountNotebookNumberNotes(notebookId);
            return(note);
        }
Example #4
0
        private async Task InsertLogAsync(string url)
        {
            var           headers       = Request.Headers;
            StringBuilder stringBuilder = new StringBuilder();

            foreach (var item in headers)
            {
                stringBuilder.Append(item.Key + "---" + item.Value + "\r\n");
            }
            string RealIP = headers["X-Forwarded-For"].ToString().Split(",")[0];

            AccessRecords accessRecords = new AccessRecords()
            {
                AccessId        = SnowFlake_Net.GenerateSnowFlakeID(),
                IP              = RealIP,
                X_Real_IP       = headers["X-Real-IP"],
                X_Forwarded_For = headers["X-Forwarded-For"],
                Referrer        = headers["Referer"],
                RequestHeader   = stringBuilder.ToString(),
                AccessTime      = DateTime.Now,
                UnixTime        = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds,
                TimeInterval    = -1,
                url             = url
            };
            await AccessService.InsertAccessAsync(accessRecords).ConfigureAwait(false);
        }
        public void InsertThemeTest()
        {
            Theme theme = new Theme();

            theme.ThemeId = SnowFlake_Net.GenerateSnowFlakeID();
            // theme.FriendLinksArray =new FriendLinks[]{ new FriendLinks() {FriendLinksId= SnowFlake_Net.GenerateSnowFlakeID() ,Title="A",Url="A"} };
            ThemeService.InsertTheme(theme);
            Assert.Fail();
        }
Example #6
0
        public void GenerateTokenTest()
        {
            long id = SnowFlake_Net.GenerateSnowFlakeID();

            Console.WriteLine(id);
            string token = TokenSerivce.GenerateToken(id, 16);

            Console.WriteLine(token);
        }
        public void InsertURLTest()
        {
            FriendLinks friendLinks = new FriendLinks();

            friendLinks.FriendLinksId = SnowFlake_Net.GenerateSnowFlakeID();
            friendLinks.ThemeId       = SnowFlake_Net.GenerateSnowFlakeID();
            friendLinks.Title         = "标题1";
            friendLinks.Title         = "标题2";
            Assert.Fail();
        }
        public void InsertNoteContentTest()
        {
            string      ContentJson = System.IO.File.ReadAllText(@"E:\Project\JSON\note\getNoteContent.json");
            NoteContent noteConteny = JsonSerializer.Deserialize <NoteContent>(ContentJson, MyJsonConvert.GetOptions());

            noteConteny.NoteId        = 201901;
            noteConteny.UpdatedUserId = SnowFlake_Net.GenerateSnowFlakeID();
            noteConteny.UserId        = SnowFlake_Net.GenerateSnowFlakeID();
            NoteContentService.InsertNoteContent(noteConteny);
        }
Example #9
0
 public static bool AddNoteTag(NoteTag noteTag)
 {
     if (noteTag.TagId == 0)
     {
         noteTag.TagId = SnowFlake_Net.GenerateSnowFlakeID();
     }
     using (var db = new DataContext())
     {
         var result = db.NoteTag.Add(noteTag);
         return(db.SaveChanges() > 0);
     }
 }
Example #10
0
        private static string GenerateToken()
        {
            StringBuilder tokenBuilder = new StringBuilder();

            long tokenid = SnowFlake_Net.GenerateSnowFlakeID();

            tokenBuilder.Append(tokenid.ToString("x"));
            tokenBuilder.Append("@");
            tokenBuilder.Append(RandomTool.CreatRandomString(16));
            tokenBuilder.Append("@");
            tokenBuilder.Append(DateTime.Now);
            var token = Base64Util.ToBase64String(tokenBuilder.ToString());

            return(token);
        }
Example #11
0
 public static bool AddUser(User
                            user)
 {
     if (user.UserId == 0)
     {
         user.UserId = SnowFlake_Net.GenerateSnowFlakeID();
     }
     user.CreatedTime = DateTime.Now;
     user.Email       = user.Email.ToLower();
     EmailService.RegisterSendActiveEmail(user, user.Email);
     using (var db = new DataContext())
     {
         db.User.Add(user);
         return(db.SaveChanges() > 0);
     }
 }
Example #12
0
        // 注册

        /*
         * 注册 [email protected] userId = "5368c1aa99c37b029d000001"
         * 添加 在博客上添加一篇欢迎note, note1 5368c1b919807a6f95000000
         *
         * 将nk1(只读), nk2(可写) 分享给该用户
         * 将note1 复制到用户的生活nk上
         */
        // 1. 添加用户
        // 2. 将leanote共享给我
        // [ok]
        public static bool Register(string email, string pwd, long fromUserId, out string Msg)
        {
            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(pwd) || pwd.Length < 6)
            {
                Msg = "参数错误";
                return(false);
            }
            if (UserService.IsExistsUser(email))
            {
                Msg = "userHasBeenRegistered-" + email;
                return(false);
            }
            //产生一个盐用于保存密码
            string salt = RandomTool.CreatSafeSalt();
            //对用户密码做哈希运算
            string genPass = SHAEncrypt_Helper.Hash256Encrypt(pwd + salt);

            if (string.IsNullOrEmpty(genPass))
            {
                Msg = "密码处理过程出现错误";
                return(false);
            }
            User user = new User()
            {
                UserId     = SnowFlake_Net.GenerateSnowFlakeID(),
                Email      = email,
                Username   = email,
                Pwd        = genPass,
                Salt       = salt,
                FromUserId = fromUserId,
                Usn        = 1
            };

            if (Register(user))
            {
                Msg = "注册成功";
                return(true);
            }
            else
            {
                Msg = "注册失败";
                return(false);
            }
        }
Example #13
0
        //添加notebook
        public IActionResult AddNotebook(string token, string title, string parentNotebookId, int seq)
        {
            User user = TokenSerivce.GetUserByToken(token);

            if (user == null)
            {
                ApiRe apiRe = new ApiRe()
                {
                    Ok  = false,
                    Msg = "Not logged in",
                };

                return(Json(apiRe, MyJsonConvert.GetOptions()));
            }
            else
            {
                Notebook notebook = new Notebook()
                {
                    NotebookId       = SnowFlake_Net.GenerateSnowFlakeID(),
                    Title            = title,
                    Seq              = seq,
                    UserId           = user.UserId,
                    ParentNotebookId = MyConvert.HexToLong(parentNotebookId)
                };
                if (NotebookService.AddNotebook(ref notebook))
                {
                    ApiNotebook apiNotebook = fixNotebook(notebook);

                    return(Json(apiNotebook, MyJsonConvert.GetOptions()));
                }
                else
                {
                    ApiRe apiRe = new ApiRe()
                    {
                        Ok  = false,
                        Msg = "AddNotebook is error",
                    };

                    return(Json(apiRe, MyJsonConvert.GetOptions()));
                }
            }
        }
Example #14
0
        public static bool AddNotebook(ref Notebook notebook)
        {
            if (notebook.NotebookId == 0)
            {
                notebook.NotebookId = SnowFlake_Net.GenerateSnowFlakeID();
            }
            notebook.UrlTitle = notebook.NotebookId.ToString("X");

            notebook.Usn = UserService.IncrUsn(notebook.UserId);

            DateTime now = DateTime.Now;

            notebook.CreatedTime = now;
            notebook.UpdatedTime = now;

            using (var db = new DataContext())
            {
                var result = db.Notebook.Add(notebook);
                return(db.SaveChanges() > 0);
            }
        }
Example #15
0
 public static Note AddNoteAndContent(Note note, NoteContent noteContent, long myUserId)
 {
     if (note.NoteId == 0)
     {
         note.NoteId = SnowFlake_Net.GenerateSnowFlakeID();
     }
     noteContent.NoteContentId = SnowFlake_Net.GenerateSnowFlakeID();
     noteContent.NoteId        = note.NoteId;
     if (note.UserId != 0 && note.UserId != myUserId)
     {
         note = AddSharedNote(note, myUserId);
     }
     else
     {
         note = AddNote(note, false);
     }
     if (note.NoteId != 0)
     {
         NoteContentService.AddNoteContent(noteContent);
     }
     return(note);
 }
Example #16
0
        //---------------------------
        // v2
        // 第二版标签, 单独一张表, 每一个tag一条记录

        // 添加或更新标签, 先查下是否存在, 不存在则添加, 存在则更新
        // 都要统计下tag的note数
        // 什么时候调用? 笔记添加Tag, 删除Tag时
        // 删除note时, 都可以调用
        // 万能
        public static NoteTag AddOrUpdateTag(long userId, string tag)
        {
            NoteTag noteTag = GetTag(userId, tag);

            // 存在, 则更新之
            if (noteTag != null && noteTag.TagId != 0)
            {
                // 统计note数
                int count = NoteService.CountNoteByTag(userId, tag);
                noteTag.Count       = count;
                noteTag.UpdatedTime = DateTime.Now;
                // 之前删除过的, 现在要添加回来了
                if (noteTag.IsDeleted)
                {
                    noteTag.Usn       = UserService.IncrUsn(userId);
                    noteTag.IsDeleted = false;
                    UpdateByIdAndUserId(noteTag.TagId, userId, noteTag);
                }
                return(noteTag);
            }
            // 不存在, 则创建之
            var timeNow = DateTime.Now;

            noteTag = new NoteTag()
            {
                TagId       = SnowFlake_Net.GenerateSnowFlakeID(),
                Count       = 1,
                Tag         = tag,
                UserId      = userId,
                CreatedTime = timeNow,
                UpdatedTime = timeNow,
                Usn         = UserService.IncrUsn(userId),
                IsDeleted   = false
            };
            AddNoteTag(noteTag);
            return(noteTag);
        }
Example #17
0
        public async Task <IActionResult> GetRandomImage(string type)
        {
            int hour = DateTime.Now.Hour;

            lock (_fuseObj)
            {
                _fuseCount++;
            }
            string ext = null;

            if (string.IsNullOrEmpty(type))
            {
                type = "动漫综合2";
            }
            if (type.Equals("少女映画"))
            {
                string userHex = HttpContext.Session.GetString("_userId");
                if (string.IsNullOrEmpty(userHex))
                {
                    //没登陆
                    return(Redirect("/Auth/login"));
                }
            }
            if (!_randomImageList.ContainsKey(type))
            {
                _randomImageList.Add(type, new List <RandomImage>(size));
            }
            RandomImage randomImage = RandomImageService.GetRandomImage(type);

            if (_randomImageList[type].Count < size)
            {
                randomImage = RandomImageService.GetRandomImage(type);
                if (random == null)
                {
                    return(NotFound());
                }
                _randomImageList[type].Add(randomImage);
            }
            else
            {
                if (DateTime.Now.Hour != _initTime)
                {
                    _fuseCount = 0;
                    _initTime  = DateTime.Now.Hour;
                    _randomImageList[type].Clear();
                    randomImage = RandomImageService.GetRandomImage(type);
                    if (random == null)
                    {
                        return(NotFound());
                    }
                    _randomImageList[type].Add(randomImage);
                }
                else
                {
                    if (_fuseCount > _randomImageFuseSize)
                    {
                        Response.StatusCode = (int)HttpStatusCode.BadGateway;
                        return(Content("接口并发太高,接口已经熔断"));
                    }
                    int index = random.Next(_randomImageList[type].Count - 1);
                    randomImage = _randomImageList[type][index];
                }
            }

            if (randomImage == null)
            {
                return(NotFound());
            }
            ext = Path.GetExtension(randomImage.FileName);
            var           headers       = Request.Headers;
            StringBuilder stringBuilder = new StringBuilder();

            foreach (var item in headers)
            {
                stringBuilder.Append(item.Key + "---" + item.Value + "\r\n");
            }
            string        RealIP        = headers["X-Forwarded-For"].ToString().Split(",")[0];
            AccessRecords accessRecords = new AccessRecords()
            {
                AccessId        = SnowFlake_Net.GenerateSnowFlakeID(),
                IP              = RealIP,
                X_Real_IP       = headers["X-Real-IP"],
                X_Forwarded_For = headers["X-Forwarded-For"],
                Referrer        = headers["Referer"],
                RequestHeader   = stringBuilder.ToString(),
                AccessTime      = DateTime.Now,
                UnixTime        = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds,
                TimeInterval    = -1,
                url             = "/api/GetRandomImage"
            };
            await AccessService.InsertAccessAsync(accessRecords).ConfigureAwait(false);

            type         = randomImage.TypeNameMD5;
            upyun.secret = postgreSQLConfig.upyunSecret;;
            Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            unixTimestamp += 3;
            //开启token防盗链

            if (postgreSQLConfig.token_anti_theft_chain)
            {
                string _upt = upyun.CreatToken(unixTimestamp.ToString(), upyun.secret, $"/upload/{type}/{randomImage.FileSHA1}{ext}");
                return(Redirect($"https://upyun.morenote.top/upload/{type}/{randomImage.FileSHA1}{ext}?_upt={_upt}"));
            }
            else
            {
                return(Redirect($"https://upyun.morenote.top/upload/{type}/{randomImage.FileSHA1}{ext}"));
            }
        }
Example #18
0
        public IActionResult AddAPP(long appid, string appautor, string appdetail, string appname, string apppackage,
                                    string appdownurl, string applogourl, string appversion, string imglist, long appsize, bool agreement, string password)
        {
            if (!password.Equals("9qMDpc4anxbckAFX47LIz7uaqpubicKSZMyd47RSbO3D7kgR51ui3V5dLFPDu7WS"))
            {
                return(Content("管理员密码错误"));
            }
            if (string.IsNullOrEmpty(appautor))
            {
                return(Content("appautor 不能为空"));
            }
            if (string.IsNullOrEmpty(appdetail))
            {
                return(Content("appdetail 不能为空"));
            }
            if (string.IsNullOrEmpty(appname))
            {
                return(Content("appname 不能为空"));
            }
            if (string.IsNullOrEmpty(apppackage))
            {
                return(Content("apppackage 不能为空"));
            }
            if (string.IsNullOrEmpty(appdownurl))
            {
                return(Content("appdownurl 不能为空"));
            }
            if (string.IsNullOrEmpty(applogourl))
            {
                return(Content("applogourl 不能为空"));
            }
            if (string.IsNullOrEmpty(appversion))
            {
                return(Content("appversion 不能为空"));
            }
            if (string.IsNullOrEmpty(imglist))
            {
                return(Content("imglist 不能为空"));
            }
            if (appsize == 0)
            {
                return(Content("appsize 不能为空"));
            }
            if (!agreement)
            {
                return(Content("你没有同意协议"));
            }
            AppInfo appInfo = new AppInfo()
            {
                appid      = SnowFlake_Net.GenerateSnowFlakeID(),
                appautor   = appautor,
                appdetail  = appdetail,
                appname    = appname,
                apppackage = apppackage,
                appdownurl = appdownurl,
                applogourl = applogourl,
                appversion = appversion,
                imglist    = imglist.Split("\n"),
                appsize    = appsize.ToString()
            };

            if (APPStoreInfoService.AddAPP(appInfo))
            {
                return(Content("发布成功,APP id=" + appInfo.appid));
            }
            else
            {
                return(Content("发布成功,APP id=" + appInfo.appid));
            }
        }
Example #19
0
 // 添加笔记时通过title得到urlTitle
 public static string fixUrlTitle(string urlTitle)
 {
     return(SnowFlake_Net.GenerateSnowFlakeIDHex());
 }
Example #20
0
        public bool upload(string name, long userId, long noteId, bool isAttach, out long serverFileId, out string msg)
        {
            if (isAttach)
            {
                return(uploadAttach(name, userId, noteId, out msg, out serverFileId));
            }
            msg          = "";
            serverFileId = 0;

            var uploadDirPath = $"{RuntimeEnvironment.DirectorySeparatorChar}www/upload/{userId.ToString("x")}/images/{DateTime.Now.ToString("yyyy_MM")}/";

            if (RuntimeEnvironment.IsWindows)
            {
                uploadDirPath = $@"upload\{userId.ToString("x")}\images\{DateTime.Now.ToString("yyyy_MM")}\";
            }
            var diskFileId = SnowFlake_Net.GenerateSnowFlakeID();

            serverFileId = diskFileId;
            var httpFiles = _accessor.HttpContext.Request.Form.Files;

            //检查是否登录
            if (userId == 0)
            {
                userId = GetUserIdBySession();
                if (userId == 0)
                {
                    msg = "NoLogin";
                    return(false);
                }
            }

            if (httpFiles == null || httpFiles.Count < 1)
            {
                return(false);
            }
            var httpFile = httpFiles[name];
            var fileEXT  = Path.GetExtension(httpFile.FileName).Replace(".", "");

            if (!IsAllowImageExt(fileEXT))
            {
                msg = $"The_image_extension_{fileEXT}_is_blocked";
                return(false);
            }
            var fileName = diskFileId.ToString("x") + "." + fileEXT;

            //判断合法性
            if (httpFiles == null || httpFile.Length < 0)
            {
                return(false);
            }
            //将文件保存在磁盘
            Task <bool> task   = SaveUploadFileOnDiskAsync(httpFile, uploadDirPath, fileName);
            bool        result = task.Result;

            if (result)
            {
                //将结果保存在数据库
                NoteFile noteFile = new NoteFile()
                {
                    FileId      = diskFileId,
                    UserId      = userId,
                    AlbumId     = 1,
                    Name        = fileName,
                    Title       = fileName,
                    Path        = uploadDirPath + fileName,
                    Size        = httpFile.Length,
                    CreatedTime = DateTime.Now
                                  //todo: 增加特性=图片管理
                };
                var AddResult = FileService.AddImage(noteFile, 0, userId, true);
                if (!AddResult)
                {
                    msg = "添加数据库失败";
                }
                return(AddResult);
            }
            else
            {
                msg = "磁盘保存失败";
                return(false);
            }
        }
        //todo:添加笔记
        public JsonResult AddNote(ApiNote noteOrContent, string token)
        {
            var x = _accessor.HttpContext.Request.Form.Files;
            var z = x["FileDatas[5e36bafc26f2af1a79000000]"];
            //json 返回状态好乱呀 /(ㄒoㄒ)/~~
            Re   re          = Re.NewRe();
            long tokenUserId = getUserIdByToken(token);;
            long myUserId    = tokenUserId;

            if (noteOrContent == null || string.IsNullOrEmpty(noteOrContent.NotebookId))
            {
                return(Json(new ApiRe()
                {
                    Ok = false, Msg = "notebookIdNotExists"
                }, MyJsonConvert.GetSimpleOptions()));
            }
            long noteId = SnowFlake_Net.GenerateSnowFlakeID();


            if (noteOrContent.Title == null)
            {
                noteOrContent.Title = "无标题";
            }

            // TODO 先上传图片/附件, 如果不成功, 则返回false
            //-------------新增文件和附件内容
            int attachNum = 0;

            if (noteOrContent.Files != null && noteOrContent.Files.Length > 0)
            {
                for (int i = 0; i < noteOrContent.Files.Length; i++)
                {
                    var file = noteOrContent.Files[i];
                    if (file.HasBody)
                    {
                        if (!string.IsNullOrEmpty(file.LocalFileId))
                        {
                            var result = upload("FileDatas[" + file.LocalFileId + "]", tokenUserId, noteId, file.IsAttach, out long serverFileId, out string msg);
                            if (!result)
                            {
                                if (string.IsNullOrEmpty(msg))
                                {
                                    re.Msg = "fileUploadError";
                                }
                                else
                                {
                                    re.Msg = msg;
                                    return(Json(re, MyJsonConvert.GetOptions()));
                                }
                            }
                            else
                            {
                                // 建立映射
                                file.FileId            = serverFileId.ToString("x");
                                noteOrContent.Files[i] = file;
                                if (file.IsAttach)
                                {
                                    attachNum++;
                                }
                            }
                        }
                        else
                        {   //存在疑问
                            return(Json(new ReUpdate()
                            {
                                Ok = false,
                                Msg = "LocalFileId_Is_NullOrEmpty",
                                Usn = 0
                            }, MyJsonConvert.GetSimpleOptions()));
                        }
                    }
                }
            }
            else
            {
            }
            //-------------替换笔记内容中的文件ID
            FixPostNotecontent(ref noteOrContent);
            if (noteOrContent.Tags != null)
            {
                if (noteOrContent.Tags.Length > 0 && noteOrContent.Tags[0] == null)
                {
                    noteOrContent.Tags = Array.Empty <string>();
                    //noteOrContent.Tags= new string[] { ""};
                }
            }
            //-------------新增笔记对象
            Note note = new Note()
            {
                UserId        = tokenUserId,
                NoteId        = noteId,
                CreatedUserId = noteId,
                UpdatedUserId = noteId,
                NotebookId    = MyConvert.HexToLong(noteOrContent.NotebookId),
                Title         = noteOrContent.Title,
                Tags          = noteOrContent.Tags,
                Desc          = noteOrContent.Desc,
                IsBlog        = noteOrContent.IsBlog.GetValueOrDefault(),
                IsMarkdown    = noteOrContent.IsMarkdown.GetValueOrDefault(),
                AttachNum     = attachNum,
                CreatedTime   = noteOrContent.CreatedTime,
                UpdatedTime   = noteOrContent.UpdatedTime,
                ContentId     = SnowFlake_Net.GenerateSnowFlakeID()
            };

            //-------------新增笔记内容对象
            NoteContent noteContent = new NoteContent()
            {
                NoteContentId = note.ContentId,
                NoteId        = noteId,
                UserId        = tokenUserId,
                IsBlog        = note.IsBlog,
                Content       = noteOrContent.Content,
                Abstract      = noteOrContent.Abstract,
                CreatedTime   = noteOrContent.CreatedTime,
                UpdatedTime   = noteOrContent.UpdatedTime,
                IsHistory     = false
            };

            //-------------得到Desc, abstract
            if (string.IsNullOrEmpty(noteOrContent.Abstract))
            {
                if (noteOrContent.IsMarkdown.GetValueOrDefault())
                {
                    // note.Desc = MyHtmlHelper.SubMarkDownToRaw(noteOrContent.Content, 200);
                    noteContent.Abstract = MyHtmlHelper.SubMarkDownToRaw(noteOrContent.Content, 200);
                }
                else
                {
                    //note.Desc = MyHtmlHelper.SubHTMLToRaw(noteOrContent.Content, 200);
                    noteContent.Abstract = MyHtmlHelper.SubHTMLToRaw(noteOrContent.Content, 200);
                }
            }
            else
            {
                note.Desc = MyHtmlHelper.SubHTMLToRaw(noteOrContent.Abstract, 200);
            }
            if (noteOrContent.Desc == null)
            {
                if (noteOrContent.IsMarkdown.GetValueOrDefault())
                {
                    note.Desc = MyHtmlHelper.SubMarkDownToRaw(noteOrContent.Content, 200);
                }
                else
                {
                    note.Desc = MyHtmlHelper.SubHTMLToRaw(noteOrContent.Content, 200);
                }
            }
            else
            {
                note.Desc = noteOrContent.Desc;
            }

            note = NoteService.AddNoteAndContent(note, noteContent, myUserId);
            //-------------将笔记与笔记内容保存到数据库
            if (note == null || note.NoteId == 0)
            {
                return(Json(new ApiRe()
                {
                    Ok = false,
                    Msg = "AddNoteAndContent_is_error"
                }));
            }
            //-------------API返回客户端信息
            noteOrContent.NoteId      = noteId.ToString("x");
            noteOrContent.UserId      = tokenUserId.ToString("x");
            noteOrContent.Title       = note.Title;
            noteOrContent.Tags        = note.Tags;
            noteOrContent.IsMarkdown  = note.IsMarkdown;
            noteOrContent.IsBlog      = note.IsBlog;
            noteOrContent.IsTrash     = note.IsTrash;
            noteOrContent.IsDeleted   = note.IsDeleted;
            noteOrContent.IsTrash     = note.IsTrash;
            noteOrContent.IsTrash     = note.IsTrash;
            noteOrContent.Usn         = note.Usn;
            noteOrContent.CreatedTime = note.CreatedTime;
            noteOrContent.UpdatedTime = note.UpdatedTime;
            noteOrContent.PublicTime  = note.PublicTime;
            //Files = files

            //------------- 删除API中不需要返回的内容
            noteOrContent.Content  = "";
            noteOrContent.Abstract = "";
            //	apiNote := info.NoteToApiNote(note, noteOrContent.Files)

            return(Json(noteOrContent, MyJsonConvert.GetOptions()));
        }
        private async Task GetHttpWebRequestForAnYaAsync(string type)
        {
            string url = "";

            if (type.Equals("少女映画"))
            {
                url = "https://api.r10086.com:8443/少女映画.php?password=20";
            }
            else
            {
                url = $"https://api.r10086.com:8443/" + type + ".php";
            }
            //建立请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            //添加Referer信息
            request.Headers.Add(HttpRequestHeader.Referer, "http://www.bz08.cn/");
            //伪装成谷歌浏览器
            //request.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36");
            request.Headers.Add(HttpRequestHeader.UserAgent, "I am a cute web crawler");
            //添加cookie认证信息
            Cookie cookie = new Cookie("PHPSESSID", "s9gajue8h7plf7n5ab8fehiuoq");

            cookie.Domain = "api.r10086.com";
            if (request.CookieContainer == null)
            {
                request.CookieContainer = new CookieContainer();
            }
            request.CookieContainer.Add(cookie);
            //发送请求获取Http响应
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //HttpWebResponse response = (HttpWebResponse)(await request.GetResponseAsync().ConfigureAwait(false));

            var originalString = response.ResponseUri.OriginalString;

            Console.WriteLine(originalString);
            //获取响应流
            Stream receiveStream = response.GetResponseStream();
            //获取响应流的长度
            int length = (int)response.ContentLength;
            //读取到内存
            MemoryStream stmMemory = new MemoryStream();

            byte[] buffer1 = new byte[length];
            int    i;

            //将字节逐个放入到Byte 中
            while ((i = receiveStream.Read(buffer1, 0, buffer1.Length)) > 0)
            {
                stmMemory.Write(buffer1, 0, i);
            }

            //写入磁盘
            string name = System.IO.Path.GetFileName(originalString);

            byte[] imageBytes = stmMemory.ToArray();
            string fileSHA1   = SHAEncrypt_Helper.Hash1Encrypt(imageBytes);

            //上传到又拍云
            if (!RandomImageService.Exist(type, fileSHA1))
            {
                upyun.writeFile($"/upload/{SHAEncrypt_Helper.MD5Encrypt(type)}/{fileSHA1}{Path.GetExtension(name)}", imageBytes, true);
                RandomImage randomImage = new RandomImage()
                {
                    RandomImageId = SnowFlake_Net.GenerateSnowFlakeID(),
                    TypeName      = type,
                    TypeNameMD5   = SHAEncrypt_Helper.MD5Encrypt(type),
                    TypeNameSHA1  = SHAEncrypt_Helper.Hash1Encrypt(type),
                    FileName      = name,
                    FileNameMD5   = SHAEncrypt_Helper.MD5Encrypt(name),
                    FileNameSHA1  = SHAEncrypt_Helper.Hash1Encrypt(name),
                    FileSHA1      = fileSHA1,
                    Sex           = false,
                };
                //记录到数据库
                await RandomImageService.InsertImageAsync(randomImage).ConfigureAwait(false);
            }

            //name = $"{dir}{dsc}upload{dsc}{type}{dsc}{name}";
            //if (!Directory.Exists($"{dir}{dsc}upload{dsc}{type}"))
            //{
            //    Directory.CreateDirectory($"{dir}{dsc}upload{dsc}{type}");
            //}
            //if (!System.IO.File.Exists(name))
            //{
            //    FileStream file = new FileStream(name, FileMode.Create, FileAccess.ReadWrite);
            //    file.Write(stmMemory.ToArray());
            //    file.Flush();
            //    file.Close();
            //}
            //FileStream file = new FileStream("1.jpg",FileMode.Create, FileAccess.ReadWrite);
            //关闭流
            stmMemory.Close();
            receiveStream.Close();
            response.Close();
        }
        public static bool UpdateNoteContent(ApiNote apiNote,
                                             out string msg, out long contentId)
        {
            using (var db = new DataContext())
            {
                //更新 将其他笔记刷新
                var noteId      = MyConvert.HexToLong(apiNote.NoteId);
                var note        = db.Note.Where(b => b.NoteId == noteId).First();
                var noteContent = db.NoteContent.Where(b => b.NoteId == noteId && b.IsHistory == false).FirstOrDefault();
                //如果笔记内容发生变化,生成新的笔记内容
                if (apiNote.Content != null)
                {
                    //新增笔记内容,需要将上一个笔记设置为历史笔记
                    db.NoteContent.Where(b => b.NoteId == noteId && b.IsHistory == false).Update(x => new NoteContent()
                    {
                        IsHistory = true
                    });
                    contentId = SnowFlake_Net.GenerateSnowFlakeID();
                    NoteContent contentNew = new NoteContent()
                    {
                        NoteContentId = contentId,
                        NoteId        = noteContent.NoteId,
                        UserId        = noteContent.UserId,
                        IsBlog        = noteContent.IsBlog,
                        Content       = noteContent.Content,
                        Abstract      = noteContent.Abstract,
                        CreatedTime   = noteContent.CreatedTime,
                        UpdatedTime   = noteContent.UpdatedTime,
                        UpdatedUserId = noteContent.UpdatedUserId,
                        IsHistory     = noteContent.IsHistory,
                    };
                    contentNew.IsHistory = false;
                    if (apiNote.IsBlog != null)
                    {
                        contentNew.IsBlog = apiNote.IsBlog.GetValueOrDefault();
                    }
                    if (apiNote.Abstract != null)
                    {
                        contentNew.Abstract = apiNote.Abstract;
                    }
                    if (apiNote.Content != null)
                    {
                        contentNew.Content = apiNote.Content;
                    }
                    if (apiNote.UpdatedTime != null)
                    {
                        contentNew.UpdatedTime = apiNote.UpdatedTime;
                    }
                    db.NoteContent.Add(contentNew);
                    msg = "";
                    return(db.SaveChanges() > 0);
                }
                else
                {   //没有新增笔记内容,那么仅仅修改原始笔记内容就可以了
                    contentId = noteContent.NoteContentId;
                    if (apiNote.IsBlog != null)
                    {
                        noteContent.IsBlog = apiNote.IsBlog.GetValueOrDefault();
                    }
                    if (apiNote.Abstract != null)
                    {
                        noteContent.Abstract = apiNote.Abstract;
                    }

                    if (apiNote.UpdatedTime != null)
                    {
                        noteContent.UpdatedTime = apiNote.UpdatedTime;
                    }
                }
                msg = "";
                db.SaveChanges();
                return(true);
            }
        }
Example #24
0
        public void GenerateSnowFlakeIDHexTest()
        {
            string str = SnowFlake_Net.GenerateSnowFlakeIDHex();

            Console.WriteLine(str);
        }