From 78b952846ba42f59d67bfd9bcfb4c35757be9266 Mon Sep 17 00:00:00 2001 From: xingsu1021 Date: Fri, 23 Sep 2022 20:41:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=AB=99=E7=82=B9=E7=94=A8?= =?UTF-8?q?=E6=88=B7=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/common/sites_user.py | 92 +++++++++--- apps/common/utils.py | 4 +- apps/cron/crontabs.py | 10 +- .../templates/dashboard/dashboard.html | 92 +++++++----- apps/dashboard/views.py | 33 +--- apps/rss/migrations/0018_alter_config_url.py | 18 +++ apps/rss/models.py | 2 +- apps/sites/urls/views_urls.py | 4 +- apps/sites/views_request.py | 141 +++++++++++++++++- 9 files changed, 297 insertions(+), 99 deletions(-) create mode 100644 apps/rss/migrations/0018_alter_config_url.py diff --git a/apps/common/sites_user.py b/apps/common/sites_user.py index 4288868..6e4376f 100644 --- a/apps/common/sites_user.py +++ b/apps/common/sites_user.py @@ -7,7 +7,7 @@ import requests import simplejson as json import re import time -from .utils import getSiteUrl, parseUrl +from .utils import getSiteUrl, parseUrl, capacity_convert, filesizeformat logger = logging.getLogger('user') @@ -142,9 +142,9 @@ def general(site_name, site_name_cn, site_url, site_cookie): data['create_time'] = create_time td = soup.findAll('td', string=["等级","等級"], limit=1) - level = re.sub("\(.*\)",'',td[0].nextSibling.get_text().strip()) - if level == "": - level = re.sub("\(.*\)",'',td[0].nextSibling.img.attrs['title']) + #level = re.sub("\(.*\)",'',td[0].nextSibling.get_text().strip()) + #if level == "": + level = re.sub("\(.*\)",'',td[0].nextSibling.img.attrs['title']) data['level'] = level td = soup.findAll('td', string=["邀请","邀請","剩余邀请量"], limit=1) @@ -155,10 +155,10 @@ def general(site_name, site_name_cn, site_url, site_cookie): else: data['invite'] = 0 - td = soup.findAll('td', string="做种积分", limit=1) + td = soup.findAll('td', string=["做种积分","做種積分"], limit=1) try: - score = re.sub("\(.*\)",'', td[0].nextSibling.get_text()) - score = re.sub("\[.*\]",'', score) + score = re.sub("\(.*\)|\[.*\]|(.*)",'', td[0].nextSibling.get_text()) + #score = re.sub("\[.*\]",'', score) except: #无做种积分 score = '0' @@ -188,8 +188,11 @@ def general(site_name, site_name_cn, site_url, site_cookie): try: upload = td[0].nextSibling.get_text() except: - td = soup.findAll('strong', string=["上传量","上傳量"], limit=1) + td = soup.findAll('strong', string=["上传量","上傳量","总上传量/奖励上传量/纯上传量"], limit=1) upload = re.sub("\(.*\)",'', td[0].nextSibling.get_text().split(':')[-1]) + #吐鲁番 + if '/' in upload: + upload = upload.split('/')[0] data['upload'] = upload.strip() td = soup.findAll('td', string=["下载量","下載量"], limit=1) @@ -231,27 +234,76 @@ def general(site_name, site_name_cn, site_url, site_cookie): else: data['published_seed_num'] = 0 - td = soup.findAll('td', string=["当前做种","目前做種"], limit=1) + td = soup.findAll('td', string=["当前做种","目前做種","做种统计"], limit=1) s = td[0].nextSibling.get_text() - if '个种子' in s or '记录' in s: + #if '个种子' in s or '记录' in s or '做种' in s: + if '个种子' in s or '做种' in s: if '察看' in s: data['seed_num'] = s.split(',')[0].split('(')[-1].replace('个种子','') data['totle_seed_size'] = s.split(',')[-1].replace(')','').replace('共计','') + elif '做种' in s: + #柠檬,海棠(\xa0为html空格) + data['seed_num'] = s.replace('\xa0',' ').split(' ')[1] + data['totle_seed_size'] = s.split(':')[-1] else: + #提取数字 data['seed_num'] = re.sub(r'\D+', '', s) data['totle_seed_size'] = 0 else: - url = site_url + "/getusertorrentlistajax.php?userid=%s&type=seeding" % data['user_id'] - response = session.get(url, headers=headers, timeout=10) - soup1 = BeautifulSoup(response.text, "lxml") - seed_num= soup1.find('b') - if seed_num != None: - data['seed_num'] = seed_num.get_text() - data['totle_seed_size'] = seed_num.nextSibling.get_text().split(':')[-1] + if 'pttime' in site_url: + #资源总大小:8.452 TB + url = site_url + "/getusertorrentlist.php?userid=%s&type=seeding" % data['user_id'] + response = session.get(url, headers=headers, timeout=10) + soup1 = BeautifulSoup(response.text, "lxml") + b = soup1.findAll('b', string="资源总大小:", limit=1) + data['totle_seed_size'] = b[0].nextSibling.get_text().replace('\xa0',' ') + data['seed_num'] = re.sub(r'\D+', '', s) else: - data['seed_num'] = 0 - data['totle_seed_size'] = 0 + url = site_url + "/getusertorrentlistajax.php?userid=%s&type=seeding" % data['user_id'] + response = session.get(url, headers=headers, timeout=10) + soup1 = BeautifulSoup(response.text, "lxml") + seed_num= soup1.find('b') + if seed_num != None: + data['seed_num'] = seed_num.get_text() + if '|' in seed_num.nextSibling.get_text(): + #条记录 | 总大小:1.349 TB + totle_seed_size = re.sub(":|:","-",seed_num.nextSibling.get_text()) + data['totle_seed_size'] = totle_seed_size.split('-')[-1] + else: + #判断字符串中是否包含数字 + if bool(re.search(r'\d', seed_num.nextSibling.get_text())): + + if "條記錄" in seed_num.nextSibling.get_text(): + #芒果 + #條記錄718.99 GB + data['totle_seed_size'] = seed_num.nextSibling.get_text().replace('條記錄','') + else: + #条记录 Total: 1.890 TB + data['totle_seed_size'] = " ".join(seed_num.nextSibling.get_text().split(' ')[2:4]) + + else: + table = soup1.findAll('table', limit=1) + total_size = 0 + if table != []: + for index, tr in enumerate(table[0].find_all('tr')): + if index == 0: + continue + #获取所有td + tds = tr.find_all('td') + #获取种子大小 数字单位 + seed_size = tds[2].get_text() + #转换为K + size, unit = capacity_convert(seed_size,'K') + total_size += size + #转换成字节在转成带单位的体积 + data['totle_seed_size'] = filesizeformat(total_size*1024) + else: + data['totle_seed_size'] = 0 + else: + data['seed_num'] = 0 + data['totle_seed_size'] = 0 + print("--->", data) return True, data else: data['msg'] = "格式错误" @@ -264,5 +316,5 @@ def general(site_name, site_name_cn, site_url, site_cookie): except: data['msg'] = "无法登录" - + print("err--->", data) return False, data diff --git a/apps/common/utils.py b/apps/common/utils.py index b5ef139..41cc828 100644 --- a/apps/common/utils.py +++ b/apps/common/utils.py @@ -213,11 +213,11 @@ def utc_to_local_unixtime(utc_time_str, utc_format='%Y-%m-%dT%H:%M:%SZ'): time_str = local_dt.strftime(local_format) return int(time.mktime(time.strptime(time_str, local_format))) -def capacity_convert(size, expect='auto', rate=1000): +def capacity_convert(size, expect='auto', rate=1024): """ :param size: '100MB', '1G' :param expect: 'K, M, G, T - :param rate: Default 1000, may be 1024 + :param rate: Default 1024 :return: """ rate_mapping = ( diff --git a/apps/cron/crontabs.py b/apps/cron/crontabs.py index 72a5846..c7376bb 100644 --- a/apps/cron/crontabs.py +++ b/apps/cron/crontabs.py @@ -25,8 +25,6 @@ from django_apscheduler.jobstores import DjangoJobStore, register_job user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36' -logger = logging.getLogger('sign') - executors = { # 执行器的线程与进程数 'default': ThreadPoolExecutor(10), @@ -145,6 +143,7 @@ def sign(crontab_id): 参数: crontab_id:执行任务的ID """ + logger = logging.getLogger('sign') #获取任务ID对应的站点 job_sites = list(Job.objects.filter(crontab_id=crontab_id).values_list('sites',flat=True)) @@ -201,7 +200,8 @@ def signonekey(): 参数: crontab_id:执行任务的ID """ - + logger = logging.getLogger('sign') + #获取任务ID对应的站点 job_sites = list(Job.objects.filter(jobtype_id=1000).values_list('sites',flat=True)) crontab_id = list(Job.objects.filter(jobtype_id=1000).values_list('crontab_id',flat=True))[0] @@ -255,6 +255,7 @@ def re_fail_sign(crontab_id): """ 重试签到失败 """ + logger = logging.getLogger('sign') #保存最后发送的结果 send_data = [] @@ -315,6 +316,8 @@ def send_msg(crontab_id = None, send_data = [], title='PT助手提示'): """ 发送消息 """ + logger = logging.getLogger('sign') + #消息为空则不发送 if send_data == []: return @@ -369,6 +372,7 @@ def rss(crontab_id): 参数: crontab_id:执行任务的ID """ + logger = logging.getLogger('rss') headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36', diff --git a/apps/dashboard/templates/dashboard/dashboard.html b/apps/dashboard/templates/dashboard/dashboard.html index a8e7674..b25197b 100644 --- a/apps/dashboard/templates/dashboard/dashboard.html +++ b/apps/dashboard/templates/dashboard/dashboard.html @@ -126,43 +126,20 @@
-
+
-
用户信息    - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - {{ siteusers|safe }} - -
站点用户名用户ID等级分享率做种数做种体积魔力值积分入站时间
+ +
+
+ +
+ +
+
+
+ +
@@ -206,6 +183,37 @@ ]] }); + var siteuserTb = tableX.render({ + elem: '#siteuserTable', + url: setter.base_server + 'sites/siteuser', + method: 'GET', + page: true, + skin: 'line', //不显示竖线 row不显示横线 nob (无边框风格) + even: true, //开启隔行背景 + limit: 200, + limits:['全部'], + cols: [[ + {field: 'id', title: 'ID',hide:true}, + {field: 'site_url', title: 'site_url',hide:true}, + {field: 'site_name', title: '站点', templet: function (d) { + return '' + d.site_name + ''; + }, unresize: true + }, + {field: 'username', title: '用戶名', width:110}, + {field: 'uid', title: '用戶ID', width:80}, + {field: 'level', title: '级别', width:120}, + {field: 'ratio', sort: true, title: '分享率', width:100}, + {field: 'upload', title: '上传'}, + {field: 'download', title: '下载'}, + {field: 'bonus', sort: true, title: '魔力值'}, + {field: 'score', title: '积分'}, + {field: 'published_seed_num', title: '发种数', width:75}, + {field: 'seed_num', title: '做种数', sort: true, width:100}, + {field: 'totle_seed_size', title: '做种体积'}, + {field: 'invite', title: '邀请码',sort: true, width:100}, + ]] + }); + // 工具条点击事件 table.on('tool(signFailTable)', function (obj) { var data = obj.data; @@ -241,5 +249,19 @@ } }); + // 更新数据按钮点击事件 + $('#updateuserBtn').click(function () { + layer.load(2); + admin.req('sites/siteuser/update', function (data) { + layer.closeAll('loading'); + if (data.code == 1) { + table.reload('siteuserTable', {}); + layer.msg(data.msg, {icon: 1}); + } else { + layer.msg(data.msg, {icon: 2}); + } + }, 'POST'); + return false; + }); }); \ No newline at end of file diff --git a/apps/dashboard/views.py b/apps/dashboard/views.py index da4ac87..8af4c59 100644 --- a/apps/dashboard/views.py +++ b/apps/dashboard/views.py @@ -14,40 +14,9 @@ class DashboardListView(LoginRequiredMixin, TemplateView): #配置站点总数 count_sites = SiteInfo.objects.count() - - html_data = [] - count_siteuser = SiteUser.objects.count() - if count_siteuser == 0: - html_data.append("请等待数据更新或手动点击更新") - else: - ormdata_siteuser = SiteUser.objects.all() - for i in ormdata_siteuser: - d = "%s(%s) \ - %s \ - %s \ - %s \ - %s \ - %s \ - %s \ - %s \ - %s \ - %s \ - " % (i.siteinfo_id.siteconfig_name,i.siteinfo_id.siteconfig_name_cn, - i.username, - i.uid, - i.level, - i.ratio, - i.seed_num, - i.totle_seed_size, - i.bonus, - i.score, - i.create_time - ) - html_data.append(d) - + context = { 'sites_num': count_sites, - 'siteusers': "".join(html_data), } kwargs.update(context) return super(DashboardListView, self).get_context_data(**kwargs) diff --git a/apps/rss/migrations/0018_alter_config_url.py b/apps/rss/migrations/0018_alter_config_url.py new file mode 100644 index 0000000..550649f --- /dev/null +++ b/apps/rss/migrations/0018_alter_config_url.py @@ -0,0 +1,18 @@ +# Generated by Django 4.1 on 2022-09-22 15:37 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('rss', '0017_config_name_alter_config_url'), + ] + + operations = [ + migrations.AlterField( + model_name='config', + name='url', + field=models.URLField(blank=True, max_length=350, verbose_name='RSS地址'), + ), + ] diff --git a/apps/rss/models.py b/apps/rss/models.py index 7ffb785..f4f76a2 100644 --- a/apps/rss/models.py +++ b/apps/rss/models.py @@ -28,7 +28,7 @@ class FilmType(models.Model): class Config(models.Model): """RSS配置""" name = models.CharField('自定义配置名称', max_length=50, null=True) - url = models.URLField('RSS地址', blank=True, max_length=350, unique=True) + url = models.URLField('RSS地址', blank=True, max_length=350) #site_name = models.CharField('网站名简称,英文', max_length=50, unique=True) #site_name_cn = models.CharField('网站名简称,中文', max_length=50, unique=True) #on_update 和 on_delete 后面可以跟的词语有四个 diff --git a/apps/sites/urls/views_urls.py b/apps/sites/urls/views_urls.py index a27656d..8c5ae6c 100644 --- a/apps/sites/urls/views_urls.py +++ b/apps/sites/urls/views_urls.py @@ -31,6 +31,8 @@ urlpatterns = [ path('siteinfo/export', views_request.siteinfoExport), path('siteinfo/import', views_request.siteinfoImport), path('siteinfo/select/list', views_request.select_siteinfo), - + #用戶信息 + path('siteuser', views_request.siteuser), + path('siteuser/update', views_request.getUserInfo), ] diff --git a/apps/sites/views_request.py b/apps/sites/views_request.py index 387068c..8dbc418 100644 --- a/apps/sites/views_request.py +++ b/apps/sites/views_request.py @@ -2,13 +2,15 @@ from django.http import JsonResponse, StreamingHttpResponse,HttpResponse from django.db.models import Q from django.contrib.auth.decorators import login_required - -from .models import SiteConfig, SiteRank, SiteInfo -from rss.models import Config import simplejson as json import io from urllib import parse import tempfile +import datetime + +from common.sites_user import userIngress +from .models import SiteConfig, SiteRank, SiteInfo, SiteUser +from rss.models import Config #直接使用检查是否管理员 #from django.contrib.auth.decorators import user_passes_test @@ -137,7 +139,7 @@ def siterankconfig(request): return JsonResponse(data) - +#=================================================================================================== @login_required def siteinfo(request): """ @@ -199,6 +201,67 @@ def siteinfo(request): #return HttpResponse(json.dumps(data,ensure_ascii = False), "application/json") return JsonResponse(data) +#=================================================================================================== +@login_required +def siteuser(request): + """ + 提供相应的数据 + """ + + #得到排序字段 + sort = request.GET.get('sort','id') + #得到排序规则 + order_by_type = request.GET.get('order','') + + if order_by_type == 'asc': + order_by = sort + else: + order_by = '-' + sort + + data = {} + data['code'] = 0 + data['msg'] = "" + data['data'] = [] + + data['count'] = SiteConfig.objects.count() + ormdata = SiteUser.objects.order_by(order_by) + + #已经配置的站点列表 + siteconfig_names = list(SiteInfo.objects.all().values_list('siteconfig_name',flat=True)) + + for i in ormdata: + ormdata_siteconfig = SiteConfig.objects.get(name=i.siteinfo_id.siteconfig_name) + data['data'].append({"id":i.id, + "site_name":i.siteinfo_id.siteconfig_name + '(' + i.siteinfo_id.siteconfig_name_cn + ')', + "site_url": ormdata_siteconfig.index_url, + 'username':i.username, + "uid":i.uid, + "ratio":i.ratio, + "upload":i.upload, + "download":i.download, + "bonus":i.bonus, + "score":i.score, + "level":i.level, + "published_seed_num":i.published_seed_num, + "seed_num":i.seed_num, + "totle_seed_size":i.totle_seed_size, + "create_time":i.create_time, + "invite":i.invite, + }) + #删除已经获取数据的 + siteconfig_names.remove(i.siteinfo_id.siteconfig_name) + + for i in siteconfig_names: + ormdata_siteconfig = SiteConfig.objects.get(name=i) + data['data'].append({"site_name":ormdata_siteconfig.name + '(' + ormdata_siteconfig.name_cn + ')', + "site_url": ormdata_siteconfig.index_url, + 'username':"无数据", + }) + #返回json串 + #return HttpResponse(json.dumps(data,ensure_ascii = False), "application/json") + return JsonResponse(data) + +#===================================================================================================================== def get_stream(data): # 开始这里我用ByteIO流总是出错,但是后来参考廖雪峰网站用StringIO就没问题 file = io.StringIO() @@ -491,4 +554,72 @@ def select_siteinfo(request): "name":i.siteconfig_name + "(" + i.siteconfig_name_cn + ")" }) - return JsonResponse(data) \ No newline at end of file + return JsonResponse(data) + + +#=============================================================================== +def getUserInfo(request): + """ + 更新用户信息 + """ + + #保存最后发送的结果 + send_data = [] + count_siteinfo = SiteInfo.objects.count() + #未配置任何站点直接返回 + if count_siteinfo == 0: + return + + _TIME_FORMAT = "%Y-%m-%d %H:%M:%S" + + ormdata_siteinfo = SiteInfo.objects.all() + for i in ormdata_siteinfo: + #记录ID值 + site_id = i.id + site_name = i.siteconfig_name + site_cookie = i.cookie + site_name_cn = i.siteconfig_name_cn + #获取站点配置信息 + site_config = SiteConfig.objects.get(name=site_name) + site_url = site_config.index_url + site_sign_type = site_config.sign_type + + flag, data = userIngress(site_name, site_name_cn, site_url, site_cookie, site_sign_type) + if flag: + count_userinfo = SiteUser.objects.filter(siteinfo_id = site_id).count() + if count_userinfo == 0: + #无记录 + SiteUser.objects.create(siteinfo_id=i, + username = data['user_name'], + uid = int(data['user_id']), + invite = int(data['invite']), + create_time = datetime.datetime.strptime(data['create_time'].strip(), _TIME_FORMAT).strftime('%Y-%m-%d %H:%M:%S'), + ratio = data['ratio'].strip(), + upload = data['upload'].strip(), + download = data['download'].strip(), + bonus = data['bonus'], + score = data['score'], + level = data['level'], + published_seed_num = int(data['published_seed_num']), + seed_num = int(data['seed_num']), + totle_seed_size = data['totle_seed_size'] + ) + else: + #已经存在 + SiteUser.objects.filter(siteinfo_id=site_id).update(username = data['user_name'], + uid = int(data['user_id']), + invite = int(data['invite']), + ratio = data['ratio'].strip(), + upload = data['upload'].strip(), + download = data['download'].strip(), + bonus = data['bonus'], + score = data['score'], + level = data['level'], + published_seed_num = int(data['published_seed_num']), + seed_num = int(data['seed_num']), + totle_seed_size = data['totle_seed_size'] + ) + + response_data={"code":1,"msg":"更新成功"} + + return JsonResponse(response_data) \ No newline at end of file