| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359 |
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc.Controllers;
- using Microsoft.AspNetCore.Mvc.Filters;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using dodohold.core;
- using Spire.Pdf.Exporting.XPS.Schema;
- using System.Xml.Linq;
- using System.Net;
- using TencentCloud.Mrs.V20200910.Models;
- using YunhuiKit;
- namespace molilian.core
- {
- public partial class TkPoolCore
- {
- public enum TkAction
- {
- all,
- parse,
- coupon,
- promotionQuery
- }
- private static string _end_point;
- static TkPoolCore()
- {
- _end_point = Environment.GetEnvironmentVariable("EndPoint");
- }
- private static SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
- private static IEnumerable<TkPoolDTO> _cached;
- private static IEnumerable<TkPoolDTO> _all_cached;
- public static async Task<TkPoolDTO> GetOneAsync(TkAction action)
- {
- var list = await ListAsync();
- if (!list.Any()) return null;
- return list.Where(e => FilterNodes(e, action)).OrderBy(l => Guid.NewGuid()).FirstOrDefault();
- }
- public static async Task<TkPoolDTO> GetOneAsync(int id)
- {
- var list = await ListAsync();
- if (!list.Any()) return null;
- return list.Where(e => e.id == id).FirstOrDefault();
- }
- private static bool FilterNodes(TkPoolDTO item, TkAction action)
- {
- if (!string.IsNullOrEmpty(item.suspended_endpoint) && item.suspended_endpoint.Contains($"{_end_point}|")) return false;
- if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point))
- {
- if (item.end_point != _end_point) return false;
- }
- // 使用初始化参数创建工作时间表
- if (!new WorkSchedule(item.time_range).IsWorkHour()) return false;
- if (item.daily_calls_limit > 0)
- {
- int daily_num = RiskControlCore.GetCalls(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMdd"));
- if (daily_num >= item.daily_calls_limit) return false;
- }
- if (item.hourly_calls_limit > 0)
- {
- int hourly_num = RiskControlCore.GetCalls(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMddHH"));
- if (hourly_num >= item.hourly_calls_limit) return false;
- }
- switch (action)
- {
- case TkAction.parse:
- if (!item.enable_parse) return false;
- break;
- case TkAction.promotionQuery:
- if (!item.enable_promotionQuery) return false;
- break;
- case TkAction.coupon:
- if (!item.enable_coupon) return false;
- break;
- }
- if (item.daily_income_limit == 0) return true;
- decimal income_amt = RiskControlCore.GetIncomeAmt(TkChannelEnum.tb, $"{item.id}");
- return income_amt < item.daily_income_limit;
- }
- public static async Task<IEnumerable<TkPoolDTO>> AllListAsync(bool force = false)
- {
- if (!force && _all_cached != default) return _all_cached;
- try
- {
- await _semaphore.WaitAsync();
- string cache_key = $"cache:all_tk_pool";
- var list = await RedisKit.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
- if (force || list == default)
- {
- list = new DBContext.Table("tk_pool").Select<TkPoolDTO>();
- if (list == null) return default;
- // 等待 Redis 写入完成
- await RedisKit.SetAsync(cache_key, list, 30 * 86400);
- }
- _all_cached = list;
- return list;
- }
- catch (Exception)
- {
- // 发生异常时返回上一次的缓存,如果没有则返回默认值
- return _all_cached ?? default;
- }
- finally
- {
- _semaphore.Release();
- }
- }
- public static async Task<IEnumerable<TkPoolDTO>> ListAsync(bool force = false)
- {
- // 内存缓存检查
- if (!force && _cached != null) return _cached;
- string cache_key = "cache:tk_pool";
- if (!force)
- {
- var cachedList = await RedisHelper.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
- if (cachedList != null)
- {
- _cached = cachedList;
- return cachedList;
- }
- }
- // 获取新数据
- await _semaphore.WaitAsync();
- try
- {
- // 双重检查,防止并发情况下重复加载
- if (!force)
- {
- var cachedList = await RedisHelper.GetAsync<IEnumerable<TkPoolDTO>>(cache_key);
- if (cachedList != null)
- {
- _cached = cachedList;
- return cachedList;
- }
- }
- // 从数据库加载数据
- var list = new DBContext.Table("tk_pool")
- .Where("status=@status", new { status = 1 })
- .Select<TkPoolDTO>();
- if (list == null) return default;
- // 更新调用次数
- foreach (var item in list)
- {
- _ = RiskControlCore.SetCallsAsync(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMddHH"), item.current_hourly_calls);
- _ = RiskControlCore.SetCallsAsync(TkChannelEnum.tb, item.id, DateTime.Now.ToString("yyyyMMdd"), item.current_daily_calls);
- }
- // 更新缓存
- await RedisHelper.SetAsync(cache_key, list, 30 * 86400);
- _cached = list;
- return list;
- }
- finally
- {
- _semaphore.Release();
- }
- }
- public static void Refresh()
- {
- _ = AllListAsync(true);
- _ = ListAsync(true);
- }
- public static void UpdateDrawBalance(string name, decimal amout)
- {
- new DBContext.Table("tk_pool")
- .Add("draw_balance", amout)
- .Where("name=@name", new { name })
- .Update();
- _ = ListAsync(true);
- }
- public static void Suspend(string endpoint, int accountId, string name, string content)
- {
- string cache_key = $"cache:tk_pool:{accountId}:suspend";
- long count = RedisHelper.IncrBy(cache_key);
- RedisHelper.Expire(cache_key, 10);
- if (count > 1) return;
- var update = new DBContext.Table("tk_pool").Add("suspended_endpoint:", $"CONCAT(suspended_endpoint, '{endpoint},')");
- if (accountId > 0)
- {
- update.Where("id=@accountId", new { accountId }).Update();
- }
- else
- {
- update.Where("name=@name", new { name }).Update();
- }
- _ = ListAsync(true);
- NotifyCore.Notify(new NifyMessage
- {
- message = $"【淘客{accountId}:{name}】{endpoint} 暂停",
- priority = NifyMessagePriority.high,
- tags = ["red_circle"]
- });
- NotifyCore.AnPushNotify("暂停", $"【淘客{accountId}:{name}】{endpoint} 暂停");
- EndPointCore.NotifyReload(true);
- }
- public static bool IsNeedSwitchBackup(int accountId)
- {
- string cache_key = $"cache:tk_pool:{accountId}:switchBackup";
- long count = RedisHelper.Get<int>(cache_key);
- return count != 0;
- }
- public static void SwitchBackup(string endpoint, int accountId, string name, string content)
- {
- string cache_key = $"cache:tk_pool:{accountId}:switchBackup";
- long count = RedisHelper.IncrBy(cache_key);
- RedisHelper.Expire(cache_key, 3600 * 4);
- if (count > 1) return;
- //_ = ListAsync(true);
- NotifyCore.Notify(new NifyMessage
- {
- message = $"【淘客{accountId}:{name}】{endpoint} 风控,切换备用接口",
- priority = NifyMessagePriority.high,
- tags = ["red_circle"]
- });
- NotifyCore.AnPushNotify("切换接口", $"【淘客{accountId}:{name}】{endpoint} 切换备用接口");
- EndPointCore.NotifyReload(true);
- }
- public static void Disabled(int accountId, string name, string content)
- {
- #if DEBUG
- #else
- #endif
- string cache_key = $"cache:tk_pool:{accountId}:disabled";
- long count = RedisHelper.IncrBy(cache_key);
- RedisHelper.Expire(cache_key, 10);
- if (count > 1) return;
- var update = new DBContext.Table("tk_pool").Add("status", 0);
- if (accountId > 0)
- {
- update.Where("id=@accountId", new { accountId }).Update();
- }
- else
- {
- update.Where("name=@name", new { name }).Update();
- }
- _ = ListAsync(true);
- NotifyCore.Notify(new NifyMessage
- {
- message = $"【淘客{accountId}:{name}】cookie 掉线\n\n{content}",
- priority = NifyMessagePriority.high,
- tags = ["red_circle"]
- });
- NotifyCore.AnPushNotify("掉线", $"【淘客{accountId}:{name}】cookie 掉线");
- EndPointCore.NotifyReload(true);
- }
- public static int UpdateCookies(string cookies, string user_agent)
- {
- if (string.IsNullOrEmpty(cookies)) return 0;
- cookies += ";";
- string dnk = cookies.GetContentPart("dnk=", ";");
- string company = dnk;
- int accountId = 0;
- string tb_token = cookies.GetContentPart("_tb_token_=", ";");
- if (string.IsNullOrEmpty(dnk) || string.IsNullOrEmpty(tb_token)) return 0;
- var exist = new DBContext.Table("tk_pool").Fields("id, name, company, refpid, status").Get<dynamic>("name=@dnk", new { dnk });
- if (exist != null)
- {
- int status = exist.status;
- string refpid = exist.refpid;
- company = exist.company;
- accountId = exist.id;
- if (!string.IsNullOrEmpty(refpid)) status = 1;
- new DBContext.Table("tk_pool")
- .Add("name", dnk)
- .Add("tb_token", tb_token)
- .Add("cookies", cookies)
- .Add("user_agent", user_agent)
- .Add("status", status)
- .Add("suspended_endpoint", string.Empty)
- .Add("last_time", DateTime.Now)
- .Add("login_time", DateTime.Now)
- .Where("id=@id", new { exist.id })
- .Update();
- if (status == 1) _ = ListAsync(true);
- }
- else
- {
- accountId = new DBContext.Table("tk_pool")
- .Add("name", dnk)
- .Add("description", "由cookies上报创建此记录")
- .Add("tb_token", tb_token)
- .Add("refpid", string.Empty)
- .Add("cookies", cookies)
- .Add("user_agent", user_agent)
- .Add("create_time", DateTime.Now)
- .Add("last_time", DateTime.Now)
- .Add("login_time", DateTime.Now)
- .Add("status", 0)
- .Create();
- }
- NotifyCore.Notify(new NifyMessage
- {
- message = $"【淘客{accountId}:{company}】cookie 上线",
- tags = ["green_circle"]
- });
- EndPointCore.NotifyReload(true);
- //NotifyCore.AnPushNotify("上线", $"【淘宝联盟:{dnk}】cookie 上报更新");
- return accountId;
- }
- internal static void AccountExhausted()
- {
- string cache_key = $"cache:tk_pool:account:exhausted";
- long count = RedisHelper.IncrBy(cache_key);
- if (count > 1) return;
- RedisHelper.Expire(cache_key, 3600);
- NotifyCore.Notify(new NifyMessage
- {
- message = $"【淘客】没有匹配账号",
- priority = NifyMessagePriority.high,
- tags = ["red_circle"]
- });
- NotifyCore.AnPushNotify("没账号", $"【淘客】没有匹配账号");
- }
- }
- }
|