private Post Submit(SubmitData data) { if (Reddit.User == null) { throw new RedditException("No user logged in."); } var request = WebAgent.CreatePost(SubmitLinkUrl); WebAgent.WritePostBody(request.GetRequestStream(), data); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(result); ICaptchaSolver solver = Reddit.CaptchaSolver; if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "BAD_CAPTCHA" && solver != null) { data.Iden = json["json"]["captcha"].ToString(); CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(data.Iden)); // We throw exception due to this method being expected to return a valid Post object, but we cannot // if we got a Captcha error. if (captchaResponse.Cancel) { throw new CaptchaFailedException("Captcha verification failed when submitting " + data.Kind + " post"); } data.Captcha = captchaResponse.Answer; return(Submit(data)); } else if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "ALREADY_SUB") { throw new DuplicateLinkException(String.Format("Post failed when submitting. The following link has already been submitted: {0}", SubmitLinkUrl)); } return(new Post().Init(Reddit, json["json"], WebAgent)); }
/// <summary> /// Upload a header image. /// </summary> /// <param name="name">name of image.</param> /// <param name="imageType"><see cref="ImageType"/> of image</param> /// <param name="file">image buffer</param> public async Task UploadHeaderImageAsync(string name, ImageType imageType, byte[] file) { var request = WebAgent.CreateRequest(UploadImageUrl, "POST"); var formData = new MultipartFormBuilder(request); formData.AddDynamic(new { name, r = Name, formid = "image-upload", img_type = imageType == ImageType.PNG ? "png" : "jpg", upload = "", header = 1 }); formData.AddFile("file", "foo.png", file, imageType == ImageType.PNG ? "image/png" : "image/jpeg"); formData.Finish(); var response = await WebAgent.GetResponseAsync(request).ConfigureAwait(false); var data = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // TODO: Detect errors }
/// <summary> /// Invite a contributor to the live thread. /// </summary> /// <param name="name">reddit username.</param> /// <param name="permissions">permissions.</param> public void InviteContributor(string userName, LiveUpdateEventPermission permissions) { if (Reddit.User == null) { throw new AuthenticationException("No user logged in."); } var request = WebAgent.CreatePost(String.Format(InviteContributorUrl, Name)); var stream = request.GetRequestStream(); var perms = GetPermissionsString(permissions); WebAgent.WritePostBody(stream, new { api_type = "json", name = userName, permissions = perms, type = "liveupdate_contributor_invite", uh = Reddit.User.Modhash, }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); }
public async Task UploadHeaderImageAsync(string name, ImageType imageType, byte[] file) { var request = WebAgent.CreatePost(UploadImageUrl); var formData = new MultipartFormBuilder(request); formData.AddDynamic(new { name, uh = Reddit.User.Modhash, r = Name, formid = "image-upload", img_type = imageType == ImageType.PNG ? "png" : "jpg", upload = "", header = 1 }); formData.AddFile("file", "foo.png", file, imageType == ImageType.PNG ? "image/png" : "image/jpeg"); formData.Finish(); var response = await request.GetResponseAsync(); var data = WebAgent.GetResponseString(response.GetResponseStream()); // TODO: Detect errors }
/// <summary> /// Vote on this item. /// </summary> /// <param name="type"></param> public void SetVote(VoteType type) { if (this.Vote == type) { return; } var request = WebAgent.CreatePost(VoteUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { dir = (int)type, id = FullName, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); if (Liked == true) { Upvotes--; } if (Liked == false) { Downvotes--; } switch (type) { case VoteType.Upvote: Liked = true; Upvotes++; return; case VoteType.None: Liked = null; return; case VoteType.Downvote: Liked = false; Downvotes++; return; } }
/// <summary> /// Replaces the text in this post with the input text. /// </summary> /// <param name="newText">The text to replace the post's contents</param> public async Task EditTextAsync(string newText) { if (!IsSelfPost) { throw new Exception("Submission to edit is not a self-post."); } var json = await WebAgent.Post(EditUserTextUrl, new { api_type = "json", text = newText, thing_id = FullName }).ConfigureAwait(false); if (json.ToString().Contains("\"errors\": []")) { SelfText = newText; } else { throw new Exception("Error editing text."); } }
/// <summary> /// Sets your claim /// </summary> /// <param name="flairText">Text to set your flair</param> /// <param name="flairClass">class of the flair</param> public void SetFlair(string flairText, string flairClass) { if (Reddit.User == null) { throw new Exception("No user logged in."); } var request = WebAgent.CreatePost(string.Format(SetFlairUrl, SubredditName)); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", css_class = flairClass, link = FullName, name = Reddit.User.Name, text = flairText, uh = Reddit.User.Modhash }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(result); LinkFlairText = flairText; }
private SauceNaoResult[] GetApiResults(string url) { if (m_apiKey == null) { // todo return(Array.Empty <SauceNaoResult>()); } var req = new RestRequest(); req.AddQueryParameter("db", "999"); req.AddQueryParameter("output_type", "2"); req.AddQueryParameter("numres", "16"); req.AddQueryParameter("api_key", m_apiKey); req.AddQueryParameter("url", url); var res = m_client.Execute(req); WebAgent.AssertResponse(res); //Console.WriteLine("{0} {1} {2}", res.IsSuccessful, res.ResponseStatus, res.StatusCode); //Console.WriteLine(res.Content); string c = res.Content; if (String.IsNullOrWhiteSpace(c)) { CliOutput.WriteError("No SN results!"); } return(ReadResults(c)); }
/// <summary> /// Comment on this post. /// </summary> /// <param name="message">Markdown text.</param> /// <returns></returns> public async Task <Comment> CommentAsync(string message) { var json = await WebAgent.Post(CommentUrl, new { text = message, thing_id = FullName, api_type = "json" }).ConfigureAwait(false); if (json["errors"].Any()) { if (json["errors"][0].Any(x => x.ToString() == "RATELIMIT" || x.ToString() == "ratelimit")) { var timeToReset = TimeSpan.FromMinutes(Convert.ToDouble(Regex.Match(json["errors"][0].ElementAt(1).ToString(), @"\d+").Value)); throw new RateLimitException(timeToReset); } else { throw new Exception(json["errors"][0][0].ToString()); } } return(new Comment(WebAgent, json["data"]["things"][0], this)); }
/// <summary> /// Get a <see cref="List{T}"/> of comments. /// </summary> /// <param name="limit">Maximum number of comments to return</param> /// <returns></returns> public async Task <List <Comment> > GetCommentsAsync(int limit = 0, CommentSort sort = CommentSort.Best) { var url = string.Format(GetCommentsUrl, Id); //Only 'best' comment sorting isn't named the same if (sort == CommentSort.Best) { url = $"{url}?sort=confidence"; } else { url = $"{url}?sort={sort.ToString().ToLower()}"; } if (limit > 0) { url = $"{url}&limit={limit}"; } var json = await WebAgent.Get(url).ConfigureAwait(false); var postJson = json.Last()["data"]["children"]; var comments = new List <Comment>(); foreach (var comment in postJson) { Comment newComment = new Comment(WebAgent, comment, this); if (newComment.Kind != "more") { comments.Add(newComment); } } return(comments); }
public override LoginResult Login(LoginUser user) { Regex regex = new Regex(@"^(?<Group>\w+?)_"); SortedDictionary <string, object> data = new SortedDictionary <string, object>() { { "SiteID", this.SiteID }, { "UserID", user.UserName }, { "UserName", user.UserName }, { "Code", user.Code }, { "Time", WebAgent.GetTimestamp() } }; if (regex.IsMatch(user.UserName)) { data.Add("Group", regex.Match(user.UserName).Groups["Group"].Value); } ResultStatus status = this.POST("Login", data, out JToken res); if (status == ResultStatus.Success) { return(new LoginResult(((JObject)res).Get <string>("Url"), HttpMethod.Get)); } return(new LoginResult(status)); }
public async Task Test() { var limiter = new RollingWindowRateLimiter(10000, TimeSpan.FromMinutes(1)); var proxyService = new DefaultProxyService(); var agent = new WebAgent(limiter, proxyService); var job = new CrawlJob() { Domain = new Uri("https://reddit.com/"), CompletionConditions = new List <ICrawlCompletionCondition> { new MaxPagesCrawledCondition(100), new MaxTimeCondition(TimeSpan.FromMinutes(3)), new MaxResultsFoundCondition(2000) }, ThreadAllowance = 10, Cookies = new List <Cookie> { new Cookie("over18", "1", "/", "reddit.com") }, Regex = "<img.+?src=\"(?<image>.+?)\"" }; using (var crawler = new Crawler(agent)) { var results = await crawler.Crawl(job); Console.WriteLine(results.CrawlCount); Console.WriteLine(results.QueueSize); Console.WriteLine(results.ResultsCount); foreach (var item in results.Data) { Console.WriteLine(item.Item2); } } }
protected void btnSubmit_Click(object sender, EventArgs e) { string chkCode = txtChkCode.Value + ""; string valCode = hdValCode.Value + ""; if (chkCode != "") { if (valCode == "") { return; } if (LFL.Utility.Security.MD5Util.ToMD5(valCode).Replace("-", "").Replace("A", "").Replace("B", "").Replace("C", "").Replace("D", "").Replace("E", "").Replace("F", "").Substring(0, 4) != chkCode) { AlertAndBack("验证码错误!"); } } LFL.Favorite.Model.User user = new LFL.Favorite.Model.User(); string strUsername, strPassword, strRePassword, strEmail; strUsername = txtUsername.Value.Trim(); if (string.IsNullOrEmpty(strUsername) || strUsername.Length < 4 || strUsername.Length > 20) { AlertAndBack("用户名不能为空且长度于5-20之间!"); } strPassword = txtPassword.Value.Trim(); if (string.IsNullOrEmpty(strPassword) || strPassword.Length < 6 || strPassword.Length > 50) { AlertAndBack("密码不能为空且长度于6-50之间!"); } strRePassword = txtRePassword.Value.Trim(); if (string.IsNullOrEmpty(strRePassword) || !strPassword.Equals(strRePassword)) { AlertAndBack("两次密码不一致!"); } strEmail = txtEmail.Value.Trim(); if (string.IsNullOrEmpty(strEmail)) { AlertAndBack("邮箱不能为空!"); } if (!chkAgreement.Checked) { AlertAndBack("请仔细阅读注册协议。"); } LFL.Favorite.BLL.UserBll bll = new LFL.Favorite.BLL.UserBll(); if (bll.Exists(strUsername, strEmail)) { AlertAndBack("该用户名或邮箱已经被注册!"); } DateTime dtmNow = DateTime.Now; string strActivateCode = MD5Util.ToMD5(dtmNow.ToString("yyyyss7MMddongmmHH")); user.Username = strUsername; user.Nickname = strUsername; user.Password = MD5Util.ToMD5(strPassword); user.Email = strEmail; user.Sex = "保密"; user.ActivateCode = strActivateCode; user.RegTime = dtmNow; user.RegIP = WebAgent.GetIP(); user.LoginCount = 0; user.Level = 0; user.Credit = 0; user.Status = 0; // try { bll = new LFL.Favorite.BLL.UserBll(); bll.Add(user); } catch (Exception ex) { WebLog.WriteErrLog("注册失败!原因:" + ex.Message); AlertAndBack("注册失败!原因:" + ex.Message); } try { SendActiveCodeEmail(strEmail, strUsername, strPassword, strActivateCode); } catch (Exception ex) { WebLog.WriteErrLog("发送注册邮件失败!原因:" + ex.Message); AlertAndBack("发送注册邮件失败!原因:" + ex.Message); } WebLog.WriteInfoLog("注册用户名:" + user.Username + ", Email:" + user.Email + "成功!"); //成功 lblUsername.Text = strUsername; lblPassword.Text = strPassword; hdRegTime.Value = dtmNow.ToString("yyyyss7MMddongmmHH"); regForm.Visible = false; regOk.Visible = true; }
public Task SaveSiteTemplateInfo([FromForm] int id, [FromForm] string name, [FromForm] PlatformSource platform, [FromForm] string domain, [FromForm] int siteid, [FromForm] string model) { ViewSiteTemplate template = new ViewSiteTemplate() { ID = id, Name = name, Platform = platform, Domain = domain, SiteID = siteid }; return(this.GetResult(ViewAgent.Instance().SaveSiteTemplateInfo(template, WebAgent.GetArray <int>(model)))); }
/** * Entry point */ private static void Main(string[] args) { if (args == null || args.Length == 0) { return; } RuntimeInfo.Setup(); CliParse.ReadArguments(args); var img = RuntimeInfo.Config.Image; bool run = img != null; if (run) { var sr = new SearchResults(); var ok = Search.RunSearch(img, ref sr); var results = sr.Results; // Console.WriteLine("Elapsed: {0:F} sec", result.Duration.TotalSeconds); ConsoleKeyInfo cki; do { Console.Clear(); for (int i = 0; i < sr.Results.Length; i++) { var r = sr.Results[i]; var tag = (i + 1).ToString(); if (r != null) { string str = r.Format(tag); Console.Write(str); } else { Console.WriteLine("{0} - ...", tag); } } Console.WriteLine(); // Exit if (RuntimeInfo.Config.AutoExit) { SearchConfig.Cleanup(); return; } CliOutput.WriteSuccess("Enter the result number to open or escape to quit."); while (!Console.KeyAvailable) { // Block until input is entered. } // Key was read cki = Console.ReadKey(true); char keyChar = cki.KeyChar; if (Char.IsNumber(keyChar)) { int idx = (int)Char.GetNumericValue(cki.KeyChar) - 1; if (idx < results.Length && idx >= 0) { var res = results[idx]; WebAgent.OpenUrl(res.Url); } } } while (cki.Key != ConsoleKey.Escape); // Exit SearchConfig.Cleanup(); } else { //CliOutput.WriteInfo("Exited"); } }
protected string GetIndexURL() { return(WebAgent.GetDomainURL() + "/Default.aspx"); }
protected void AlertAndGo(string msg, string url) { WebAgent.SuccAndGo(msg, url); }
protected void AlertAndBack(string msg) { WebAgent.AlertAndBack(msg); }
/// <summary> /// Retrieve a list of public Multis belonging to a given user /// </summary> /// <param name="username">Username to search</param> /// <returns>A list of MultiData containing the public Multis of the searched user</returns> public async Task <IList <MultiData> > GetPublicUserMultisAsync(string username) { var json = await WebAgent.Get(GetPublicUserMultiUrl(username)).ConfigureAwait(false); return(json.Select(m => new MultiData(WebAgent, m)).ToList()); }
/// <summary> /// Redis值转化成为系统值 /// </summary> /// <param name="value"></param> /// <param name="type"></param> /// <returns></returns> public static Object GetRedisValue(this RedisValue value, Type type) { Object obj; switch (type?.Name) { case "Decimal": obj = ((long)value).ToRedisValue(); break; case "Boolean": obj = (bool)value; break; case "DateTime": obj = new DateTime((long)value); break; case "Int64": obj = (long)value; break; case "Int32": obj = (int)value; break; case "Int16": obj = (short)value; break; case "Byte": obj = (byte)(int)value; break; case "String": obj = (string)value; break; case "Int32[]": obj = WebAgent.GetArray <int>((string)value); break; case "Guid": obj = ((string)value).GetValue <Guid>(); break; case null: obj = null; break; default: if (type.IsEnum) { obj = type.GetValue((long)value); } else { obj = value; } break; } return(obj); }
public void Authenticate(WebAgent webAgent, Credentials credentials) { try { var content = webAgent.GetString( "https://live.xbox.com/Account/Signin?returnUrl=http%3a%2f%2fwww.xbox.com%2fen-US%2f"); var postUrl = content.ParseBetween("urlPost:'", "'"); var ppftVal = content.ParseBetween("name=\"PPFT\" id=\"i0327\" value=\"", "\""); var ppsxVal = content.ParseBetween("j:'", "'"); var postContent = new StringBuilder(); postContent.Append("login="******"&passwd=" + credentials.Password); postContent.Append("&SI=Sign in"); postContent.Append("&type=11"); postContent.Append("&PPFT=" + ppftVal); postContent.Append("&PPSX=" + ppsxVal); postContent.Append("&idsbho=1"); postContent.Append("&sso=0"); postContent.Append("&NewUser=1"); postContent.Append("&LoginOptions=3"); postContent.Append("&i1=0"); postContent.Append("&i2=1"); postContent.Append("&i3=34903"); postContent.Append("&i4=0"); postContent.Append("&i7=0"); postContent.Append("&i12=1"); postContent.Append("&i13=0"); postContent.Append("&i14=79"); postContent.Append("&i15=1605"); postContent.Append("&i18=__Login_Strings|1,__Login_Core|1,"); var response = webAgent.Post(postUrl, postContent.ToString()); content = response.GetResponseStream().ReadAsString(); if (content.Contains("sErrTxt")) { throw new AuthenticationException( "Authentication failed. This is most likely due to invalid credentials."); } postUrl = content.ParseBetween("id=\"fmHF\" action=\"", "\""); var napVal = content.ParseBetween("id=\"NAP\" value=\"", "\""); var anonVal = content.ParseBetween("id=\"ANON\" value=\"", "\""); var tVal = content.ParseBetween("id=\"t\" value=\"", "\""); postContent.Clear(); postContent.Append("NAP=" + napVal); postContent.Append("&ANON=" + anonVal); postContent.Append("&t=" + tVal); response = webAgent.Post(postUrl, postContent.ToString()); content = response.GetResponseStream().ReadAsString(); bool authenticated = content.Contains("https://live.xbox.com/Account/Signout"); if (!authenticated) { throw new AuthenticationException("Authentication failed."); } } catch (WebException exception) { throw new AuthenticationException( "Authentication failed. The service could be unavailable", exception); } }
/// <summary> /// 转账 /// </summary> /// <param name="siteId">所属商户</param> /// <param name="game">当前游戏配置</param> /// <param name="user">用户信息</param> /// <param name="action">转入转出类型</param> /// <param name="orderID">转账订单号(本地)</param> /// <param name="currency">货币类型</param> /// <param name="money">金额</param> /// <returns></returns> public TransferResult Transfer(Site site, GameSetting game, UserGame user, TransferAction action, string orderID, decimal money) { if (user == null) { return(new TransferResult(ResultStatus.NoUser)); } // 订单格式的判断 if (WebAgent.IsUserName(orderID, 2, 16)) { return(new TransferResult(ResultStatus.OrderIDFormat)); } // 金额判断(默认是2位小数,如果游戏接口的特别要求,则在游戏接口中返回金额错误) if (money <= 0M || Math.Round(money, 2) != money) { return(new TransferResult(ResultStatus.BadMoney)); } // 本地锁(如果部署集群则需要修改成为分布式锁) lock (LockHelper.GetLoker($"{user.ToString()}")) { //同一个商户订单重复,不允许操作 if (this.ReadDB.Exists <UserTransfer>(t => t.SiteID == site.ID && t.SourceID == orderID)) { return(new TransferResult(ResultStatus.ExistsOrder)); } //添加转账记录,把状态设置为转账中 UserTransfer userTransfer = new UserTransfer() { SiteID = site.ID, GameID = game.ID, UserID = user.UserID, Money = money, Action = action, CreateAt = DateTime.Now, FinishAt = DateTime.MinValue, SystemID = string.Empty, SourceID = orderID, Status = TransferStatus.Paying }; this.WriteDB.InsertIdentity(userTransfer); // 调用API接口 TransferResult result = game.Setting.Transfer(new TransferInfo() { Prefix = site.Prefix, UserName = user.Account, Action = action, OrderID = orderID, Currency = site.Currency, Money = money }); userTransfer.SystemID = result.SystemID; userTransfer.FinishAt = DateTime.Now; userTransfer.Status = result.Status switch { ResultStatus.Exception => TransferStatus.Exception, ResultStatus.Success => TransferStatus.Success, _ => TransferStatus.Faild }; this.WriteDB.Update(userTransfer, t => t.SystemID, t => t.FinishAt, t => t.Status); if (!result) { return(new TransferResult(result.Status)); } if (result.Balance != null) { UserAgent.Instance().UpdateBalance(user, result.Balance.Value); } else { BalanceResult balanceResult = this.GetBalance(site, game, user); if (balanceResult) { result.Balance = balanceResult.Balance; } } return(result); } }
public override SearchResult GetResult(string url) { /*string u = BASIC_RESULT + url; * var sr = new SearchResult(u, Name); * sr.ExtendedInfo.Add("API not configured"); * return sr;*/ SearchResult sr = null; var sz = WebAgent.GetString(BASIC_RESULT + url); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(sz); // todo: for now, just return the first link found, as SN already sorts by similarity and the first link is the best result var links = doc.DocumentNode.SelectNodes("//*[@class='resultcontentcolumn']/a/@href"); foreach (var link in links) { var lk = link.GetAttributeValue("href", null); if (lk != null) { sr = new SearchResult(lk, Name); break; } } if (sr == null) { string u = BASIC_RESULT + url; sr = new SearchResult(u, Name); } return(sr); // TODO: finish for more refined and complete results /*var classToGet = "result"; * * var results = doc.DocumentNode.SelectNodes("//*[@class='" + classToGet + "']"); * * Console.WriteLine("nresults: "+results.Count); * * foreach (HtmlNode node in results) * { * //string value = node.InnerText; * // etc... * * //var n2 = node.SelectSingleNode("//*[@id=\"middle\"]/div[3]/table/tbody/tr/td[2]/div[1]/div[1]"); * * //Console.WriteLine(n2.InnerText); * * // //*[@id="middle"]/div[2]/table/tbody/tr/td[2]/div[1] * // //*[@id="middle"]/div[3]/table/tbody/tr/td[2]/div[1] * // //*[@id="middle"]/div[3]/table/tbody/tr/td[2]/div[1] * * var table = node.FirstChild; * var tbody = table.FirstChild; * var resulttablecontent = tbody.ChildNodes[1]; * var resultmatchinfo = resulttablecontent.FirstChild; * * var resultsimilarityinfo = resultmatchinfo.FirstChild; * * var resultcontent = resulttablecontent.ChildNodes[1]; * var resulttitle = resultcontent.FirstChild; * * // resultcontentcolumn comes after resulttitle * * // //*[@class='resultcontentcolumn']/a * * /*var links = resultcontent.SelectNodes("//*[@class='resultcontentcolumn']/a/@href"); * var links2 = links.Where(l => l.Name != "span").ToArray(); * * foreach (var link in links2) { * string hrefValue = link.GetAttributeValue("href", string.Empty); * Console.WriteLine(">>> "+hrefValue); * }#1# * * foreach (var resultcontentChildNode in resultcontent.ChildNodes) { * if (resultcontentChildNode.GetAttributeValue("class", String.Empty)=="resultcontentcolumn") { * foreach (var rcccnChildNode in resultcontentChildNode.ChildNodes) { * var href = rcccnChildNode.GetAttributeValue("href", String.Empty); * * if (!string.IsNullOrWhiteSpace(href)) { * Console.WriteLine("!>>>>"+href); * } * } * } * } * * Console.WriteLine(resultsimilarityinfo.InnerText); * }*/ //Console.ReadLine(); //var sr = new SearchResult(BASIC_RESULT+url,Name); //return sr; }
public void Authenticate(WebAgent webAgent, Credentials credentials) { // null object pattern. }
/// <summary> /// Retrieve the information for a given subreddit in a Multi /// </summary> /// <param name="path">URL path to use</param> /// <param name="subreddit">Subreddit name to get information for</param> /// <returns>A MultiSubs element containing the information for the searched subreddit</returns> public async Task <MultiSubs> GetSubInformationAsync(string path, string subreddit) { var json = await WebAgent.Get(GetMultiSubUrl(path, subreddit)).ConfigureAwait(false); return(new MultiSubs(WebAgent, json)); }
/// <summary> /// Retrieve the description for the Multi based on the URL path given /// </summary> /// <param name="path">URL path to use</param> /// <returns>A MultiData containing the description for the found Multi</returns> public async Task <MultiData> GetMultiDescriptionAsync(string path) { var json = await WebAgent.Get(GetMultiDescriptionPathUrl(path)).ConfigureAwait(false); return(new MultiData(WebAgent, json, false)); }
public override IEnumerable <OrderModel> GetOrderLog(OrderTaskModel task) { long time = this.GetStartMark(task); SortedDictionary <string, object> data = new SortedDictionary <string, object>() { { "SiteID", this.SiteID }, { "Time", WebAgent.GetTimestamp() }, { "Update", time }, { "Count", 100 } }; ResultStatus resultStatus = this.POST("Orders", data, out JToken info); if (resultStatus != ResultStatus.Success) { yield break; } foreach (JObject item in info.Value <JArray>()) { OrderStatus status = OrderStatus.Wait; switch (item["Status"].Value <string>()) { case "None": status = OrderStatus.Wait; break; case "Revoke": status = OrderStatus.Return; break; case "Win": status = OrderStatus.Win; break; case "Lose": status = OrderStatus.Lose; break; } long updateTime = WebAgent.GetTimestamp(item.Get <DateTime>("CreateAt") .Max(item.Get <DateTime>("ResultAt")) .Max(item.Get <DateTime>("RewardAt"))); yield return(new OrderModel() { Provider = this.GetType().Name, Code = item.Get <string>("Code"), UserName = item.Get <string>("UserName"), Category = GameCategory.Lottery, CreateAt = item.Get <DateTime>("CreateAt"), ResultAt = item.Get <DateTime>("ResultAt"), BetMoney = item.Get <decimal>("BetMoney"), BetAmount = item.Get <decimal>("BetAmount"), Content = $"{ item.Get<string>("Index") } - { item.Get<string>("PlayCode") } / { item.Get<string>("Number") } / { item.Get<string>("Result") }", Money = item.Get <decimal>("Money"), SourceID = item.Get <string>("ID"), Status = status, RawData = item.ToString() }); if (updateTime > time) { time = updateTime; } } this.GameDelegate.SaveMarkTime(task, time); }
protected void Alert(string msg) { WebAgent.Alert(msg); }
/// <summary> /// 显示验证码 /// </summary> /// <param name="key"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> private Result ShowCode(string key, int width, int height) { string random = WebAgent.GetRandom(0, 9999).ToString().PadLeft(4, '0'); MemoryUtils.Set(key, random, TimeSpan.FromMinutes(5)); using (Bitmap bitmap = new Bitmap(width, height)) { Bitmap bg = (Bitmap) new ResourceManager(typeof(Resources)).GetObject("validcode_bg"); Rectangle rectangle = new Rectangle(WebAgent.GetRandom(0, bg.Width - width), WebAgent.GetRandom(0, bg.Height - height), width, height); using (Graphics g = Graphics.FromImage(bitmap)) { g.Clear(Color.White); g.DrawImage(bg, new Rectangle(0, 0, width, height), rectangle, GraphicsUnit.Pixel); for (int i = 0; i < random.Length; i++) { Bitmap code = (Bitmap) new ResourceManager(typeof(Resources)).GetObject($"validcode_{random[i]}"); Rectangle codeRectangle = new Rectangle(width / random.Length * i + WebAgent.GetRandom(-5, 5), WebAgent.GetRandom(-5, 5), width / 4, height); g.DrawImage(code, codeRectangle, new Rectangle(0, 0, code.Width, code.Height), GraphicsUnit.Pixel); } } using (MemoryStream ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Png); return(new Result(ContentType.PNG, ms.ToArray())); } } }
/// <summary> /// Retrieve a list of the Multis belonging to the currently authenticated user /// </summary> /// <returns>A List of MultiData containing the authenticated user's Multis</returns> public async Task <IList <MultiData> > GetCurrentUsersMultisAsync() { var json = await WebAgent.Get(GetCurrentUserMultiUrl).ConfigureAwait(false); return(json.Select(m => new MultiData(WebAgent, m)).ToList()); }