Commit beadfd91 beadfd913ea6fa5906791a107c7ab3aba7c64c46 by 杨俊

Init

0 parents
No preview for this file type
.idea
*.exe
*.pyc
*.log
api/static
HisinApi/settings.py
\ No newline at end of file
# 使用方 Python 基础镜像作为基础
FROM python:3.7.4
# 设置工目录
WORKDIR /
RUN apt-get update && apt-get install -y libsndfile1 ffmpeg
# 将 requirements.txt 复到容器中
COPY requirements.txt .
# 安装赖包
RUN pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
# 将整个项目复制到容器中
COPY . .
# 运行 Django 服务器
CMD python manage.py runserver 0.0.0.0:8000
\ No newline at end of file
No preview for this file type
import pymysql
pymysql.version_info = (1, 4, 13, "final", 0)
pymysql.install_as_MySQLdb()
\ No newline at end of file
"""
ASGI config for HisinApi project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HisinApi.settings')
application = get_asgi_application()
"""HisinApi URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from api.ApiList import login,index,audition,my,notifications,appversion,community
urlpatterns = [
#登录注册模块
path('admin', admin.site.urls),
path('', index.index),
path('api/sendsms',login.sendsms),
path('api/v2/sendsms', login.v2sendsms),
path('api/login', login.user_login),
path('api/sms_verify/login', login.sms_verify_login),
path('api/wechat/auth', login.wechatAuth),
path('api/register', login.register),
path('api/v2/register', login.v2register),
path('api/v3/register', login.v3register),
path('api/reset', login.restPwd),
path('api/business_list', login.businessList),
#首页模块
path('api/user', index.user),
path('api/activity/view', index.UserViewActivity),
path('api/examines', index.Examines.as_view()), #注册用户待审核列表
path('api/activitys', index.GetActivitys.as_view()),
path('api/v2/activitys', index.V2GetActivitys.as_view()), #去掉收藏活动
path('api/v3/activitys', index.V3GetActivitys.as_view()), #加入收藏活动
path('api/examine_status', index.examineStatus.as_view()),
path('api/banner', index.banners),
path('api/v2/banner', index.v2banners),
path('api/banner/detail', index.bannerDetail),
path('api/activity/attend_user',index.GetActivityUser.as_view() ),
path('api/activity/unlike', index.Unlike.as_view()),
path('api/activity/completes', index.GetCompleteActivity.as_view()),
path('api/events', index.Events),
path('api/action', index.Action),
path('api/band_list', index.BandList.as_view()),
path('api/band_detail', index.BandDetail.as_view()),
path('api/band_link_activity', index.BandLinkActivity.as_view()),
path('api/activity/recommend', index.RecommenCasedList.as_view()),
#我的模块
path('api/upload', my.upload),
path('api/user/avatar',my.updateUserAvatar),
path('api/user/activitys',my.MyActivitys.as_view()),
path('api/user/activity_detail', my.SaveOrSubmitList),
path('api/v2/user/activity_detail', my.V2SaveOrSubmitList),
path('api/user/activity_sumbit', my.UpdateSumbit),
path('api/user/submit_examine', my.SubmitExamine),
path('api/v2/user/submit_examine', my.V2SubmitExamine),
path('api/user/set_tag', my.SetUserTags),
path('api/user/tag_list', my.getUserTag),
path('api/user/unbind', my.unbind),
path('api/user/bind', my.bind),
path('api/admin/activitys', my.AdminActivitys.as_view()),
path('api/admin/submit_list', my.AdminSubmitList),
path('api/v2/admin/submit_list', my.V2AdminSubmitList),
path('api/user/singer_list', my.MySinget.as_view()),
path('api/user/singer', my.SingerInfo.as_view()),
path('api/v2/user/singer', my.SingerInfoV2.as_view()),
path('api/user/singer/avtivitys', my.SingerAvtivity.as_view()),
path('api/user/singer/complete', my.SingerComplete.as_view()), #我的歌手-被选中
path('api/user/singer/avtivity_detail', my.AvtivityDetail.as_view()),
path('api/user/banner', my.banners),
path('api/user/listen', my.Listen.as_view()),
path('api/user/ta_collection', my.TaCollection.as_view()),
path('api/user/ta_audition', my.TaAudition.as_view()),
path('api/user/resume_like', my.ResumeLike.as_view()),
path('api/user/remove_save', my.remove_save),
path('api/user/editor', my.editor),
path('api/user/change_phone', my.change_phone),
path('api/user/sound', my.UserSound.as_view()),
path('api/user/home', my.UserHome.as_view()),
path('api/user/tidings', my.UserTidings.as_view()),
path('api/user/follow', my.UserFollow.as_view()),
path('api/user/following', my.UserFollowing.as_view()),
path('api/user/find_singer', my.FindSinger.as_view()),
path('api/user/visitors', my.Visitors.as_view()),
path('api/user/remove_device', my.RemoveDevice.as_view()),
path('api/user/avtivitys/price', my.AvtivitysPrice.as_view()),
path('api/avtivitys/price_info', my.AvtivitysPriceInfo.as_view()),
#管理员查看试唱确认合作
path('api/admin/activity/confirm',my.ConfirmSinger),
#注销账号
path('api/user/delete', my.UserDelete),
#试唱模块
path('api/audition/materials', audition.AuditionMaterials), #小程序端物料,要升降调文件
path('api/activity/materials', audition.ActivityMaterials), #app 端物料,无须升降调文件
path('api/audition/send_materials', audition.SendMaterials), #自主上传方式发送物料
path('api/audition/split_audio', audition.SplitAudio),
path('api/audition/auto_submit', audition.AotoSubmit),
path('api/audition/online_save', audition.OnlineSave),
path('api/audition/join', audition.JoinActivity), # APP线上保存或提交
path('api/audition/upload', audition.UploadAudio),
path('api/audition/mixin_preview', audition.MixinPreview),
path('api/audition/part_preview', audition.PartPreview),
path('api/audition/mixin_check', audition.MixinCheck),
path('api/audition/collection', audition.Collection.as_view()),
path('api/audition/remove_collection', audition.cancelcollection),
#活动确定分享人
path('api/audition/share_users_list', audition.ShareUsersList.as_view()),
path('api/audition/share_users', audition.ShareUsers.as_view()),
#社区模块
path('api/community/tidings', community.Tidings.as_view()),
path('api/community/tidings/selete_activity', community.SeleteActivity.as_view()),
path('api/community/tidings_list', community.TidingsList.as_view()),
path('api/community/tidings/show', community.TidingsShow.as_view()),
path('api/community/tidings/limiting', community.TidingsLimiting.as_view()),
path('api/community/tidings/report', community.TidingsReport.as_view()),
path('api/community/tidings/record_user', community.RecordUser.as_view()),
path('api/community/tidings/interacts',community.TidingsInteracts.as_view()),
path('api/community/tidings/chat', community.TidingsChat.as_view()),
path('api/community/chat/relation', community.ChatRelation.as_view()),
path('api/community/chat/agent', community.ChatAgent.as_view()),
path('api/community/chat/agent_record', community.ChatAgentRecord.as_view()),
path('api/community/unlike', community.Unlike.as_view()),
path('api/community/tidings/comments', community.TidingsComments.as_view()), #动态评论
#消息通知模块
path('api/notifica/read_message', notifications.read),
path('api/notifica/system_message', notifications.SystemMessage.as_view()),
#极光推送
path('api/notifica/push', notifications.push_notifications),
#积分接口
path('api/user/point', my.UserPoint.as_view()),
# 用户协议
path('h5/user_agreement', index.useragreement),
#分享活动页面
path('h5/share/<id>/', index.songshare),
# 分享动态页面
# path('h5/sharetidings/<id>/', index.tidingsshare),
# app分享页面
path('h5/shareapp/', index.appshare),
#版本更新
path('api/app/version', appversion.versioninfo),
#获取app分享内容
path('api/share/dictionary_list', my.sharechildlist),
path('api/share/dictionary', my.sharechild),
#客服列表
path('api/customer_service', my.CustomerService.as_view()),
]
"""
WSGI config for HisinApi project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HisinApi.settings')
application = get_wsgi_application()
#### Python版本
- Python 3.7.0
#### 依赖安装
- pip install -r requirements.txt
#### 本地项目启动命令
- python manage.py runserver
#### 线上项目进程管理,启动/更新
- 服务已经配置supervisor进程管理
- git pull拉取代码后会更新服务
#### 主要目录结构说明
> HisinApi 文件主目录
>> api 接口编写主目录
> > > ApiList 接口模块列表
> > >
> > > jobs 定时任务脚本
> > >
> > > templates 页面文件
> > >
> > > admin.py
> > >
> > > apps.py
> > >
> > > loggin.py 日志模块
> > >
> > > models.py 数据表模型文件
> > >
> > > serializers.py 接口返回数据序列化,定义返回字段和结构
> > >
> > > tests.py
> > >
> > > verification.py 接口接受参数校验文件
> > >
> > > views.py 接口通用方法都写在这里
>>
>> HisinApi 项目环境配置
> > > settings.py 环境配置文件
> > >
> > > urls.py 接口路由定义文件
> >
> > manage.py 项目启动文件
> >
> > requirements.txt 项目依赖文件
\ No newline at end of file
No preview for this file type
from api import models
from api.views import ResponseFactory
from django.http import JsonResponse
from api import serializers
def versioninfo(requests):
"""
版本更新信息
:param requests:
:return:
"""
if requests.method != 'GET':
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
os = requests.GET['os']
app_version = requests.GET['app_version']
# verobject = models.AppVersion.objects.filter(os=os,app_ver__gt=app_version,deleted_at=None).first()
# if verobject:data = serializers.AppVersionSerializer(models.AppVersion.objects.filter(os=os,deleted_at=None).last(),many=False,context={"app_version":app_version,"os":os}).data
# else:data = serializers.AppVersionSerializer(models.AppVersion.objects.filter(os=os,deleted_at=None).last(),many=False,context={"app_version":app_version,"os":os}).data
data = serializers.AppVersionSerializer(models.AppVersion.objects.filter(os=os, deleted_at=None).last(), many=False,context={"app_version": app_version, "os": os}).data
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
\ No newline at end of file
import json
from django.core.mail import send_mail
from django.http import JsonResponse
from api.views import ResponseFactory,PageNumberPagination,createMessage,deleteMessage,pushSubscribeMessage,get_oss_file
from api import models,serializers
from HisinApi import settings
from django.utils import timezone
from api.views import upload_audio,auto_upload_audio, AuthPermissionRequired,get_user_info,ChangeAudio,WeChatApi,user_point_record,JPush,user_permission
import threading
from api import verification
from rest_framework.views import APIView
from django.utils.decorators import method_decorator
from django.db import transaction
from api import loggin
import librosa
import pyroomacoustics as pra
import pydub
import numpy as np
import time
import os
import random
import shutil
from math import log
from django.db.models import Q
from django_redis import get_redis_connection
from api.loggin import logger
import requests
sem = threading.Semaphore(4)
con = get_redis_connection("default")
# 板式混响
def plate_mixin(person_voice_path,result_file_path,mixin_ratio):
fs = 44100
room_dim = [18 * mixin_ratio, 15 * mixin_ratio] # 房间尺寸米
mic1_dim = [9 * mixin_ratio - 0.4, 7.5 * mixin_ratio, ] # 麦克风1位置
mic2_dim = [9 * mixin_ratio + 0.4, 7.5 * mixin_ratio] # 麦克风2位置
per_dim = [9 * mixin_ratio, 7.5 * mixin_ratio - 0.2] # 人声位置
scattering = 'rpg_qrd' # 散射模式,可选项 rpg_skyline ,rpg_qrd
max_order = 20 # 最大反射次数
absorption = False # 是否开启空气吸收
humidity = 0 # 空气湿度
room = pra.ShoeBox(room_dim, fs=fs,
materials=pra.Material(energy_absorption="hard_surface", scattering=scattering)
, max_order=max_order, air_absorption=absorption, humidity=humidity)
audio, _ = librosa.load(person_voice_path, sr=fs) # 导入一个单通道语音作为源信号 source signal
room.add_source(per_dim, signal=audio, delay=0)
mic_locs = np.c_[
mic1_dim, # mic 1
mic2_dim, # mic 2
]
room.add_microphone_array(mic_locs) # 最后将麦克风阵列放在房间里
room.compute_rir()
room.simulate(reference_mic=0)
room.mic_array.to_wav(result_file_path, norm=True, bitdepth=np.float32, )
# room混响
def room_mixin(person_voice_path,result_file_path):
mixin_ratio = 1
fs = 44100
rt60_tgt = 0.5
room_dim = [9*mixin_ratio, 7.5*mixin_ratio, 3.5*mixin_ratio]
e_absorption, max_order = pra.inverse_sabine(rt60_tgt, room_dim)
room = pra.ShoeBox(room_dim, fs=fs, materials=pra.Material(e_absorption), max_order=max_order)
audio, _ = librosa.load(person_voice_path, sr=fs)
room.add_source([6.3*mixin_ratio, 4.9*mixin_ratio, 1.2], signal=audio, delay=0.3)
mic_locs = np.c_[
[6.3*mixin_ratio, 4.87*mixin_ratio, 1.2], # mic 1
[6.3*mixin_ratio, 4.93*mixin_ratio, 1.2], # mic 2
]
room.add_microphone_array(mic_locs)
room.compute_rir()
room.simulate(reference_mic=0)
room.mic_array.to_wav(result_file_path, norm=True, bitdepth=np.float32, )
# room混响
def hall_mixin(person_voice_path, result_file_path):
mixin_ratio = 2
fs = 44100
rt60_tgt = 3
room_dim = [6 * mixin_ratio, 6 * mixin_ratio, 3.5]
e_absorption, max_order = pra.inverse_sabine(rt60_tgt, room_dim)
room = pra.ShoeBox(room_dim, fs=fs, materials=pra.Material(e_absorption), max_order=30)
audio, _ = librosa.load(person_voice_path, sr=fs)
room.add_source([3 * mixin_ratio, 3*mixin_ratio , 1.2], signal=audio, delay=0)
mic_locs = np.c_[
[3 * mixin_ratio, 2.95 * mixin_ratio, 1.2], # mic 1
[3 * mixin_ratio, 3.05 * mixin_ratio, 1.2], # mic 2
]
room.add_microphone_array(mic_locs)
room.compute_rir()
room.simulate(reference_mic=0)
room.mic_array.to_wav(result_file_path, norm=True, bitdepth=np.float32, )
def mixin(person_voice_path,person_volume,bg_audio_path,bg_volume, mixin_ratio,offset,mixin_pre_id,remove_path):
"""预览合成"""
with sem:
try:
t = str(int(time.time())) + str(random.randint(0, 10000000000))
os.mkdir("./api/static/{}".format(t))
base_path = "./api/static/{}".format(t)
mixin_output_path = base_path + '/mixin_out-{}.wav'.format(str(random.randint(0, 10000000000)))
out_path = base_path + '/compose_out.mp3'.format(str(random.randint(0, 10000000000)))
if mixin_ratio:
if mixin_ratio == 1:
room_mixin(person_voice_path, mixin_output_path)
elif mixin_ratio == 2:
plate_mixin(person_voice_path,mixin_output_path,1)
elif mixin_ratio == 3:
hall_mixin(person_voice_path,mixin_output_path)
compose(mixin_output_path,person_volume,bg_audio_path,bg_volume,offset,out_path,mixin_ratio)
else:
compose(person_voice_path, person_volume, bg_audio_path, bg_volume, offset, out_path,mixin_ratio)
with open(out_path, 'rb') as of:
file_data = of.read()
of.close()
demo_url = upload_audio(file_data)
# 删除零时文件
shutil.rmtree(remove_path)
shutil.rmtree(base_path)
#修改合成状态和demo
models.MixinPreviews.objects.filter(id=mixin_pre_id).update(url=demo_url, syn_status=1,updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
except:
models.MixinPreviews.objects.filter(id=mixin_pre_id).update(url='',syn_status=3,updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
def mixin_save(person_voice_path,person_volume,bg_audio_path,bg_volume, mixin_ratio,offset,ahu_id,remove_path):
"""保存合成"""
with sem:
try:
# 状态修改为合成中
models.ActivityHasUsers.objects.filter(id=ahu_id).update(syn_status=2, updated_at=timezone.now().strftime(
"%Y-%m-%d %H:%M:%S"))
t = str(int(time.time())) + str(random.randint(0, 10000000000))
os.mkdir("./api/static/{}".format(t))
base_path = "./api/static/{}".format(t)
mixin_output_path = base_path + '/mixin_out-{}.wav'.format(str(random.randint(0, 10000000000)))
out_path = base_path + '/compose_out.wav'.format(str(random.randint(0, 10000000000)))
if mixin_ratio:
if mixin_ratio == 1:
plate_mixin(person_voice_path,mixin_output_path,1)
elif mixin_ratio == 2:
room_mixin(person_voice_path,mixin_output_path)
elif mixin_ratio == 3:
hall_mixin(person_voice_path,mixin_output_path)
compose(mixin_output_path,person_volume,bg_audio_path,bg_volume,offset,out_path,mixin_ratio)
else:
compose(person_voice_path, person_volume, bg_audio_path, bg_volume, offset, out_path,mixin_ratio)
with open(out_path, 'rb') as of:
file_data = of.read()
of.close()
#获取时长
demo_music = pydub.AudioSegment.from_mp3(out_path)
duration = demo_music.duration_seconds
demo_url = upload_audio(file_data)
# 删除零时文件
shutil.rmtree(base_path)
shutil.rmtree(remove_path)
#保存至参与活动表中
models.ActivityHasUsers.objects.filter(id=ahu_id).update(demo_url=demo_url,durations=duration,syn_status=1,updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
except Exception as e:
models.ActivityHasUsers.objects.filter(id=ahu_id).update(demo_url='',syn_status=3,updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
def person_voice_mixin(person_voice_path,result_file_path,mixin_ratio):
fs = 44100
room_dim = [18 * mixin_ratio, 15 * mixin_ratio] # 房间尺寸米
mic1_dim = [9 * mixin_ratio - 0.4, 7.5 * mixin_ratio, ] # 麦克风1位置
mic2_dim = [9 * mixin_ratio + 0.4, 7.5 * mixin_ratio] # 麦克风2位置
per_dim = [9 * mixin_ratio, 7.5 * mixin_ratio - 0.2] # 人声位置
scattering = 'rpg_qrd' # 散射模式,可选项 rpg_skyline ,rpg_qrd
max_order = 10 # 最大反射次数
absorption = False # 是否开启空气吸收
humidity = 0 # 空气湿度
room = pra.ShoeBox(room_dim, fs=fs,
materials=pra.Material(energy_absorption="hard_surface", scattering=scattering)
, max_order=max_order, air_absorption=absorption, humidity=humidity)
audio, _ = librosa.load(person_voice_path, sr=fs) # 导入一个单通道语音作为源信号 source signal
room.add_source(per_dim, signal=audio, delay=0)
mic_locs = np.c_[
mic1_dim, # mic 1
mic2_dim, # mic 2
]
room.add_microphone_array(mic_locs) # 最后将麦克风阵列放在房间里
room.compute_rir()
room.simulate(reference_mic=0)
room.mic_array.to_wav(result_file_path, norm=True, bitdepth=np.float32, )
# 将伴奏和人声合成
def compose(person_voice_path,person_volume,bg_audio_path,bg_volume,offset,out_path,mixin_ratio):
if mixin_ratio :
per_sound = pydub.AudioSegment.from_wav(person_voice_path)
else:
per_sound = pydub.AudioSegment.from_mp3(person_voice_path)
audio_sound = pydub.AudioSegment.from_mp3(bg_audio_path)
audio_sound_length = audio_sound.duration_seconds * 1000
per_sound_length = per_sound.duration_seconds * 1000
if per_sound_length < audio_sound_length:
audio_sound = audio_sound[:int(per_sound_length)]
elif per_sound_length > audio_sound_length:
per_sound = per_sound[:int(audio_sound_length)]
per_dBFS = per_sound.dBFS
bg_dBFs = audio_sound.dBFS
per_radio = 10 ** (per_dBFS / 20)
bg_radio = 10 ** (bg_dBFs / 20)
to_per_radio = per_radio * person_volume
to_bg_radio = bg_radio * bg_volume
if to_per_radio == 0:
to_per_radio = 0.0001
if to_bg_radio == 0:
to_bg_radio = 0.0001
to_per_dbfs = 20 * log(to_per_radio, 10)
to_bg_dbfs = 20 * log(to_bg_radio, 10)
per_change_dBFS = to_per_dbfs - per_dBFS
bg_chang_dBFs = to_bg_dbfs - bg_dBFs
per_sound = per_sound.apply_gain(per_change_dBFS)
audio_sound = audio_sound.apply_gain(bg_chang_dBFs)
if offset>=0:
played_togther = per_sound.overlay(audio_sound,position=offset)
played_togther.export(out_path, format="mp3")
else:
played_togther = audio_sound.overlay(per_sound,position=-offset)
played_togther.export(out_path, format="mp3")
@AuthPermissionRequired()
def MixinPreview(request):
"""
混响预览
"""
if request.method == 'POST':
postdata = json.loads(request.body)
obj = verification.mixin_previews(postdata)
if obj.is_valid():
data = obj.clean()
user = get_user_info(request)
t = str(int(time.time())) + str(random.randint(0, 10000000000))
os.mkdir("./api/static/{}".format(t))
base_path = "./api/static/{}".format(t)
person_voice_path = base_path + "/voice-{}.mp3".format(str(random.randint(0, 10000000000)))
try:
# person_voice_file = requests.get(data.get('person_url'),verify=False).content
person_voice_file = get_oss_file(data.get('person_url'))
# bg_audio_file = requests.get(data.get('bg_url'),verify=False).content
bg_audio_file = get_oss_file(data.get('bg_url'))
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="上传物料链接获取不到资源,检查链接", data=None, status='fail'))
# #保存上传文件
with open(person_voice_path, "wb") as f:
f.write(person_voice_file)
f.close()
bg_audio_path = base_path + "/bg-{}.mp3".format(str(random.randint(0, 10000000000)))
# #保存上传文件
with open(bg_audio_path, "wb") as ff:
ff.write(bg_audio_file)
ff.close()
person_volume = data.get('person_volume')
bg_volume = data.get('bg_volume')
mixin_ratio = data.get('mix_type')
offset = data.get('offset')
# 查看时候需要切片段
begin_time = postdata.get('begin_time', '')
if begin_time != '':
# 获取人声音频时长
person_input_music = pydub.AudioSegment.from_file(person_voice_path)
duration = person_input_music.duration_seconds
# #伴奏音频切片
bg_input_music = pydub.AudioSegment.from_file(bg_audio_path)
# 截取音频 1000毫秒 = 1秒
bg_output_music = bg_input_music[begin_time * 1000:begin_time * 1000 + duration * 1000]
# 保存音频,指定音频比特率为64k
bg_output_music.export(bg_audio_path, bitrate="64k")
mixin_pre = models.MixinPreviews.objects.create(
activity_id=data['activity_id'],
user_id=user['id'],
url='',
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
t = threading.Thread(target=mixin,args=[person_voice_path,person_volume,bg_audio_path,bg_volume, mixin_ratio,offset,mixin_pre.id,base_path])
t.setDaemon(True)
t.start()
data = {'id':mixin_pre.id,'activity_id':mixin_pre.activity_id,'url':mixin_pre.url}
return JsonResponse(ResponseFactory(code=200, message="音频合成中", data=data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def PartPreview(request):
"""
片段混响
"""
if request.method == 'POST':
obj = verification.part_mixin_previews(json.loads(request.body))
if obj.is_valid():
data = obj.clean()
user = get_user_info(request)
t = str(int(time.time())) + str(random.randint(0, 10000000000))
os.mkdir("./api/static/{}".format(t))
base_path = "./api/static/{}".format(t)
person_voice_path = base_path + "/voice-{}.mp3".format(str(random.randint(0, 10000000000)))
try:
# person_voice_file = requests.get(data.get('person_url')).content
person_voice_file = get_oss_file(data.get('person_url'))
# bg_audio_file = requests.get(data.get('bg_url')).content
bg_audio_file = get_oss_file(data.get('bg_url'))
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="上传物料链接获取不到资源,检查链接", data=None, status='fail'))
# #保存人声文件
with open(person_voice_path, "wb") as f:
f.write(person_voice_file)
f.close()
bg_audio_path = base_path + "/bg-{}.mp3".format(str(random.randint(0, 10000000000)))
# #保存伴奏文件
with open(bg_audio_path, "wb") as ff:
ff.write(bg_audio_file)
ff.close()
#提取伴奏片段
part_bg_path = base_path + "/part-bg-{}.mp3".format(str(random.randint(0, 10000000000)))
input_music = pydub.AudioSegment.from_mp3(bg_audio_path)
# 截取音频 1000毫秒 = 1秒
output_music = input_music[data.get('start_time')*1000:data.get('end_time')*1000]
# 保存音频,指定音频比特率为64k
output_music.export(part_bg_path, bitrate="64k")
person_volume = data.get('person_volume')
bg_volume = data.get('bg_volume')
mixin_ratio = data.get('mix_type')
offset = data.get('offset')
mixin_pre = models.MixinPreviews.objects.create(
activity_id=data['activity_id'],
user_id=user['id'],
url='',
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
t = threading.Thread(target=mixin,args=[person_voice_path,person_volume,part_bg_path,bg_volume, mixin_ratio,offset,mixin_pre.id,base_path])
t.setDaemon(True)
t.start()
data = {'id':mixin_pre.id,'activity_id':mixin_pre.activity_id,'url':mixin_pre.url}
return JsonResponse(ResponseFactory(code=200, message="音频合成中", data=data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def MixinCheck(request):
if request.method == 'GET':
try:
id = int(request.GET['id'])
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="id参数错误", data=None, status='fail'))
mixin_pre = serializers.MixinPreviewsSerializer(models.MixinPreviews.objects.get(id=id,deleted_at=None),many=False)
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=mixin_pre.data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def OnlineSave(request):
"""
在线上传
"""
if request.method == 'POST':
user = get_user_info(request)
try:
data = json.loads(request.body)
# 获取上次提交版本信息
obj = models.ActivityHasUsers.objects.filter(user_id=user['id'], activity_id=data['activity_id'],deleted_at=None).last()
if obj:
version = obj.version
if version:
version += 1
else:
version = 1
else:
version = 1
#预览完成保存
if data['demo_url'] != '':
#获取音频时长
try:
# demo_data = requests.get(data['demo_url'],verify=False).content
demo_data = get_oss_file(data['demo_url'])
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="音频地址获取不到资源,检查链接", data=None, status='fail'))
# #保存demo文件获取时长
demo_path = "./api/static/demo-{}.mp3".format(str(random.randint(0, 10000000000)))
with open(demo_path, "wb") as f:
f.write(demo_data)
f.close()
demo_music = pydub.AudioSegment.from_mp3(demo_path)
duration = demo_music.duration_seconds
# 删除零时文件
os.remove(demo_path)
ahu = models.ActivityHasUsers.objects.create(
activity_id=data['activity_id'],
user_id=user['id'],
demo_url=data['demo_url'],
durations = duration,
status=0,
syn_status=1,
syn_data=data,
type="Save",
version = version,
mode = 0,
sing_type=data.get('sing_type',None),
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
data = {'id':ahu.id,'activity_id':ahu.activity_id,'demo_url':ahu.demo_url}
return JsonResponse(ResponseFactory(code=200, message="保存成功", data=data, status='success'))
#未预览保存
else:
t = str(int(time.time())) + str(random.randint(0, 10000000000))
os.mkdir( os.getcwd() + "/api/static/{}".format(t))
base_path = os.getcwd() + "/api/static/{}".format(t)
person_voice_path = base_path + "/voice-{}.mp3".format(str(random.randint(0, 10000000000)))
try:
# person_voice_file = requests.get(data.get('person_url'),verify=False).content
person_voice_file = get_oss_file(data.get('person_url'))
# bg_audio_file = requests.get(data.get('bg_url'),verify=False).content
bg_audio_file = get_oss_file(data.get('bg_url'))
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="上传物料链接获取不到资源,检查链接", data=None, status='fail'))
# #保存上传文件
with open(person_voice_path, "wb") as f:
f.write(person_voice_file)
f.close()
bg_audio_path = base_path + "/bg-{}.mp3".format(str(random.randint(0, 10000000000)))
# #保存上传文件
with open(bg_audio_path, "wb") as ff:
ff.write(bg_audio_file)
ff.close()
person_volume = data.get('person_volume')
bg_volume = data.get('bg_volume')
mixin_ratio = data.get('mix_type')
offset = data.get('offset')
#查看时候需要切片段
begin_time = data.get('begin_time','')
if begin_time != '' :
# 获取人声音频时长
person_input_music = pydub.AudioSegment.from_mp3(person_voice_path)
duration = person_input_music.duration_seconds
# #伴奏音频切片
bg_input_music = pydub.AudioSegment.from_file(bg_audio_path)
# 截取音频 1000毫秒 = 1秒
bg_output_music = bg_input_music[begin_time*1000:begin_time*1000+duration*1000]
# 保存音频,指定音频比特率为64k
bg_output_music.export(bg_audio_path, bitrate="64k")
ahu = models.ActivityHasUsers.objects.create(
activity_id=data['activity_id'],
user_id=user['id'],
demo_url='',
syn_status = 0,
syn_data = data ,
status=0,
type="Save",
mode=0,
version = version,
sing_type=data.get('sing_type', None),
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
t = threading.Thread(target=mixin_save,
args=[person_voice_path, person_volume, bg_audio_path, bg_volume, mixin_ratio, offset,
ahu.id, base_path])
t.setDaemon(True)
t.start()
data = {'id': ahu.id, 'activity_id': ahu.activity_id, 'demo_url': ahu.demo_url}
return JsonResponse(ResponseFactory(code=200, message="音频合成中,合成后会自动保存", data=data, status='success'))
except Exception as e:
logger.info('提交异常:用户ID:{},参数:{},错误信息:{}'.format(user['id'], request.body,e))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def JoinActivity(request):
if request.method != 'POST':
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
user = get_user_info(request)
# 检查是否有提交权限
permission = user_permission(user['id'])
if 2 not in permission:
return JsonResponse(ResponseFactory(code=400, message='用户无此权限', data=None, status='fail'))
post_data = json.loads(request.body)
dataobj = verification.join_activity(post_data)
if not dataobj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(dataobj), data=None, status='fail'))
dataobj = dataobj.clean()
activity_id = dataobj.get('activity_id')
url = dataobj.get('url')
type = dataobj.get('join_type')
sing_type = dataobj.get('sing_type')
is_hide = post_data.get('is_hide',1)
# 判断活动状态
activity_status = models.Activitys.objects.filter(id=activity_id).first().status
if activity_status != 1:
return JsonResponse(ResponseFactory(code=201, message="活动已结束", data=None, status='fail'))
self_price = post_data.get('self_price',None)
#校验自主报价参数
if self_price:
ver = verification.SubmitPriceVerification(data=self_price)
if not ver.is_valid():
return JsonResponse(
ResponseFactory(code=400, message=verification.error_message(ver), data=None, status='fail'))
if self_price['value']['amounts']:
if not (0 <= self_price['value']['amounts'] <= 9999999): return JsonResponse(
ResponseFactory(code=201, message="金额在0-9999999之间", data=None, status='fail'))
if self_price['value']['ratio']:
if not (0 <= self_price['value']['ratio'] <= 100): return JsonResponse(
ResponseFactory(code=201, message="分成比列在0%-100%之间", data=None, status='fail'))
try:
# 获取上次提交版本信息
ahu_obj = models.ActivityHasUsers.objects.filter(user_id=user['id'], activity_id=activity_id,deleted_at=None).last()
if ahu_obj:
version = ahu_obj.version
if version:version += 1
else:version = 1
else:
version = 1
try:
demo_data = get_oss_file(url)
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="音频地址获取不到资源,检查链接", data=None, status='fail'))
# #保存demo文件获取时长
file_type = url.split('.')[-1]
demo_path = "./api/static/demo-{}.{}".format(str(random.randint(0, 10000000000)), file_type)
with open(demo_path, "wb") as f:
f.write(demo_data)
f.close()
demo_music = pydub.AudioSegment.from_file(demo_path)
duration = demo_music.duration_seconds
# 删除零时文件
os.remove(demo_path)
if type == 'Submit':
try:
with transaction.atomic():
models.ActivityHasUsers.objects.filter(user_id=user['id'], activity_id=activity_id).update(type="Save", updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
ahu = models.ActivityHasUsers.objects.create(
activity_id=activity_id,
user_id=user['id'],
demo_url=url,
durations=duration,
status=0,
type=type,
open_id='',
syn_status=1,
mode=0,
is_hide = is_hide,
version=version,
sing_type=sing_type,
submit_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
#存入自主报价
if self_price:
models.ActivityUserHasPrices.objects.update_or_create(
user_id=user['id'], activity_id=activity_id,
defaults={
"value": self_price['value'],
"is_deduct": self_price['is_deduct'],
"is_talk": self_price['is_talk'],
"address_id": self_price['address_id'],
"is_accept_address": self_price['is_accept_address'],
"created_at": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
"updated_at": timezone.now().strftime("%Y-%m-%d %H:%M:%S"), },
)
# 更新到动态
is_tidings = post_data.get("is_tidings", 0)
if is_tidings == 1:
models.UserHasTidings.objects.create(user_id=user['id'], activity_id=activity_id,type=2, url=url,created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
# 提交作品计数 1.先检查用户对该作品之前是否有提交且未读的消息
user_msg = models.UserMessages.objects.filter(is_read=0, sender_id=user['id'],activity_id=activity_id, deleted_at=None, type=3)
if user_msg:
user_msg.update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
# 获取全体管理员和推荐人open_id
project_id = models.Activitys.objects.filter(id=activity_id).first().project_id
project = models.Projects.objects.filter(id=project_id).first()
project_user_ids = []
if project:
if project.is_public:project_user_ids = list(models.UserHasProjects.objects.filter(project_id=project_id).values_list('user_id',flat=True))
else:project_user_ids = [models.Activitys.objects.filter(id=activity_id).first().user_id]
project_user_unionid = list(
models.Users.objects.filter(id__in=project_user_ids, deleted_at=None, status=1).values_list(
'unionid', flat=True))
admin_unionid = list(models.Users.objects.filter(scope=1,deleted_at=None,status=1).values_list('unionid', flat=True))
push_open_ids = list(
models.WechatOfficialUsers.objects.filter(union_id__in=admin_unionid + project_user_unionid,is_subscribe=1).values_list('open_id', flat=True))
song_name = models.Activitys.objects.filter(id=activity_id).first().song_name
# 再创建消息
business_id = user['business_id']
if business_id:
# 获取推荐人公众号open_id
unionid = models.Users.objects.filter(id=business_id).values_list('unionid', flat=True)
wechat_official = models.WechatOfficialUsers.objects.filter(union_id__in=unionid,is_subscribe=1).last()
if wechat_official:
# 公众号推送
p_data = {'channel': 'singer_related', 'open_id': [wechat_official.open_id],
'data': {"title": "您的歌手参加了试唱歌曲",
"name": user['nick_name'] + "("+user['real_name']+")",
"intro": "参加了试唱歌曲《{}》".format(song_name),
"remark": "点击前往 >",
"page": "/packageMy/pages/like?tab=2"}}
pushSubscribeMessage(p_data)
# 发给绑定的推荐人
m_data = {'sender_id': user['id'], 'receivers': [business_id],
'activity_id': activity_id, 'type': 3, 'is_bind': 1}
createMessage(m_data)
# 极光推送-提交作品推荐人
j_title = "您的歌手参加了试唱"
j_content = "您的歌手{}参加了试唱活动《{}》".format(user['nick_name'], song_name)
jdata = {"title": j_title, "content": j_content, "content_type": "text",
"receiver_value": [business_id],
"extras": {"type": "ToTaSing", "value": ""}}
JPush().jpush_v3(jdata)
# 给全体管理员和项目管理员推服务号消息
p_data = {'channel': 'activity_join', 'open_id': push_open_ids,
'data': {
"first": "{}({})提交了试唱作品".format(user['nick_name'], user['real_name']),
"keyword1": "《"+song_name+"》",
"keyword2": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
"remark": "点击试听 >", "page": "/pages/index/index"}
}
pushSubscribeMessage(p_data)
# 外部管理员id
activity_manage_ids = list(
models.UserManageActivitie.objects.filter(activity_id=activity_id).values_list(
'user_id', flat=True))
# 发送系统消息(平台管理员+项目管理员+外部管理员)
receivers = list(models.Users.objects.filter(scope=1).values_list('id', flat=True))
receivers = list(set(receivers + project_user_ids +activity_manage_ids))
m_data = {'sender_id': user['id'], 'receivers': receivers,
'activity_id': activity_id,
'type': 3, 'is_bind': 0}
createMessage(m_data)
# 极光推送-提交作品全体管理员
j_title = "有新用户提交试唱"
j_content = "{}参与了试唱《{}》".format(user['nick_name'], song_name)
jdata = {"title": j_title, "content": j_content, "content_type": "text",
"receiver_value": receivers,
"extras": {"type": "ToPlatfromSing", "value": ""}}
JPush().jpush_v3(jdata)
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="提交失败:{}".format(e), data=None, status='fail'))
if sing_type == 'Part':
# 歌手积分
user_point_record(user_id=user['id'], type='SubmitPart', activity_id=activity_id)
# 推荐人积分
if user['business_id']:
user_point_record(user_id=user['business_id'], type='SingerSubmitPart',activity_id=activity_id,singer_id=user['id'])
else:
# 歌手积分
user_point_record(user_id=user['id'], type='SubmitFull', activity_id=activity_id,)
# 推荐人积分
if user['business_id']:
user_point_record(user_id=user['business_id'], type='SingerSubmitFull',activity_id=activity_id,singer_id=user['id'])
data = {'id': ahu.id, 'activity_id': ahu.activity_id, 'demo_url': ahu.demo_url}
return JsonResponse(ResponseFactory(code=200, message="提交成功", data=data, status='success'))
else:
ahu = models.ActivityHasUsers.objects.create(
activity_id=activity_id,
user_id=user['id'],
demo_url=url,
durations=duration,
status=0,
type=type,
open_id='',
mode=0,
syn_status = 1,
version=version,
sing_type=sing_type,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
data = {'id': ahu.id, 'activity_id': ahu.activity_id, 'demo_url': ahu.demo_url}
return JsonResponse(ResponseFactory(code=200, message="保存成功", data=data, status='success'))
except Exception as e:
logger.info('提交异常:用户ID:{},参数:{},错误信息:{}'.format(user['id'], request.body, e))
return JsonResponse(ResponseFactory(code=201, message="服务器网络波动,请稍后重试", data=None, status='fail'))
@AuthPermissionRequired()
def AuditionMaterials(request):
if request.method == 'GET':
activity_id = request.GET['activity_id']
user_id = get_user_info(request)['id']
queryset = models.Activitys.objects.filter(id=activity_id).first()
activity_ser = serializers.ActivityDetailSerializer(queryset,many=False,context={"user_id":user_id,"project_many":False},
fields=['id','song_name','lyric','clip_lyric','cover','status','project_id','sex','mark','speed','lang','guide_duration','guide_clip_duration','is_collection','is_confirm_share','project','tags','is_promote','estimate_release_at','publish_at','comfirm_time','total_song_count','online_song_count','public_audio_count','arranger'])
activity = activity_ser.data
#活动配置信息
config_ids = list(models.SystemConfig.objects.filter(identifier__in=['activity_lang', 'activity_speed', 'activity_sex','activity_mark']).values_list('id',flat=True).all())
configs = models.SystemConfig.objects.filter(parent_id__in=config_ids).values_list('identifier','name','content')
lang = activity['lang'] if activity['lang'] else []
langs = []
for config in configs:
if config[0] == activity['sex']:
activity['sex'] = config[1] if activity['sex'] else None
if config[0] == activity['mark']:
activity['mark'] = config[2] if activity['mark'] else None
if config[0] == activity['speed']:
activity['speed'] = config[1] if activity['speed'] else None
if config[0] in lang:
langs.append(config[1])
activity['lang'] = langs
ser = serializers.ActivityMaterialsSerializer(models.ActivityMaterials.objects.filter(activity_id=activity_id,deleted_at=None),many=True)
data = {'activity':activity,'materials':ser.data}
# 积分
user_point_record(user_id=user_id, type='Listen',activity_id=activity_id)
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def ActivityMaterials(request):
if request.method == 'GET':
activity_id = request.GET['activity_id']
user_id = get_user_info(request)['id']
queryset = models.Activitys.objects.filter(id=activity_id).first()
activity_ser = serializers.ActivityDetailSerializer(queryset, many=False, context={"user_id": user_id,"project_many":False},
fields=['id','song_name','lyric','sex','mark','speed','lang','guide','guide_duration','guide_clip','guide_clip_duration','karaoke','karaoke_clip','clip_lyric','cover','status','project_id','is_collection','is_confirm_share','project','tags','is_promote','estimate_release_at','publish_at','guide_duration','guide_clip_duration','comfirm_time','total_song_count','online_song_count','public_audio_count','arranger'])
activity = activity_ser.data
# 活动配置信息
config_ids = list(models.SystemConfig.objects.filter(
identifier__in=['activity_lang', 'activity_speed', 'activity_sex', 'activity_mark']).values_list('id',
flat=True).all())
configs = models.SystemConfig.objects.filter(parent_id__in=config_ids).values_list('identifier', 'name',
'content')
lang = activity['lang'] if activity['lang'] else []
langs = []
for config in configs:
if config[0] == activity['sex']:
activity['sex'] = config[1] if activity['sex'] else None
if config[0] == activity['mark']:
activity['mark'] = config[2] if activity['mark'] else None
if config[0] == activity['speed']:
activity['speed'] = config[1] if activity['speed'] else None
if config[0] in lang:
langs.append(config[1])
activity['lang'] = langs
data = {'activity':activity}
# 积分
user_point_record(user_id=user_id, type='Listen',activity_id=activity_id)
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def SendEmail(request,user):
activity_id = request.GET['activity_id']
activity = models.Activitys.objects.filter(id=activity_id).first()
subject = '【海星试唱】-' + activity.song_name + '-试唱物料资源'
message = '{},您好:\n' \
'\n 【海星试唱】-{}-物料资源如下,包含导唱(含人声)、伴奏(不含人声)、歌词内容。请复制下方链接内容在浏览器打开进行下载。\n' \
'\n导唱(含人声):{}' \
'\n' \
'\n伴奏(不含人声):{}' \
'\n' \
'\n《歌词》:\n' \
'{}' \
'\n' \
'\n 1.本邮件含有保密信息,仅限于收件人所用。禁止任何人未经发件人许可以任何形式(包括但不限于部分地泄露、复制或散发)不当地使用本邮件中的信息。如果您错收了本邮件,请您立即电话或邮件通知发件人并删除本邮件。' \
'\n 2.本公司员工存在受贿、索贿、贪污、盗窃、挪用资金等行为,请将相关证据以邮件形式发送至公司反腐败举报邮箱:service@hikoon.com' \
'\n' \
'\n' \
'对于您通过本邮件所获取的试唱资料(包括但不限于歌词、伴奏、音频等)及/或您录制的试唱音视频,您仅能用于个人试唱录制使用,并仅能上传至海星试唱平台,未经海星试唱平台书面同意,您不得泄露给任何第三方或发布在任何其他平台,试唱资料及您使用试唱资料制作的全部音乐作品/录音录像制品/视听作品的完整著作权和邻接权均归属于北京海葵科技有限公司(以下简称“海葵”)或其指定的第三方,您不得抄袭、模仿或提前泄露在短视频或音乐平台,也不可在未取得海葵书面许可的情况下翻唱、二次创作。如因您未按规定使用试唱资料及/或您录制的试唱音视频,海葵或其指定的第三方有权要求您赔偿因此造成的一切直接损失、间接损失(包括但不限于词曲成本、软件运营成本、海葵支付的差旅费、律师费、公证费、诉讼/仲裁费、保全费、鉴定费等)。' \
.format(user['nick_name'], activity.song_name, activity.expand['guide_source']['url'],activity.expand['karaoke_source']['url'],
activity.lyric)
send_mail(
subject=subject,
message=message,
from_email=settings.EMAIL_HOST_USER,
recipient_list=[user['email'], settings.EMAIL_HOST_USER] # 接收者的邮箱账号
)
@AuthPermissionRequired()
def SendMaterials(request):
if request.method != 'GET':
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
user = get_user_info(request)
if not user['email']:
return JsonResponse(ResponseFactory(code=201, message="请先绑定邮箱", data=None, status='success'))
t = threading.Thread(target=SendEmail,
args=[request,user])
t.setDaemon(True)
t.start()
return JsonResponse(ResponseFactory(code=200, message="发送中,请稍等片刻...", data=None, status='success'))
def SplitAudio(request):
"""
音频文件拆分
"""
post_data = json.loads(request.body)
obj = verification.SplitAudio(data=post_data)
loggin.logger.info('拆分参数:{}'.format(post_data))
if not obj.is_valid():
return JsonResponse({"code":"400", "message":verification.error_message(obj), "data":None, "status":"fail"})
id = obj.data['activity_id']
status = obj.data['status']
data = str({"id":id,"status":status,"time":timezone.now().strftime("%Y-%m-%d %H:%M:%S")})
con.lpush('split_audio_queue',data)
return JsonResponse({"code":"200", "message":"已添加到拆分队列中", "data":None, "status":":success"})
@AuthPermissionRequired()
def AotoSubmit(request):
"""
自主提交
"""
if request.method == "POST":
user = get_user_info(request)
#检查是否有提交权限
permission = user_permission(user['id'])
if 2 not in permission:
return JsonResponse(ResponseFactory(code=400, message='用户无此权限', data=None, status='fail'))
post_data = json.loads(request.body)
obj = verification.aoto_submit(post_data)
is_hide = post_data.get('is_hide', 1)
if obj.is_valid():
data = obj.clean()
type = data['type']
# 校验自主报价参数
self_price = post_data.get('self_price', None)
if self_price:
ver = verification.SubmitPriceVerification(data=self_price)
if not ver.is_valid():
return JsonResponse(
ResponseFactory(code=400, message=verification.error_message(ver), data=None, status='fail'))
if self_price['value']['amounts']:
if not (0 <= self_price['value']['amounts'] <= 9999999): return JsonResponse(
ResponseFactory(code=201, message="金额在0-9999999之间", data=None, status='fail'))
if self_price['value']['ratio']:
if not (0 <= self_price['value']['ratio'] <= 100): return JsonResponse(
ResponseFactory(code=201, message="分成比列在0%-100%之间", data=None, status='fail'))
#判断活动状态
activity_status = models.Activitys.objects.filter(id = data['activity_id']).first().status
if activity_status != 1:
return JsonResponse(ResponseFactory(code=201, message="活动已结束", data=None, status='fail'))
#获取小程序openid
try:
vx_code = post_data.get("vx_code","")
open_id, unionid = WeChatApi(vx_code)
except:
open_id = ''
# 获取上次提交版本信息
obj = models.ActivityHasUsers.objects.filter(user_id=user['id'], activity_id=data['activity_id'],deleted_at=None).last()
if obj:
version = obj.version
if version:
version += 1
else:
version = 1
else:
version = 1
try:
demo_data = get_oss_file(data['url'])
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="音频地址获取不到资源,检查链接", data=None, status='fail'))
# #保存demo文件获取时长
demo_path = "./api/static/demo-{}.mp3".format(str(random.randint(0, 10000000000)))
with open(demo_path, "wb") as f:
f.write(demo_data)
f.close()
duration = librosa.get_duration(filename=demo_path)
# 删除零时文件
os.remove(demo_path)
try:
with transaction.atomic():
if type == 'Submit':
models.ActivityHasUsers.objects.filter(user_id=user['id'],activity_id=data['activity_id']).update(type="Save",updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
ahu = models.ActivityHasUsers.objects.create(
activity_id = data['activity_id'],
user_id = user['id'],
demo_url = data['url'],
durations=duration,
wav_url = post_data.get("wav_url",""),
wav_durations=post_data.get("wav_durations", 0),
status = 0,
syn_status = 1,
type = type,
open_id = open_id,
is_hide = is_hide,
mode = 1,
version = version,
submit_at= timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
created_at = timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
# 存入自主报价
if self_price:
models.ActivityUserHasPrices.objects.update_or_create(
user_id=user['id'],activity_id=data['activity_id'],
defaults={
"value": self_price['value'],
"is_deduct": self_price['is_deduct'],
"is_talk": self_price['is_talk'],
"address_id": self_price['address_id'],
"is_accept_address": self_price['is_accept_address'],
"created_at": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
"updated_at": timezone.now().strftime("%Y-%m-%d %H:%M:%S"), },
)
#更新到动态
is_tidings = post_data.get("is_tidings", 0)
if is_tidings == 1:
models.UserHasTidings.objects.create(user_id=user['id'],activity_id=data['activity_id'],type=2,url=data['url'], created_at = timezone.now().strftime("%Y-%m-%d %H:%M:%S"),updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
# 提交作品计数 1.先检查用户对该作品之前是否有提交且未读的消息
user_msg = models.UserMessages.objects.filter(is_read=0, sender_id=user['id'],activity_id=data['activity_id'], deleted_at=None, type=3)
if user_msg:
user_msg.update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
# 获取全体管理员和推荐人和项目管理员open_id
project_id = models.Activitys.objects.filter(id=data['activity_id']).first().project_id
project = models.Projects.objects.filter(id=project_id).first()
project_user_ids = []
if project:
if project.is_public:project_user_ids = list(models.UserHasProjects.objects.filter(project_id=project_id).values_list('user_id',flat=True))
else:project_user_ids = [models.Activitys.objects.filter(id=data['activity_id']).first().user_id]
project_user_unionid = list(models.Users.objects.filter(id__in=project_user_ids,deleted_at=None,status=1).values_list('unionid', flat=True))
admin_unionid = list(models.Users.objects.filter(scope=1,deleted_at=None,status=1).values_list('unionid', flat=True))
push_open_ids = list(models.WechatOfficialUsers.objects.filter(union_id__in=admin_unionid+project_user_unionid,is_subscribe=1).values_list('open_id', flat=True))
song_name = models.Activitys.objects.filter(id=data['activity_id']).first().song_name
# 再创建消息
business_id = user['business_id']
if business_id:
#获取推荐人公众号open_id
unionid = models.Users.objects.filter(id=business_id).values_list('unionid', flat=True)
wechat_official = models.WechatOfficialUsers.objects.filter(union_id__in=unionid,is_subscribe=1).last()
if wechat_official:
# 公众号推送
p_data = {'channel': 'singer_related', 'open_id': [wechat_official.open_id],
'data': {"title": "您的歌手参加了试唱歌曲", "name": user['nick_name']+"("+user['real_name']+")",
"intro": "参加了试唱歌曲《{}》".format(song_name),
"remark": "点击前往 >",
"page": "/packageMy/pages/like?tab=2"}}
pushSubscribeMessage(p_data)
#发给绑定的推荐人
m_data = {'sender_id': user['id'], 'receivers': [business_id], 'activity_id': data['activity_id'],'type': 3,'is_bind':1}
createMessage(m_data)
# 极光推送-提交作品推荐人
j_title = "您的歌手参加了试唱"
j_content = "您的歌手{}参加了试唱活动《{}》".format(user['nick_name'], song_name)
jdata = {"title": j_title, "content": j_content, "content_type": "text",
"receiver_value": [business_id],
"extras": {"type": "ToTaSing", "value": ""}}
JPush().jpush_v3(jdata)
#给全体管理员和项目管理员推服务号消息
p_data = {'channel': 'activity_join', 'open_id': push_open_ids,
'data': {"first":"{}({})提交了试唱作品".format(user['nick_name'],user['real_name']),"keyword1": "《"+song_name+"》", "keyword2": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
"remark": "点击试听 >","page":"/pages/index/index"}
}
pushSubscribeMessage(p_data)
#外部管理员id
activity_manage_ids = list(models.UserManageActivitie.objects.filter(activity_id=data['activity_id']).values_list('user_id',flat=True))
# 发送系统消息(平台管理员+项目管理员+外部管理员)
receivers = list(models.Users.objects.filter(scope=1).values_list('id', flat=True))
receivers = list(set(receivers+project_user_ids+activity_manage_ids))
m_data = {'sender_id': user['id'], 'receivers': receivers,'activity_id': data['activity_id'], 'type': 3,'is_bind':0}
createMessage(m_data)
# 极光推送-提交作品全体管理员
j_title = "有新用户提交试唱"
j_content = "{}参与了试唱《{}》".format(user['nick_name'],song_name)
jdata = {"title": j_title, "content": j_content, "content_type": "text",
"receiver_value": receivers,
"extras": {"type": "ToPlatfromSing", "value": ""}}
JPush().jpush_v3(jdata)
# 歌手积分
user_point_record(user_id=user['id'], type='AutoSubmit', activity_id=data['activity_id'])
# 推荐人积分
if user['business_id']:
user_point_record(user_id=user['business_id'], type='SingerAutoSubmit',
activity_id=data['activity_id'], singer_id=user['id'])
data = {'id': ahu.id, 'activity_id': ahu.activity_id, 'demo_url': ahu.demo_url}
return JsonResponse(ResponseFactory(code=200, message="提交成功", data=data, status='success'))
else:
ahu = models.ActivityHasUsers.objects.create(
activity_id=data['activity_id'],
user_id=user['id'],
demo_url=data['url'],
durations=duration,
wav_url=post_data.get("wav_url", ""),
wav_durations=post_data.get("wav_durations", 0),
status=0,
syn_status=1,
type=type,
open_id=open_id,
is_hide=is_hide,
mode=1,
version=version,
submit_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
data = {'id': ahu.id, 'activity_id': ahu.activity_id, 'demo_url': ahu.demo_url}
return JsonResponse(ResponseFactory(code=200, message="保存成功", data=data, status='success'))
except Exception as e:
logger.info('提交异常:用户ID:{},参数:{},错误信息:{}'.format(user['id'], request.body, e))
return JsonResponse(ResponseFactory(code=201, message="提交失败:{}".format(e), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def toFileData(file_name,file_type):
path = './api/static/'
t = str(int(time.time())) + str(random.randint(0, 10000000000))
file_path = path + t + "." + file_type
os.system("ffmpeg -i "+ path+file_name+ " " + file_path)
with open(file_path, 'rb') as f:
fileData = f.read()
f.close()
#删除零时文件
os.remove(file_path)
return fileData
# @AuthPermissionRequired()
def UploadAudio(request):
if request.method == "POST":
fileData = request.FILES.get('file')
if not fileData:
return JsonResponse(ResponseFactory(code=400, message="未读取到上传文件", data=None, status='fail'))
file_type = fileData.name.split('.')[1]
if file_type == 'mp3':
file_url = auto_upload_audio(fileData.read(),'mp3')
else:
path = './api/static/'
t = str(int(time.time())) + str(random.randint(0, 10000000000))
filename = t + "." + file_type
with open(path + filename, "wb") as f:
f.write(fileData.read())
f.close()
fileData = toFileData(filename,'mp3')
file_url = auto_upload_audio(fileData,'mp3')
os.remove(path + filename)
data = {"type": "mp3", "name": "", "url": file_url, "size": "", "disk": "oss", "created_at": "", "id": 0}
return JsonResponse(ResponseFactory(code=200, message="上传成功", data=data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
class Collection(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
status = request.GET.get('status','all') #默认所有
text = request.GET.get('text') #默认所有
user_id = get_user_info(request)['id']
ids = list(models.UserActivityCollections.objects.filter(user_id=user_id,deleted_at=None).order_by('-created_at').values_list('activity_id',flat=True))
idList = ",".join('%s' % id for id in ids)
kwargs = {"deleted_at":None,"id__in":ids}
if status == 'active':kwargs['status'] = 1
if text:kwargs['song_name__icontains'] = text
queryset = models.Activitys.objects.filter(**kwargs).extra(select={'m': 'FIELD(id,{})'.format(idList)}, order_by=['m'])
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
activitys = serializers.CollectionActivitysSerializer(page_data, many=True, context={"user_id": user_id}).data
# 活动配置信息
config_ids = list(models.SystemConfig.objects.filter(
identifier__in=['activity_lang', 'activity_speed', 'activity_sex', 'activity_mark']).values_list('id',
flat=True).all())
configs = models.SystemConfig.objects.filter(parent_id__in=config_ids).values_list('identifier', 'name',
'content')
for activity in activitys:
lang = activity['lang'] if activity['lang'] else []
langs = []
for config in configs:
if config[0] == activity['sex']:
activity['sex'] = config[1] if activity['sex'] else None
if config[0] == activity['mark']:
activity['mark'] = config[2] if activity['mark'] else None
if config[0] == activity['speed']:
activity['speed'] = config[1] if activity['speed'] else None
if config[0] in lang:
langs.append(config[1])
activity['lang'] = langs
data = {"activitys": activitys, "count": len(queryset)}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
@method_decorator(AuthPermissionRequired())
def post(self,request):
obj = verification.collection(json.loads(request.body))
if obj.is_valid():
data = json.loads(request.body)
user = get_user_info(request)
is_active = models.UserActivityCollections.objects.filter(user_id=user['id'],activity_id=data['activity_id'], deleted_at=None)
if is_active:
return JsonResponse(ResponseFactory(code=400, message='请勿重复收藏', data=None, status='fail'))
try:
with transaction.atomic():
models.UserActivityCollections.objects.create(
user_id=user['id'],
activity_id=data['activity_id'],
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
# 消息计数
business_id = user['business_id']
role = user['role']
#有商务且为歌手
if business_id and role=='Singer':
m_data = {'receivers': [business_id], 'sender_id': user['id'],'activity_id':data['activity_id'], 'type': 2,'is_bind':1}
createMessage(m_data)
# 推送消息给推荐人
business_unionid = models.Users.objects.filter(id=business_id).first().unionid
business_wechat_official = models.WechatOfficialUsers.objects.filter(union_id=business_unionid,is_subscribe=1).last()
song_name = models.Activitys.objects.filter(id=data['activity_id']).first().song_name
if business_wechat_official:
business_open_id = business_wechat_official.open_id
name = user['nick_name'] + "({})".format(user['real_name'])
p_data = {'channel': 'singer_related', 'open_id': [business_open_id],
'data': {"title": "您的歌手收藏了试唱活动", "name": name, "intro": "收藏了试唱活动《{}》".format(song_name),
"remark": "点击前往 >",
"page": "packageMy/pages/like?tab=1"}}
pushSubscribeMessage(p_data)
# 极光推送-歌手收藏
j_title = "您的歌手收藏了试唱"
j_content = "您的歌手{}收藏了试唱活动《{}》".format( user['nick_name'],song_name)
jdata = {"title": j_title, "content": j_content, "content_type": "text",
"receiver_value": [business_id],
"extras": {"type": "ToTaCollection", "value": ""}}
JPush().jpush_v3(jdata)
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="收藏失败。请联系管理员", data=None, status='fail'))
return JsonResponse(ResponseFactory(code=200, message="收藏成功", data=None, status='success'))
else:
return JsonResponse(
ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
@method_decorator(AuthPermissionRequired())
def delete(self,request):
obj = verification.collection(json.loads(request.body))
if obj.is_valid():
data = json.loads(request.body)
user = get_user_info(request)
is_active = models.UserActivityCollections.objects.filter( user_id=user['id'],activity_id=data['activity_id'],deleted_at=None)
if is_active:
try:
with transaction.atomic():
is_active.update(updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),deleted_at = timezone.now().strftime("%Y-%m-%d %H:%M:%S") )
#取消收藏取消计数
m_data = {"sender_id":user['id'],"activity_id":data['activity_id'],"type":2}
deleteMessage(m_data)
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="取消失败。请联系管理员", data=None, status='fail'))
return JsonResponse(ResponseFactory(code=200, message="已取消收藏", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message='未收藏不能取消', data=None, status='fail'))
else:
return JsonResponse(
ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
def cancelcollection(request):
if request.method == "POST":
obj = verification.collection(json.loads(request.body))
if obj.is_valid():
data = json.loads(request.body)
user = get_user_info(request)
is_active = models.UserActivityCollections.objects.filter(user_id=user['id'],activity_id=data['activity_id'], deleted_at=None)
if is_active:
try:
with transaction.atomic():
is_active.update(updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
# 取消收藏取消计数
m_data = {"sender_id": user['id'], "activity_id": data['activity_id'], "type": 2}
deleteMessage(m_data)
except:
return JsonResponse(ResponseFactory(code=201, message="取消失败。请联系管理员", data=None, status='fail'))
return JsonResponse(ResponseFactory(code=200, message="已取消收藏", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message='未收藏不能取消', data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
class ShareUsersList(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
text = request.GET.get('text','')
if text:
user_id = get_user_info(request)['id']
queryset = models.Users.objects.filter(Q(nick_name__icontains=text) | Q(real_name__icontains=text),~Q(id=user_id),audit_status=1,status=1,deleted_at=None)
else:
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=[], status='success'))
users = serializers.BusinessSerializer(queryset,many=True).data
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=users, status='success'))
class ShareUsers(APIView):
@method_decorator(AuthPermissionRequired())
def post(self,request):
try:
post_data = json.loads(request.body)
except:
return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.ShareUsersVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
user_id = get_user_info(request)['id']
activity_id = obj.data.get('activity_id')
share_id = obj.data.get('share_id')
models.ActivityShareUsers.objects.update_or_create(
activity_id=activity_id, user_id=user_id,
defaults={'share_id': share_id,'created_at':timezone.now().strftime("%Y-%m-%d %H:%M:%S"),'updated_at':timezone.now().strftime("%Y-%m-%d %H:%M:%S")},
)
return JsonResponse(ResponseFactory(code=200, message="保存成功", data=None, status='success'))
def test(request):
if request.method == "POST":
fileData = json.loads(request.body).get('file')
print (type(fileData),fileData)
import numpy as np
data = np.array(fileData.get('data'))
data.tofile('./ttt.mp3')
return JsonResponse(ResponseFactory(code=200, message="上传成功", data=fileData, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
import json
from django.http import JsonResponse
from api import models
from api import serializers
from rest_framework.views import APIView
from api import verification
from django.db import transaction
from django.utils import timezone
from django.utils.decorators import method_decorator
from api.views import ResponseFactory,PageNumberPagination,createMessage,pushSubscribeMessage,JPush,get_user_info,AuthPermissionRequired,senstive_word_check
from ratelimit.decorators import ratelimit
from django.db.models import Q
from api import loggin
class Tidings(APIView):
@method_decorator(AuthPermissionRequired())
# @method_decorator(rate_limit())
@method_decorator(ratelimit(key='ip',rate='1/1s', block=True))
def post(self,request):
"""发布动态"""
post_data = json.loads(request.body)
obj = verification.TidingsVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
title = obj.data.get('title')
activity_ids = obj.data.get('activity_ids')
singer_ids = obj.data.get('singer_ids')
sounds = obj.data.get('sounds')
photos = obj.data.get('photos')
type= obj.data.get('type')
#获取用户信息
user = get_user_info(request)
user_id = user['id']
role = user['role']
#活动动态除歌手以外都能发
if type == 4 and role == 'Singer':
return JsonResponse(ResponseFactory(code=400, message='歌手不能发布活动动态', data=None, status='fail'))
if title==activity_ids==singer_ids==sounds==photos==None:
return JsonResponse(ResponseFactory(code=400, message='发布内容不能为空', data=None, status='fail'))
#创建动态
try:
with transaction.atomic():
#创建动态
tidings=models.UserHasTidings.objects.create(
title=title,
user_id=user_id,
type =type,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
#补充关联数据-推荐活动
items_list = [singer_ids,activity_ids,sounds,photos]
save_list = []
for items in items_list:
if items:
for value in items:
saveobj = models.TidingsHasContents(
tidings_id = tidings.id,
type = items_list.index(items)+1,
value = value,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
save_list.append(saveobj)
models.TidingsHasContents.objects.bulk_create(save_list)
except Exception as e:
return JsonResponse(ResponseFactory(code=400, message='发布动态失败:{}'.format(e), data=None, status='fail'))
return JsonResponse(ResponseFactory(code=200, message="发布成功", data=None, status='success'))
class TidingsList(APIView):
def get(self, request):
kwargs = dict()
type = int(request.GET.get('type',3))
try:
user = get_user_info(request)
user_id = user['id']
scope = user['scope']
except:
user_id = 0
scope = 0
#去掉不感兴趣的
tidings_ids = list(models.UserUnlikeTidings.objects.filter(user_id=user_id).values_list('tidings_id',flat=True))
orderbyList = ['-is_top','-created_at']
kwargs['deleted_at'] = None
#用户没删除且状态为启用中
kwargs['user__deleted_at'] = None
kwargs['user__status'] = 1
if scope != 1:
kwargs['status'] = 0
if type == 4:
kwargs['type'] = 4
queryset = models.UserHasTidings.objects.filter(~Q(id__in=tidings_ids),**kwargs).order_by(*orderbyList)
else:
queryset = models.UserHasTidings.objects.filter(~Q(type=4),~Q(type=2),~Q(id__in=tidings_ids),**kwargs).order_by(*orderbyList)
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.CommunityTidingsSerializer(page_data, many=True, context={"user_id": user_id})
data = {"data": ser_obj.data, "count": queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class TidingsLimiting(APIView):
@method_decorator(AuthPermissionRequired())
def put(self,request):
scope = get_user_info(request)['scope']
if scope != 1:
return JsonResponse(ResponseFactory(code=400, message="你不是管理员,无此权限", data=None, status='fail'))
try:post_data = json.loads(request.body)
except: return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.TidingsLimitVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
tidings_id = obj.data.get('tidings_id')
status = obj.data.get('status')
#限流或者解除限流
models.UserHasTidings.objects.filter(id=tidings_id).update(status=status)
message = "已解除限流" if status == 0 else "已限流"
#创建消息内容组装
user = get_user_info(request)
user_id = user['id']
tidings = models.UserHasTidings.objects.filter(id=tidings_id).first()
auther = models.Users.objects.filter(id=tidings.user_id).first()
title = "您发布的动态已被解除限流" if status == 0 else "您的发布动态被限制查看.如有疑问请联系微信LZX19960101"
send_type = 9 if status == 0 else 8
if tidings.type == 2:
activity = models.Activitys.objects.filter(id=tidings.activity_id).first()
content = "《{}》{}".format(activity.song_name, auther.nick_name)
elif tidings.type in [3,4] :
tidings_has_content = serializers.SystemMsgTidingsSerializer(tidings, many=False).data
content = "{}".format(tidings.title)
for recommend_activity in tidings_has_content['recommend_activitys']:
content = content + "[试唱活动《{}》]".format(recommend_activity['song_name'])
for recommend_singer in tidings_has_content['recommend_singers']:
content = content + "[{}的名片]".format(recommend_singer['nick_name'])
if tidings_has_content['photos']:
content = content + "[图片]"
if tidings_has_content['sounds']:
content = content + "[音频]"
# 极光推送
j_title = "您发布的动态被平台解除限流" if status == 0 else "您发布的动态被平台限流"
jdata = {"title": j_title, "content": content, "content_type": "text",
"receiver_value": [tidings.user_id],
"extras": {"type": "ToSystemMsg", "value": ""}}
JPush().jpush_v3(jdata)
#服务号推送
wechat_data = models.WechatOfficialUsers.objects.filter(union_id=auther.unionid).first()
if wechat_data:
p_data = {'channel': 'square_result', 'open_id': [wechat_data.open_id],
'data': {"first": j_title, "keyword1": content,
"keyword2": str(tidings.created_at), 'keyword3': auther.nick_name}
}
pushSubscribeMessage(p_data)
#创建消息
m_data = {"title": title, "content": content, 'receivers': [tidings.user_id], "activity_id": tidings_id,
'sender_id': user_id, 'type': send_type}
createMessage(m_data)
return JsonResponse(ResponseFactory(code=200, message=message, data=None, status='success'))
class TidingsReport(APIView):
@method_decorator(AuthPermissionRequired())
def post(self,request):
try:post_data = json.loads(request.body)
except: return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.TidingsReportVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
user = get_user_info(request)
user_id = user['id']
if user['audit_status'] in [0, 2]:
return JsonResponse(ResponseFactory(code=400, message="请等待账号审核通过后再操作", data=None, status='fail'))
tidings_id = obj.data.get('tidings_id',0)
comment_id = post_data.get('comment_id', 0)
person_id = post_data.get('person_id', 0)
reason = obj.data.get('reason')
type = post_data.get('type',1)
desc = post_data.get('desc',None)
if tidings_id:
is_exists = models.TidingsHasReports.objects.filter(tidings_id=tidings_id,user_id=user_id,type=type,status=0).exists()
if is_exists:
return JsonResponse(ResponseFactory(code=400, message="已举报,请勿重复操作", data=None, status='fail'))
if person_id:
is_exists = models.TidingsHasReports.objects.filter(person_id=person_id,user_id=user_id,status=0).exists()
if is_exists:
return JsonResponse(ResponseFactory(code=400, message="平台已接收到您提交的举报信息,正在处理中 ~", data=None, status='fail'))
models.TidingsHasReports.objects.create(
tidings_id=tidings_id,
comment_id = comment_id,
reason=reason,
user_id=user_id,
person_id = person_id,
desc = desc,
type = type,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
return JsonResponse(ResponseFactory(code=200, message="举报成功", data=None, status='success'))
class RecordUser(APIView):
@method_decorator(AuthPermissionRequired())
def post(self,request):
try:post_data = json.loads(request.body)
except:return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.TidingsRecordUserVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
tidings_ids = obj.data.get('tidings_id')
user_id = get_user_info(request)['id']
save_list = []
for tidings_id in tidings_ids:
is_exists = models.UserViewTidings.objects.filter(tidings_id=tidings_id, user_id=user_id).exists()
if not is_exists:
save_data = models.UserViewTidings(
tidings_id=tidings_id,
user_id=user_id,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
save_list.append(save_data)
models.UserViewTidings.objects.bulk_create(save_list)
return JsonResponse(ResponseFactory(code=200, message="记录成功", data=None, status='success'))
class TidingsInteracts(APIView):
@method_decorator(AuthPermissionRequired())
@method_decorator(ratelimit(key='ip',rate='1/1s', block=True))
# @method_decorator(rate_limit())
def post(self,request):
"""互动"""
try:post_data = json.loads(request.body)
except:return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.TidingsInteractsVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
type_id = obj.data.get('type_id')
type = obj.data.get('type')
status= obj.data.get('status')
user = get_user_info(request)
if user['audit_status'] in [0,2]:
return JsonResponse(ResponseFactory(code=400, message="请等待账号审核通过后再操作", data=None, status='fail'))
user_id = user['id']
is_exists = models.TidingsHasInteracts.objects.filter(type_id=type_id, type=type,user_id=user_id,status=status,deleted_at=None).exists()
if is_exists:
return JsonResponse(ResponseFactory(code=400, message="重复数据", data=None, status='fail'))
#创建消息内容组装
if type == 1:
tidings = models.UserHasTidings.objects.filter(id=type_id).first()
auther = models.Users.objects.filter(id=tidings.user_id).first()
tidings_has_content = serializers.SystemMsgTidingsSerializer(tidings, many=False).data
receivers = tidings.user_id
if tidings.type == 2:
activity = models.Activitys.objects.filter(id=tidings.activity_id).first()
if status == 1:
send_type = 6
title = "{}觉得好听".format(user["nick_name"])
else:
send_type = 7
title = "{}觉得很开心".format(user["nick_name"])
content = "《{}》{}".format(activity.song_name, auther.nick_name)
elif tidings.type == 3:
title = "{}觉得很赞".format(user["nick_name"])
send_type = 5
content = "{}".format(tidings.title)
for recommend_activity in tidings_has_content['recommend_activitys']:
content = content + "[试唱活动《{}》]".format(recommend_activity['song_name'])
for recommend_singer in tidings_has_content['recommend_singers']:
content = content + "[{}的名片]".format(recommend_singer['nick_name'])
if tidings_has_content['photos']:
content = content + "[图片]"
if tidings_has_content['sounds']:
content = content + "[音频]"
# 生成消息通知
m_data = {"title": title, "content": content, 'receivers': [receivers], "activity_id": type_id,
'sender_id': user_id, 'type': send_type}
createMessage(m_data)
if type == 3:
auther = models.Users.objects.filter(id=type_id).first()
if not auther.sound:
return JsonResponse(ResponseFactory(code=400, message="用户还未上传声音", data=None, status='fail'))
receivers = auther.id
title = "{}觉得你的声音很赞".format(user["nick_name"])
send_type = 4
content = "[{}的声音]".format(auther.nick_name)
# 生成消息通知
m_data = {"title": title, "content": content, 'receivers': [receivers], "activity_id": type_id,
'sender_id': user_id, 'type': send_type}
createMessage(m_data)
#极光推送
# j_title = "有人回复了您的动态"
# jdata = {"title": j_title, "content": content, "content_type": "text",
# "receiver_value": [tidings.user_id],
# "extras": {"type": "ToSystemMsg", "value": ""}}
# JPush().jpush_v3(jdata)
# #服务号推送
# wechat_data = models.WechatOfficialUsers.objects.filter(union_id = auther.unionid).first()
# if wechat_data:
# p_data = {'channel': 'square_result', 'open_id': [wechat_data.open_id],
# 'data': {"first": j_title, "keyword1":content ,
# "keyword2": str(tidings.created_at),'keyword3':auther.nick_name}
# }
# pushSubscribeMessage(p_data)
models.TidingsHasInteracts.objects.create(
type_id=type_id,
type=type,
user_id=user_id,
status=status,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
return JsonResponse(ResponseFactory(code=200, message="记录成功", data=None, status='success'))
@method_decorator(AuthPermissionRequired())
def put(self,request):
"""取消互动"""
try:
post_data = json.loads(request.body)
except:
return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.InteractsDeleteVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
type_id = obj.data.get('type_id')
type = obj.data.get('type')
status = obj.data.get('status')
user = get_user_info(request)
user_id = user['id']
is_exists = models.TidingsHasInteracts.objects.filter(type_id=type_id, type=type, user_id=user_id,status=status, deleted_at=None)
if not is_exists:
return JsonResponse(ResponseFactory(code=400, message="不存在的数据", data=None, status='fail'))
#删除操作
is_exists.update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
return JsonResponse(ResponseFactory(code=200, message="取消成功", data=None, status='success'))
class SeleteActivity(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
text = request.GET.get('text', '')
orderbyList = ['-weight', '-created_at']
if text:
queryset = models.Activitys.objects.filter(status=1,song_name__icontains=text,audit_status=1,deleted_at=None).order_by(*orderbyList)
else:
queryset = models.Activitys.objects.filter(status=1,audit_status=1,deleted_at=None).order_by(*orderbyList)
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.TidingsSeleteActivitySerializer(page_data, many=True)
data = {"activitys": ser_obj.data, "count": queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class TidingsShow(APIView):
def get(self,request):
id = request.GET.get('id')
try:user_id = get_user_info(request)['id']
except:user_id=0
tidings = models.UserHasTidings.objects.filter(id=id,deleted_at=None).first()
if not tidings:
return JsonResponse(ResponseFactory(code=200, message="内容已被删除", data=None, status='fail'))
data = serializers.CommunityTidingsSerializer(tidings,many=False,context={'user_id':user_id}).data
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class TidingsChat(APIView):
@method_decorator(AuthPermissionRequired())
def post(self,request):
"""
记录动态私聊用户
:param request:
:return:
"""
try:
post_data = json.loads(request.body)
except:
return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.TidingsChatVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(
ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
tidings_id = obj.data.get('tidings_id')
user_id = get_user_info(request)['id']
models.TidingsHasChat.objects.update_or_create(
user_id=user_id, tidings_id=tidings_id,
defaults={
"created_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
"updated_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S")},
)
return JsonResponse(ResponseFactory(code=200, message="记录成功", data=None, status='success'))
class ChatRelation(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
receiver_id = request.GET.get('id')
sender = get_user_info(request)
query = models.Users.objects.filter(id=receiver_id)
data = serializers.ChatRelationSerializer(query, many=False, context={"sender": sender,"receiver_id":receiver_id}).data
return JsonResponse(ResponseFactory(code=200, message="查询成功", data=data, status='success'))
class ChatAgent(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
receiver_id = request.GET.get('id')
receiver = models.Users.objects.filter(id=receiver_id).first()
send_id = get_user_info(request)['id']
if receiver:
data = serializers.ChatAgentSerializer(receiver,many=False,context={"send_id":send_id}).data
return JsonResponse(ResponseFactory(code=200, message="查询成功", data=data, status='success'))
else:return JsonResponse(ResponseFactory(code=400, message="不存在的用户", data=None, status='fail'))
class ChatAgentRecord(APIView):
@method_decorator(AuthPermissionRequired())
def post(self,request):
"""
记录代理私聊信息
:param request:
:return:
"""
try:post_data = json.loads(request.body)
except:return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.ChatAgentRecordVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
send_id = get_user_info(request)['id']
user_id = obj.data.get('user_id')
business_id = models.Users.objects.filter(id=user_id).first().business_id
models.UserChatAgentRecords.objects.update_or_create(
user_id=user_id, send_id=send_id,business_id=business_id,
defaults={
"created_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
"updated_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S")},
)
return JsonResponse(ResponseFactory(code=200, message="记录成功", data=None, status='success'))
class Unlike(APIView):
@method_decorator(AuthPermissionRequired())
def post(self,request):
"""用户不感兴趣动态"""
try:post_data = json.loads(request.body)
except:return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.UnlikeTidingsVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
tidings_id = obj.data.get('tidings_id')
user_id = get_user_info(request)['id']
models.UserUnlikeTidings.objects.update_or_create(
user_id=user_id, tidings_id=tidings_id,
defaults={
"created_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
"updated_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S")},
)
return JsonResponse(ResponseFactory(code=200, message="记录成功", data=None, status='success'))
class TidingsComments(APIView):
def get(self,request):
"""
动态评论列表
:param request:
:return:
"""
id= request.GET.get('id')
orderbyList = ['-created_at']
queryset = models.TidingsHasComments.objects.filter(tidings_id=id,deleted_at=None).order_by(*orderbyList)
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.TidingsHasCommentsSerializer(page_data, many=True)
data = {"comments": ser_obj.data, "count": queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
@method_decorator(AuthPermissionRequired())
def post(self,request):
"""
发布评论
:param request:
:return:
"""
try:post_data = json.loads(request.body)
except:return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.PushTidingsCommentsVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
user = get_user_info(request)
user_id = user['id']
tidings_id = obj.data.get('tidings_id')
parent_id = int(post_data.get('parent_id',0))
content = obj.data.get('content')
is_senstive = senstive_word_check(content)
if is_senstive:
return JsonResponse(ResponseFactory(code=400, message='评论包含敏感词,请检查', data=None, status='fail'))
try:
with transaction.atomic():
if parent_id:
title = '{}回复了您的评论'.format(user['nick_name'])
receivers_id = models.TidingsHasComments.objects.filter(id=parent_id).first().user_id
data = {"title":title , "content": content, 'receivers': [receivers_id], "activity_id": tidings_id,'sender_id': user_id, 'type': 12}
else:
title = '{}评论您的动态'.format(user['nick_name'])
receivers_id = models.UserHasTidings.objects.filter(id=tidings_id).first().user_id
data = {"title": title, "content": content, 'receivers': [receivers_id], "activity_id": tidings_id,'sender_id': user_id, 'type': 13}
#自己给自己恢复不发系统消息
if user_id != receivers_id:
createMessage(data)
models.TidingsHasComments.objects.create(
user_id=user_id,
tidings_id=tidings_id,
parent_id = parent_id,
content = content,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at = timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
except Exception as e:
loggin.logger.info('评论失败:{}'.format(e))
return JsonResponse(ResponseFactory(code=400, message='失败,请联系管理员', data=None, status='fail'))
return JsonResponse(ResponseFactory(code=200, message="记录成功", data=None, status='success'))
@method_decorator(AuthPermissionRequired())
def put(self,request):
try:post_data = json.loads(request.body)
except:return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.DeleCommentsVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
user = get_user_info(request)
comment_id = obj.data.get('comment_id')
comment = models.TidingsHasComments.objects.filter(id=comment_id).first()
author_id = comment.user_id
if not (user['id'] == author_id or user['scope'] == 1):
return JsonResponse(ResponseFactory(code=400, message='无此权限', data=None, status='fail'))
try:
with transaction.atomic():
title = '您的评论被删除'
if user['id'] != author_id:
data = {"title": title, "content": comment.content, 'receivers': [author_id], "activity_id":comment.tidings_id ,'sender_id': user['id'], 'type': 14}
createMessage(data)
models.TidingsHasComments.objects.filter(id=comment_id).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
return JsonResponse(ResponseFactory(code=200, message="删除成功", data=None, status='success'))
except Exception as e:
return JsonResponse(ResponseFactory(code=400, message='失败,请联系管理员{}'.format(e), data=None, status='fail'))
import json
from django.http import JsonResponse
from api import models
from api.views import AuthPermissionRequired,get_user_info
from django.utils import timezone
from django.db import transaction
from api import serializers
from api.views import ResponseFactory,PageNumberPagination,GetWxToken,pushSubscribeMessage,WeChatApi,createMessage,user_point_record,JPush
from rest_framework.views import APIView
from django.utils.decorators import method_decorator
from api import verification
from api.loggin import logger
from django.shortcuts import render
from django.db.models import Q
from HisinApi import settings
import requests
def useragreement(request):
return render(request, 'user_agreement.html')
def appshare(request):
return render(request, 'appshare.html')
def songshare(request,id):
activity = models.Activitys.objects.filter(id=id).first()
data = {"song_name": activity.song_name,"cover":activity.cover,"clip_lyric":activity.clip_lyric,"guide_clip":activity.guide_clip}
return render(request,'share.html',{"data":json.dumps(data)})
def tidingsshare(request,id):
tidings = models.UserHasTidings.objects.filter(id=id).first()
data = {}
return render(request,'tidingsShare.html',{"data":json.dumps(data)})
def index(request):
return render(request, 'index.html')
@AuthPermissionRequired()
def user(request):
if request.method == 'GET':
#转发接口
url = "{domain}/app/auth".format(domain=settings.SERVICE_DOMAOIN)
headers = {
'Content-Type': 'application/json',
'Authorization': request.META.get('HTTP_AUTHORIZATION')
}
resp = requests.request("GET", url, headers=headers,verify=False)
return JsonResponse(ResponseFactory(code=resp.json()['code'], message=resp.json()['message'], data=resp.json()['data'],
status=resp.json()['status']))
#
# user = get_user_info(request)
# user_id = user['id']
# #获取正在进行的活动id
# activity_ids = list(models.Activitys.objects.filter(status=1,deleted_at=None).values_list('id',flat=True))
# # # 获取所有活动id
# all_activity_ids = list(models.Activitys.objects.filter(deleted_at=None).values_list('id', flat=True))
# userData = serializers.UsersSerializer(models.Users.objects.get(id=user_id),many=False,context={"activity_ids":activity_ids,"all_activity_ids":all_activity_ids}).data
# return JsonResponse(ResponseFactory(code=200, message="获取成功", data=userData, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
class Examines(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
userData = get_user_info(request)
if userData['scope'] == 1:
user_ids = list(models.Users.objects.filter(audit_status=0,deleted_at=None).values_list('id',flat=True))
queset = models.UserExamines.objects.filter(user_id__in=user_ids,status=0,deleted_at=None).order_by('-created_at')
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queset, request)
serializer = serializers.UserExaminesSerializer(page_data, many=True)
data = {"data":serializer.data,"count":queset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data= data, status='success'))
else:
return JsonResponse(ResponseFactory(code=201, message="用户不是管理员身份", data=None, status='fail'))
class GetActivitys(APIView):
"""
首页活动推荐:
1.根据用户标签推送
2.无标签用户根据创建时间倒序
3.增加活动名搜索
"""
def get(self, request):
try:tag_ids = eval(request.GET.get('tag_id'))
except :tag_ids = []
text = request.GET.get('text','')
orderbyList = ['-weight','-created_at']
try:user_id = get_user_info(request)['id']
except:user_id = 0
if len(tag_ids) > 0 and not text:
activitys_ids = models.ActivityHasTags.objects.filter(tag_id__in=tag_ids,deleted_at=None).values_list('activity_id',flat=True)
queryset = models.Activitys.objects.filter(status=1,audit_status=1,song_name__icontains=text,id__in=activitys_ids,deleted_at=None).order_by(*orderbyList)
else:
#活动名查询
activitys_ids1 = list(models.Activitys.objects.filter(status=1,audit_status=1,song_name__icontains=text,deleted_at=None).order_by(*orderbyList).values_list('id',flat=True))
# 项目名关联活动查询
project_ids = list(models.Projects.objects.filter(status=1, name__icontains=text, deleted_at=None).values_list('id',flat=True))
activitys_ids2 = list(models.Activitys.objects.filter(status=1, audit_status=1,project_id__in=project_ids, deleted_at=None).order_by(*orderbyList).values_list('id',flat=True))
#去重
activitys_ids3 = activitys_ids1 + activitys_ids2
activitys_ids = list(set(activitys_ids3))
activitys_ids.sort(key=activitys_ids3.index)
activity_id_str = ",".join('%s' % id for id in activitys_ids)
queryset = models.Activitys.objects.filter(status=1,audit_status=1,id__in=activitys_ids,deleted_at=None).extra(select={'m':'FIELD(id,{})'.format(activity_id_str)},order_by=['m'])
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.ActivitysSerializer(page_data, many=True,context={"user_id":user_id})
data = {"has_activitys":ser_obj.data,"count":len(queryset)}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class V2GetActivitys(APIView):
def get(self,request):
tag_ids = eval(request.GET['tag_id'])
text = request.GET.get('text', '')
orderbyList = ['-weight','-created_at']
try:user_id = get_user_info(request)['id']
except:user_id = 0
if len(tag_ids) > 0 and not text: #搜索text搜索全局,不考虑tag_ids限制,活动是推荐活动is_recommend=1
activitys_ids1 = list(models.ActivityHasTags.objects.filter(tag_id__in=tag_ids, activity__is_recommend=1,deleted_at=None).values_list('activity_id', flat=True))
# 去掉不喜欢标签和已收藏的
collection_activitys_ids = list(models.UserActivityCollections.objects.filter(user_id=user_id, deleted_at=None).values_list('activity_id', flat=True))
unlike_activitys_ids = list(models.UserActivityUnlikes.objects.filter(user_id=user_id, deleted_at=None).values_list('activity_id',flat=True))
delete_list = collection_activitys_ids + unlike_activitys_ids
activitys_ids = [x for x in activitys_ids1 if x not in delete_list]
else:
#活动名查询
activitys_ids1 = list(models.Activitys.objects.filter(status=1,audit_status=1,song_name__icontains=text,deleted_at=None).order_by(*orderbyList).values_list('id',flat=True))
# 项目名关联活动查询
project_ids = list(models.Projects.objects.filter(status=1, name__icontains=text, deleted_at=None).values_list('id',flat=True))
activitys_ids2 = list(models.Activitys.objects.filter(status=1, audit_status=1,project_id__in=project_ids, deleted_at=None).order_by(*orderbyList).values_list('id',flat=True))
#去重
activitys_ids3 = activitys_ids1 + activitys_ids2
activitys_ids = list(set(activitys_ids3))
activitys_ids.sort(key=activitys_ids3.index)
if len(activitys_ids) == 0 :
data = {"has_activitys": [], "count": 0}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
idList = ",".join('%s' % id for id in activitys_ids)
sql = """
select
activitys.id,activitys.song_name,activitys.project_id,activitys.sub_title,activitys.created_at,
IF(uva.id IS NULL,0,1) AS `is_listen`,
IF(ahu.id IS NULL,0,1) AS `is_submit`,
IF(uac.id IS NULL,0,1) AS `is_collection`,
IF(ahu.`status`=1,1,0) AS `is_take`,
(select count(*) from user_view_activitys where user_view_activitys.activity_id = activitys.id ) as view_count,
(select count(*) from activity_has_users where activity_has_users.activity_id = activitys.id and activity_has_users.type='Submit' AND activity_has_users.deleted_at is NULL ) as attend_count
from `activitys`
left join `user_activity_collections` as uac on `uac`.`activity_id` = `activitys`.`id` and `uac`.user_id={user_id} and `uac`.deleted_at is NULL
left join `user_view_activitys` as uva on `uva`.`activity_id` = `activitys`.`id` and `uva`.user_id={user_id}
left join `activity_has_users` as ahu on `ahu`.`activity_id` = `activitys`.`id` and `ahu`.user_id={user_id} and `ahu`.`type`='Submit' and `ahu`.deleted_at is NULL
where activitys.id IN ({activitys_id}) AND activitys.`status`=1 AND audit_status=1 AND activitys.deleted_at is NULL GROUP BY activitys.id order by is_listen asc,is_submit asc,is_collection asc,activitys.weight desc,activitys.created_at desc
""".format(activitys_id = idList, user_id=user_id)
queryset = models.Activitys.objects.raw(sql)
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.V2ActivitysSerializer(page_data, many=True, context={"user_id": user_id})
data = {"has_activitys": ser_obj.data, "count":len(queryset)}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class V3GetActivitys(APIView):
def get(self,request):
tag_ids = eval(request.GET['tag_id'])
text = request.GET.get('text', '')
orderbyList = ['-weight','-created_at']
try:user_id = get_user_info(request)['id']
except:user_id = 0
if len(tag_ids) > 0 and not text:
#活动是推荐活动is_recommend=1
activitys_ids1 = list(models.ActivityHasTags.objects.filter(tag_id__in=tag_ids,activity__is_recommend=1, deleted_at=None).values_list('activity_id', flat=True))
# 去掉不喜欢标签和已收藏的
unlike_activitys_ids = list(models.UserActivityUnlikes.objects.filter(user_id=user_id, deleted_at=None).values_list('activity_id',flat=True))
activitys_ids = [x for x in activitys_ids1 if x not in unlike_activitys_ids]
else:
# 活动名查询
activitys_ids1 = list(models.Activitys.objects.filter(status=1, audit_status=1, song_name__icontains=text,deleted_at=None).order_by(*orderbyList).values_list('id', flat=True))
# 项目名关联活动查询
project_ids = list(models.Projects.objects.filter(status=1, name__icontains=text, deleted_at=None).values_list('id',flat=True))
activitys_ids2 = list(models.Activitys.objects.filter(status=1, audit_status=1, project_id__in=project_ids,deleted_at=None).order_by(*orderbyList).values_list('id', flat=True))
# 去重
activitys_ids3 = activitys_ids1 + activitys_ids2
activitys_ids = list(set(activitys_ids3))
activitys_ids.sort(key=activitys_ids3.index)
if len(activitys_ids) == 0 :
data = {"has_activitys": [], "count": 0}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
idList = ",".join('%s' % id for id in activitys_ids)
sql = """
select
activitys.id,activitys.song_name,activitys.project_id,activitys.sub_title,activitys.created_at,
IF(uva.id IS NULL,0,1) AS `is_listen`,
IF(ahu.id IS NULL,0,1) AS `is_submit`,
IF(uac.id IS NULL,0,1) AS `is_collection`,
IF(ahu.`status`=1,1,0) AS `is_take`,
(select count(*) from user_view_activitys where user_view_activitys.activity_id = activitys.id ) as view_count,
(select count(*) from activity_has_users where activity_has_users.activity_id = activitys.id and activity_has_users.type='Submit' AND activity_has_users.deleted_at is NULL ) as attend_count
from `activitys`
left join `user_activity_collections` as uac on `uac`.`activity_id` = `activitys`.`id` and `uac`.user_id={user_id} and `uac`.deleted_at is NULL
left join `user_view_activitys` as uva on `uva`.`activity_id` = `activitys`.`id` and `uva`.user_id={user_id}
left join `activity_has_users` as ahu on `ahu`.`activity_id` = `activitys`.`id` and `ahu`.user_id={user_id} and `ahu`.`type`='Submit' and `ahu`.deleted_at is NULL
where activitys.id IN ({activitys_id}) AND activitys.`status`=1 AND audit_status=1 AND activitys.deleted_at is NULL GROUP BY activitys.id order by is_listen asc,is_submit asc,is_collection asc,activitys.weight desc,activitys.created_at desc
""".format(activitys_id = idList, user_id=user_id)
queryset = models.Activitys.objects.raw(sql)
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.V2ActivitysSerializer(page_data, many=True, context={"user_id": user_id})
data = {"has_activitys": ser_obj.data, "count":len(queryset)}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class GetActivityUser(APIView):
"""
获取参加活动所有用户
"""
def get(self,request):
activity_id = request.GET['activity_id']
queryset = models.ActivityHasUsers.objects.filter(activity_id=activity_id,deleted_at=None).values('user_id').distinct()
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ids = []
for user in page_data:
ids.append(user['user_id'])
data = serializers.UserListSerializer (models.Users.objects.in_bulk(ids).values(),many=True).data
data = {'data':data,'count':queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class examineStatus(APIView):
"""
2种身份,2种审核状态,判断是否已审核
歌手审核:
1.通过:查看关联商务已关联人数,不满10人则通过,修改审核表状态,用户表状态且用户表关联商务
2.拒绝:直接改变审核表审核状态,用户表状态且用户表
商务审核:
1.通过:修改审核表状态,用户表状态
2.拒绝:直接改变审核表审核状态,用户表状态且用户表
:param requests:
:return:
"""
@method_decorator(AuthPermissionRequired())
def put(self,request):
put_data = json.loads(request.body)
logger.info(put_data)
obj = verification.examine_verification(put_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
obj = obj.clean()
examine_id = obj.get('examine_id')
examine_status = obj.get('examine_status')
examine_info = put_data.get('examine_info','') #非必传
business_id = put_data.get('business_id',0) #非必传
#判断是否已审核
is_examines = models.Users.objects.filter(id = examine_id,audit_status=1,deleted_at=None)
if is_examines:
return JsonResponse(ResponseFactory(code=201, message="用户已被审核通过,请勿重复审核", data=None, status='fail'))
# 获取管理员身份
userData = get_user_info(request)
# 获取被审核人身份
examine_user = models.Users.objects.filter(id=examine_id, deleted_at=None).first()
if not examine_user:
return JsonResponse(ResponseFactory(code=201, message="不存在的用户,无法审核", data=None, status='fail'))
#获取审核表对象
examine_item = models.UserExamines.objects.filter(user_id=examine_id, status=0, deleted_at=None).order_by('-created_at').first()
open_id = examine_item.open_id
if examine_status == 2:
models.UserExamines.objects.filter(user_id=examine_id, status=0, deleted_at=None).update(
admin_id = userData.get('id'),
examine_info = examine_info,
status = examine_status,
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
models.Users.objects.filter(id=examine_id, deleted_at=None).update(audit_status=examine_status,updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
elif examine_status == 1:
#判断是歌手还是商务
if examine_user.role == "Singer" and business_id :
business_has_singer = models.Users.objects.filter(business_id=business_id,status=1,audit_status=1,deleted_at=None).count()
if business_has_singer >= 999:
return JsonResponse(ResponseFactory(code=201, message="该商务已关联超过999人", data=None, status='fail'))
try:
with transaction.atomic():
# # 修改审核信息
models.UserExamines.objects.filter(user_id=examine_id, status=0, deleted_at=None).update(admin_id=userData.get('id'),examine_info=examine_info,status=examine_status,updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
models.Users.objects.filter(id=examine_id,deleted_at=None).update(audit_status=examine_status,business_id=business_id,updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
# 消息计数
m_data = {'receivers':[business_id],'sender_id':examine_id,'type':1,'is_bind':1}
createMessage(m_data)
# 推送消息给推荐人
business_unionid = models.Users.objects.filter(id=business_id).first().unionid
business_wechat_official = models.WechatOfficialUsers.objects.filter(union_id=business_unionid,is_subscribe=1).last()
if business_wechat_official:
business_open_id = business_wechat_official.open_id
name = examine_item.user_info['nick_name']+"({})".format(examine_item.user_info['real_name'])
data = {'channel': 'singer_related', 'open_id': [business_open_id],
'data': {"title":"您有新的歌手入驻平台成功","name":name,"intro":"通过【海星试唱】平台审核","remark":"欢迎{}入驻平台,快去为ta挑选合适的歌曲吧~".format(name),"page":"packageMy/pages/like?tab=0"}}
pushSubscribeMessage(data)
#极光推送-绑定歌手
j_title = "您有歌手入驻平台"
j_content = "您的歌手{}已入驻平台,快去为ta挑歌吧~".format(examine_item.user_info['nick_name'])
jdata = {"title": j_title, "content": j_content, "content_type": "text",
"receiver_value": [business_id], "extras": {"type": "ToMySinger", "value": ""}}
JPush().jpush_v3(jdata)
#绑定歌手成功,推荐人积分
user_point_record(user_id=business_id, singer_id=examine_id,type='BindSinger')
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="审核失败。请联系管理员", data=None, status='fail'))
else:
try:
with transaction.atomic():
# 修改审核信息
models.UserExamines.objects.filter(user_id=examine_id, status=0, deleted_at=None).update(admin_id=userData.get('id'),examine_info=examine_info,status=examine_status,updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
models.Users.objects.filter(id=examine_id, deleted_at=None).update(audit_status=examine_status,business_id=None,updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="审核失败。请联系管理员", data=None, status='fail'))
# #推送审核消息通知用户
if open_id:
result = "通过" if examine_status == 1 else "拒绝"
if examine_info == "":
examine_info = "审核通过,快去寻找适合你的Demo吧!"
data = {'channel':'register_audit','open_id':[open_id] , 'data': { "nick_name": examine_user.nick_name, "status": result,"msg": examine_info}}
pushSubscribeMessage(data)
#极光推送-歌手审核
j_title = "注册申请已通过" if examine_status == 1 else "注册申请未通过"
j_content = "点击前往海星试唱挑选歌曲" if examine_status == 1 else "点击查看详情"
j_type = "OpenSelectTag" if examine_status == 1 else "OpenApp"
jdata = {"title": j_title, "content": j_content, "content_type": "text", "receiver_value": [examine_id],"extras": {"type": j_type, "value": ""}}
JPush().jpush_v3(jdata)
return JsonResponse(ResponseFactory(code=200, message="审核完成", data=None, status='success'))
def banners(request):
if request.method == 'GET':
user = dict()
try:
user = get_user_info(request)
# 记录用户审核完成访问小程序
is_record = models.Actions.objects.filter(event_name='audited_visit',user_id=user.get('id')).exists()
if not is_record:
models.Actions.objects.create(event_name='audited_visit',
user_id=user['id'],
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
except Exception as e:
user['role'] = 'Visitor' #游客
# sql = """ SELECT * FROM banners where type=1 and status=1 and
# deleted_at is null and json_contains(banners.role,CONCAT('"',"{}",'"'))
# and json_contains(banners.scope,JSON_Array({}))
# ORDER BY `weight` DESC,`created_at` DESC """.format(user['role'],user['scope'])
sql = """ SELECT * FROM banners where scope=1 and status=1 and
deleted_at is null and json_contains(banners.role,CONCAT('"',"{}",'"'))
ORDER BY `weight` DESC,`created_at` DESC """.format(user['role'])
queset = models.Banners.objects.raw(sql)
ser = serializers.BanneraSerializer(queset,many=True)
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=ser.data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def v2banners(request):
if request.method == 'GET':
scope = request.GET.get('type',1)
try:
user = get_user_info(request)
# 记录用户审核完成访问小程序
is_record = models.Actions.objects.filter(event_name='audited_visit',user_id=user.get('id')).exists()
if not is_record:
models.Actions.objects.create(event_name='audited_visit',
user_id=user['id'],
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
roleDict = {"0": ["Visitor"], "1": ["Singer"], "2": ["Business"],
"3": ["Singer","Business"]}
scopeDict = {"1":["System"],"2":["Project"]}
my_list = roleDict[str(user['identity'])]
if user['scope']:
my_list = my_list + scopeDict[str(user['scope'])]
except Exception as e:
my_list = ["UnLogin"]#游客
query = Q()
for value in my_list:
query |= Q(role__contains=[value])
queset = models.Banners.objects.filter(query,scope=scope,status=1,deleted_at=None).order_by(*['-weight','-created_at'])
ser = serializers.BanneraSerializer(queset,many=True,fields=['id','name','cover','content_picture','type'])
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=ser.data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def bannerDetail(request):
if request.method != 'GET':
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
id = request.GET.get('id')
queryset = models.Banners.objects.filter(id=id).first()
data =serializers.BanneraSerializer(queryset,many=False,fields=['id','name','cover','type','content']).data
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
@AuthPermissionRequired()
def UserViewActivity(request):
if request.method == 'POST':
obj = verification.view_activity_verification(json.loads(request.body))
if obj.is_valid():
data = obj.clean()
user_id = get_user_info(request)['id']
item = models.UserViewActivity.objects.filter(user_id=user_id,activity_id=data.get('activity_id'))
if not item:
models.UserViewActivity.objects.create(
user_id=user_id,
activity_id=data.get('activity_id'),
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
else:
item.update(
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
return JsonResponse(ResponseFactory(code=200, message='记录成功', data=None, status='success'))
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
class Unlike(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
user_id = get_user_info(request)['id']
ids = list(models.UserActivityUnlikes.objects.filter(user_id=user_id,deleted_at=None).order_by('-created_at').values_list('activity_id',flat=True))
if ids != []:
idList = ",".join('%s' %id for id in ids)
sql = """select * from activitys where id in ({}) order by field(id,{})""".format(idList,idList)
queryset = models.Activitys.objects.raw(sql)
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.ActivitysSerializer(page_data, many=True, context={"user_id": user_id})
data = {"activitys": ser_obj.data, "count": len(ids)}
else:
data = {"activitys": [], "count": len(ids)}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
@method_decorator(AuthPermissionRequired())
def post(self,request):
obj = verification.user_activity_unlike(json.loads(request.body))
if obj.is_valid():
data = json.loads(request.body)
user = get_user_info(request)
models.UserActivityUnlikes.objects.create(
user_id=user['id'],
activity_id=data['activity_id'],
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
return JsonResponse(ResponseFactory(code=200, message="设置完成", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
class GetCompleteActivity(APIView):
"""
获取确认歌手的活动
"""
def get(self,request):
queryset = models.Activitys.objects.filter(status=3,deleted_at=None).order_by('-updated_at')
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_data = serializers.CompleteActivity(page_data,many=True)
data = {'data':ser_data.data,'count':queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
def Events(request):
if request.method == 'GET':
data = serializers.Events(models.Events.objects.all(),many=True).data
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def Action(request):
if request.method == 'POST':
postdata = json.loads(request.body)
try:user_id = get_user_info(request)['id']
except:user_id=0
vx_code = postdata.get('vx_code','')
if vx_code:open_id, unionid = WeChatApi(vx_code)
else:open_id = ''
now = timezone.now().strftime("%Y-%m-%d %H:%M:%S")
models.Actions.objects.create(
event_name = postdata.get('event_name',''),
open_id = open_id,
user_id=user_id,
activity_id=postdata.get('activity_id', 0),
start_at=postdata.get('start_at', None),
end_at=postdata.get('end_at', None),
created_at=now,
updated_at=now
)
return JsonResponse(ResponseFactory(code=200, message="记录成功", data='', status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
class BandList(APIView):
def get(self,request):
"""厂牌列表:厂牌发布过试唱"""
is_recommend = int(request.GET.get('is_recommend',0))
project_id = models.Activitys.objects.filter(deleted_at=None,audit_status=1).values_list('project_id',flat=True)
if is_recommend:
orderbyList = ['-r_weight', '-created_at']
kwargs = {"status":1,"r_status":1,"deleted_at":None}
else:
orderbyList = ['-r_status','-r_weight','-weight', '-created_at']
kwargs = {"status":1,"deleted_at":None}
kwargs['id__in'] = project_id
queryset = models.Projects.objects.filter(**kwargs).order_by(*orderbyList)
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_data = serializers.ProjectsSerializer(page_data, many=True)
data = {'data': ser_data.data, 'count': queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class BandDetail(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
"""厂牌详情"""
id = int(request.GET.get('id'))
user_id = get_user_info(request)['id']
queryset = models.Projects.objects.filter(id=id,status=1,deleted_at=None).first()
if not queryset:
return JsonResponse(ResponseFactory(code=400, message="厂牌已被禁用或删除", data=None, status='fail'))
projects = serializers.ProjectsSerializer(queryset, many=False)
#记录访问信息
models.ProjectVisitors.objects.create(project_id=id,user_id=user_id, created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=projects.data, status='success'))
class BandLinkActivity(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
"""厂牌关联活动"""
try:user_id = get_user_info(request)['id']
except:user_id = 0
id = int(request.GET.get('id'))
activityid_list = []
kwargs = {"project_id":id,"audit_status":1,"status":1,"song_type":1,"deleted_at":None}
activity_ids = models.Activitys.objects.filter(**kwargs).values_list('id',flat=True)
#去掉不喜欢的标签
unlike_activitys_ids = list(models.UserActivityUnlikes.objects.filter(user_id=user_id, deleted_at=None).values_list('activity_id',flat=True))
for m in activity_ids:
if m not in unlike_activitys_ids:
activityid_list.append(m)
if len(activityid_list) == 0:
data = {"data": None, "count": 0}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
idList = ",".join('%s' % id for id in activityid_list)
sql = """
select
activitys.id,activitys.song_name,activitys.project_id,activitys.sub_title,activitys.created_at,
IF(uva.id IS NULL,0,1) AS `is_listen`,
IF(ahu.id IS NULL,0,1) AS `is_submit`,
IF(uac.id IS NULL,0,1) AS `is_collection`,
IF(ahu.`status`=1,1,0) AS `is_take`,
(select count(*) from user_view_activitys where user_view_activitys.activity_id = activitys.id ) as view_count,
(select count(*) from activity_has_users where activity_has_users.activity_id = activitys.id and activity_has_users.type='Submit' AND activity_has_users.deleted_at is NULL ) as attend_count
from `activitys`
left join `user_activity_collections` as uac on `uac`.`activity_id` = `activitys`.`id` and `uac`.user_id={user_id} and `uac`.deleted_at is NULL
left join `user_view_activitys` as uva on `uva`.`activity_id` = `activitys`.`id` and `uva`.user_id={user_id}
left join `activity_has_users` as ahu on `ahu`.`activity_id` = `activitys`.`id` and `ahu`.user_id={user_id} and `ahu`.`type`='Submit' and `ahu`.deleted_at is NULL
where activitys.id IN ({activitys_id}) AND activitys.`status`=1 AND audit_status=1 AND activitys.deleted_at is NULL GROUP BY activitys.id order by p_is_top desc,is_listen asc,activitys.weight desc,activitys.created_at desc
""".format(activitys_id=idList, user_id=user_id)
queryset = models.Activitys.objects.raw(sql)
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
activitys = serializers.BandActivitySerializer(page_data, many=True,context={"user_id":user_id,"project_many":True}, fields=['id','song_name','sub_title','lyric','sex','mark','speed','lang','guide','guide_duration','guide_clip','guide_clip_duration','karaoke','karaoke_clip','clip_lyric','cover','status','project_id','is_collection','status_tag','is_confirm_share','project','tags','is_promote','estimate_release_at','publish_at','guide_duration','guide_clip_duration','comfirm_time','total_song_count','online_song_count','public_audio_count','arranger','is_master','p_is_top']).data
# 活动配置信息
config_ids = list(models.SystemConfig.objects.filter(identifier__in=['activity_lang', 'activity_speed', 'activity_sex', 'activity_mark']).values_list('id',flat=True).all())
configs = models.SystemConfig.objects.filter(parent_id__in=config_ids).values_list('identifier', 'name','content')
for activity in activitys:
lang = activity['lang'] if activity['lang'] else []
langs =[]
for config in configs:
if config[0] == activity['sex']:
activity['sex'] = config[1] if activity['sex'] else None
if config[0] == activity['mark']:
activity['mark'] = config[2] if activity['mark'] else None
if config[0] == activity['speed']:
activity['speed'] = config[1] if activity['speed'] else None
if config[0] in lang:
langs.append(config[1])
activity['lang'] = langs
data = {'data': activitys, "count":len(queryset)}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class RecommenCasedList(APIView):
def get(self,request):
is_recommend = int(request.GET.get('is_recommend', 0))
if is_recommend:
kwargs = {"audit_status":1,"status": 5, "r_status": 1, "deleted_at": None} #已发行
orderbyList = ['-r_weight', '-updated_at']
else:
kwargs = {"audit_status": 1, "status__in": [3,5], "deleted_at": None} #已发行或确认合作
orderbyList = ['-r_status', '-r_weight', '-updated_at']
queryset = models.Activitys.objects.filter(**kwargs).order_by(*orderbyList)
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_data = serializers.RecommendActivitySerializer(page_data, many=True)
data = {'data': ser_data.data, 'count': queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
\ No newline at end of file
# Create your views here
import json
from django.utils import timezone
from api import models
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from django.contrib.auth.hashers import make_password
from HisinApi import settings
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.conf import settings
from django.http import JsonResponse
from django.contrib.auth import get_user_model
from django.core.cache import caches
import random
import re
from api.views import ResponseFactory,WeChatApi,pushSubscribeMessage,AppWechatApi,JPush
from django.db import transaction
from api.serializers import SystemBusinessSerializer,WeiXinAuthUser
from api import verification
from twilio.rest import Client
UserModel = get_user_model()
class CustomBackend(ModelBackend):
def authenticate(self,username=None, password=None, **kwargs):
"""
登录校验逻辑,重写authenticate
"""
try:
user = models.Users.objects.filter(deleted_at=None).get(Q(phone=username)|Q(email=username))
if user.status:
if user.check_password(password):
return user
else:
return None
return 'User.Disable'
except Exception as e:
return None
def v2authenticate(self,username=None, **kwargs):
"""
登录校验逻辑,重写authenticate
"""
try:
user = models.Users.objects.filter(deleted_at=None).get(Q(phone=username)|Q(email=username))
if user.status:
return user
return 'User.Disable'
except Exception as e:
return None
def cntw_sms_server(template,phone, area_code):
account_sid = 'AC556f91c359069fb23b608cb7852d98cf'
auth_token = '65ee1a4b53c4387b1b5049e83e37dabe'
client = Client(account_sid, auth_token)
message = client.messages.create(
messaging_service_sid='MG5c28f0230f888e02fe0ec47b0eea4c15',
body='[海星试唱] 验证码{}'.format(template['code']),
to='+{}{}'.format(area_code,phone)
)
if message.status == 'accepted':response = b'{"Code":"OK"}'
else:response = b'{"Code":"fail"}'
return response
def send_sms(template, phone, area_code):
"""
阿里云短信服务SDK
"""
client = AcsClient(settings.ALY_ACCESS_KEY_ID, settings.ALY_ACCESS_KEY_SECRET, 'default')
request = CommonRequest()
request.set_accept_format('json')
request.set_domain('dysmsapi.aliyuncs.com')
request.set_method('POST')
request.set_protocol_type('http') # https | http
request.set_version('2017-05-25')
request.set_action_name('SendSms')
request.add_query_param('RegionId', "default")
request.add_query_param('SignName', settings.ALY_SIGN_NAME)
if area_code == 86:
#国内
request.add_query_param('TemplateCode', settings.ALY_REGISTER_TEMPLATE)
elif area_code == 886:
response = cntw_sms_server(template, phone, area_code)
return response
else:
# 国外
phone = str(area_code) + str(phone)
request.add_query_param('TemplateCode', settings.ALY_REGISIER_TEMPLATE2)
request.add_query_param('PhoneNumbers', phone)
request.add_query_param('TemplateParam', template)
response = client.do_action_with_exception(request)
return response
def gen_mobile_code(length=6):
all_charts = '123456789'
return ''.join(random.choices(all_charts,k = length))
def v2sendsms(request):
"""
国际,国内
:param request:
:return:
"""
if request.method == 'POST':
post_data = json.loads(request.body)
obj = verification.v2SendVerify(data=post_data)
if obj.is_valid():
phone = obj.data.get('phone')
type = post_data.get('type','')
area_code = obj.data.get('area_code')
if type == 'login':
user = models.Users.objects.filter(phone=phone,deleted_at=None)
if not user:
return JsonResponse(ResponseFactory(code=201, message="用户不存在,请先注册", data=None, status='fail'))
if type == 'register':
user = models.Users.objects.filter(phone=phone,deleted_at=None)
if user:
return JsonResponse(ResponseFactory(code=201, message="您的手机号码已经注册,无法再次注册", data=None, status='fail'))
if type == 'change':
user = models.Users.objects.filter(phone=phone,deleted_at=None)
if user:
return JsonResponse(ResponseFactory(code=201, message="手机号已经注册,请使用其它手机号码", data=None, status='fail'))
if caches['default'].get(f'voteapp: polls:block: {phone}'): # 获取缓存中是否有保存的电话号码
return JsonResponse(ResponseFactory(code=204, message="请不要短时间内重复发送短信验证码", data=None, status='fail'))
else:
code = gen_mobile_code() # 随机生成指定位数的数字
template = {'code': code}
result = json.loads(send_sms(template, phone,area_code=area_code)) # 调用三方平台的接口
if result['Code'] == "OK":
caches['default'].add(f'voteapp: polls:block: {phone}', int(code), 60) # 设置60秒内勿重复发短信
caches['default'].set(f'voteapp: polls:valid: {phone}', int(code), 60*10) # 缓存中保存发送的验证码并设置短信的过期时间
return JsonResponse(ResponseFactory(code=200, message="发送成功", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=201, message="发送失败", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def sendsms(request):
"""短信发送接口"""
if request.method == 'POST':
obj = verification.SendVerify(data=json.loads(request.body))
if obj.is_valid():
phone = obj.data.get('phone')
TEL_PATTERN = re.compile(r'^(1[0-9])[0-9]{9}$')
if TEL_PATTERN.match(phone):
if caches['default'].get(f'voteapp: polls:block: {phone}'): # 获取缓存中是否有保存的电话号码
return JsonResponse(ResponseFactory(code=204, message="请不要短时间内重复发送短信验证码", data=None, status='fail'))
else:
code = gen_mobile_code() # 随机生成指定位数的数字
template = {'code': code}
result = json.loads(send_sms(template, phone,area_code=86)) # 调用三方平台的接口
if result['Code'] == "OK":
caches['default'].add(f'voteapp: polls:block: {phone}', int(code), 60) # 设置60秒内勿重复发短信
caches['default'].set(f'voteapp: polls:valid: {phone}', int(code), 60*10) # 缓存中保存发送的验证码并设置短信的过期时间
return JsonResponse(ResponseFactory(code=200, message="发送成功", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=201, message="发送失败", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=203, message="手机号码无效", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def user_login(request):
"""用户登录"""
if request.method == 'POST':
obj = verification.LoginVerify(data=json.loads(request.body))
if obj.is_valid():
user = CustomBackend().authenticate(username=obj.data.get('phone'), password=obj.data.get('password'))
if user == 'User.Disable':
return JsonResponse(ResponseFactory(code=201, message="登录失败,用户已被禁用", data=None, status='fail'))
if user is not None:
return JsonResponse(ResponseFactory(code=200, message="登录成功", data={'token':user.token}, status='success'))
else:
return JsonResponse(ResponseFactory(code=204, message="用户名或密码错误", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def sms_verify_login(request):
if request.method == 'POST':
obj = verification.V2LoginVerify(data=json.loads(request.body))
if obj.is_valid():
# 获取缓存中的验证码
obj = obj.data
mob = caches['default'].get(f'voteapp: polls:valid: {obj.get("phone")}')
# is_dev = int(obj.get('sms_code')) == 123456 and settings.ENV == 'dev'
is_dev = int(obj.get('sms_code')) == 966446 #暂时正式环境也加万能验证码
if mob == int(obj.get('sms_code')) or is_dev:
user = CustomBackend().v2authenticate(username=obj.get('phone'))
if user == 'User.Disable':
return JsonResponse(ResponseFactory(code=201, message="登录失败,用户已被禁用", data=None, status='fail'))
if user is not None:
caches['default'].delete(f'paopao: polls:valid: {obj.get("phone")}')
return JsonResponse(ResponseFactory(code=200, message="登录成功", data={'token': user.token}, status='success'))
else:
return JsonResponse(ResponseFactory(code=204, message="此用户不存在", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=204, message="验证码错误", data=None, status='fail'))
else:
return JsonResponse(
ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def register(request):
"""用户注册"""
if request.method == 'POST':
post_data = json.loads(request.body)
role = post_data.get('role')
if role == "Singer":
obj = verification.SingerRegister(post_data)
elif role == "Business" :
obj = verification.BusinessRegister(post_data)
if obj.is_valid():
obj = obj.clean()
if obj.get("password") == obj.get("confirm_password",''):
re_phone = models.Users.objects.filter(phone=obj.get("phone"),deleted_at=None).exists()
if re_phone:
return JsonResponse(ResponseFactory(code=400, message="手机号码已被注册", data=None, status='fail'))
re_email = models.Users.objects.filter(email=obj.get("email"),deleted_at=None).exists()
if re_email:
return JsonResponse(ResponseFactory(code=400, message="邮箱已被注册", data=None, status='fail'))
re_nick_name = models.Users.objects.filter(nick_name=obj.get("nick_name"),deleted_at=None).exists()
if re_nick_name:
return JsonResponse(ResponseFactory(code=400, message="艺名已被注册", data=None, status='fail'))
#获取缓存中的验证码
mob = caches['default'].get(f'voteapp: polls:valid: {obj.get("phone")}')
is_dev = int(obj.get('sms_code')) == 123456 and settings.ENV == 'dev'
if mob == int(obj.get('sms_code')) or is_dev:
try:
with transaction.atomic():
# 获取微信openid
open_id, unionid = WeChatApi(post_data.get("vx_code", ""))
#生成用户信息
# 歌手
if role == "Singer":
user = models.Users.objects.create(
nick_name=obj.get("nick_name"),
real_name=obj.get("real_name"),
phone=obj.get("phone"),
email=obj.get("email"),
province=obj.get("province"),
city=obj.get("city"),
is_referee=obj.get("is_referee"),
password=make_password(obj.get("password")),
role=role,
audit_status=0,
status=1,
open_id = open_id,
unionid = unionid,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
)
user_info = {"email": obj.get("email"), "phone": obj.get("phone"),
"nick_name": obj.get("nick_name"),
"business_id": post_data.get("business_id",None), "role": role,
"province": obj.get("province"), "city": obj.get("city"),
"remarks":post_data.get('remarks',''),
"is_referee": obj.get("is_referee"), "real_name": obj.get("real_name"),
"created_at": timezone.now().strftime("%Y-%m-%d %H:%M:%S")}
else :
user = models.Users.objects.create(
nick_name=obj.get("nick_name"),
real_name=obj.get("real_name"),
phone=obj.get("phone"),
email=obj.get("email"),
password=make_password(obj.get("password")),
role=role,
audit_status=0,
status=1,
open_id=open_id,
unionid=unionid,
company = obj.get("company"),
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
)
user_info = {"email": obj.get("email"), "phone": obj.get("phone"),
"nick_name": obj.get("nick_name"),"role": role,"real_name": obj.get("real_name"),"company":obj.get("company"),
"created_at": timezone.now().strftime("%Y-%m-%d %H:%M:%S")}
# 生成待审核信息
models.UserExamines.objects.create(
user_id=user.id,
type = role,
admin_id = 0,
open_id = open_id if obj.get("is_push") else None,
business_id=post_data.get("business_id",None),
user_info=user_info,
status=0,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="注册失败:{}".format(e), data=None, status='fail'))
userdata = {"id": user.id, "nick_name": user.nick_name, "real_name": user.real_name,
'token': user.token}
#给全体管理员推送注册信息
admin_unionid = list(models.Users.objects.filter(scope=1).values_list('unionid', flat=True))
admin_open_ids = list(models.WechatOfficialUsers.objects.filter(union_id__in=admin_unionid,is_subscribe=1).values_list('open_id', flat=True))
data = {'channel': 'register_create', 'open_id': admin_open_ids,
'data': {"nick_name":user.nick_name,"real_name": user.real_name,"time":user.created_at}
}
pushSubscribeMessage(data)
return JsonResponse(
ResponseFactory(code=200, message="注册成功", data=userdata, status='success'))
else:
return JsonResponse(ResponseFactory(code=201, message="验证码不正确或已失效", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="2次输入的密码不一致", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def v2register(request):
"""V2用户注册"""
if request.method == 'POST':
post_data = json.loads(request.body)
role = post_data.get('role')
if role == "Singer":obj = verification.V2SingerRegister(post_data)
else:obj = verification.V2BusinessRegister(post_data)
if obj.is_valid():
obj = obj.clean()
re_phone = models.Users.objects.filter(phone=obj.get("phone"),deleted_at=None).exists()
if re_phone:
return JsonResponse(ResponseFactory(code=400, message="手机号码已被注册", data=None, status='fail'))
re_email = models.Users.objects.filter(email=obj.get("email"),deleted_at=None).exists()
reg = "\w+[@][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)+"
valid = re.findall(reg, obj.get("email"))
if re_email or not valid:
return JsonResponse(ResponseFactory(code=400, message="邮箱已被注册或格式不正确", data=None, status='fail'))
re_nick_name = models.Users.objects.filter(nick_name=obj.get("nick_name"),deleted_at=None).exists()
if re_nick_name:
return JsonResponse(ResponseFactory(code=400, message="艺名已被注册", data=None, status='fail'))
#获取缓存中的验证码
mob = caches['default'].get(f'voteapp: polls:valid: {obj.get("phone")}')
is_dev = int(obj.get('sms_code')) == 123456 and settings.ENV == 'dev'
if mob == int(obj.get('sms_code')) or is_dev:
try:
with transaction.atomic():
# 获取微信openid
open_id, unionid = WeChatApi(post_data.get("vx_code", ""))
#生成用户信息
# 歌手
if role == "Singer":
user = models.Users.objects.create(
nick_name=obj.get("nick_name"),
real_name=obj.get("real_name"),
area_code = obj.get("area_code"),
phone=obj.get("phone"),
email=obj.get("email"),
is_referee=obj.get("is_referee"),
role=role,
audit_status=0,
status=1,
open_id = open_id,
unionid = unionid,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
)
user_info = {"email": obj.get("email"), "phone": obj.get("phone"),
"nick_name": obj.get("nick_name"),
"business_id": post_data.get("business_id",None), "role": role,
"sound":post_data.get('sound',''),
"remarks":post_data.get('remarks',''),
"is_referee": obj.get("is_referee"), "real_name": obj.get("real_name"),
"created_at": timezone.now().strftime("%Y-%m-%d %H:%M:%S")}
else :
user = models.Users.objects.create(
nick_name=obj.get("nick_name"),
real_name=obj.get("real_name"),
area_code=obj.get("area_code"),
phone=obj.get("phone"),
email=obj.get("email"),
role=role,
audit_status=0,
status=1,
open_id=open_id,
unionid=unionid,
company = obj.get("company"),
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
)
user_info = {"email": obj.get("email"), "phone": obj.get("phone"),
"nick_name": obj.get("nick_name"),"role": role,"real_name": obj.get("real_name"),"company":obj.get("company"),
"created_at": timezone.now().strftime("%Y-%m-%d %H:%M:%S")}
# 生成待审核信息
models.UserExamines.objects.create(
user_id=user.id,
type = role,
admin_id = 0,
open_id = open_id if post_data.get("is_push","") else None,
business_id=post_data.get("business_id",None),
user_info=user_info,
status=0,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="注册失败:{}".format(e), data=None, status='fail'))
userdata = {'token': user.token}
#给全体管理员推送注册信息
admin_ids = list(models.Users.objects.filter(scope=1).values_list('id', flat=True))
admin_unionid = list(models.Users.objects.filter(scope=1).values_list('unionid', flat=True))
admin_open_ids = list(models.WechatOfficialUsers.objects.filter(union_id__in=admin_unionid,is_subscribe=1).values_list('open_id', flat=True))
data = {'channel': 'register_create', 'open_id': admin_open_ids,
'data': {"nick_name":user.nick_name,"real_name": user.real_name,"time":user.created_at}
}
pushSubscribeMessage(data)
# 极光推送-注册
j_title = "有新用户注册账号"
role_dict = {"Singer":"歌手","Business":"推荐人"}
j_content = "{}{}提交了注册申请".format(role_dict[role],obj.get("nick_name"))
jdata = {"title": j_title, "content": j_content, "content_type": "text",
"receiver_value": admin_ids,
"extras": {"type": "ToExamine", "value": ""}}
JPush().jpush_v3(jdata)
return JsonResponse(
ResponseFactory(code=200, message="注册成功", data=userdata, status='success'))
else:
return JsonResponse(ResponseFactory(code=201, message="验证码不正确或已失效", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def v3register(request):
"""V3用户注册"""
if not request.method == 'POST':
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
post_data = json.loads(request.body)
obj = verification.V3UserRegister(post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
obj = obj.clean()
re_phone = models.Users.objects.filter(phone=obj.get("phone"), deleted_at=None).exists()
if re_phone:
return JsonResponse(ResponseFactory(code=400, message="手机号码已被注册", data=None, status='fail'))
re_email = models.Users.objects.filter(email=obj.get("email"), deleted_at=None).exists()
reg = "\w+[@][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)+"
valid = re.findall(reg, obj.get("email"))
if re_email or not valid:
return JsonResponse(ResponseFactory(code=400, message="邮箱已被注册或格式不正确", data=None, status='fail'))
re_nick_name = models.Users.objects.filter(nick_name=obj.get("nick_name"), deleted_at=None).exists()
if re_nick_name:
return JsonResponse(ResponseFactory(code=400, message="艺名已被注册", data=None, status='fail'))
# 获取缓存中的验证码
mob = caches['default'].get(f'voteapp: polls:valid: {obj.get("phone")}')
is_dev = int(obj.get('sms_code')) == 123456 and settings.ENV == 'dev'
if not (mob == int(obj.get('sms_code')) or is_dev):
return JsonResponse(ResponseFactory(code=201, message="验证码不正确或已失效", data=None, status='fail'))
try:
with transaction.atomic():
# 获取微信openid
open_id, unionid = WeChatApi(post_data.get("vx_code", ""))
limit_config = models.SystemConfig.objects.filter(identifier='svMC9TNFz2Acx8ccPdAIH').first()
business_singer_limit = limit_config.content if limit_config else 0
user = models.Users.objects.create(
nick_name=obj.get("nick_name"),
real_name=obj.get("real_name"),
area_code=obj.get("area_code"),
phone=obj.get("phone"),
email=obj.get("email"),
audit_status=1,
status=1,
open_id=open_id,
unionid=unionid,
business_singer_limit = business_singer_limit,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
)
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message="注册失败:{}".format(e), data=None, status='fail'))
userdata = {'token': user.token}
return JsonResponse(ResponseFactory(code=200, message="注册成功", data=userdata, status='success'))
def restPwd(request):
if request.method == 'PUT':
obj = verification.reset_verification(json.loads(request.body))
if obj.is_valid():
obj = obj.clean()
mob = caches['default'].get(f'voteapp: polls:valid: {obj.get("phone")}')
if obj.get('password') == obj.get('confirm_password'):
is_dev = int(obj.get('sms_code')) == 123456 and settings.ENV == 'dev'
if mob == int(obj.get('sms_code')) or is_dev:
user = models.Users.objects.filter(phone=obj.get("phone"),deleted_at=None)
if user:
user.update(password=make_password(obj.get("password")))
return JsonResponse(ResponseFactory(code=200, message="修改完成", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=201, message="不存在此账号,请检查手机号", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=201, message="验证码不正确,请重新输入", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="2次输入的密码不一致", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def businessList(request):
if request.method == 'GET':
ser = SystemBusinessSerializer(models.Users.objects.filter(role='Business',status=1,audit_status=1,deleted_at=None),many=True)
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=ser.data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def wechatAuth(request):
if request.method == 'POST':
obj = verification.WechatAuth(json.loads(request.body))
if obj.is_valid():
platform = obj.clean().get('platform')
vx_code = obj.clean().get('vx_code')
if platform == 'app':
open_id, unionid = AppWechatApi(vx_code)
elif platform == 'applet':
open_id, unionid = WeChatApi(vx_code)
if open_id is not None and unionid is not None:
users = WeiXinAuthUser(models.Users.objects.filter(unionid=unionid,status=1,deleted_at=None),many=True).data
if users:
return JsonResponse(ResponseFactory(code=200, message="登录成功", data=users, status='success'))
else:
return JsonResponse(ResponseFactory(code=200, message="用户不存在或用户未绑定微信用户", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=201, message="不正确的vx_code", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
import re
import json
from django.http import JsonResponse
from api import models
from api.views import AuthPermissionRequired,get_user_info,user_point_record
from django.utils import timezone
from api import serializers
from api.views import ResponseFactory,PageNumberPagination,createMessage,pushSubscribeMessage,JPush,Msg_Push_Server,remove_alias_device,user_permission
from rest_framework.views import APIView
from django.db import transaction
from django.utils.decorators import method_decorator
from api.views import upload_image,WeChatApi,AppWechatApi
import base64
from api import verification
from api.loggin import logger
from django.core.cache import caches
from HisinApi import settings
from django.db.models import Q
from datetime import timedelta
import requests
def dedupe(activity_ids):
new_activity_ids = []
for activity_id in activity_ids:
if activity_id not in new_activity_ids:
new_activity_ids.append(activity_id)
return new_activity_ids
@AuthPermissionRequired()
def upload(request):
"""
base64图片上传
"""
filebase64 = json.loads(request.body).get('file')
temp = base64.b64decode(filebase64)
file_url = upload_image(temp)
data = {"type": "jpg", "name": "", "url": file_url, "size": "", "disk": "oss", "created_at": "", "id": 0}
return JsonResponse(ResponseFactory(code=200, message="上传成功", data=data, status='success'))
@AuthPermissionRequired()
def updateUserAvatar(request):
"""
修改头像
"""
if request.method == "PUT":
obj = verification.update_user_verification(json.loads(request.body))
if obj.is_valid():
data = obj.clean()
userData = get_user_info(request)
models.Users.objects.filter(id=userData.get('id')).update( avatar = data['avatar'])
# activity_ids = list(models.Activitys.objects.filter(status=1, deleted_at=None).values_list('id', flat=True))
# all_activity_ids = list(models.Activitys.objects.filter(deleted_at=None).values_list('id', flat=True))
user = serializers.UserListSerializer(models.Users.objects.filter(id=userData['id']).first(),many=False)
return JsonResponse(ResponseFactory(code=200, message="修改成功", data=user.data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
class MyActivitys(APIView):
"""
我参与的活动
"""
@method_decorator(AuthPermissionRequired())
def get(self, request):
user_id = get_user_info(request)['id']
ids = models.ActivityHasUsers.objects.filter(user_id=user_id,deleted_at=None).order_by('-created_at').values_list('activity_id',flat=True).distinct()
activity_id_str = ",".join('%s' % id for id in ids)
queryset = models.Activitys.objects.filter(id__in=ids,deleted_at=None).extra(select={'m':'FIELD(id,{})'.format(activity_id_str)},order_by=['m'])
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.MyActivitysSerializer(page_data, many=True,context={"user_id":user_id})
data = {"activitys":ser_obj.data,"count":queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
@AuthPermissionRequired()
def SaveOrSubmitList(request):
"""
查看参加活动详情:提交的与保存的demo
"""
if request.method == "GET":
a_id = request.GET['activity_id']
user_id = get_user_info(request)['id']
activity =serializers.ActivitysSerializer(models.Activitys.objects.filter(id=a_id,deleted_at=None),many=True,context={'user_id':user_id})
queryset = models.ActivityHasUsers.objects.filter(user_id=user_id,activity_id=a_id,deleted_at=None).order_by('-created_at')
ser_obj = serializers.ManyActivitysHasUserSerializer(queryset, many=True)
#增加自主报价信息
price_set = models.ActivityUserHasPrices.objects.filter(user_id=user_id,activity_id=a_id).first()
if price_set:self_price = serializers.ActivitysPriceSerializer(price_set,many=False,context={'activity_id':a_id}).data
else:self_price = None
data = {'data':{'activity':activity.data,'list':ser_obj.data,"self_price":self_price}}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def V2SaveOrSubmitList(request):
"""
查看参加活动详情:提交的与保存的demo
"""
if request.method == "GET":
a_id = request.GET['activity_id']
user_id = get_user_info(request)['id']
activity =serializers.ActivitysSerializer(models.Activitys.objects.filter(id=a_id,deleted_at=None).first(),many=False,context={'user_id':user_id})
queryset = models.ActivityHasUsers.objects.filter(user_id=user_id,activity_id=a_id,deleted_at=None).order_by('-created_at')
ser_obj = serializers.ManyActivitysHasUserSerializer(queryset, many=True)
# 增加自主报价信息
price_set = models.ActivityUserHasPrices.objects.filter(user_id=user_id, activity_id=a_id).first()
if price_set:self_price = serializers.ActivitysPriceSerializer(price_set, many=False,context={'activity_id':a_id}).data
else:self_price = None
data = {'activity':activity.data,'list':ser_obj.data,"self_price":self_price}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def UpdateSumbit(request):
"""
更新提交的版本
"""
if request.method == "PUT":
userData = get_user_info(request)
try:
# 检查是否有提交权限
permission = user_permission(userData['id'])
if 2 not in permission:
return JsonResponse(ResponseFactory(code=400, message='用户无此权限', data=None, status='fail'))
put_data = json.loads(request.body)
is_hide = put_data.get('is_hide', None)
obj = verification.update_submit_verification(put_data)
if obj.is_valid():
data = obj.clean()
self_price = put_data.get('self_price', None)
if is_hide == None:
ahu = models.ActivityHasUsers.objects.filter(type='Submit', user_id=userData.get('id'),activity_id=data.get('activity_id')).last()
is_hide = ahu.is_hide if ahu else 1
# 校验自主报价参数
if self_price:
ver = verification.SubmitPriceVerification(data=self_price)
if not ver.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(ver), data=None, status='fail'))
if self_price['value']['amounts']:
if not (0 <= self_price['value']['amounts'] <= 9999999): return JsonResponse(
ResponseFactory(code=201, message="金额在0-9999999之间", data=None, status='fail'))
if self_price['value']['ratio']:
if not (0 <= self_price['value']['ratio'] <= 100): return JsonResponse(
ResponseFactory(code=201, message="分成比列在0%-100%之间", data=None, status='fail'))
#查看活动状态
activity = models.Activitys.objects.get(id=data.get('activity_id'))
if activity.status != 1:
return JsonResponse(ResponseFactory(code=400, message="活动已完成或下架", data=None, status='fail'))
try:
try:
vx_code = put_data.get("vx_code","")
open_id, unionid = WeChatApi(vx_code)
except:
open_id = ''
with transaction.atomic():
models.ActivityHasUsers.objects.filter(activity_id=data.get('activity_id'),user_id=userData.get('id')).update(type='Save',updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
updateItem = models.ActivityHasUsers.objects.filter(id=data.get('has_id'))
updateItem.update(
type='Submit',
is_hide = is_hide,
open_id = open_id,
submit_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
# 存入自主报价
if self_price:
models.ActivityUserHasPrices.objects.update_or_create(
activity_id = data.get('activity_id'), user_id= userData.get('id'),
defaults={
"value":self_price['value'],
"is_deduct":self_price['is_deduct'],
"is_talk":self_price['is_talk'],
"address_id":self_price['address_id'],
"is_accept_address":self_price['is_accept_address'],
"created_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
"updated_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S"),},
)
#更新到动态
is_tidings = put_data.get("is_tidings", 0)
if is_tidings == 1:
url = updateItem.first().demo_url
if url:
models.UserHasTidings.objects.create(user_id=userData['id'],activity_id=data.get('activity_id'),type=2,url=url, created_at = timezone.now().strftime("%Y-%m-%d %H:%M:%S"),updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
else:
return JsonResponse(ResponseFactory(code=201, message="保存音频处理中,请5秒后再提交", data=None, status='fail'))
#提交作品计数 1.先检查用户对该作品之前是否有提交且未读的消息
user_msg = models.UserMessages.objects.filter(is_read=0,sender_id=userData['id'],activity_id=data.get('activity_id'),deleted_at=None,type=3)
if user_msg:
user_msg.update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
# 获取全体管理员和推荐人open_id
project_id = models.Activitys.objects.filter(id=data['activity_id']).first().project_id
project = models.Projects.objects.filter(id=project_id).first()
project_user_ids = []
if project:
if project.is_public:project_user_ids = list(models.UserHasProjects.objects.filter(project_id=project_id).values_list('user_id',flat=True))
else:project_user_ids = [models.Activitys.objects.filter(id=data['activity_id']).first().user_id]
project_user_unionid = list(models.Users.objects.filter(id__in=project_user_ids, deleted_at=None, status=1).values_list('unionid', flat=True))
admin_unionid = list(models.Users.objects.filter(scope=1,deleted_at=None,status=1).values_list('unionid', flat=True))
push_open_ids = list(models.WechatOfficialUsers.objects.filter(union_id__in=admin_unionid + project_user_unionid,is_subscribe=1).values_list('open_id', flat=True))
song_name = models.Activitys.objects.filter(id=data['activity_id']).first().song_name
# 再创建消息
business_id = userData['business_id']
if business_id:
# 获取推荐人公众号open_id
unionid = models.Users.objects.filter(id=business_id).values_list('unionid', flat=True)
wechat_official = models.WechatOfficialUsers.objects.filter(union_id__in=unionid, is_subscribe=1).last()
if wechat_official:
# 公众号推送
p_data = {'channel': 'singer_related', 'open_id': [wechat_official.open_id],
'data': {"title": "您的歌手参加了试唱歌曲",
"name": userData['nick_name'] + "("+userData['real_name']+")",
"intro": "参加了试唱歌曲《{}》".format(song_name),
"remark": "点击前往 >",
"page": "/packageMy/pages/like?tab=2"}}
pushSubscribeMessage(p_data)
# 发给绑定的推荐人
m_data = {'sender_id': userData['id'], 'receivers': [business_id],
'activity_id': data['activity_id'], 'type': 3, 'is_bind': 1}
#之前的提交消息设为已读
models.UserMessages.objects.filter(is_read=0,activity_id=data['activity_id'],type=3,receiver_id=business_id,deleted_at=None,is_bind=1).update(is_read=1)
#创建新的未读消息
createMessage(m_data)
# 极光推送-提交作品推荐人
j_title = "您的歌手参加了试唱"
j_content = "您的歌手{}参加了试唱活动《{}》".format(userData['nick_name'], song_name)
jdata = {"title": j_title, "content": j_content, "content_type": "text",
"receiver_value": [business_id],
"extras": {"type": "ToTaSing", "value": ""}}
JPush().jpush_v3(jdata)
# 给全体管理员和项目管理员推服务号消息
p_data = {'channel': 'activity_join', 'open_id': push_open_ids,
'data': {"first": "{}({})提交了试唱作品".format(userData['nick_name'], userData['real_name']),
"keyword1": "《"+song_name+"》",
"keyword2": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
"remark": "点击试听 >","page":"/pages/index/index"}
}
pushSubscribeMessage(p_data)
# 外部管理员id
activity_manage_ids = list(
models.UserManageActivitie.objects.filter(activity_id=data['activity_id']).values_list(
'user_id', flat=True))
# 发送系统消息(平台管理员+项目管理员+外部管理员)
receivers = list(models.Users.objects.filter(scope=1).values_list('id', flat=True))
receivers = list(set(receivers + project_user_ids +activity_manage_ids))
m_data = {'sender_id': userData['id'], 'receivers': receivers, 'activity_id': data['activity_id'],
'type': 3, 'is_bind': 0}
# 之前的提交消息设为已读
models.UserMessages.objects.filter(is_read=0, activity_id=data['activity_id'], type=3,receiver_id__in=receivers, deleted_at=None, is_bind=0).update(is_read=1)
# 创建新的未读消息
createMessage(m_data)
# 极光推送-提交作品全体管理员
j_title = "有新用户提交试唱"
j_content = "{}参与了试唱《{}》".format(userData['nick_name'], song_name)
jdata = {"title": j_title, "content": j_content, "content_type": "text",
"receiver_value": receivers,
"extras": {"type": "ToPlatfromSing", "value": ""}}
JPush().jpush_v3(jdata)
except Exception as e:
logger.info('提交异常:用户ID:{},参数:{},错误信息:{}'.format(userData['id'], request.body, e))
return JsonResponse(ResponseFactory(code=201, message="修改失败:{}".format(e), data=None, status='fail'))
#积分逻辑(区分全曲还是片段)
sing_type = updateItem.first().sing_type
if sing_type == 'Part':
# 歌手积分
user_point_record(user_id=userData['id'], type='SubmitPart', activity_id=data['activity_id'])
# 推荐人积分
if userData['business_id']:
user_point_record(user_id=userData['business_id'], type='SingerSubmitPart',activity_id=data['activity_id'],singer_id=userData['id'])
else:
# 歌手积分
user_point_record(user_id=userData['id'], type='SubmitFull', activity_id=data['activity_id'])
# 推荐人积分
if userData['business_id']:
user_point_record(user_id=userData['business_id'], type='SingerSubmitFull',activity_id=data['activity_id'],singer_id=userData['id'])
return JsonResponse(ResponseFactory(code=200, message="修改成功", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
except Exception as e:
logger.info('提交异常:用户ID:{},参数:{},错误信息:{}'.format(userData['id'], request.body,e))
return JsonResponse(ResponseFactory(code=201, message="修改失败:{}".format(e), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
class AdminActivitys(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
"""管理员查看试唱"""
user = get_user_info(request)
user_id = user['id']
scope = user['scope']
kwargs = {"status":1,"deleted_at":None}
text = request.GET.get('text','')
if text:kwargs['song_name__icontains'] = text
activity_ids = list(models.ActivityHasUsers.objects.filter(user__deleted_at=None,user__status=1,type='Submit',deleted_at=None).order_by('-created_at').values_list('activity_id',flat=True))
#去重保序
activity_ids2 = list(set(activity_ids))
activity_ids2.sort(key=activity_ids.index)
idList = ",".join('%s' % id for id in activity_ids2)
kwargs['id__in'] = activity_ids2
if scope == 2:
project_ids = list(models.UserHasProjects.objects.filter(user_id=user_id).values_list('project_id', flat=True))
kwargs['project_id__in'] = project_ids
#过滤掉不相关的活动,去掉不公开的厂牌下活动不是自己创建的活动
nopublic_project_id = list(models.Projects.objects.filter(id__in=project_ids,is_public=0,deleted_at=None).values_list('id',flat=True))
noself_activity_id = list(models.Activitys.objects.filter(project_id__in=nopublic_project_id, status=1,deleted_at=None).exclude(user_id=user_id).values_list('id', flat=True))
ret = [x for x in activity_ids if x not in noself_activity_id]
kwargs['id__in'] = ret
queryset = models.Activitys.objects.filter(**kwargs).select_related('project').extra(select={'m':'FIELD(activitys.id,{})'.format(idList)},order_by=['m'])
# # #获取所有活动
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
for page in page_data:
page.ahus = models.ActivityHasUsers.objects.select_related('user__business').filter(type='Submit',activity_id=page.id,deleted_at=None).order_by('-created_at')\
.extra(select={'share_user_nick_name':'SELECT users.nick_name FROM activity_share_users LEFT JOIN users ON activity_share_users.share_id=users.id WHERE activity_share_users.activity_id = activity_has_users.activity_id and activity_share_users.user_id=activity_has_users.user_id',
'share_user_real_name':'SELECT users.real_name FROM activity_share_users LEFT JOIN users ON activity_share_users.share_id=users.id WHERE activity_share_users.activity_id = activity_has_users.activity_id and activity_share_users.user_id=activity_has_users.user_id',
})
ser_obj = serializers.PlatfromAuditionSerializer(page_data, many=True, context={"user_id": user_id})
data = {"activitys": ser_obj.data, "count": queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
@AuthPermissionRequired()
def AdminSubmitList(request):
"""
管理员查看参加活动详情:提交的与demo
"""
if request.method == "GET":
a_id = request.GET['activity_id']
user_id = get_user_info(request)['id']
activity =serializers.ActivitysSerializer( models.Activitys.objects.filter(id=a_id,deleted_at=None),many=True,context={'user_id':user_id})
queryset = models.ActivityHasUsers.objects.filter(activity_id=a_id,type='Submit',deleted_at=None).order_by('-created_at')
ser_obj = serializers.ManyActivitysHasUserSerializer(queryset, many=True)
data = {'data':{'activity':activity.data,'list':ser_obj.data}}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def V2AdminSubmitList(request):
"""
管理员查看参加活动详情:提交的与demo
"""
if request.method == "GET":
a_id = request.GET['activity_id']
user_id = get_user_info(request)['id']
activity =serializers.ActivitysSerializer( models.Activitys.objects.filter(id=a_id,deleted_at=None).first(),many=False,context={'user_id':user_id})
queryset = models.ActivityHasUsers.objects.filter(activity_id=a_id,type='Submit',deleted_at=None).order_by('-created_at')
ser_obj = serializers.ManyActivitysHasUserSerializer(queryset, many=True)
data = {'activity':activity.data,'list':ser_obj.data}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def SubmitExamine(request):
"""
再次提交审核
:param request:
:return:
"""
if request.method == "POST":
user = get_user_info(request)
post_data = json.loads(request.body)
role = user['role']
if role == "Singer":
obj = verification.singer_submit_examine_verification(post_data)
elif role == "Business":
obj = verification.business_submit_examine_verification(post_data)
if obj.is_valid():
obj = obj.clean()
#判断该用户是否存在待审核的数据
is_examines = models.UserExamines.objects.filter(user_id=user.get('id'),status=0,deleted_at=None).exists()
if is_examines:
return JsonResponse(ResponseFactory(code=201, message="已提交审核,请勿重复申请", data=None, status='fail'))
# 获取小程序openid
try:
vx_code = post_data.get("vx_code")
open_id, unionid = WeChatApi(vx_code)
except:
open_id = ''
if role == "Singer":
user_info = {"email": obj.get("email"), "phone": user.get("phone"),
"nick_name": obj.get("nick_name"),
"remarks": post_data.get('remarks', ''),
"business_id": post_data.get("business_id",None), "role": role,
"province": obj.get("province"), "city": obj.get("city"),
"is_referee": obj.get("is_referee"), "real_name": obj.get("real_name"),
"created_at": timezone.now().strftime("%Y-%m-%d %H:%M:%S")}
elif role == 'Business':
user_info = {"email": obj.get("email"), "phone": user.get("phone"),
"nick_name": obj.get("nick_name"), "role": role, "real_name": obj.get("real_name"),
"company": obj.get("company"),
"created_at": timezone.now().strftime("%Y-%m-%d %H:%M:%S")}
try:
with transaction.atomic():
# 生成待审核信息
models.UserExamines.objects.create(
user_id=user.get('id'),
type = role,
admin_id=0,
open_id = open_id,
user_info = user_info,
business_id=obj.get("business_id", 0),
status=0,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
#修改用户信息
models.Users.objects.filter(id=user.get('id')).update(
audit_status=0,
nick_name = obj.get("nick_name"),
real_name = obj.get("real_name"),
is_referee = obj.get("is_referee", None),
province = obj.get("province", ""),
city = obj.get("city", ""),
company = obj.get("company", ""),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
return JsonResponse(ResponseFactory(code=200, message="提交成功", data=None, status='success'))
except Exception as e:
return JsonResponse(ResponseFactory(code=400, message="提交失败:{}".format(e), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def V2SubmitExamine(request):
"""
再次提交审核
:param request:
:return:
"""
if request.method == "POST":
user = get_user_info(request)
post_data = json.loads(request.body)
role = user['role']
if role == "Singer":
obj = verification.v2_singer_submit_examine_verification(post_data)
else:
obj = verification.v2_business_submit_examine_verification(post_data)
if obj.is_valid():
obj = obj.clean()
#判断该用户是否存在待审核的数据
is_examines = models.UserExamines.objects.filter(user_id=user.get('id'),status=0,deleted_at=None).exists()
if is_examines:
return JsonResponse(ResponseFactory(code=201, message="已提交审核,请勿重复申请", data=None, status='fail'))
# 判断邮箱格式正确且唯一
reg = "\w+[@][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)+"
valid = re.findall(reg, obj.get("email"))
re_email = models.Users.objects.filter(~Q(id=user['id']),email=obj.get("email"), deleted_at=None).exists()
if re_email or not valid:
return JsonResponse(ResponseFactory(code=400, message="邮箱已被注册或格式不正确", data=None, status='fail'))
# 获取小程序openid
try:
vx_code = post_data.get("vx_code","")
open_id, unionid = WeChatApi(vx_code)
except:
open_id = ''
if role == "Singer":
user_info = {"email": obj.get("email"), "phone": user.get("phone"),
"nick_name": obj.get("nick_name"),
"remarks": post_data.get('remarks', ''),
"sound":post_data.get('sound', ''),
"business_id": post_data.get("business_id",None), "role": role,
"is_referee": post_data.get("is_referee",None), "real_name": obj.get("real_name"),
"created_at": timezone.now().strftime("%Y-%m-%d %H:%M:%S")}
else:
user_info = {"email": obj.get("email"), "phone": user.get("phone"),
"nick_name": obj.get("nick_name"), "role": role, "real_name": obj.get("real_name"),
"company": obj.get("company"),
"created_at": timezone.now().strftime("%Y-%m-%d %H:%M:%S")}
try:
with transaction.atomic():
# 生成待审核信息
models.UserExamines.objects.create(
user_id=user.get('id'),
type = role,
admin_id=0,
open_id = open_id,
user_info = user_info,
business_id=post_data.get("business_id", 0),
status=0,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
#修改用户信息
models.Users.objects.filter(id=user.get('id')).update(
audit_status=0,
nick_name = obj.get("nick_name"),
real_name = obj.get("real_name"),
is_referee = obj.get("is_referee", None),
company = obj.get("company", None),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
return JsonResponse(ResponseFactory(code=200, message="提交成功", data=None, status='success'))
except Exception as e:
return JsonResponse(ResponseFactory(code=400, message="提交失败:{}".format(e), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def SetUserTags(request):
"""
设置用户标签
"""
if request.method == "PUT":
obj = verification.user_tags_verification(json.loads(request.body))
if obj.is_valid():
tag_ids = json.loads(request.body)['tags']
user = get_user_info(request)
#删除以前的标签设置
models.UserHasTags.objects.filter(user_id=user.get('id'),deleted_at=None).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
if len(tag_ids) == 0:
return JsonResponse(ResponseFactory(code=400, message='至少选择一个标签', data=None, status='fail'))
for tag_id in tag_ids:
models.UserHasTags.objects.create(
user_id=user.get('id'),
tag_id = tag_id,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
return JsonResponse(ResponseFactory(code=200, message="设置成功", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
def getUserTag(request):
"""
获取所有标签和用户标签
"""
if request.method == "GET":
type = request.GET.get('type',1)
orderbyList = ['-weight', '-created_at']
allTag = serializers.SystemTagsSerializer(models.SystemTags.objects.filter(type=type,deleted_at=None).order_by(*orderbyList),many=True)
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=allTag.data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def unbind(request):
"""
解绑微信
:return:
"""
if request.method == "PUT":
user = get_user_info(request)
models.Users.objects.filter(id=user.get('id')).update(unionid='', open_id='', updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
return JsonResponse(ResponseFactory(code=200, message="解绑成功", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def bind(request):
"""
重新绑定微信
:return:
"""
if request.method == "POST":
post_data = json.loads(request.body)
obj = verification.bind_verification(post_data)
if obj.is_valid():
obj = obj.clean()
platform = post_data.get('platform','')
if platform == 'app':
open_id, unionid = AppWechatApi(obj.get("vx_code"))
else:
open_id, unionid = WeChatApi(obj.get("vx_code"))
user = get_user_info(request)
models.Users.objects.filter(id=user.get('id')).update(unionid=unionid, open_id=open_id,updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
return JsonResponse(ResponseFactory(code=200, message="换绑成功", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
class MySinget(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
user = get_user_info(request)
text = request.GET.get('text', '')
if text :
queset = models.Users.objects.filter(business_id=user.get('id'),nick_name__icontains=text,audit_status=1,status=1,deleted_at=None).order_by('-created_at')
else:
queset = models.Users.objects.filter(business_id=user.get('id'),audit_status=1,status=1,deleted_at=None).order_by('-created_at')
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queset, request)
serializer = serializers.MySingerSerializer(page_data, many=True,context={"user_id":user['id'] })
data = {"data":serializer.data,"count":queset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data= data, status='success'))
class SingerInfo(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
singer_id = request.GET['singer_id']
user_id = get_user_info(request)['id']
data = serializers.MySingerSerializer(models.Users.objects.filter(id=singer_id).first(), many=False,context={"user_id": user_id}).data
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
@method_decorator(AuthPermissionRequired())
def put(self,request):
obj = verification.singer_update(json.loads(request.body))
logger.info(obj)
if obj.is_valid():
obj = obj.clean()
singer_id = obj.get('singer_id')
company = obj.get('company')
rate = obj.get('rate')
models.Users.objects.filter(id=singer_id).update(rate=rate,company=company)
return JsonResponse(ResponseFactory(code=200, message="更新成功", data=None, status='success'))
else:
return JsonResponse(
ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
class SingerInfoV2(APIView):
@method_decorator(AuthPermissionRequired())
def put(self,request):
put_data = json.loads(request.body)
try:obj = verification.singer_updatev2(put_data)
except:return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
logger.info(obj)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
obj = obj.clean()
singer_id = obj.get('singer_id')
company = put_data.get('company','')
rate = put_data.get('rate','')
chat_mode = obj.get('chat_mode')
is_all = obj.get('is_all')
user_id = get_user_info(request)['id']
if chat_mode:
title = '您的私聊模式已改为“队长代理沟通”'
content = '如有疑问,请和队长沟通'
else:
title = '您的私聊模式已改为“成员自主沟通”'
content = '您可以自主进行私聊啦~'
models.Users.objects.filter(id=singer_id).update(rate=rate, company=company)
if not is_all:
models.Users.objects.filter(id=singer_id).update(chat_mode=chat_mode)
# 创建消息
m_data = {"title": title, "content": content, 'receivers': [singer_id], "activity_id": singer_id,
'sender_id': user_id, 'type': 11}
else:
models.Users.objects.filter(business_id=user_id,deleted_at=None).update(chat_mode=chat_mode)
all_singer_id = list(models.Users.objects.filter(business_id=user_id,deleted_at=None).values_list('id',flat=True))
# 创建消息
m_data = {"title": title, "content": content, 'receivers': all_singer_id, "activity_id": singer_id,
'sender_id': user_id, 'type': 11}
createMessage(m_data)
return JsonResponse(ResponseFactory(code=200, message="更新成功", data=None, status='success'))
class SingerAvtivity(APIView):
@method_decorator(AuthPermissionRequired())
def get(self, request):
singer_id = request.GET['singer_id']
ids = models.ActivityHasUsers.objects.filter(user_id=singer_id,type='Submit',deleted_at=None).values_list('activity_id', flat=True).distinct().order_by('-created_at')
queryset = models.Activitys.objects.filter(id__in=ids)
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.MySingerActivitysSerializer(page_data, many=True, context={"user_id": singer_id})
data = {"activitys": ser_obj.data, "count": queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class SingerComplete(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
singer_id = request.GET['singer_id']
ids = models.ActivityHasUsers.objects.filter(user_id=singer_id, type='Submit',status=1, deleted_at=None).values_list('activity_id', flat=True).distinct().order_by('-updated_at')
activity_id_str = ",".join('%s' % id for id in ids)
queryset = models.Activitys.objects.filter(id__in=ids).extra(select={'m':'FIELD(id,{})'.format(activity_id_str)},order_by=['m'])
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.SingerCompleteSerializer(page_data, many=True, context={"user_id": singer_id})
data = {"activitys": ser_obj.data, "count": queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class AvtivityDetail(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
singer_id = request.GET['singer_id']
activity_id = request.GET['activity_id']
activity = serializers.SingerActivitysSerializer(models.Activitys.objects.filter(id=activity_id, deleted_at=None).first(), many=False,context={'singer_id': singer_id})
queryset = models.ActivityHasUsers.objects.filter(user_id=singer_id, activity_id=activity_id,deleted_at=None).order_by('-created_at')
ser_obj = serializers.ManyActivitysHasUserSerializer(queryset, many=True)
data = {'activity': activity.data, 'list': ser_obj.data}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
@AuthPermissionRequired()
def banners(request):
if request.method == 'GET':
user = get_user_info(request)
# sql = """ SELECT * FROM banners where type=2 and status=1 and deleted_at is null and
# json_contains(banners.role,CONCAT('"',"{}",'"'))
# and json_contains(banners.scope,JSON_Array({})) ORDER BY `weight` DESC,`created_at` DESC """.format(user['role'],user['scope'])
sql = """ SELECT * FROM banners where scope=2 and status=1 and deleted_at is null and
json_contains(banners.role,CONCAT('"',"{}",'"'))
ORDER BY `weight` DESC,`created_at` DESC """.format(user['role'])
queset = models.Banners.objects.raw(sql)
ser = serializers.BanneraSerializer(queset,many=True)
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=ser.data, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
class Listen(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
user_id = get_user_info(request)['id']
activity_ids = list(models.UserViewActivity.objects.filter(user_id=user_id, deleted_at=None).values_list('activity_id',flat=True).order_by('-updated_at'))
activity_id_str = ",".join('%s' % id for id in activity_ids)
queset = models.Activitys.objects.filter(id__in=activity_ids,deleted_at=None).extra(select={'m':'FIELD(id,{})'.format(activity_id_str)},order_by=['m'])
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queset, request)
ser = serializers.ListenActivitysSerializer(page_data,many=True,context={"user_id": user_id})
data = {"activitys": ser.data, "count":queset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class TaCollection(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
user_id = get_user_info(request)['id']
#获取关联的歌手id
singer_ids = list(models.Users.objects.filter(business_id=user_id,deleted_at=None).values_list('id',flat=True))
#获取歌手收藏的活动id
activity_ids = list(models.UserActivityCollections.objects.filter(user_id__in=singer_ids,deleted_at=None).values_list('activity_id',flat=True).order_by('-created_at'))
activity_ids = dedupe(activity_ids)
activity_id_str = ",".join('%s' % id for id in activity_ids)
queset = models.Activitys.objects.filter(id__in=activity_ids ,status=1, deleted_at=None).extra(select={'m': 'FIELD(id,{})'.format(activity_id_str)}, order_by=['m'])
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queset, request)
ser = serializers.ActivitysCollectionSerializer(page_data, many=True, context={"singer_ids": singer_ids,"user_id":user_id})
data = {"activitys": ser.data, "count": queset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class TaAudition(APIView):
@method_decorator(AuthPermissionRequired())
def get(self, request):
user_id = get_user_info(request)['id']
# 获取关联的歌手id
singer_ids = list(models.Users.objects.filter(business_id=user_id, deleted_at=None).values_list('id', flat=True))
# 获取歌手提交的活动id
activity_ids = list(models.ActivityHasUsers.objects.filter(user_id__in=singer_ids,type='Submit',deleted_at=None).values_list('activity_id', flat=True).order_by('-created_at'))
activity_ids = dedupe(activity_ids)
activity_id_str = ",".join('%s' % id for id in activity_ids)
queset = models.Activitys.objects.filter(id__in=activity_ids, status=1,deleted_at=None).extra(select={'m': 'FIELD(id,{})'.format(activity_id_str)}, order_by=['m'])
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queset, request)
for page in page_data:
page.ahus = models.ActivityHasUsers.objects.select_related('user__business').filter(user_id__in=singer_ids,type='Submit',activity_id=page.id,deleted_at=None).order_by('-created_at')
ser = serializers.ActivitysSubmitUserSerializer(page_data, many=True, context={"singer_ids": singer_ids,"user_id":user_id})
data = {"activitys": ser.data, "count": queset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class ResumeLike(APIView):
@method_decorator(AuthPermissionRequired())
def put(self,request):
put_data = json.loads(request.body)
user_id = get_user_info(request)['id']
activity_id = put_data['activity_id']
obj = models.UserActivityUnlikes.objects.filter(user_id=user_id,activity_id=activity_id,deleted_at=None)
if obj:
obj.update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
return JsonResponse(ResponseFactory(code=200, message="恢复成功", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=201, message="不存在数据", data=None, status='fail'))
@AuthPermissionRequired()
def remove_save(request):
if request.method in ['PUT','DELETE','POST']:
put_data = json.loads(request.body)
models.ActivityHasUsers.objects.filter(id=put_data.get('id')).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
return JsonResponse(ResponseFactory(code=200, message="删除成功", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def editor(request):
if request.method == 'PUT':
put_data = json.loads(request.body)
obj = verification.EditorUser(data=put_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
user = get_user_info(request)
if user['audit_status'] != 1:
return JsonResponse(ResponseFactory(code=201, message="审核未通过,不允许编辑", data=None, status='fail'))
if put_data == {}:
return JsonResponse(ResponseFactory(code=201, message="参数为空", data=None, status='fail'))
#可更新字段
field_list = ['nick_name','email','city','avatar','province','company','rate','intro','cover','sex','art_tag','style_tag','wechat_account']
for key,value in put_data.items():
# if not value:
# return JsonResponse(ResponseFactory(code=201, message="值不能为空", data=None, status='fail'))
if key in field_list:
if key == 'email':#验证邮箱是否唯一且有效
reg = "\w+[@][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)+"
valid = re.findall(reg, value)
is_exists = models.Users.objects.filter(email=value,deleted_at=None).exclude(id=user['id']).exists() #过滤当前用户,查看邮箱是否重复
if valid and not is_exists:
pass
else:
return JsonResponse(ResponseFactory(code=201, message="邮箱已注册或格式不正确", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=201, message="不支持字段{}的更新".format(key), data=None, status='fail'))
for key,value in put_data.items():
if key in ['art_tag','style_tag']:
type = 2 if key == 'art_tag' else 1
# 删除之前的用户嗓音标签
models.UserTagRelations.objects.filter(user_id=user['id'], type=type).delete()
# 创建新的用户嗓音标签
for tag in value:
models.UserTagRelations.objects.create(user_id=user['id'], type=type, tag_id=tag,created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
else:
models.Users.objects.filter(id=user['id'], deleted_at=None).update(**{key: value})
return JsonResponse(ResponseFactory(code=200, message="更新成功", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def ConfirmSinger(request):
"""
确认合作歌手
:param request:
:return:
"""
if request.method != 'POST':
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
put_data = json.loads(request.body)
obj = verification.ConfirmSingerVerify(put_data)
if obj.is_valid():
singer_id = obj.clean().get('singer_id')
status = obj.clean().get('status')
activity_id = obj.clean().get('activity_id')
remark = put_data.get('weixin_code',"")
ahu = models.ActivityHasUsers.objects.filter(user_id=singer_id, activity_id=activity_id, type='Submit',status=0, deleted_at=None)
if not ahu:
return JsonResponse(ResponseFactory(code=400, message="不支持的数据,请刷新重试", data=None, status='fail'))
work_id = str(ahu.last().id)
url = "{domain}/app/admin/activity/{work_id}/confirm".format(domain=settings.SERVICE_DOMAOIN,work_id=work_id)
payload = {"status":status,"remark":remark}
headers = {
'Content-Type': 'application/json',
'Authorization': request.META.get('HTTP_AUTHORIZATION')
}
resp = requests.request("POST", url, headers=headers, json=payload)
return JsonResponse(ResponseFactory(code=resp.json()['code'], message=resp.json()['message'], data=None, status=resp.json()['status']))
@AuthPermissionRequired()
def UserDelete(request):
if request.method == 'DELETE':
user_id = get_user_info(request)['id']
try:
with transaction.atomic():
#删除用户提交,保存的作品
# models.ActivityHasUsers.objects.filter(user_id=user_id,deleted_at=None).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
#修改关联歌手聊天设置,解绑歌手
has_singers = models.Users.objects.filter(business_id=user_id)
if has_singers:has_singers.update(chat_mode=0, business_id=None)
# 删除用户的信息记录
models.UserMessages.objects.filter(sender_id=user_id,deleted_at=None).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
#解除经纪人关联
business = models.Users.objects.filter(id=user_id).first()
if business:business_id = business.business_id
else:business_id = 0
business = models.Users.objects.filter(id=business_id).first()
if business:
models.Users.objects.filter(id=user_id).update(business_id=None)
singer_tag_id = models.SystemConfig.objects.get(identifier='auth_singer_tag').content
business_has_user =list(models.Users.objects.filter(business_id=business_id,status=1,deleted_at=None).exclude(id=user_id).values_list('id',flat=True))
is_has_singer = models.UserTagRelations.objects.filter(user_id__in=business_has_user,tag_id=singer_tag_id,type=4).exists()
if not is_has_singer:
identity = 1 if business.identity in [1, 3] else 0
else:
identity = 3 if business.identity in [1, 3] else 2
models.Users.objects.filter(id=business_id).update(identity=identity)
# 删除待认证信息
models.UserAuthInfos.objects.filter(user_id=user_id).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
#用户入团申请,邀请信息改为失效
models.GorupInvites.objects.filter(invite_id=user_id).update(status=4)
models.GorupInvites.objects.filter(user_id=user_id).update(status=4)
#是否存在团
query = models.GroupHasMembers.objects.filter(member_id=user_id,deleted_at=None).first()
if query:
#是否是团长,团长注销删除团队
is_master = models.GroupHasMembers.objects.filter(member_id=user_id,role=1, deleted_at=None).exists()
#成员数少于2人,删除团队
member_count = models.GroupHasMembers.objects.filter(group_id=query.group_id,deleted_at=None).count()
# 删除成员
models.GroupHasMembers.objects.filter(member_id=user_id, deleted_at=None).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
if (member_count <= 2 or is_master ):
models.Users.objects.filter(business_id=business_id).update(business_id=None)
models.Groups.objects.filter(id=query.group_id).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
models.GroupHasMembers.objects.filter(group_id=query.group_id, deleted_at=None).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
# 删除用户信息
models.Users.objects.filter(id=user_id).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
return JsonResponse(ResponseFactory(code=200, message="注销完成", data=None, status='success'))
except Exception as e:
return JsonResponse(ResponseFactory(code=201, message='操作失败,请联系管理员', data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
@AuthPermissionRequired()
def change_phone(request):
if request.method == 'PUT':
put_data = json.loads(request.body)
obj = verification.ChangePhoneVrify(put_data)
if obj.is_valid():
obj = obj.clean()
user = get_user_info(request)
if user['phone'] == obj.get("phone"):
return JsonResponse(ResponseFactory(code=204, message="新手机号码不能与之前手机号码一致", data=None, status='fail'))
check_user = models.Users.objects.filter(phone=int(obj.get("phone")), deleted_at=None).first()
if check_user:
return JsonResponse(ResponseFactory(code=204, message="手机号已被使用", data=None, status='fail'))
mob = caches['default'].get(f'voteapp: polls:valid: {obj.get("phone")}')
is_dev = int(obj.get('sms_code')) == 123456 and settings.ENV == 'dev'
if mob == int(obj.get('sms_code')) or is_dev:
models.Users.objects.filter(id=user['id']).update(phone=obj.get("phone"),area_code=obj.get("area_code"))
caches['default'].delete(f'paopao: polls:valid: {obj.get("phone")}')
return JsonResponse(ResponseFactory(code=200, message="更换成功", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=204, message="验证码错误", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
class UserPoint(APIView):
@method_decorator(AuthPermissionRequired())
def put(self,request):
"""
微信分享积分
:param request:
:return:
"""
user_id = get_user_info(request)['id']
user_point_record(user_id,type='ShareSong')
return JsonResponse(ResponseFactory(code=200, message="操作成功", data=None, status='success'))
def sharechildlist(request):
identifier = request.GET['identifier']
parentobj = models.SystemConfig.objects.filter(identifier=identifier,status=1,deleted_at=None).first()
if parentobj:
data = serializers.SystemConfigSerializer(models.SystemConfig.objects.filter(parent_id=parentobj.id,status=1,deleted_at=None).order_by('-weight'),many=True).data
else:
data = None
if identifier == 'year_limit':
#获取分成年限的时候把较高分成比列也返回
high_ratio_obj = models.SystemConfig.objects.filter(identifier='high_ratio',status=1,deleted_at=None).first()
high_ratio = serializers.SystemConfigSerializer(high_ratio_obj, many=False).data
data = {"year_limit":data,"high_ratio":high_ratio}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
def sharechild(request):
identifier = request.GET['identifier']
childobj = models.SystemConfig.objects.filter(identifier=identifier,status=1,deleted_at=None).first()
if childobj:
data = serializers.SystemConfigSerializer(childobj,many=False).data
else:
data = None
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class UserSound(APIView):
@method_decorator(AuthPermissionRequired())
def put(self,request):
put_data = json.loads(request.body)
obj = verification.UserSound(data=put_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
user = get_user_info(request)
user_id = user['id']
data = obj.data
sound_url = data['sound_url']
tags = data['tags']
try:
with transaction.atomic():
models.Users.objects.filter(id=user_id).update(sound=sound_url,sound_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
#删除之前的用户嗓音标签
models.UserTagRelations.objects.filter(user_id=user_id, type=3).delete()
#创建新的用户嗓音标签
if tags:
for tag in tags:
models.UserTagRelations.objects.create(user_id=user_id,type=3,tag_id=tag, created_at = timezone.now().strftime("%Y-%m-%d %H:%M:%S"),updated_at = timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
return JsonResponse(ResponseFactory(code=200, message="更改完成", data=None, status='success'))
except Exception as e:
return JsonResponse(ResponseFactory(code=400, message="编辑失败:{}".format(e), data=None, status='fail'))
class UserHome(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
"""
获取用户主页信息
:return:
"""
try:request_usre_id = get_user_info(request)['id']
except:request_usre_id = 0
user_id = request.GET['id']
if request_usre_id == int(user_id):
#是否进入主页字段更新
models.Users.objects.filter(id=user_id,is_home=0).update(is_home=1)
else:
#增加访客记录,不记录游客
if request_usre_id != 0:
models.UserVisitors.objects.create(user_id=user_id, visitor_id=request_usre_id,created_at = timezone.now().strftime("%Y-%m-%d %H:%M:%S"),updated_at = timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
# 获取正在进行的活动id
activity_ids = list(models.Activitys.objects.filter(status=1, deleted_at=None).values_list('id', flat=True))
queryset = models.Users.objects.filter(id=user_id, deleted_at=None).first()
if queryset:user = serializers.UserHomeSerializer(queryset,many=False,context={"request_usre_id":request_usre_id,"activity_ids":activity_ids})
else:return JsonResponse(ResponseFactory(code=400, message='该用户已注销', data=None, status='fail'))
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=user.data, status='success'))
class UserTidings(APIView):
# @method_decorator(AuthPermissionRequired())
def get(self,request):
"""
获取用户动态
:return:
"""
author_id = request.GET['id']
try:
user = get_user_info(request)
user_id = user['id']
scope = user['scope']
except:
user_id = 0
scope = 0
# if int(author_id) == user_id or scope -=1:
if int(author_id) == user_id or scope == 1:
#所有动态
queset = models.UserHasTidings.objects.filter(user_id=author_id,deleted_at=None).order_by('-created_at')
else:
# 未被限流动态
queset = models.UserHasTidings.objects.filter(user_id=author_id,status=0,deleted_at=None).order_by('-created_at')
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queset, request)
tidings = serializers.CommunityTidingsSerializer(page_data,many=True,context={'user_id':user_id})
data = {"data":tidings.data,"count":queset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
@method_decorator(AuthPermissionRequired())
def post(self,request):
try:
post_data = json.loads(request.body)
except:
return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.TidingsDeleteVerify(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
tidings_id = obj.data.get('tidings_id')
tidings = models.UserHasTidings.objects.filter(id=tidings_id,deleted_at=None).first()
auther = models.Users.objects.filter(id=tidings.user_id).first()
if not tidings:
return JsonResponse(ResponseFactory(code=400, message="不存在此动态", data=None, status='fail'))
user_id = get_user_info(request)['id']
if tidings.user_id != user_id:
return JsonResponse(ResponseFactory(code=400, message="只能删除自己的动态", data=None, status='fail'))
#删除动态
models.UserHasTidings.objects.filter(id=tidings_id).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
if auther.id != user_id:
# 极光推送
j_title = "您发布的动态被平台删除"
if tidings.type == 2:
activity = models.Activitys.objects.filter(id=tidings.activity_id).first()
content = "《{}》{}".format(activity.song_name, auther.nick_name)
elif tidings.type == 3:
tidings_has_content = serializers.SystemMsgTidingsSerializer(tidings, many=False).data
content = "{}".format(tidings.title)
for recommend_activity in tidings_has_content['recommend_activitys']:
content = content + "[试唱活动《{}》]".format(recommend_activity['song_name'])
for recommend_singer in tidings_has_content['recommend_singers']:
content = content + "[{}的名片]".format(recommend_singer['nick_name'])
if tidings_has_content['photos']:
content = content + "[图片]"
if tidings_has_content['sounds']:
content = content + "[音频]"
jdata = {"title": j_title, "content": content, "content_type": "text",
"receiver_value": [tidings.user_id],
"extras": {"type": "ToSystemMsg", "value": ""}}
JPush().jpush_v3(jdata)
# 服务号推送
wechat_data = models.WechatOfficialUsers.objects.filter(union_id=auther.unionid).first()
if wechat_data:
p_data = {'channel': 'square_result', 'open_id': [wechat_data.open_id],
'data': {"first": j_title, "keyword1": content,
"keyword2": str(tidings.created_at), 'keyword3': auther.nick_name}
}
pushSubscribeMessage(p_data)
return JsonResponse(ResponseFactory(code=200, message="删除成功", data=None, status='success'))
class UserFollow(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
"""
获取用户粉丝列表
:return:
"""
user_id = request.GET['id']
text = request.GET.get('text', '')
follower_ids = models.UserFollowRelations.objects.filter(following_id=user_id,deleted_at=None).order_by('-created_at').values_list('follower_id',flat=True)
follower_ids_str = ",".join('%s' % id for id in follower_ids)
kwargs = {"id__in":follower_ids,"status":1,"deleted_at":None}
if text:
kwargs['nick_name__icontains'] = text
queset = models.Users.objects.filter(**kwargs).extra(select={'m': 'FIELD(id,{})'.format(follower_ids_str)}, order_by=['m'])
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queset, request)
data = serializers.UserFollowSerializer(page_data,many=True,context={"user_id":user_id}).data
#关注全部已读
models.UserFollowRelations.objects.filter(following_id=user_id, is_read=0).update(is_read=1)
data = {"follows":data,"count":queset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
@method_decorator(AuthPermissionRequired())
def post(self,request):
"""
关注
:param request:
:return:
"""
post_data = json.loads(request.body)
obj = verification.CreataFollow(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
user_id = get_user_info(request)['id']
following_id = obj.data.get('following_id')
if user_id == following_id:
return JsonResponse(ResponseFactory(code=400, message="关注失败,您无法关注自己~", data=None, status='fail'))
models.UserFollowRelations.objects.update_or_create(follower_id=user_id,following_id=following_id,deleted_at=None,defaults={"created_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S"),"updated_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S")})
return JsonResponse(ResponseFactory(code=200, message="已关注", data=None, status='success'))
@method_decorator(AuthPermissionRequired())
def put(self,request):
"""
取消关注
:param request:
:return:
"""
post_data = json.loads(request.body)
obj = verification.CreataFollow(data = post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
user_id = get_user_info(request)['id']
following_id = obj.data.get('following_id')
models.UserFollowRelations.objects.filter(follower_id=user_id,following_id=following_id,deleted_at=None).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
return JsonResponse(ResponseFactory(code=200, message="已取消关注", data=None, status='success'))
class UserFollowing(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
"""
获取关注列表
:return:
"""
user_id = request.GET['id']
text = request.GET.get('text', '')
following_ids = models.UserFollowRelations.objects.filter(follower_id=user_id,deleted_at=None).order_by('-created_at').values_list('following_id',flat=True)
following_ids_str = ",".join('%s' % id for id in following_ids)
if text:
queset = models.Users.objects.filter(id__in=following_ids, nick_name__icontains=text,status=1, deleted_at=None).extra(select={'m': 'FIELD(id,{})'.format(following_ids_str)}, order_by=['m'])
else:
queset = models.Users.objects.filter(id__in=following_ids,status=1,deleted_at=None).extra(select={'m': 'FIELD(id,{})'.format(following_ids_str)}, order_by=['m'])
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queset, request)
following = serializers.UserFollowingSerializer(page_data,many=True,context={"user_id":user_id})
data = {"following":following.data,"count":queset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class FindSinger(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
kwargs = {'role':'Singer','status':1,'audit_status':1,'deleted_at':None}
orderbyList = ['-sound_at']
text = request.GET.get('text','')
sound_tags_id = eval(request.GET.get('sound_tags_id','[]'))
style_tags_id = eval(request.GET.get('style_tags_id','[]'))
submit_sound_tag_user = models.UserTagRelations.objects.filter(type=3).values_list('user_id', flat=True)
if text:
kwargs['id__in'] = submit_sound_tag_user
queryset = models.Users.objects.filter(~Q(sound=''),Q(nick_name__icontains=text)|Q(real_name__icontains=text),**kwargs).order_by(*orderbyList)
else:
sound_user = models.UserTagRelations.objects.filter(type=3,tag_id__in=sound_tags_id).values_list('user_id', flat=True)
style_user = models.UserTagRelations.objects.filter( type=1,tag_id__in=style_tags_id).values_list('user_id', flat=True)
#取交集
if len(sound_tags_id) > 0 and len(style_tags_id) > 0:user_ids = [v for v in style_user if v in sound_user]
elif len(sound_tags_id) == 0 and len(style_tags_id) > 0:user_ids = [v for v in style_user if v in submit_sound_tag_user]
elif len(sound_tags_id) > 0 and len(style_tags_id) == 0:user_ids = sound_user
else:user_ids = submit_sound_tag_user
kwargs['id__in'] = user_ids
queryset = models.Users.objects.filter(~Q(sound=''), **kwargs).order_by(*orderbyList)
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.FindSingerSerializer(page_data, many=True)
data = {"singers":ser_obj.data,"count":queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class CustomerService(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
obj = models.SystemConfig.objects.filter(identifier='customer_service', status=1, deleted_at=None).first()
id = obj.remark
queryset = models.Users.objects.filter(id=id).first()
ser_obj = serializers.CustomerUserSerializer(queryset, many=False)
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=ser_obj.data, status='success'))
class Visitors(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
user_id = get_user_info(request)['id']
# 获取当前日期和时间
now = timezone.now()
# 计算 30 天前的日期和时间
thirty_days_ago = now - timedelta(days=30)
visitor_ids = list(models.UserVisitors.objects.filter(user_id=user_id,created_at__gte=thirty_days_ago).order_by('-created_at').values_list('visitor_id',flat=True))
visitor_ids = sorted(set(visitor_ids), key=visitor_ids.index)
visitor_ids_str = ",".join('%s' % id for id in visitor_ids)
queryset = models.Users.objects.filter(id__in=visitor_ids).extra(select={'m':'FIELD(id,{})'.format(visitor_ids_str)},order_by=['m'])
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.VisitorUserSerializer(page_data, many=True,context={'user_id':user_id})
data = {"visitors": ser_obj.data,"count":len(visitor_ids)}
# 访客都已读
models.UserVisitors.objects.filter(user_id=user_id, is_read=0).update(is_read=1)
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
class RemoveDevice(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
user_id = get_user_info(request)['id']
remove_alias_device(user_id)
return JsonResponse(ResponseFactory(code=200, message="处理成功", data=None, status='success'))
class AvtivitysPrice(APIView):
@method_decorator(AuthPermissionRequired())
def put(self,request):
try:post_data = json.loads(request.body)
except:return JsonResponse(ResponseFactory(code=400, message="参数错误", data=None, status='fail'))
obj = verification.AvtivitysPriceVerification(data=post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
if obj.data.get('value')['amounts']:
if not (0 <= obj.data.get('value')['amounts'] <= 9999999): return JsonResponse(
ResponseFactory(code=201, message="金额在0-9999999之间", data=None, status='fail'))
if obj.data.get('value')['ratio']:
if not (0 <= obj.data.get('value')['ratio'] <= 100): return JsonResponse(
ResponseFactory(code=201, message="分成比列在0%-100%之间", data=None, status='fail'))
user_id = get_user_info(request)['id']
activity_id = obj.data.get('activity_id')
models.ActivityUserHasPrices.objects.update_or_create(
activity_id = activity_id,
user_id = user_id,
defaults = {
"value" :obj.data.get('value'),
"is_deduct" :obj.data.get('is_deduct'),
"is_talk" :obj.data.get('is_talk'),
"address_id" :obj.data.get('address_id'),
"is_accept_address" :obj.data.get('is_accept_address'),
"created_at" :timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
"updated_at" :timezone.now().strftime("%Y-%m-%d %H:%M:%S")}
)
return JsonResponse(ResponseFactory(code=200, message="修改成功", data=None, status='success'))
class AvtivitysPriceInfo(APIView):
@method_decorator(AuthPermissionRequired())
def get(self, request):
activity_id = request.GET.get('activity_id')
user_id = get_user_info(request)['id']
queryset = models.ActivityUserHasPrices.objects.filter(activity_id=activity_id,user_id=user_id).first()
if queryset:data = serializers.ActivitysPriceSerializer(queryset, many=False,context={'activity_id':activity_id}).data
else:
queryset = models.ActivityUserHasPrices.objects.filter(user_id=user_id).order_by('updated_at').last()
if queryset:data = serializers.ActivitysPriceSerializer(queryset, many=False,context={'activity_id':activity_id}).data
else: data = None
return JsonResponse(ResponseFactory(code=200, message="获取成功", data={"price_info":data}, status='success'))
from api.views import AuthPermissionRequired,get_user_info
from django.http import JsonResponse
from api.views import ResponseFactory,PageNumberPagination,GetWxToken,pushSubscribeMessage,WeChatApi,JPush
from rest_framework.decorators import api_view
from api import models,verification,serializers
import json
from django.utils.decorators import method_decorator
from rest_framework.views import APIView
def push_notifications(request):
if request.method != "POST":
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
post_data = json.loads(request.body)
obj = verification.PushNotifications(post_data)
if not obj.is_valid():
return JsonResponse(ResponseFactory(code=400, message=verification.error_message(obj), data=None, status='fail'))
obj = obj.clean()
jdata = {"title": obj.get('title'), "content": obj.get('content'), "content_type": "text",
"receiver_value": obj.get('receivers'),
"extras": {"type": post_data.get('type',""), "value": post_data.get('value',"")}}
result = JPush().jpush_v3(jdata)
return JsonResponse(result)
@AuthPermissionRequired()
def read(request):
put_data = json.loads(request.body)
user_id = get_user_info(request)['id']
if request.method == "PUT":
type = put_data.get('type')
#我的歌手审核消息已读
if type == 1:
models.UserMessages.objects.filter(type=type,receiver_id=user_id,sender_id=put_data['sender_id'],deleted_at=None).update(is_read=1)
return JsonResponse(ResponseFactory(code=200, message="已阅读", data=None, status='success'))
# 我的歌手收藏消息已读
elif type == 2:
models.UserMessages.objects.filter(type=type,receiver_id=user_id,deleted_at=None).update(is_read=1)
return JsonResponse(ResponseFactory(code=200, message="已阅读", data=None, status='success'))
# 我的歌手或平台用户试唱消息已读(注意区分是绑定用户,还是平台用户)
elif type == 3:
models.UserMessages.objects.filter(type=type,sender_id=put_data['sender_id'],receiver_id=user_id,activity_id=put_data['activity_id'],is_bind=put_data['is_bind'],deleted_at=None).update(is_read=1)
return JsonResponse(ResponseFactory(code=200, message="已阅读", data=None, status='success'))
#系统消息已读
elif type == 4:
models.UserMessages.objects.filter(type__in=[4,5,6,7,8,9,10,11,12,13,14], receiver_id=user_id, deleted_at=None).update(is_read=1)
return JsonResponse(ResponseFactory(code=200, message="已阅读", data=None, status='success'))
else:
return JsonResponse(ResponseFactory(code=400, message="不支持的请求方法", data=None, status='fail'))
class SystemMessage(APIView):
@method_decorator(AuthPermissionRequired())
def get(self,request):
user_id = get_user_info(request)['id']
queryset = models.UserMessages.objects.filter(type__in=[4,5,6,7,8,9,10,11,12,13,14],receiver_id=user_id,deleted_at=None).order_by('-created_at')
page_obj = PageNumberPagination()
page_data = page_obj.paginate_queryset(queryset, request)
ser_obj = serializers.SystemMessageSerializer(page_data, many=True)
data = {"message": ser_obj.data, "count": queryset.count()}
return JsonResponse(ResponseFactory(code=200, message="获取成功", data=data, status='success'))
\ No newline at end of file
#! /usr/bin/python
# coding:utf-8
import hmac
import hashlib
import base64
import zlib
import json
import time
def base64_encode_url(data):
""" base url encode 实现"""
base64_data = base64.b64encode(data)
base64_data_str = bytes.decode(base64_data)
base64_data_str = base64_data_str.replace('+', '*')
base64_data_str = base64_data_str.replace('/', '-')
base64_data_str = base64_data_str.replace('=', '_')
return base64_data_str
def base64_decode_url(base64_data):
""" base url decode 实现"""
base64_data_str = bytes.decode(base64_data)
base64_data_str = base64_data_str.replace('*', '+')
base64_data_str = base64_data_str.replace('-', '/')
base64_data_str = base64_data_str.replace('_', '=')
raw_data = base64.b64decode(base64_data_str)
return raw_data
class TLSSigAPIv2:
__sdkappid = 0
__version = '2.0'
__key = ""
def __init__(self, sdkappid, key):
self.__sdkappid = sdkappid
self.__key = key
##用于生成实时音视频(TRTC)业务进房权限加密串,具体用途用法参考TRTC文档:https://cloud.tencent.com/document/product/647/32240
# TRTC业务进房权限加密串需使用用户定义的userbuf
# @brief 生成 userbuf
# @param account 用户名
# @param dwSdkappid sdkappid
# @param dwAuthID 数字房间号
# @param dwExpTime 过期时间:该权限加密串的过期时间,实际过期时间:当前时间+dwExpTime
# @param dwPrivilegeMap 用户权限,255表示所有权限
# @param dwAccountType 用户类型,默认为0
# @param roomStr 字符串房间号,数字房间号非0时存在
# @return userbuf {string} 返回的userbuf
# /
##It is used to generate real-time audio and video (TRTC) business access rights encryption string. For specific usage, please refer to the TRTC document:https://cloud.tencent.com/document/product/647/32240
# User-defined userbuf is used for the encrypted string of TRTC service entry permission
# @brief generate userbuf
# @param account username
# @param dwSdkappid sdkappid
# @param dwAuthID digital room number
# @param dwExpTime Expiration time: The expiration time of the encrypted string of this permission. Expiration time = now+dwExpTime
# @param dwPrivilegeMap User permissions, 255 means all permissions
# @param dwAccountType User type, default is 0
# @param roomStr String room number
# @return userbuf string returned userbuf
# /
def _gen_userbuf(self, account, dwAuthID, dwExpTime,
dwPrivilegeMap, dwAccountType, roomStr):
userBuf = b''
if len(roomStr) > 0:
userBuf += bytearray([1])
else:
userBuf += bytearray([0])
userBuf += bytearray([
((len(account) & 0xFF00) >> 8),
(len(account) & 0x00FF),
])
userBuf += bytearray(map(ord, account))
# dwSdkAppid
userBuf += bytearray([
((self.__sdkappid & 0xFF000000) >> 24),
((self.__sdkappid & 0x00FF0000) >> 16),
((self.__sdkappid & 0x0000FF00) >> 8),
(self.__sdkappid & 0x000000FF),
])
# dwAuthId
userBuf += bytearray([
((dwAuthID & 0xFF000000) >> 24),
((dwAuthID & 0x00FF0000) >> 16),
((dwAuthID & 0x0000FF00) >> 8),
(dwAuthID & 0x000000FF),
])
# dwExpTime = now + 300;
expire = dwExpTime + int(time.time())
userBuf += bytearray([
((expire & 0xFF000000) >> 24),
((expire & 0x00FF0000) >> 16),
((expire & 0x0000FF00) >> 8),
(expire & 0x000000FF),
])
# dwPrivilegeMap
userBuf += bytearray([
((dwPrivilegeMap & 0xFF000000) >> 24),
((dwPrivilegeMap & 0x00FF0000) >> 16),
((dwPrivilegeMap & 0x0000FF00) >> 8),
(dwPrivilegeMap & 0x000000FF),
])
# dwAccountType
userBuf += bytearray([
((dwAccountType & 0xFF000000) >> 24),
((dwAccountType & 0x00FF0000) >> 16),
((dwAccountType & 0x0000FF00) >> 8),
(dwAccountType & 0x000000FF),
])
if len(roomStr) > 0:
userBuf += bytearray([
((len(roomStr) & 0xFF00) >> 8),
(len(roomStr) & 0x00FF),
])
userBuf += bytearray(map(ord, roomStr))
return userBuf
def __hmacsha256(self, identifier, curr_time, expire, base64_userbuf=None):
""" 通过固定串进行 hmac 然后 base64 得的 sig 字段的值"""
raw_content_to_be_signed = "TLS.identifier:" + str(identifier) + "\n" \
+ "TLS.sdkappid:" + str(self.__sdkappid) + "\n" \
+ "TLS.time:" + str(curr_time) + "\n" \
+ "TLS.expire:" + str(expire) + "\n"
if None != base64_userbuf:
raw_content_to_be_signed += "TLS.userbuf:" + base64_userbuf + "\n"
return base64.b64encode(hmac.new(self.__key.encode('utf-8'),
raw_content_to_be_signed.encode('utf-8'),
hashlib.sha256).digest())
def __gen_sig(self, identifier, expire=180 * 86400, userbuf=None):
""" 用户可以采用默认的有效期生成 sig """
curr_time = int(time.time())
m = dict()
m["TLS.ver"] = self.__version
m["TLS.identifier"] = str(identifier)
m["TLS.sdkappid"] = int(self.__sdkappid)
m["TLS.expire"] = int(expire)
m["TLS.time"] = int(curr_time)
base64_userbuf = None
if None != userbuf:
base64_userbuf = bytes.decode(base64.b64encode(userbuf))
m["TLS.userbuf"] = base64_userbuf
m["TLS.sig"] = bytes.decode(self.__hmacsha256(
identifier, curr_time, expire, base64_userbuf))
raw_sig = json.dumps(m)
sig_cmpressed = zlib.compress(raw_sig.encode('utf-8'))
base64_sig = base64_encode_url(sig_cmpressed)
return base64_sig
##
# 【功能说明】用于签发 TRTC 和 IM 服务中必须要使用的 UserSig 鉴权票据
#
# 【参数说明】
# userid - 用户id,限制长度为32字节,只允许包含大小写英文字母(a-zA-Z)、数字(0-9)及下划线和连词符。
# expire - UserSig 票据的过期时间,单位是秒,比如 86400 代表生成的 UserSig 票据在一天后就无法再使用了。
# /
# Function: Used to issue UserSig that is required by the TRTC and IM services.
# Parameter description:
# userid - User ID. The value can be up to 32 bytes in length and contain letters (a-z and A-Z), digits (0-9), underscores (_), and hyphens (-).
# expire - UserSig expiration time, in seconds. For example, 86400 indicates that the generated UserSig will expire one day after being generated.
def genUserSig(self, userid, expire=180 * 86400):
""" 用户可以采用默认的有效期生成 sig """
return self.__gen_sig(userid, expire, None)
##
# 【功能说明】
# 用于签发 TRTC 进房参数中可选的 PrivateMapKey 权限票据。
# PrivateMapKey 需要跟 UserSig 一起使用,但比 UserSig 有更强的权限控制能力:
# - UserSig 只能控制某个 UserID 有无使用 TRTC 服务的权限,只要 UserSig 正确,其对应的 UserID 可以进出任意房间。
# - PrivateMapKey 则是将 UserID 的权限控制的更加严格,包括能不能进入某个房间,能不能在该房间里上行音视频等等。
# 如果要开启 PrivateMapKey 严格权限位校验,需要在【实时音视频控制台】=>【应用管理】=>【应用信息】中“启动权限密钥”。
#
# 【参数说明】
# userid - 用户id,限制长度为32字节,只允许包含大小写英文字母(a-zA-Z)、数字(0-9)及下划线和连词符。
# expire - PrivateMapKey 票据的过期时间,单位是秒,比如 86400 生成的 PrivateMapKey 票据在一天后就无法再使用了。
# roomid - 房间号,用于指定该 userid 可以进入的房间号
# privilegeMap - 权限位,使用了一个字节中的 8 个比特位,分别代表八个具体的功能权限:
# - 第 1 位:0000 0001 = 1,创建房间的权限
# - 第 2 位:0000 0010 = 2,加入房间的权限
# - 第 3 位:0000 0100 = 4,发送语音的权限
# - 第 4 位:0000 1000 = 8,接收语音的权限
# - 第 5 位:0001 0000 = 16,发送视频的权限
# - 第 6 位:0010 0000 = 32,接收视频的权限
# - 第 7 位:0100 0000 = 64,发送辅路(也就是屏幕分享)视频的权限
# - 第 8 位:1000 0000 = 200,接收辅路(也就是屏幕分享)视频的权限
# - privilegeMap == 1111 1111 == 255 代表该 userid 在该 roomid 房间内的所有功能权限。
# - privilegeMap == 0010 1010 == 42 代表该 userid 拥有加入房间和接收音视频数据的权限,但不具备其他权限。
# /
# Function:
# Used to issue PrivateMapKey that is optional for room entry.
# PrivateMapKey must be used together with UserSig but with more powerful permission control capabilities.
# - UserSig can only control whether a UserID has permission to use the TRTC service. As long as the UserSig is correct, the user with the corresponding UserID can enter or leave any room.
# - PrivateMapKey specifies more stringent permissions for a UserID, including whether the UserID can be used to enter a specific room and perform audio/video upstreaming in the room.
# To enable stringent PrivateMapKey permission bit verification, you need to enable permission key in TRTC console > Application Management > Application Info.
# *
# Parameter description:
# userid - User ID. The value can be up to 32 bytes in length and contain letters (a-z and A-Z), digits (0-9), underscores (_), and hyphens (-).
# roomid - ID of the room to which the specified UserID can enter.
# expire - PrivateMapKey expiration time, in seconds. For example, 86400 indicates that the generated PrivateMapKey will expire one day after being generated.
# privilegeMap - Permission bits. Eight bits in the same byte are used as the permission switches of eight specific features:
# - Bit 1: 0000 0001 = 1, permission for room creation
# - Bit 2: 0000 0010 = 2, permission for room entry
# - Bit 3: 0000 0100 = 4, permission for audio sending
# - Bit 4: 0000 1000 = 8, permission for audio receiving
# - Bit 5: 0001 0000 = 16, permission for video sending
# - Bit 6: 0010 0000 = 32, permission for video receiving
# - Bit 7: 0100 0000 = 64, permission for substream video sending (screen sharing)
# - Bit 8: 1000 0000 = 200, permission for substream video receiving (screen sharing)
# - privilegeMap == 1111 1111 == 255: Indicates that the UserID has all feature permissions of the room specified by roomid.
# - privilegeMap == 0010 1010 == 42: Indicates that the UserID has only the permissions to enter the room and receive audio/video data.
def genPrivateMapKey(self, userid, expire, roomid, privilegeMap):
""" 带 userbuf 生成签名 """
userbuf = self._gen_userbuf(userid, roomid, expire, privilegeMap, 0, "")
print(userbuf)
return self.__gen_sig(userid, expire, userbuf)
##
# 【功能说明】
# 用于签发 TRTC 进房参数中可选的 PrivateMapKey 权限票据。
# PrivateMapKey 需要跟 UserSig 一起使用,但比 UserSig 有更强的权限控制能力:
# - UserSig 只能控制某个 UserID 有无使用 TRTC 服务的权限,只要 UserSig 正确,其对应的 UserID 可以进出任意房间。
# - PrivateMapKey 则是将 UserID 的权限控制的更加严格,包括能不能进入某个房间,能不能在该房间里上行音视频等等。
# 如果要开启 PrivateMapKey 严格权限位校验,需要在【实时音视频控制台】=>【应用管理】=>【应用信息】中“启动权限密钥”。
#
# 【参数说明】
# userid - 用户id,限制长度为32字节,只允许包含大小写英文字母(a-zA-Z)、数字(0-9)及下划线和连词符。
# expire - PrivateMapKey 票据的过期时间,单位是秒,比如 86400 生成的 PrivateMapKey 票据在一天后就无法再使用了。
# roomstr - 字符串房间号,用于指定该 userid 可以进入的房间号
# privilegeMap - 权限位,使用了一个字节中的 8 个比特位,分别代表八个具体的功能权限:
# - 第 1 位:0000 0001 = 1,创建房间的权限
# - 第 2 位:0000 0010 = 2,加入房间的权限
# - 第 3 位:0000 0100 = 4,发送语音的权限
# - 第 4 位:0000 1000 = 8,接收语音的权限
# - 第 5 位:0001 0000 = 16,发送视频的权限
# - 第 6 位:0010 0000 = 32,接收视频的权限
# - 第 7 位:0100 0000 = 64,发送辅路(也就是屏幕分享)视频的权限
# - 第 8 位:1000 0000 = 200,接收辅路(也就是屏幕分享)视频的权限
# - privilegeMap == 1111 1111 == 255 代表该 userid 在该 roomid 房间内的所有功能权限。
# - privilegeMap == 0010 1010 == 42 代表该 userid 拥有加入房间和接收音视频数据的权限,但不具备其他权限。
# /
# Function:
# Used to issue PrivateMapKey that is optional for room entry.
# PrivateMapKey must be used together with UserSig but with more powerful permission control capabilities.
# - UserSig can only control whether a UserID has permission to use the TRTC service. As long as the UserSig is correct, the user with the corresponding UserID can enter or leave any room.
# - PrivateMapKey specifies more stringent permissions for a UserID, including whether the UserID can be used to enter a specific room and perform audio/video upstreaming in the room.
# To enable stringent PrivateMapKey permission bit verification, you need to enable permission key in TRTC console > Application Management > Application Info.
# *
# Parameter description:
# @param userid - User ID. The value can be up to 32 bytes in length and contain letters (a-z and A-Z), digits (0-9), underscores (_), and hyphens (-).
# @param roomstr - ID of the room to which the specified UserID can enter.
# @param expire - PrivateMapKey expiration time, in seconds. For example, 86400 indicates that the generated PrivateMapKey will expire one day after being generated.
# @param privilegeMap - Permission bits. Eight bits in the same byte are used as the permission switches of eight specific features:
# - Bit 1: 0000 0001 = 1, permission for room creation
# - Bit 2: 0000 0010 = 2, permission for room entry
# - Bit 3: 0000 0100 = 4, permission for audio sending
# - Bit 4: 0000 1000 = 8, permission for audio receiving
# - Bit 5: 0001 0000 = 16, permission for video sending
# - Bit 6: 0010 0000 = 32, permission for video receiving
# - Bit 7: 0100 0000 = 64, permission for substream video sending (screen sharing)
# - Bit 8: 1000 0000 = 200, permission for substream video receiving (screen sharing)
# - privilegeMap == 1111 1111 == 255: Indicates that the UserID has all feature permissions of the room specified by roomid.
# - privilegeMap == 0010 1010 == 42: Indicates that the UserID has only the permissions to enter the room and receive audio/video data.
def genPrivateMapKeyWithStringRoomID(self, userid, expire, roomstr, privilegeMap):
""" 带 userbuf 生成签名 """
userbuf = self._gen_userbuf(userid, 0, expire, privilegeMap, 0, roomstr)
print(userbuf)
return self.__gen_sig(userid, expire, userbuf)
def main():
api = TLSSigAPIv2(1400752528, "a68603354e10d70dc0e8b834da884f383ebc21180a382dac79efd1194b77f1b7")
sig = api.genUserSig("administrator")
print(sig)
sig = api.genPrivateMapKey("xiaojun", 86400 * 180, 10000, 255)
print(sig)
# sig = api.genPrivateMapKeyWithStringRoomID("xiaojun", 86400*180,"adbjkl",255)
# print(sig)
if __name__ == "__main__":
main()
\ No newline at end of file
File mode changed
from django.contrib import admin
from django.apps import AppConfig
class WxMiniapiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api'
File mode changed
File mode changed
import logging
# 获取logger对象
logger = logging.getLogger(__name__)
\ No newline at end of file
import jwt
import json
from HisinApi import settings
from api.models import SystemHttpLogs
from django.utils import timezone
from api.views import object_to_json
import time
from api.loggin import logger
class ApiLogs(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
try:
body = json.loads(request.body.decode('utf-8'))
except:
body = {}
header = object_to_json(request.headers)['_store']
if request.method == 'GET':
query = request.GET
else:
query = request.POST
request_data = {"body":body,"header":header,"query":query}
try:body = json.loads( response._container[0].decode('utf-8'))
except: body = None
response_data = {"body":body, "header": object_to_json(response.headers)['_store'],"code":response.status_code}
try:
try:
auth = request.META.get('HTTP_AUTHORIZATION').split()
dict = jwt.decode(auth[1], settings.SECRET_KEY, algorithms=['HS256'])
user_id = dict.get('data').get('id')
except:
user_id = 0
SystemHttpLogs(
guard='App',
user_id=user_id,
method=request.method,
uri=request.path,
ip=request.META['REMOTE_ADDR'],
request=request_data,
response=response_data,
consume =response.headers['time'],
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")).save()
except Exception as e:
logger.info('API Log Error:{}'.format(e))
return response
class ResponseTime:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start_time = time.time()
response = self.get_response(request)
duration = time.time() - start_time
response["time"] = int(duration * 1000)
return response
\ No newline at end of file
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from datetime import datetime,timedelta
import jwt
from HisinApi import settings
class UserDynamics(models.Model):
user_id = models.IntegerField(default=0)
type = models.CharField(max_length=255)
intro = models.CharField(max_length=255)
properties = models.JSONField()
is_top = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_dynamics'
class BrokerUserConfigs(models.Model):
title = models.CharField(default='',max_length=255)
begin_at = models.DateTimeField(blank=True, null=True)
end_at = models.DateTimeField(blank=True, null=True)
user_id = models.IntegerField(default=0)
push_type = models.IntegerField(default=0)
push_at = models.DateTimeField(blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'broker_user_configs'
class BrokerUserConfigItems(models.Model):
user_id = models.IntegerField(default=0)
config = models.ForeignKey(BrokerUserConfigs, on_delete=models.CASCADE)
identifier = models.CharField(default='',max_length=255)
singer_num = models.IntegerField(default=0)
status = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'broker_user_config_items'
class ProjectHasMembers(models.Model):
invite_id = models.IntegerField(default=0)
user_id = models.IntegerField(default=0)
project_id = models.IntegerField(default=0)
status = models.IntegerField(default=0)
is_top = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'project_has_members'
class ProjectVisitors(models.Model):
project_id = models.IntegerField(default=0)
user_id = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'project_visitors'
class UserManageActivitie(models.Model):
user_id = models.IntegerField(default=0)
activity_id = models.IntegerField(default=0)
project_id = models.IntegerField(default=0)
activity_publish_at = models.DateTimeField(blank=True, null=True)
activity_status = models.IntegerField(default=0)
permission = models.JSONField()
class Meta:
managed = False
db_table = 'user_manage_activities'
class GorupInvites(models.Model):
group_id = models.IntegerField(default=0)
invite_id = models.IntegerField(default=0)
user_id = models.IntegerField(default=0)
type = models.IntegerField(default=1)
status = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'group_invites'
class GroupHasMembers(models.Model):
group_id = models.IntegerField(default=0)
member_id = models.IntegerField(default=0)
is_top = models.IntegerField(default=0)
role = models.IntegerField(default=3)
status = models.IntegerField(default=1)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'group_has_members'
class Groups(models.Model):
user_id = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'groups'
class SystemSmsLogs(models.Model):
gateway = models.CharField(max_length=80)
phone = models.CharField(max_length=255)
content = models.JSONField()
result = models.JSONField()
status = models.CharField(max_length=80)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'system_sms_logs'
class UserAuthInfos(models.Model):
user_id = models.IntegerField(default=0)
nick_name = models.CharField(max_length=80)
platform = models.JSONField()
works = models.CharField(max_length=255)
img = models.JSONField()
tags = models.JSONField()
audio_info = models.JSONField()
reason = models.TextField()
status = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_auth_infos'
class ActivityLinks(models.Model):
activity_id = models.IntegerField(default=0)
type = models.CharField(max_length=80)
link_type = models.CharField(max_length=255)
link_id = models.CharField(max_length=32)
class Meta:
managed = False
db_table = 'activity_links'
class ProjectConfirmationTime(models.Model):
"""厂牌确认合作时间"""
project_id = models.IntegerField(default=0)
average_day = models.FloatField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'project_confirmation_times'
class CountryRegions(models.Model):
"""地区信息"""
parent_id = models.IntegerField(default=0)
country_id = models.IntegerField(default=0)
identifier = models.CharField(max_length=255)
name = models.CharField(max_length=255)
code = models.CharField(max_length=255)
weight = models.IntegerField(default=1)
status = models.IntegerField(max_length=255)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'country_regions'
class ActivityUserHasPrices(models.Model):
"""自主报价"""
user_id = models.IntegerField(default=0)
activity_id = models.IntegerField(default=0)
value = models.JSONField()
is_deduct = models.IntegerField(default=0)
is_talk = models.IntegerField(default=0)
address_id = models.CharField(max_length=255)
is_accept_address = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'activity_user_has_prices'
class SystemHttpLogs(models.Model):
"""接口日志"""
guard = models.CharField(default='Other',max_length=255)
user_id = models.IntegerField(default=0)
method = models.CharField(default='GET',max_length=255)
uri = models.CharField(max_length=500)
ip = models.CharField(max_length=255)
request = models.JSONField()
response = models.JSONField()
consume = models.FloatField()
created_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'system_http_logs'
class TidingsHasComments(models.Model):
"""动态评论"""
tidings_id = models.IntegerField(default=0)
parent_id = models.IntegerField(default=0)
user_id = models.IntegerField(default=0)
content = models.TextField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'tidings_has_comments'
class UserChatAgentRecords(models.Model):
"""设置私聊代理,聊天关系"""
user_id = models.IntegerField(default=0)
send_id = models.IntegerField(default=0)
business_id = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_chatagent_records'
class UserUnlikeTidings(models.Model):
"""用户不感兴趣的动态"""
user_id = models.IntegerField(default=0)
tidings_id = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_unlike_tidings'
class ActivityHasRecommends(models.Model):
"""活动确定分享人"""
activity_id = models.IntegerField(default=0)
type = models.IntegerField(default=0)
content = models.TextField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'activity_has_recommends'
class UserVisitors(models.Model):
"""活动确定分享人"""
user_id = models.IntegerField(default=0)
visitor_id = models.IntegerField(default=0)
is_read = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_visitors'
class ActivityShareUsers(models.Model):
"""活动确定分享人"""
activity_id = models.IntegerField(default=0)
user_id = models.IntegerField(default=0)
share_id = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'activity_share_users'
class TidingsHasChat(models.Model):
tidings_id = models.IntegerField(default=0)
user_id = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'tidings_has_chat'
class UserViewTidings(models.Model):
"""动态活动"""
tidings_id = models.IntegerField(default=0)
user_id = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_view_tidings'
class TidingsHasReports(models.Model):
"""举报"""
tidings_id = models.IntegerField(default=0)
comment_id = models.IntegerField(default=0)
person_id = models.IntegerField(default=0)
user_id = models.IntegerField(default=0)
reason = models.TextField()
desc = models.TextField(default=None)
type = models.IntegerField(default=1)
status = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'tidings_has_reports'
class TidingsHasInteracts(models.Model):
"""动态活动"""
type_id = models.IntegerField(default=0)
type = models.IntegerField(default=1)
user_id = models.IntegerField(default=0)
status = models.IntegerField(default=1)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'tidings_has_interacts'
class TidingsHasContents(models.Model):
"""动态关联的内容"""
tidings_id = models.IntegerField(default=0)
type = models.IntegerField(default=1)
value = models.CharField(max_length=400,default='')
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'tidings_has_contents'
class UserHasTidings(models.Model):
# user_id = models.IntegerField(default=0)
user = models.OneToOneField('Users',on_delete=models.DO_NOTHING)
title = models.TextField()
activity_id = models.IntegerField(default=0)
type = models.IntegerField(default=0)
url = models.CharField(max_length=400,default='')
status = models.IntegerField(default=0)
is_top = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_has_tidings'
class UserFollowRelations(models.Model):
follower_id = models.IntegerField(default=0)
following_id = models.IntegerField(default=0)
is_read = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_follow_relations'
class UserTagRelations(models.Model):
user_id = models.IntegerField(default=0)
tag_id = models.IntegerField(default=0)
type = models.IntegerField(max_length=255)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_tag_relations'
class SystemConfig(models.Model):
creator_id = models.IntegerField(default=0)
parent_id = models.IntegerField(default=0)
name = models.CharField(max_length=255)
identifier = models.CharField(max_length=255)
content = models.TextField()
expand = models.JSONField()
status = models.CharField(max_length=255)
weight = models.IntegerField(max_length=255)
remark = models.TextField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'system_config'
class AppVersion(models.Model):
app_ver = models.CharField(default=None,max_length=255)
app_no = models.CharField(default=None,max_length=255)
os = models.CharField(default=None,max_length=255)
url = models.CharField(default=None,max_length=512)
remark = models.CharField(default=None,max_length=1024)
is_force = models.IntegerField(default=None)
user_id = models.IntegerField(default=None)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'app_version'
class UserHasProjects(models.Model):
user_id = models.IntegerField(default=0)
project_id = models.IntegerField(default=0)
class Meta:
managed = False
db_table = 'user_has_projects'
class UserPoints(models.Model):
type = models.CharField(max_length=50,default=None)
point = models.IntegerField(default=0)
user_id = models.IntegerField(default=0)
singer_id = models.IntegerField(default=0)
activity_id = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_points'
class UserMessages(models.Model):
title = models.CharField(max_length=255,default="")
content = models.TextField()
sender_id = models.IntegerField(default=0)
receiver_id = models.IntegerField(default=0)
activity_id = models.IntegerField(default=0)
type = models.IntegerField(default=0)
is_read = models.IntegerField(default=0)
is_bind = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_messages'
class Actions(models.Model):
event_name = models.CharField(max_length=255)
open_id = models.CharField(max_length=255)
user_id = models.IntegerField(default=0)
activity_id = models.IntegerField(default=0)
start_at = models.DateTimeField(blank=True, null=True)
end_at = models.DateTimeField(blank=True, null=True)
# time = models.IntegerField(default=None)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'actions'
class Events(models.Model):
event_name = models.CharField(max_length=255,primary_key='event_name')
event_title = models.CharField(max_length=255)
event_intro = models.CharField(max_length=255)
event_path = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'events'
class UserActivityUnlikes(models.Model):
user_id = models.IntegerField(default=0)
activity_id = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_activity_unlikes'
class UserActivityCollections(models.Model):
user_id = models.IntegerField(default=0)
activity_id = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_activity_collections'
class WechatOfficialUsers(models.Model):
open_id = models.CharField(max_length=255)
union_id = models.CharField(max_length=255)
is_subscribe = models.IntegerField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'wechat_official_users'
class MixinPreviews(models.Model):
user_id = models.IntegerField()
activity_id = models.IntegerField()
url = models.CharField(max_length=255)
syn_status = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'mixin_previews'
class ActivityHasUsers(models.Model):
# activity_id = models.IntegerField()
activity = models.ForeignKey('Activitys',related_name="activityhasusers",on_delete=models.DO_NOTHING)
# user_id = models.IntegerField()
user = models.OneToOneField('Users',related_name="has_user",on_delete=models.DO_NOTHING)
broker_id = models.IntegerField(default=0)
broker_level = models.CharField(max_length=255,default='')
demo_url = models.CharField(max_length=255)
wav_url = models.CharField(max_length=255,default='',blank=True, null=True)
wav_durations = models.FloatField(default=0,blank=True, null=True)
durations = models.FloatField(default=0)
type = models.CharField(max_length=6, blank=True, null=True)
status = models.IntegerField(blank=True, null=True)
syn_status = models.IntegerField()
syn_data = models.JSONField()
is_checked = models.IntegerField(default=0)
mode = models.IntegerField(blank=True, null=True)
open_id = models.CharField(max_length=255)
submit_at = models.DateTimeField(blank=True, null=True)
is_hide = models.IntegerField(default=1)
version = models.IntegerField()
sing_type = models.CharField(default=None,max_length=50)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'activity_has_users'
class ActivityMaterials(models.Model):
activity_id = models.IntegerField()
type = models.CharField(max_length=12)
url = models.CharField(max_length=255)
tone = models.CharField(max_length=255)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'activity_materials'
class Activitys(models.Model):
song_type = models.IntegerField(blank=True, null=True)
sub_title = models.CharField(max_length=255)
song_name = models.CharField(max_length=255)
cover = models.CharField(max_length=255)
user_id = models.IntegerField(blank=True, null=True)
project = models.OneToOneField("Projects", null=True,related_name="has_project",on_delete=models.DO_NOTHING)
lyric = models.TextField(blank=True, null=True)
clip_lyric = models.TextField()
guide = models.CharField(max_length=400)
guide_duration = models.IntegerField()
guide_clip = models.CharField(max_length=400)
guide_clip_duration = models.IntegerField()
karaoke = models.CharField(max_length=400)
karaoke_clip = models.CharField(max_length=400)
send_url = models.JSONField()
weight = models.IntegerField(blank=True, null=True)
r_weight = models.IntegerField(blank=True, null=True)
r_status=models.IntegerField(blank=True, null=True)
status = models.IntegerField(blank=True, null=True)
is_official = models.IntegerField(default=0)
is_recommend = models.IntegerField(default=0)
sex = models.CharField(max_length=255)
mark = models.CharField(max_length=255)
speed = models.CharField(max_length=255)
lang = models.JSONField()
expand = models.JSONField()
audit_status = models.IntegerField(blank=True, null=True)
estimate_release_at = models.DateField()
publish_at = models.DateTimeField(blank=True, null=True)
p_is_top = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
match_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'activitys'
class Banners(models.Model):
name = models.CharField(max_length=255)
cover = models.CharField(max_length=255)
content_picture = models.CharField(max_length=255)
role = models.JSONField()
weight = models.CharField(max_length=255)
status = models.IntegerField(blank=True, null=True)
type = models.IntegerField(blank=True, null=True)
scope = models.IntegerField()
content = models.JSONField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'banners'
class Projects(models.Model):
name = models.CharField(max_length=255)
cover = models.CharField(max_length=400)
intro = models.CharField(max_length=255)
user_id = models.IntegerField()
master_id = models.IntegerField()
status = models.IntegerField(blank=True, null=True)
is_promote = models.IntegerField(default=0)
weight = models.IntegerField(default=0)
r_status = models.IntegerField(default=0)
r_weight = models.IntegerField(default=0)
is_public = models.IntegerField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'projects'
class SystemBusiness(models.Model):
nick_name = models.CharField(max_length=255)
real_name = models.CharField(max_length=255)
user_id = models.IntegerField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'system_business'
class SystemLogs(models.Model):
id = models.IntegerField(primary_key=True)
user_id = models.IntegerField()
model = models.CharField(max_length=255)
type = models.CharField(max_length=255)
text = models.CharField(max_length=255, blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'system_logs'
class SystemTags(models.Model):
name = models.CharField(max_length=255)
user_id = models.IntegerField()
type = models.IntegerField()
weight = models.IntegerField(default=0)
expand = models.JSONField()
is_show = models.IntegerField(default=1)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'system_tags'
class UserExamines(models.Model):
user_id = models.IntegerField()
admin_id = models.IntegerField()
business_id = models.IntegerField()
open_id = models.CharField(max_length=255,blank=True, null=True)
type = models.CharField(max_length=255, blank=True, null=True)
examine_info = models.CharField(max_length=255, blank=True, null=True)
user_info = models.JSONField()
status = models.IntegerField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_examines'
class UserLoginLogs(models.Model):
user_id = models.PositiveBigIntegerField()
client_ip = models.CharField(max_length=50)
client_agent = models.CharField(max_length=400)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_login_logs'
class ActivityHasTags(models.Model):
activity = models.ForeignKey('Activitys',related_name='has_activity',on_delete=models.DO_NOTHING)
tag = models.ForeignKey('SystemTags',related_name='has_tag',on_delete=models.DO_NOTHING)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'activity_has_tags'
class UserHasTags(models.Model):
user_id = models.IntegerField()
tag_id = models.IntegerField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_has_tags'
class UserViewActivity(models.Model):
activity_id = models.IntegerField()
user_id = models.IntegerField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'user_view_activitys'
class Users(AbstractBaseUser):
nick_name = models.CharField(max_length=255,unique=True)
real_name = models.CharField(max_length=255)
sex = models.IntegerField(default=0)
intro = models.CharField(max_length=400,default='')
cover = models.CharField(max_length=400,default='https://hi-sing-cdn.hikoon.com/file/20231116/vbhr3e6yk4l1700102812011wg18xstw9m.jpg')
avatar = models.CharField(max_length=400, blank=True, null=True,default='https://hi-sing-cdn.hikoon.com/image/20230925/heqk7stlm31695620862622v3gdnlhzars.png')
area_code = models.CharField(max_length=255,default='86')
phone = models.IntegerField(max_length=255)
email = models.CharField(max_length=255)
# origin_type = models.CharField(max_length=8)
# remarks = models.CharField(max_length=255)
# business_id = models.IntegerField(blank=True, null=True)
business = models.ForeignKey('self',null=True,related_name='has_business',on_delete=models.DO_NOTHING)
business_singer_limit = models.IntegerField(default=0)
password = models.CharField(max_length=255)
open_id = models.CharField(max_length=255, blank=True, null=True)
unionid = models.CharField(max_length=255, blank=True, null=True)
role = models.CharField(max_length=255,default=None)
scope = models.IntegerField(default=0)
sound = models.CharField(max_length=400,default='')
sound_at = models.DateTimeField(blank=True, null=True)
province = models.CharField(max_length=255, blank=True, null=True)
city = models.CharField(max_length=255, blank=True, null=True)
is_referee = models.IntegerField()
rate = models.CharField(max_length=255)
company = models.CharField(max_length=255, blank=True, null=True)
status = models.IntegerField()
audit_status = models.IntegerField(blank=True, null=True)
last_login = models.DateTimeField(blank=True, null=True)
is_home = models.IntegerField(default=1)
chat_mode = models.IntegerField(default=0)
wechat_account = models.CharField(max_length=255,default=None)
identity = models.IntegerField(default=0)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
USERNAME_FIELD = 'nick_name'
REQUIRED_FIELDS = []
def __str__(self):
return self.nick_name
@property
def token(self):
return self._generate_jwt_token()
def _generate_jwt_token(self):
token = jwt.encode({
'exp': datetime.utcnow() + timedelta(days=90),
'iat': datetime.utcnow(),
'data': {
'id':self.id,
'env':settings.ENV
}
},
settings.SECRET_KEY, algorithm='HS256')
return token
class Meta:
managed = False
db_table = 'users'
default_permissions = ()
import time
import schedule
import threading
from api import models
from django.utils import timezone
from django.db.models import F, Func
from django.db.models.functions import Now
def project_confirmation_times():
projects = models.Projects.objects.filter(status=1,deleted_at=None)
for project in projects:
#匹配的活动均值
l1 = list()
days_diff = Func(F('match_at') - F('publish_at'), function='ABS')
results = models.Activitys.objects.filter(status__in=[3,5],project_id=project.id).annotate(days_diff=days_diff)
for result in results:
try:l1.append(result.days_diff.days)
except:l1.append(0)
# 未匹配的活动均值
days_diff = Func(Now() - F('publish_at'),function='ABS')
deltas = models.Activitys.objects.filter(status=1,project_id=project.id).annotate(days_diff=days_diff)
for delta in deltas:
try:l1.append(delta.days_diff.days)
except:pass
try:mean = sum(l1) / len(l1)
except: mean = 0
models.ProjectConfirmationTime.objects.update_or_create(
project_id=project.id,
defaults={'average_day': mean,'created_at':timezone.now().strftime("%Y-%m-%d %H:%M:%S"),'updated_at':timezone.now().strftime("%Y-%m-%d %H:%M:%S")}
)
def job1():
threading.Thread(target=project_confirmation_times).start()
schedule.every().day.at("02:00").do(job1)
# schedule.every(1).minutes.do(job1)
def run():
while True:
schedule.run_pending()
time.sleep(1)
# -*- coding: utf-8 -*-
import logging
from rest_framework import serializers
from api import models,TLSSigAPIv2
import datetime
from HisinApi import settings
from datetime import timedelta
from django.utils import timezone
class BanneraSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
# 获取传递进来的 fields 参数,如果没有默认为 None
fields = kwargs.pop('fields', None)
super().__init__(*args, **kwargs)
if fields is not None:
allowed_fields = set(fields)
existing_fields = set(self.fields.keys())
# 找出需要删除的字段
for field_name in existing_fields - allowed_fields:
self.fields.pop(field_name)
class Meta:
model = models.Banners
fields = "__all__"
class ProjectsSerializer(serializers.ModelSerializer):
intro = serializers.SerializerMethodField()
master = serializers.SerializerMethodField()
visitor_count = serializers.SerializerMethodField()
class Meta:
model = models.Projects
fields = "__all__"
def get_intro(self,obj):
if obj.intro:intro = obj.intro
else:intro = '海星试唱入驻厂牌'
return intro
def get_master(self,obj):
queryset = models.Users.objects.filter(id=obj.master_id,deleted_at=None).first()
if queryset :data = BusinessSerializer(queryset,many=False).data
else:data=None
return data
def get_visitor_count(self, obj):
# 取当前日期和时间
now = timezone.now()
# 计算 30 天前的日期和时间
thirty_days_ago = now - timedelta(days=30)
return models.ProjectVisitors.objects.filter(project_id=obj.id, created_at__gte=thirty_days_ago).values('user_id').distinct().count()
class ProjectSimplesSerializer(serializers.ModelSerializer):
class Meta:
model = models.Projects
fields = ('id','name','cover')
class SystemTagsSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
# 获取传递进来的 fields 参数,如果没有默认为 None
fields = kwargs.pop('fields', None)
super().__init__(*args, **kwargs)
if fields is not None:
allowed_fields = set(fields)
existing_fields = set(self.fields.keys())
# 找出需要删除的字段
for field_name in existing_fields - allowed_fields:
self.fields.pop(field_name)
class Meta:
model = models.SystemTags
fields = "__all__"
class UsersSerializer(serializers.ModelSerializer):
has_tags = serializers.SerializerMethodField()
examine_info = serializers.SerializerMethodField()
is_band = serializers.SerializerMethodField()
is_subscribe = serializers.SerializerMethodField()
singer_count = serializers.SerializerMethodField()
collection_count = serializers.SerializerMethodField()
my_collection = serializers.SerializerMethodField()
my_audition_count = serializers.SerializerMethodField()
my_audition = serializers.SerializerMethodField()
total_audition_count = serializers.SerializerMethodField()
listen_count = serializers.SerializerMethodField()
my_listen = serializers.SerializerMethodField()
singer_collection_count = serializers.SerializerMethodField()
singer_audition_count = serializers.SerializerMethodField()
new_singer_count = serializers.SerializerMethodField()
new_collection_count = serializers.SerializerMethodField()
new_audition_count = serializers.SerializerMethodField()
new_platform_audition_count = serializers.SerializerMethodField()
is_reject = serializers.SerializerMethodField()
follower_count = serializers.SerializerMethodField()
following_count = serializers.SerializerMethodField()
home_red_dot = serializers.SerializerMethodField()
system_message_count = serializers.SerializerMethodField()
im_usersig = serializers.SerializerMethodField()
art_tag = serializers.SerializerMethodField()
business = serializers.SerializerMethodField()
auth_count = serializers.SerializerMethodField()
auth_tags = serializers.SerializerMethodField()
auth_status = serializers.SerializerMethodField()
group_status = serializers.SerializerMethodField()
project_status = serializers.SerializerMethodField()
project_name = serializers.SerializerMethodField()
member_count = serializers.SerializerMethodField()
whitelist_permission = serializers.SerializerMethodField()
is_activity_manage = serializers.SerializerMethodField()
is_project_master = serializers.SerializerMethodField()
is_intercept_auth = serializers.SerializerMethodField()
examine_count = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = (
'id','nick_name','rate','real_name','intro','member_count','auth_count','auth_tags','whitelist_permission',
'auth_status','is_activity_manage','identity','group_status','project_status','project_name','is_project_master','art_tag',
'im_usersig','my_listen','my_audition','my_collection','system_message_count','singer_count','is_reject',
'examine_info','follower_count','following_count','home_red_dot','listen_count','new_singer_count',
'new_collection_count','new_audition_count','new_platform_audition_count','singer_collection_count',
'singer_audition_count','collection_count','my_audition_count','total_audition_count','avatar','phone','email',
'business_id','open_id','unionid','is_band','is_subscribe','role','scope','status','audit_status','has_tags',
'is_intercept_auth','examine_count','province','city','is_referee','company','chat_mode','business','last_login','created_at')
def get_examine_count(self,obj):
user_ids = list(models.Users.objects.filter(audit_status=0, role__in=['Singer','Business'],deleted_at=None).values_list('id', flat=True))
examine_count = models.UserExamines.objects.filter(user_id__in=user_ids, status=0, deleted_at=None).count()
if obj.scope != 1:
examine_count = 0
return examine_count
def get_is_intercept_auth(self,obj):
source = 0
#有无风格标签
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id, type=1).values_list('tag_id', flat=True))
is_style_tag = models.SystemTags.objects.filter(id__in=tags, deleted_at=None).exists()
#打分项配置
parentobj = models.SystemConfig.objects.filter(identifier='TeZnnaB-Pfwyz8IADs0SM', status=1, deleted_at=None).first()
if parentobj:
data = SystemConfigSerializer(models.SystemConfig.objects.filter(parent_id=parentobj.id, status=1, deleted_at=None), many=True).data
for item in data:
if item['identifier'] == 'nick_name' and obj.nick_name:
source = source + int(item['content'])
if item['identifier'] == 'sex' and obj.sex:
source = source + int(item['content'])
if item['identifier'] == 'city' and obj.city:
source = source + int(item['content'])
if item['identifier'] == 'wechat_account' and obj.wechat_account:
source = source + int(item['content'])
if item['identifier'] == 'cover' and obj.cover:
source = source + int(item['content'])
if item['identifier'] == 'company' and obj.company:
source = source + int(item['content'])
if item['identifier'] == 'intro' and obj.intro:
source = source + int(item['content'])
if item['identifier'] == 'email' and obj.email:
source = source + int(item['content'])
if item['identifier'] == 'style' and is_style_tag:
source = source + int(item['content'])
if item['identifier'] == 'video' and models.UserDynamics.objects.filter(user_id=obj.id,type='video',deleted_at=None).exists():
source = source + int(item['content'])
if item['identifier'] == 'audio' and models.UserDynamics.objects.filter(user_id=obj.id,type='audio',deleted_at=None).exists():
source = source + int(item['content'])
if item['identifier'] == 'image' and models.UserDynamics.objects.filter(user_id=obj.id,type='image',deleted_at=None).exists():
source = source + int(item['content'])
#阈值
content = int(models.SystemConfig.objects.get(identifier='iymo-wZcV2F0UWFUKJR5m', status=1, deleted_at=None).content)
return False if source >= content else True
def get_art_tag(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id,type=2).values_list('tag_id',flat=True))
if len(tags) > 0:return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None).values(), many=True).data
else:
if obj.role == 'Singer':name = "歌手"
elif obj.role == 'Business':name = "商务"
else:name = "策划"
return [{"name":name}]
def get_im_usersig(self,obj):
api = TLSSigAPIv2.TLSSigAPIv2(settings.SDK_APPID, settings.PRI_KEY)
if settings.ENV == 'dev':user_id = 'test'+str(obj.id)
else:user_id = obj.id
usersig = api.genUserSig(user_id)
return usersig
def get_system_message_count(self,obj):
return models.UserMessages.objects.filter(type__in=[4,5,6,7,8,9,10,11,12,13,14],receiver_id=obj.id,is_read=0,deleted_at=None).count()
def get_is_reject(self,obj):
return models.UserExamines.objects.filter(user_id=obj.id,status=2,deleted_at=None).exists()
def get_new_platform_audition_count(self,obj):
if obj.scope == 0:return 0
if obj.scope != 2:activity_ids = self.context['activity_ids']
else:
# 获取项目用户关联项目id
project_ids = list( models.UserHasProjects.objects.filter(user_id=obj.id).values_list('project_id', flat=True))
activity_ids = list(models.Activitys.objects.filter(project_id__in=project_ids,status=1,deleted_at=None).values_list('id', flat=True))
# 过滤掉不相关的活动,去掉不公开的厂牌下活动不是自己创建的活动
nopublic_project_id = list(models.Projects.objects.filter(id__in=project_ids, is_public=0, deleted_at=None).values_list('id',flat=True))
noself_activity_id = list(models.Activitys.objects.filter(project_id__in=nopublic_project_id, status=1, deleted_at=None).exclude(user_id=obj.id).values_list('id', flat=True))
activity_ids = [x for x in activity_ids if x not in noself_activity_id]
return models.UserMessages.objects.filter(is_read=0, activity_id__in=activity_ids, type=3,receiver_id=obj.id, deleted_at=None, is_bind=0).count()
def get_new_audition_count(self,obj):
"""
我的歌手新增试唱数
:param obj:
:return:
"""
member_count = self.get_member_count(obj)
new_audition_count = models.UserMessages.objects.filter(is_read=0, activity_id__in=self.context['activity_ids'], type=3,
receiver_id=obj.id, deleted_at=None, is_bind=1).count()
if member_count == 0:new_audition_count = 0
return new_audition_count
def get_new_collection_count(self,obj):
"""
我的歌手新增收藏数
:param obj:
:return:
"""
return models.UserMessages.objects.filter(is_read=0,activity_id__in=self.context['activity_ids'],type=2,receiver_id=obj.id,deleted_at=None).count()
def get_new_singer_count(self,obj):
"""
新增歌手数
:param obj:
:return:
"""
return models.UserMessages.objects.filter(is_read=0,type=1,receiver_id=obj.id,deleted_at=None).count()
def get_singer_audition_count(self,obj):
#获取我关联的歌手
singer_ids = list(models.Users.objects.filter(business_id=obj.id,deleted_at=None).values_list('id',flat=True))
#获取我关联歌手的提交数量
return models.ActivityHasUsers.objects.filter(user_id__in=singer_ids,activity_id__in=self.context['activity_ids'],type='Submit',deleted_at=None).count()
def get_singer_collection_count(self,obj):
#获取我关联的歌手
singer_ids = list(models.Users.objects.filter(business_id=obj.id,deleted_at=None).values_list('id',flat=True))
#获取我关联歌手的收藏数量
return models.UserActivityCollections.objects.filter(user_id__in=singer_ids,activity_id__in=self.context['activity_ids'],deleted_at=None).count()
def get_listen_count(self,obj):
return models.UserViewActivity.objects.filter(user_id=obj.id,activity_id__in=self.context['all_activity_ids'],deleted_at=None).values('activity_id').distinct().count()
def get_my_listen(self,obj):
activity_ids = list(models.UserViewActivity.objects.filter(user_id=obj.id, deleted_at=None).values_list('activity_id',flat=True).order_by('-updated_at'))
if not activity_ids:return {"count": 0,"cover":None}
activity_id_str = ",".join('%s' % id for id in activity_ids)
ids = list(models.Activitys.objects.filter(id__in=activity_ids, deleted_at=None).extra(select={'m': 'FIELD(id,{})'.format(activity_id_str)}, order_by=['m']).values_list('id',flat=True))
if ids:url = models.Activitys.objects.filter(id=ids[0]).first().cover
else:url=None
return {"count":self.get_listen_count(obj),"cover":url}
def get_singer_count(self,obj):
return models.Users.objects.filter(business_id=obj.id,deleted_at=None,audit_status=1,status=1).count()
def get_collection_count(self, obj):
"""首页收藏数:正在进行的活动"""
ids = list(models.UserActivityCollections.objects.filter(user_id=obj.id, deleted_at=None).order_by('-created_at').values_list('activity_id', flat=True))
return models.Activitys.objects.filter(id__in=ids,status=1,deleted_at=None).count()
def get_my_collection(self,obj):
ids = list(models.UserActivityCollections.objects.filter(user_id=obj.id,deleted_at=None).order_by('-created_at').values_list('activity_id',flat=True))
if not ids:return {"count": 0,"cover":None}
activity_id_str = ",".join('%s' % id for id in ids)
ids = list(models.Activitys.objects.filter(id__in=ids, deleted_at=None).extra(select={'m': 'FIELD(id,{})'.format(activity_id_str)}, order_by=['m']).values_list('id',flat=True))
if ids:url = models.Activitys.objects.filter(id=ids[0]).first().cover
else:url = None
ids = list(models.UserActivityCollections.objects.filter(user_id=obj.id, deleted_at=None).order_by(
'-created_at').values_list('activity_id', flat=True))
count = models.Activitys.objects.filter(id__in=ids, deleted_at=None).count()
return {"count":count,"cover":url}
def get_my_audition_count(self, obj):
return models.ActivityHasUsers.objects.filter(user_id=obj.id,activity_id__in=self.context['all_activity_ids'],deleted_at=None).all().values('activity_id').distinct().count()
def get_my_audition(self,obj):
ids = models.ActivityHasUsers.objects.filter(user_id=obj.id, deleted_at=None).order_by('-created_at').values_list('activity_id', flat=True).distinct()
if not ids:return {"count": 0,"cover":None}
activity_id_str = ",".join('%s' % id for id in ids)
ids = list(models.Activitys.objects.filter(id__in=ids, deleted_at=None).extra(select={'m': 'FIELD(id,{})'.format(activity_id_str)}, order_by=['m']).values_list('id',flat=True))
if ids:url = models.Activitys.objects.filter(id=ids[0]).first().cover
else:url = None
return {"count": self.get_my_audition_count(obj),"cover":url}
def get_total_audition_count(self,obj):
return models.ActivityHasUsers.objects.filter(type='Submit',deleted_at=None).all().values('user_id').distinct().count()
def get_has_tags(self,obj):
return UserHasTagsSerializer(models.UserHasTags.objects.filter(user_id=obj.id,deleted_at=None),many=True).data
def get_examine_info(self,obj):
return UserExaminesSerializer(models.UserExamines.objects.filter(user_id=obj.id).order_by('-created_at').first(),many=False).data
def get_is_band(self,obj):
if obj.open_id and obj.unionid :return True
else:return False
def get_is_subscribe(self,obj):
return models.WechatOfficialUsers.objects.filter(union_id=obj.unionid,is_subscribe=1).exists()
def get_follower_count(self,obj):
user_ids = list(models.UserFollowRelations.objects.filter(following_id=obj.id,deleted_at=None).values_list('follower_id',flat=True))
return models.Users.objects.filter(id__in =user_ids,status=1,deleted_at=None).count()
def get_following_count(self,obj):
user_ids = list(models.UserFollowRelations.objects.filter(follower_id=obj.id,deleted_at=None).values_list('following_id',flat=True))
return models.Users.objects.filter(id__in =user_ids,status=1,deleted_at=None).count()
def get_home_red_dot(self,obj):
"""
主页红点:新访客,新粉丝,有新试唱数且是推荐人身份,且审核通过
:param obj:
:return:
"""
new_visitor = models.UserVisitors.objects.filter(user_id=obj.id,is_read=0).exists()
new_fans = models.UserFollowRelations.objects.filter(following_id=obj.id,deleted_at=None,is_read=0).exists()
#平台/项目试唱数
new_platform_audition = self.get_new_platform_audition_count(obj)
# 团队管理-ta们新试唱
new_ta_audition = self.get_new_audition_count(obj)
# # 团队管理-ta们新收藏 删除于2023-12-8
# new_ta_collection = self.get_new_collection_count(obj)
# 待审核数
examine_count = self.get_examine_count(obj)
if (
new_visitor or
new_fans or
new_ta_audition or
# new_ta_collection or
examine_count or
(new_platform_audition and obj.role=='Business') and obj.audit_status==1):return True
else:return False
def get_business(self,obj):
if obj.business_id:return SingerBusinessSerializer(models.Users.objects.filter(id=obj.business_id).first(),many=False).data
else:return None
def get_auth_count(self,obj):
if obj.scope != 1:auth_count = 0
else:auth_count = models.UserAuthInfos.objects.filter(status=0,deleted_at=None).values('user_id').distinct().count()
return auth_count
def get_auth_tags(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id, type=4).values_list('tag_id', flat=True))
if len(tags) == 0:return None
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None), many=True,fields=['id','name','expand']).data
def get_auth_status(self,obj):
auth_info = models.UserAuthInfos.objects.filter(user_id=obj.id,deleted_at=None).last()
if auth_info:status = auth_info.status
else:status=3
return status
def get_group_status(self,obj):
query = models.GroupHasMembers.objects.filter(member_id=obj.id,deleted_at=None).last()
status = query.status if query else 0
return status
def get_project_status(self,obj):
query = models.ProjectHasMembers.objects.filter(user_id=obj.id, status__in= [1,3],deleted_at=None).last()
status = query.status if query else 0
return status
def get_project_name(self,obj):
projecthasmember = models.ProjectHasMembers.objects.filter(user_id=obj.id, status__in= [1,3],deleted_at=None).last()
project_id = projecthasmember.project_id if projecthasmember else 0
project = models.Projects.objects.filter(id=project_id,status=1, deleted_at=None).first()
return project.name if project else ''
def get_is_project_master(self,obj):
query = models.ProjectHasMembers.objects.filter(user_id=obj.id, status__in= [1,3],deleted_at=None).last()
if not query:
return False
return models.UserHasProjects.objects.filter(project_id=query.project_id,user_id=obj.id).exists()
def get_member_count(self, obj):
return models.Users.objects.filter(business_id=obj.id, status=1, audit_status=1, deleted_at=None).count()
def get_whitelist_permission(self,obj):
#唱权限检测
singobj = models.SystemConfig.objects.filter(identifier='Jy-zgPbcSXSGnvHIx8moq',status=1, deleted_at=None).first()
if singobj:
if str(obj.id) in singobj.content.split(','):return {"sing": True, "listen": True}
else:sing = False
else: sing = False
#听权限检测
listenobj = models.SystemConfig.objects.filter(identifier='-BIGBAR9rPOMwCrw4hIuQ', status=1,deleted_at=None).first()
if listenobj:listen = True if str(obj.id) in listenobj.content.split(',') else False
else:listen = False
return {"sing":sing,"listen":listen}
def get_is_activity_manage(self,obj):
'''是否外部管理员'''
return models.UserManageActivitie.objects.filter(user_id=obj.id).exists()
class UserHomeSerializer(serializers.ModelSerializer):
business_id = serializers.SerializerMethodField()
business = serializers.SerializerMethodField()
art_tag = serializers.SerializerMethodField()
style_tag = serializers.SerializerMethodField()
follower_count = serializers.SerializerMethodField()
new_follower_count = serializers.SerializerMethodField()
following_count = serializers.SerializerMethodField()
sound_tag = serializers.SerializerMethodField()
is_follow = serializers.SerializerMethodField()
sound_like_count = serializers.SerializerMethodField()
is_sound_like = serializers.SerializerMethodField()
visitor_count = serializers.SerializerMethodField()
new_visitor_count = serializers.SerializerMethodField()
new_platform_audition_count = serializers.SerializerMethodField()
auth_status = serializers.SerializerMethodField()
auth_tags = serializers.SerializerMethodField()
broker = serializers.SerializerMethodField()
member_count = serializers.SerializerMethodField()
source = serializers.SerializerMethodField()
dynamics_count = serializers.SerializerMethodField()
class Meta:
model = models.Users
exclude = ['password','phone','deleted_at']
def get_dynamics_count(self,obj):
image_count = models.UserDynamics.objects.filter(user_id=obj.id,type='image',deleted_at=None).count()
audio_count = models.UserDynamics.objects.filter(user_id=obj.id,type='audio',deleted_at=None).count()
video_count = models.UserDynamics.objects.filter(user_id=obj.id,type='video',deleted_at=None).count()
return {"image_count":image_count,"audio_count":audio_count,"video_count":video_count}
def get_source(self,obj):
source = 0
parentobj = models.SystemConfig.objects.filter(identifier='TeZnnaB-Pfwyz8IADs0SM', status=1, deleted_at=None).first()
if parentobj:
data = SystemConfigSerializer(models.SystemConfig.objects.filter(parent_id=parentobj.id, status=1, deleted_at=None), many=True).data
for item in data:
if item['identifier'] == 'nick_name' and obj.nick_name:
source = source + int(item['content'])
if item['identifier'] == 'sex' and obj.sex:
source = source + int(item['content'])
if item['identifier'] == 'city' and obj.city:
source = source + int(item['content'])
if item['identifier'] == 'wechat_account' and obj.wechat_account:
source = source + int(item['content'])
if item['identifier'] == 'cover' and obj.cover:
source = source + int(item['content'])
if item['identifier'] == 'company' and obj.company:
source = source + int(item['content'])
if item['identifier'] == 'intro' and obj.intro:
source = source + int(item['content'])
if item['identifier'] == 'email' and obj.email:
source = source + int(item['content'])
if item['identifier'] == 'style' and self.get_style_tag(obj):
source = source + int(item['content'])
if item['identifier'] == 'video' and models.UserDynamics.objects.filter(user_id=obj.id,type='video',deleted_at=None).exists():
source = source + int(item['content'])
if item['identifier'] == 'audio' and models.UserDynamics.objects.filter(user_id=obj.id,type='audio',deleted_at=None).exists():
source = source + int(item['content'])
if item['identifier'] == 'image' and models.UserDynamics.objects.filter(user_id=obj.id,type='image',deleted_at=None).exists():
source = source + int(item['content'])
#阈值推荐语
content_list = eval(models.SystemConfig.objects.get(identifier='YmSNBXwMB6cUo-zRT26s-', status=1, deleted_at=None).content)
text = ''
for content in content_list:
if content['min'] <= source < content['max']:text = content['content']
return {"number":source,"text":text}
def get_new_platform_audition_count(self,obj):
#是否外部管理员
is_activity_manage = models.UserManageActivitie.objects.filter(user_id=obj.id).exists()
#1.普通用户
if obj.scope == 0 and not is_activity_manage:
return 0
#2.平台管理员
if obj.scope == 1:
activity_ids = self.context['activity_ids']
#项目管理员和外部管理员
else:
# 获取项目用户关联项目id
project_ids = list( models.UserHasProjects.objects.filter(user_id=obj.id).values_list('project_id', flat=True))
activity_ids = list(models.Activitys.objects.filter(project_id__in=project_ids,status=1,deleted_at=None).values_list('id', flat=True))
# 过滤掉不相关的活动,去掉不公开的厂牌下活动不是自己创建的活动
nopublic_project_id = list(models.Projects.objects.filter(id__in=project_ids, is_public=0, deleted_at=None).values_list('id',flat=True))
noself_activity_id = list(models.Activitys.objects.filter(project_id__in=nopublic_project_id, status=1, deleted_at=None).exclude(user_id=obj.id).values_list('id', flat=True))
activity_ids = [x for x in activity_ids if x not in noself_activity_id]
#外部管理员
if is_activity_manage:
manage_activity_ids = list(models.UserManageActivitie.objects.filter(user_id=obj.id,activity_status=1).values_list('activity_id',flat=True))
activity_ids = set(sorted(activity_ids+manage_activity_ids))
return models.UserMessages.objects.filter(is_read=0, activity_id__in=activity_ids, type=3,receiver_id=obj.id, deleted_at=None, is_bind=0).count()
def get_visitor_count(self,obj):
#取当前日期和时间
now = timezone.now()
# 计算 30 天前的日期和时间
thirty_days_ago = now - timedelta(days=30)
return models.UserVisitors.objects.filter(user_id=obj.id,created_at__gte=thirty_days_ago).values('visitor_id').distinct().count()
def get_new_visitor_count(self, obj):
# 取当前日期和时间
now = timezone.now()
# 计算 30 天前的日期和时间
thirty_days_ago = now - timedelta(days=30)
return models.UserVisitors.objects.filter(user_id=obj.id,is_read=0,created_at__gte=thirty_days_ago).count()
def get_business_id(self,obj):
return obj.business_id
def get_business(self,obj):
return SystemBusinessSerializer(models.Users.objects.filter(id=obj.business_id,status=1,audit_status=1,deleted_at=None).first(),many=False).data
def get_art_tag(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id,type=2).values_list('tag_id',flat=True))
if len(tags) > 0:
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None).values(), many=True,fields=['id','name']).data
else:
if obj.role == 'Singer':
name = "歌手"
elif obj.role == 'Business':
name = "商务"
else:
name = "策划"
return [{"name":name}]
def get_style_tag(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id, type=1).values_list('tag_id', flat=True))
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None).values(), many=True,fields=['id','name']).data
def get_sound_tag(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id, type=3).values_list('tag_id', flat=True))
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None).values(), many=True,fields=['id','name']).data
def get_follower_count(self,obj):
user_ids = list(models.UserFollowRelations.objects.filter(following_id=obj.id,deleted_at=None).values_list('follower_id',flat=True))
return models.Users.objects.filter(id__in =user_ids,status=1,deleted_at=None).count()
def get_new_follower_count(self,obj):
return models.UserFollowRelations.objects.filter(following_id=obj.id,deleted_at=None,is_read=0).count()
def get_following_count(self,obj):
user_ids = list(models.UserFollowRelations.objects.filter(follower_id=obj.id,deleted_at=None).values_list('following_id',flat=True))
return models.Users.objects.filter(id__in =user_ids,status=1,deleted_at=None).count()
def get_is_follow(self,obj):
request_usre_id = self.context['request_usre_id']
return models.UserFollowRelations.objects.filter(follower_id=request_usre_id,following_id=obj.id, deleted_at=None).exists()
def get_sound_like_count(self,obj):
if obj.sound:
return models.TidingsHasInteracts.objects.filter(type=3,type_id=obj.id,status=1,deleted_at=None).count()
else:
return 0
def get_is_sound_like(self,obj):
if obj.sound:
request_usre_id = self.context['request_usre_id']
return models.TidingsHasInteracts.objects.filter(type=3,user_id=request_usre_id,status=1,type_id=obj.id,deleted_at=None).exists()
else:
return False
def get_auth_status(self,obj):
auth_info = models.UserAuthInfos.objects.filter(user_id=obj.id,deleted_at=None).last()
if auth_info:
status = auth_info.status
reason=auth_info.reason
else:
status=3
reason=None
return {"status":status,"reason":reason}
def get_auth_tags(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id, type=4).values_list('tag_id', flat=True))
if len(tags) == 0:return None
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None), many=True,fields=['id','name']).data
def get_broker(self,obj):
singer_tag_id = models.SystemConfig.objects.filter(identifier='auth_singer_tag').values_list('content',flat=True).get()
has_singer_tag = models.UserTagRelations.objects.filter(user_id=obj.id, type=4,tag_id=singer_tag_id).exists()
queryset = models.Users.objects.filter(id=obj.business_id,status=1,audit_status=1,deleted_at=None).first()
if not has_singer_tag:return None
elif not queryset: return None
else:return SystemBusinessSerializer(queryset,many=False).data
def get_member_count(self,obj):
return models.Users.objects.filter(business_id=obj.id,status=1,audit_status=1,deleted_at=None).count()
class UserTidingSerializer(serializers.ModelSerializer):
activity = serializers.SerializerMethodField()
user = serializers.SerializerMethodField()
class Meta:
model = models.UserHasTidings
exclude = ['deleted_at']
def get_user(self,obj):
return UserListSerializer(models.Users.objects.filter(id=obj.user_id).first(),many=False).data
def get_activity(self,obj):
return TidingsActivity(models.Activitys.objects.filter(id=obj.activity_id).first(),many=False).data
class UserFollowSerializer(serializers.ModelSerializer):
is_follow = serializers.SerializerMethodField()
is_read = serializers.SerializerMethodField()
follow_time = serializers.SerializerMethodField()
auth_tags = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = ('id','avatar','nick_name','real_name','intro','is_follow','is_read','follow_time','role','identity','auth_tags')
def get_is_follow(self,obj):
user_id = self.context['user_id']
return models.UserFollowRelations.objects.filter(following_id=obj.id,follower_id=user_id,deleted_at=None).exists()
def get_is_read(self,obj):
user_id = self.context['user_id']
return not models.UserFollowRelations.objects.filter(following_id=user_id,follower_id=obj.id,deleted_at=None,is_read=0).exists()
def get_follow_time(self, obj):
user_id = self.context['user_id']
return models.UserFollowRelations.objects.filter(following_id=user_id, follower_id=obj.id,deleted_at=None).first().created_at.strftime("%Y-%m-%d %H:%M:%S")
def get_auth_tags(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id, type=4).values_list('tag_id', flat=True))
if len(tags) == 0:return None
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None), many=True,fields=['id','name','expand']).data
class UserFollowingSerializer(serializers.ModelSerializer):
is_follow_me = serializers.SerializerMethodField()
art_tag = serializers.SerializerMethodField()
follow_time = serializers.SerializerMethodField()
is_read = serializers.SerializerMethodField()
auth_tags = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = ('id','avatar','nick_name','art_tag','real_name','intro','is_follow_me','identity','follow_time','is_read','auth_tags')
def get_is_follow_me(self,obj):
user_id = self.context['user_id']
return models.UserFollowRelations.objects.filter(following_id=user_id,follower_id=obj.id,deleted_at=None).exists()
def get_art_tag(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id,type=2).values_list('tag_id',flat=True))
if len(tags) > 0:
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None).values(), many=True).data
else:
if obj.role == 'Singer':
name = "歌手"
elif obj.role == 'Business':
name = "商务"
else:
name = "策划"
return [{"name":name}]
def get_follow_time(self,obj):
user_id = self.context['user_id']
return models.UserFollowRelations.objects.filter(following_id=obj.id, follower_id=user_id,deleted_at=None).first().created_at.strftime("%Y-%m-%d %H:%M:%S")
def get_is_read(self,obj):
user_id = self.context['user_id']
return not models.UserFollowRelations.objects.filter(following_id=obj.id,follower_id=user_id,deleted_at=None,is_read=0).exists()
def get_auth_tags(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id, type=4).values_list('tag_id', flat=True))
if len(tags) == 0:return None
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None), many=True,fields=['id','name','expand']).data
class ActivitysPriceSerializer(serializers.ModelSerializer):
class Meta:
model = models.ActivityUserHasPrices
fields = "__all__"
address = serializers.SerializerMethodField()
is_hide = serializers.SerializerMethodField()
def get_address(self,obj):
city = models.CountryRegions.objects.filter(id=obj.address_id).first()
if city:province = models.CountryRegions.objects.filter(id=city.parent_id).first()
else:return None
return {"province":province.name,"city":city.name}
def get_is_hide(self,obj):
"""获取音频公开属性"""
ahu = models.ActivityHasUsers.objects.filter(type='Submit', user_id=obj.user_id, activity_id=self.context['activity_id']).last()
return ahu.is_hide if ahu else 1
class ActivitysSerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
attend_user = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
attend_count = serializers.SerializerMethodField()
is_take = serializers.SerializerMethodField()
comfire_share_user = serializers.SerializerMethodField()
is_promote = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = ("id","cover","comfire_share_user","is_promote","song_name","status","created_at","sub_title","guide","lyric","clip_lyric","tags","attend_user","project","is_take","attend_count")
def get_is_promote(self,obj):
project = models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).first()
if not project:is_promote = 0
else:is_promote = project.is_promote
return is_promote
def get_comfire_share_user(self, obj):
user_id = self.context['user_id']
share_obj = models.ActivityShareUsers.objects.filter(activity_id=obj.id, user_id=user_id).first()
if share_obj:
if share_obj.share_id:return BusinessSerializer(models.Users.objects.filter(id=share_obj.share_id).first(), many=False).data
else:return None
else:
return None
def get_tags(self,obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_attend_user(self,obj):
attend_user_ids = models.ActivityHasUsers.objects.filter(type='Submit',activity_id=obj.id,deleted_at=None).all().values_list('user_id',flat=True).distinct()[:6] #最多取前6个
return UserListSerializer (models.Users.objects.in_bulk(attend_user_ids).values(),many=True).data
def get_project(self,obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(),many=True).data
def get_attend_count(self,obj):
return models.ActivityHasUsers.objects.filter(type='Submit',activity_id=obj.id,deleted_at=None).all().values('user_id').distinct().count()
def get_is_take(self,obj):
user_id = self.context['user_id']
return models.ActivityHasUsers.objects.filter(user_id=user_id,activity_id=obj.id,status=1).exists()
class PlatfromAuditionSerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
submit = serializers.SerializerMethodField()
is_promote = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = ("id","cover","song_name","status","is_promote","is_official","created_at","sub_title","guide","lyric","clip_lyric","tags","submit","project")
def get_is_promote(self,obj):
try:
if obj.project.is_promote==1 and obj.project.deleted_at == None and obj.project.status==1:is_promote = 1
else:is_promote =0
except:
is_promote = 0
return is_promote
def get_tags(self,obj):
query_set_list = models.ActivityHasTags.objects.select_related('tag').filter(activity_id=obj.id,deleted_at=None)
tag_list = []
for query_set in query_set_list:
tag_list.append(query_set.tag)
data = SystemTagsSerializer(tag_list, many=True).data
return data
def get_project(self,obj):
try:
if obj.project.deleted_at == None and obj.project.status==1:return [{"id":obj.project.id,"name":obj.project.name}]
else:return []
except: return []
def get_submit(self,obj):
user_id = self.context['user_id']
query_set = obj.ahus
messageobj_list = models.UserMessages.objects.none()
sender_id_list = []
for q in query_set:
messageobj = models.UserMessages.objects.filter(type=3, activity_id=obj.id, sender_id=q.user_id,receiver_id=user_id, is_read=0, is_bind=0, deleted_at=None)
messageobj_list = messageobj_list | messageobj
for message in messageobj_list:
sender_id_list.append(message.sender_id)
for q in query_set:
if q.user_id in sender_id_list:q.is_new = True
else:q.is_new = False
query_set = list(query_set)
query_set.sort(key=lambda x: x.is_new,reverse=True)
query_set.sort(key=lambda x: x.status)
return PlatfromAuditionHasUserSerializer(query_set,many=True,context={"user_id":user_id}).data
class ListenActivitysSerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
listen_at = serializers.SerializerMethodField()
is_unlike = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = ("id","cover","song_name","status","is_official","created_at","sub_title","guide","lyric","clip_lyric","tags","project","listen_at","is_unlike")
def get_listen_at(self,obj):
user_id = self.context['user_id']
return models.UserViewActivity.objects.filter(user_id=user_id,activity_id=obj.id,deleted_at=None).first().updated_at.strftime("%Y-%m-%d %H:%M:%S")
def get_tags(self,obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_project(self,obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(),many=True).data
def get_is_unlike(self, obj):
user_id = self.context['user_id']
return models.UserActivityUnlikes.objects.filter(user_id=user_id, activity_id=obj.id, deleted_at=None).exists()
class CollectionActivitysSerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
collection_at = serializers.SerializerMethodField()
attend_count = serializers.SerializerMethodField()
attend_user = serializers.SerializerMethodField()
view_count = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = ("id","cover","song_name","status","is_official","attend_count","view_count","attend_user","created_at","sub_title","guide","guide_clip","lyric","clip_lyric","tags","project","collection_at",'sex','mark','speed','lang',)
def get_collection_at(self,obj):
user_id = self.context['user_id']
return models.UserActivityCollections.objects.filter(user_id=user_id,activity_id=obj.id,deleted_at=None).first().created_at.strftime("%Y-%m-%d %H:%M:%S")
def get_view_count(self,obj):
return models.UserViewActivity.objects.filter(activity_id=obj.id,deleted_at=None).count()
def get_tags(self,obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_project(self,obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(),many=True).data
def get_attend_count(self, obj):
return models.ActivityHasUsers.objects.filter(type='Submit', activity_id=obj.id,deleted_at=None).all().values('user_id').distinct().count()
def get_attend_user(self,obj):
attend_user_ids = models.ActivityHasUsers.objects.filter(type='Submit',activity_id=obj.id,deleted_at=None).values_list('user_id',flat=True).distinct()[:6] #最多取前6个
return UserListSerializer (models.Users.objects.in_bulk(attend_user_ids).values(),many=True).data
class MyActivitysSerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
is_take = serializers.SerializerMethodField()
save_count = serializers.SerializerMethodField()
submit_count = serializers.SerializerMethodField()
attend_count = serializers.SerializerMethodField()
attend_user = serializers.SerializerMethodField()
sound_url = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
# fields = "__all__"
fields = (
"id", "status","is_official","cover", "song_name","attend_count","attend_user", "created_at", "sub_title", "guide", "lyric", "clip_lyric", "tags",
"project", "is_take", "save_count","submit_count","sound_url")
def get_save_count(self,obj):
user_id = self.context['user_id']
return models.ActivityHasUsers.objects.filter(activity_id=obj.id,user_id=user_id,type="Save",deleted_at=None).count()
def get_submit_count(self,obj):
user_id = self.context['user_id']
return models.ActivityHasUsers.objects.filter(activity_id=obj.id,user_id=user_id,type="Submit",deleted_at=None).count()
def get_tags(self, obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_project(self, obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(), many=True).data
def get_is_take(self, obj):
user_id = self.context['user_id']
return models.ActivityHasUsers.objects.filter(user_id=user_id, activity_id=obj.id, status=1).exists()
def get_attend_count(self, obj):
return models.ActivityHasUsers.objects.filter(type='Submit', activity_id=obj.id,deleted_at=None).all().values('user_id').distinct().count()
def get_attend_user(self, obj):
attend_user_ids = models.ActivityHasUsers.objects.filter(type='Submit', activity_id=obj.id,deleted_at=None).values_list(
'user_id', flat=True).distinct()[:6] # 最多取前6个
return UserListSerializer(models.Users.objects.in_bulk(attend_user_ids).values(), many=True).data
def get_sound_url(self,obj):
user_id = self.context['user_id']
ahu = models.ActivityHasUsers.objects.filter(activity_id=obj.id, user_id=user_id, type='Submit').first()
if ahu:
sound_url = ahu.demo_url
else:
sound_url = models.ActivityHasUsers.objects.filter(activity_id=obj.id, user_id=user_id,deleted_at=None).last().demo_url
return sound_url
class MySingerActivitysSerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
save_count = serializers.SerializerMethodField()
submit_count = serializers.SerializerMethodField()
submit_info = serializers.SerializerMethodField()
attend_count = serializers.SerializerMethodField()
is_take = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = (
"id", "status","is_official","cover", "song_name", "created_at", "sub_title", "guide", "lyric", "clip_lyric", "tags",
"project", "save_count","submit_count","submit_info","attend_count","is_take")
def get_save_count(self,obj):
user_id = self.context['user_id']
return models.ActivityHasUsers.objects.filter(activity_id=obj.id,user_id=user_id,type="Save",deleted_at=None).count()
def get_submit_count(self,obj):
user_id = self.context['user_id']
return models.ActivityHasUsers.objects.filter(activity_id=obj.id,user_id=user_id,type="Submit",deleted_at=None).count()
def get_tags(self, obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_project(self, obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(), many=True).data
def get_submit_info(self,obj):
user_id = self.context['user_id']
return ActivitysHasUserSerializer(models.ActivityHasUsers.objects.filter(activity_id=obj.id,user_id=user_id,type="Submit",deleted_at=None).first(),many=False).data
def get_attend_count(self, obj):
return models.ActivityHasUsers.objects.filter(type='Submit', activity_id=obj.id,deleted_at=None).all().values('user_id').distinct().count()
def get_is_take(self, obj):
user_id = self.context['user_id']
return models.ActivityHasUsers.objects.filter(user_id=user_id, activity_id=obj.id, status=1).exists()
class V2ActivitysSerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
attend_user = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
attend_count = serializers.SerializerMethodField()
is_take = serializers.SerializerMethodField()
is_collection = serializers.SerializerMethodField()
view_count = serializers.SerializerMethodField()
#status_tag状态标签
status_tag = serializers.SerializerMethodField()
is_listen = serializers.SerializerMethodField()
is_submit = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
# fields = "__all__"
fields = ("id","cover","song_name","status","is_official","created_at","is_listen","is_submit","is_collection","sub_title","guide","guide_clip","guide_clip_duration","lyric","clip_lyric","tags","attend_user","project","attend_count","is_take","is_collection","view_count","status_tag")
def get_is_listen(self, obj):
return obj.is_listen
def get_is_submit(self, obj):
return obj.is_submit
def get_is_collection(self, obj):
return obj.is_collection
def get_attend_count(self,obj):
return obj.attend_count
def get_is_take(self, obj):
return obj.is_take
def get_view_count(self,obj):
return obj.view_count
def get_status_tag(self,obj):
if obj.is_listen:return 'listened'
else:return 'new'
def get_is_new(self,obj):
new_day = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime("%Y-%m-%d %H:%M:%S")
is_within = models.Activitys.objects.filter(id=obj.id,created_at__gte =new_day).exists()
return not obj.is_listen and is_within
def get_tags(self,obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_attend_user(self,obj):
attend_user_ids = models.ActivityHasUsers.objects.filter(type='Submit',activity_id=obj.id,deleted_at=None).values_list('user_id',flat=True).distinct()[:6] #最多取前6个
return UserListSerializer (models.Users.objects.in_bulk(attend_user_ids).values(),many=True).data
def get_project(self,obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(),many=True).data
class ActivitysCollectionSerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
attend_count = serializers.SerializerMethodField()
collection = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = "__all__"
def get_tags(self,obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_project(self,obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(),many=True).data
def get_attend_count(self,obj):
return models.ActivityHasUsers.objects.filter(type='Submit',activity_id=obj.id,deleted_at=None).all().values('user_id').distinct().count()
def get_collection(self,obj):
singer_ids = self.context['singer_ids']
user_id = self.context['user_id']
queset = models.UserActivityCollections.objects.filter(user_id__in=singer_ids,activity_id=obj.id,deleted_at=None).order_by('-created_at')
return CollectionsHasUserSerializer(queset,many=True,context={"user_id":user_id}).data
class ActivitysSubmitUserSerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
submit = serializers.SerializerMethodField()
is_promote = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = "__all__"
def get_is_promote(self,obj):
project = models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).first()
if not project:is_promote = 0
else:is_promote = project.is_promote
return is_promote
def get_tags(self,obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_project(self,obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(),many=True).data
def get_submit(self,obj):
user_id = self.context['user_id']
query_set = obj.ahus
messageobj_list = models.UserMessages.objects.none()
sender_id_list = []
for q in query_set:
messageobj = models.UserMessages.objects.filter(type=3, activity_id=obj.id, sender_id=q.user_id,receiver_id=user_id, is_read=0, is_bind=1, deleted_at=None)
messageobj_list = messageobj_list | messageobj
for message in messageobj_list:
sender_id_list.append(message.sender_id)
for q in query_set:
if q.user_id in sender_id_list:
q.is_new = True
else:
q.is_new = False
query_set = list(query_set)
query_set.sort(key=lambda x: x.is_new, reverse=True)
query_set.sort(key=lambda x: x.status)
return AuditionHasUserSerializer(query_set,many=True,context={"user_id":user_id}).data
class SingerActivitysSerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
attend_user = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
is_join = serializers.SerializerMethodField()
attend_count = serializers.SerializerMethodField()
is_take = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = "__all__"
def get_tags(self,obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_attend_user(self,obj):
attend_user_ids = models.ActivityHasUsers.objects.filter(activity_id=obj.id,deleted_at=None).all().values_list('user_id',flat=True).distinct()[:6] #最多取前6个
return UserListSerializer (models.Users.objects.in_bulk(attend_user_ids).values(),many=True).data
def get_project(self,obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(),many=True).data
def get_is_join(self,obj):
singer_id = self.context['singer_id']
return models.ActivityHasUsers.objects.filter(user_id=singer_id, activity_id=obj.id).exists()
def get_attend_count(self,obj):
return models.ActivityHasUsers.objects.filter(activity_id=obj.id,deleted_at=None).all().values('user_id').distinct().count()
def get_is_take(self,obj):
singer_id = self.context['singer_id']
return models.ActivityHasUsers.objects.filter(user_id=singer_id,activity_id=obj.id,status=1).exists()
class ActivitysHasUserSerializer(serializers.ModelSerializer):
class Meta:
model = models.ActivityHasUsers
fields = ("demo_url","syn_status","status","version","submit_at","mode","sing_type","updated_at")
class ManyActivitysHasUserSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()
class Meta:
model = models.ActivityHasUsers
fields = (
"id", "user","demo_url","durations", "type","status","syn_status","syn_data","is_checked","mode","open_id","submit_at","version","sing_type","created_at",
"updated_at",
"deleted_at",
"activity_id")
def get_user(self,obj):
return UserListSerializer(models.Users.objects.filter(id=obj.user_id).first(),many=False).data
class UserExaminesSerializer(serializers.ModelSerializer):
has_business = serializers.SerializerMethodField()
tags = serializers.SerializerMethodField()
class Meta:
model = models.UserExamines
fields = "__all__"
def get_has_business(self,obj):
return SystemBusinessSerializer(models.Users.objects.filter(id=obj.business_id,status=1,audit_status=1,deleted_at=None),many=True).data
def get_tags(self,obj):
return
class UserHasTagsSerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
class Meta:
model = models.UserHasTags
fields = "__all__"
def get_tags(self,obj):
return SystemTagsSerializer(models.SystemTags.objects.filter(id=obj.tag_id).first(),many=False).data
class BandActivitySerializer(serializers.ModelSerializer):
is_collection = serializers.SerializerMethodField()
is_confirm_share = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
is_promote = serializers.SerializerMethodField()
comfirm_time = serializers.SerializerMethodField()
total_song_count = serializers.SerializerMethodField()
online_song_count = serializers.SerializerMethodField()
public_audio_count = serializers.SerializerMethodField()
tags = serializers.SerializerMethodField()
arranger = serializers.SerializerMethodField()
status_tag = serializers.SerializerMethodField()
is_master = serializers.SerializerMethodField()
def __init__(self, *args, **kwargs):
# 获取传递进来的 fields 参数,如果没有默认为 None
fields = kwargs.pop('fields', None)
super().__init__(*args, **kwargs)
if fields is not None:
allowed_fields = set(fields)
existing_fields = set(self.fields.keys())
# 找出需要删除的字段
for field_name in existing_fields - allowed_fields:
self.fields.pop(field_name)
class Meta:
model = models.Activitys
fields = '__all__'
def get_status_tag(self,obj):
if obj.is_listen:
return 'listened'
if self.get_is_new(obj):
return 'new'
def get_is_new(self,obj):
new_day = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime("%Y-%m-%d %H:%M:%S")
is_within = models.Activitys.objects.filter(id=obj.id,created_at__gte =new_day).exists()
return not obj.is_listen and is_within
def get_is_collection(self,obj):
return obj.is_collection
def get_is_confirm_share(self, obj):
return models.ActivityShareUsers.objects.filter(activity_id=obj.id,user_id=self.context['user_id']).exists()
def get_project(self,obj):
if self.context['project_many']:queryset = models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1)
else:queryset = models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).first()
return ProjectSimplesSerializer(queryset, many=self.context['project_many']).data
def get_is_promote(self,obj):
project = models.Projects.objects.filter(id=obj.project_id, status=1, deleted_at=None).first()
if not project:is_promote = 0
else:is_promote = project.is_promote
return is_promote
def get_comfirm_time(self,obj):
query = models.ProjectConfirmationTime.objects.filter(project_id=obj.project_id).first()
return ProjectConfirmationTimeSerializer(query,many=False).data
def get_total_song_count(self,obj):
return models.Activitys.objects.filter(project_id=obj.project_id, audit_status=1,deleted_at=None).exclude(status__in=[0,2,4]).count()
def get_online_song_count(self, obj):
return models.Activitys.objects.filter(project_id=obj.project_id, audit_status=1,status=1,deleted_at=None).count()
def get_public_audio_count(self,obj):
return models.ActivityHasUsers.objects.filter(activity_id=obj.id,type='Submit',syn_status=1,is_hide=0,deleted_at=None).count()
def get_tags(self, obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id,deleted_at=None).values_list('tag_id', flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,fields=['id','name']).data
def get_arranger(self,obj):
"""编曲"""
links = ActivityLinksSerializer( models.ActivityLinks.objects.filter(activity_id=obj.id,type='arranger'),many=True,fields=['user']).data
in_side = list()
for link in links:
in_side.append({"id":link['user']['id'],"nick_name":link['user']['nick_name']})
out_side = obj.expand['arranger']['supplement'] if obj.expand.get('arranger',0) else None
return {"in_side":in_side,"out_side":out_side}
def get_is_master(self,obj):
return models.UserHasProjects.objects.filter(project_id=obj.project_id,user_id=self.context['user_id']).exists()
class ActivityDetailSerializer(serializers.ModelSerializer):
is_collection = serializers.SerializerMethodField()
is_confirm_share = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
is_promote = serializers.SerializerMethodField()
comfirm_time = serializers.SerializerMethodField()
total_song_count = serializers.SerializerMethodField()
online_song_count = serializers.SerializerMethodField()
public_audio_count = serializers.SerializerMethodField()
tags = serializers.SerializerMethodField()
arranger = serializers.SerializerMethodField()
def __init__(self, *args, **kwargs):
# 获取传递进来的 fields 参数,如果没有默认为 None
fields = kwargs.pop('fields', None)
super().__init__(*args, **kwargs)
if fields is not None:
allowed_fields = set(fields)
existing_fields = set(self.fields.keys())
# 找出需要删除的字段
for field_name in existing_fields - allowed_fields:
self.fields.pop(field_name)
class Meta:
model = models.Activitys
fields = '__all__'
def get_is_collection(self,obj):
return models.UserActivityCollections.objects.filter(user_id=self.context['user_id'], activity_id=obj.id,deleted_at=None).exists()
def get_is_confirm_share(self, obj):
return models.ActivityShareUsers.objects.filter(activity_id=obj.id,user_id=self.context['user_id']).exists()
def get_project(self,obj):
if self.context['project_many']:queryset = models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1)
else:queryset = models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).first()
return ProjectSimplesSerializer(queryset, many=self.context['project_many']).data
def get_is_promote(self,obj):
project = models.Projects.objects.filter(id=obj.project_id, status=1, deleted_at=None).first()
if not project:is_promote = 0
else:is_promote = project.is_promote
return is_promote
def get_comfirm_time(self,obj):
query = models.ProjectConfirmationTime.objects.filter(project_id=obj.project_id).first()
return ProjectConfirmationTimeSerializer(query,many=False).data
def get_total_song_count(self,obj):
return models.Activitys.objects.filter(project_id=obj.project_id,audit_status=1, deleted_at=None).exclude(status__in=[0,2,4]).count()
def get_online_song_count(self, obj):
return models.Activitys.objects.filter(project_id=obj.project_id,audit_status=1, status=1,deleted_at=None).count()
def get_public_audio_count(self,obj):
return models.ActivityHasUsers.objects.filter(activity_id=obj.id,type='Submit',syn_status=1,is_hide=0,deleted_at=None).count()
def get_tags(self, obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id,deleted_at=None).values_list('tag_id', flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,fields=['id','name']).data
def get_arranger(self,obj):
"""编曲"""
links = ActivityLinksSerializer( models.ActivityLinks.objects.filter(activity_id=obj.id,type='arranger'),many=True,fields=['user']).data
in_side = list()
for link in links:
in_side.append({"id":link['user']['id'],"nick_name":link['user']['nick_name']})
out_side = obj.expand['arranger']['supplement'] if obj.expand.get('arranger',0) else None
return {"in_side":in_side,"out_side":out_side}
class ActivityLinksSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()
def __init__(self, *args, **kwargs):
# 获取传递进来的 fields 参数,如果没有默认为 None
fields = kwargs.pop('fields', None)
super().__init__(*args, **kwargs)
if fields is not None:
allowed_fields = set(fields)
existing_fields = set(self.fields.keys())
# 找出需要删除的字段
for field_name in existing_fields - allowed_fields:
self.fields.pop(field_name)
class Meta:
model = models.ActivityLinks
fields = "__all__"
def get_user(self,obj):
return BusinessSerializer(models.Users.objects.filter(id=obj.link_id).first(),many=False).data
class ProjectConfirmationTimeSerializer(serializers.ModelSerializer):
class Meta:
model = models.ProjectConfirmationTime
fields = ('project_id','average_day','updated_at')
class ActivityMaterialsSerializer(serializers.ModelSerializer):
class Meta:
model = models.ActivityMaterials
fields = "__all__"
class SystemBusinessSerializer(serializers.ModelSerializer):
has_singer_count = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = ('id','nick_name','real_name','avatar','has_singer_count')
def get_has_singer_count(self, obj):
return models.Users.objects.filter(business_id=obj.id,status=1,audit_status=1,deleted_at=None).count()
class BusinessSerializer(serializers.ModelSerializer):
class Meta:
model = models.Users
fields = ('id','nick_name','real_name','avatar')
class MixinPreviewsSerializer(serializers.ModelSerializer):
class Meta:
model = models.MixinPreviews
fields = "__all__"
class UserListSerializer(serializers.ModelSerializer):
class Meta:
model = models.Users
fields = ('id','nick_name','intro','real_name','avatar','province','city','company','rate')
class TidingsUserSerializer(serializers.ModelSerializer):
art_tag = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = ('id','nick_name','intro','sex','real_name','avatar','art_tag')
def get_art_tag(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id,type=2).values_list('tag_id',flat=True))
if len(tags) > 0:
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None).values(), many=True).data
else:
if obj.role == 'Singer':
name = "歌手"
elif obj.role == 'Business':
name = "商务"
else:
name = "策划"
return [{"name":name}]
class FindSingerSerializer(serializers.ModelSerializer):
sound_tag = serializers.SerializerMethodField()
style_tag = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = ('id','nick_name','intro','sex','real_name','avatar','style_tag','sound_tag','sound','sound_at')
def get_sound_tag(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id,type=3).values_list('tag_id',flat=True))
if len(tags) > 0:
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None).values(), many=True).data
else:
return None
def get_style_tag(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id,type=1).values_list('tag_id',flat=True))
if len(tags) > 0:
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None).values(), many=True).data
else:
return None
class VisitorUserSerializer(serializers.ModelSerializer):
last_visitor_at = serializers.SerializerMethodField()
visitor_count = serializers.SerializerMethodField()
is_read = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = ('id','nick_name','sex','real_name','avatar','last_visitor_at','visitor_count','is_read','role','identity')
def get_last_visitor_at(self,obj):
user_id = self.context['user_id']
return models.UserVisitors.objects.filter(user_id=user_id,visitor_id=obj.id).last().created_at.strftime("%Y-%m-%d %H:%M:%S")
def get_visitor_count(self, obj):
user_id = self.context['user_id']
return models.UserVisitors.objects.filter(user_id=user_id, visitor_id=obj.id).count()
def get_is_read(self,obj):
user_id = self.context['user_id']
return not models.UserVisitors.objects.filter(user_id=user_id, visitor_id=obj.id,is_read=0).exists()
class PlatfromAuditionUserSerializer(serializers.ModelSerializer):
business = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = ('id','nick_name','real_name','avatar','province','city','company','rate','business','chat_mode')
def get_business(self,obj):
query_set = obj.business
data = BusinessSerializer(query_set, many=False).data
return data
class UserActivityCollectionsSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserActivityCollections
fields = "__all__"
class CollectionsHasUserSerializer(serializers.ModelSerializer):
"""
推荐人,管理员绑定歌手的收藏活动用户信息
"""
user = serializers.SerializerMethodField()
is_new = serializers.SerializerMethodField()
class Meta:
model = models.UserActivityCollections
fields = ("id","user_id","activity_id","created_at","user","is_new")
def get_user(self,obj):
return UserListSerializer(models.Users.objects.filter(id=obj.user_id).first(),many=False).data
def get_is_new(self, obj):
user_id = self.context['user_id']
return models.UserMessages.objects.filter(type=2, sender_id =obj.user_id,activity_id=obj.activity_id,receiver_id=user_id, is_read=0, is_bind=1,deleted_at=None).exists()
class AuditionHasUserSerializer(serializers.ModelSerializer):
"""
推荐人,管理员绑定歌手的试唱活动用户信息
"""
user = serializers.SerializerMethodField()
is_new = serializers.SerializerMethodField()
comfire_share_user = serializers.SerializerMethodField()
class Meta:
model = models.ActivityHasUsers
fields = ("id","user_id","activity_id","version","comfire_share_user","type","demo_url",'mode','sing_type','syn_status',"status","created_at","user","is_new")
def get_user(self,obj):
return UserListSerializer(obj.user,many=False).data
def get_comfire_share_user(self, obj):
share_obj = models.ActivityShareUsers.objects.filter(activity_id=obj.activity_id, user_id=obj.user_id).first()
if share_obj:
if share_obj.share_id:return BusinessSerializer(models.Users.objects.filter(id=share_obj.share_id).first(), many=False).data
else:return None
else:
return None
def get_is_new(self, obj):
return obj.is_new
class PlatfromAuditionHasUserSerializer(serializers.ModelSerializer):
"""
推荐人,管理员绑定歌手的试唱活动用户信息
"""
is_new = serializers.SerializerMethodField()
user = serializers.SerializerMethodField()
comfire_share_user = serializers.SerializerMethodField()
self_price = serializers.SerializerMethodField()
class Meta:
model = models.ActivityHasUsers
fields = ("id","user_id","activity_id","status",'syn_status','mode','sing_type',"version","type","demo_url","durations","created_at","is_new","user","comfire_share_user","self_price") #'user' ,'comfire_share_user' self_price
def get_comfire_share_user(self, obj):
if obj.share_user_nick_name:return {"nick_name": obj.share_user_nick_name,"real_name": obj.share_user_real_name}
else: return None
def get_user(self,obj):
queryset = obj.user
return PlatfromAuditionUserSerializer(queryset,many=False,context={'activity_id':obj.activity_id}).data
def get_is_new(self, obj):
return obj.is_new
def get_self_price(self,obj):
#增加自主报价信息
price_set = models.ActivityUserHasPrices.objects.filter(user_id=obj.user_id,activity_id=obj.activity_id).first()
if price_set:self_price = ActivitysPriceSerializer(price_set,many=False).data
else:self_price = None
return self_price
class MySingerSerializer(serializers.ModelSerializer):
attend_count = serializers.SerializerMethodField()
check_count = serializers.SerializerMethodField()
is_new = serializers.SerializerMethodField()
tags = serializers.SerializerMethodField()
art_tag = serializers.SerializerMethodField()
auth_tags = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = ('id','avatar','art_tag','auth_tags','nick_name','real_name','last_login','attend_count','check_count','rate','company','chat_mode','is_new','tags','identity')
def get_auth_tags(self, obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id, type=4).values_list('tag_id', flat=True))
if len(tags) == 0: return None
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in=tags, deleted_at=None), many=True,fields=['id', 'name']).data
def get_art_tag(self,obj):
tags = list(models.UserTagRelations.objects.filter(user_id=obj.id,type=2).values_list('tag_id',flat=True))
if len(tags) > 0:
return SystemTagsSerializer(models.SystemTags.objects.filter(id__in = tags,deleted_at=None).values(), many=True).data
else:
if obj.role == 'Singer':
name = "歌手"
elif obj.role == 'Business':
name = "商务"
else:
name = "策划"
return [{"name":name}]
def get_attend_count(self,obj):
return models.ActivityHasUsers.objects.filter(user_id=obj.id,type='Submit', deleted_at=None).values_list('activity_id',flat=True).distinct().count()
def get_check_count(self, obj):
return models.ActivityHasUsers.objects.filter(user_id=obj.id,type='Submit', status=1,deleted_at=None).values_list('activity_id',flat=True).distinct().count()
def get_is_new(self,obj):
user_id = self.context['user_id']
return models.UserMessages.objects.filter(type=1,sender_id=obj.id,receiver_id=user_id,is_read=0,is_bind=1,deleted_at=None).exists()
def get_tags(self,obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
class TidingsActivity(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = ('id','song_name','is_official','sub_title','cover','tags','project')
def get_tags(self, obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_project(self, obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(), many=True).data
class CompleteActivity(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
attend_count = serializers.SerializerMethodField()
confirm_user = serializers.SerializerMethodField()
view_count = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = "__all__"
def get_view_count(self,obj):
return models.UserViewActivity.objects.filter(activity_id=obj.id,deleted_at=None).all().count()
def get_tags(self, obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_project(self, obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(), many=True).data
def get_attend_count(self, obj):
return models.ActivityHasUsers.objects.filter(activity_id=obj.id,deleted_at=None).all().values('user_id').distinct().count()
def get_confirm_user(self,obj):
ahu = models.ActivityHasUsers.objects.filter(activity_id=obj.id,status=1,deleted_at=None).first()
if ahu:
user_id = ahu.user_id
return UserListSerializer(models.Users.objects.filter(id=user_id,deleted_at=None).first(),many=False).data
else:
return None
class RecommendActivitySerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
attend_count = serializers.SerializerMethodField()
confirm_user = serializers.SerializerMethodField()
view_count = serializers.SerializerMethodField()
marks = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = "__all__"
def get_view_count(self,obj):
return models.UserViewActivity.objects.filter(activity_id=obj.id,deleted_at=None).all().count()
def get_tags(self, obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_project(self, obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(), many=True).data
def get_attend_count(self, obj):
return models.ActivityHasUsers.objects.filter(activity_id=obj.id,deleted_at=None).all().values('user_id').distinct().count()
def get_confirm_user(self,obj):
ahu = models.ActivityHasUsers.objects.filter(activity_id=obj.id,status=1,deleted_at=None).first()
if ahu:
user_id = ahu.user_id
return UserListSerializer(models.Users.objects.filter(id=user_id,deleted_at=None).first(),many=False).data
else:
return None
def get_marks(self,obj):
if obj.r_status:return ActivityHasRecommendSerializer(models.ActivityHasRecommends.objects.filter(activity_id=obj.id, type=1, deleted_at=None),many=True).data
else:
return None
class ActivityHasRecommendSerializer(serializers.ModelSerializer):
class Meta:
model = models.ActivityHasRecommends
fields = ("id","content")
class Events(serializers.ModelSerializer):
class Meta:
model = models.Events
fields = "__all__"
class WeiXinAuthUser(serializers.ModelSerializer):
token = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = ("nick_name","real_name","avatar","token","phone")
def get_token(self,obj):
return obj.token
class AppVersionSerializer(serializers.ModelSerializer):
is_force = serializers.SerializerMethodField()
class Meta:
model = models.AppVersion
fields =("app_ver","app_no","os","url","remark","is_force")
def get_is_force(self,obj):
app_version = self.context['app_version']
os = self.context['os']
force_exists = models.AppVersion.objects.filter(os=os,is_force=1,app_ver__gt=app_version,app_ver__lte=obj.app_ver,deleted_at=None).exists()
if force_exists:return 1
else:return 0
class SystemConfigSerializer(serializers.ModelSerializer):
class Meta:
model = models.SystemConfig
fields =("name","content","remark","identifier","weight","updated_at","created_at")
class SystemMsgTidingsSerializer(serializers.ModelSerializer):
auther = serializers.SerializerMethodField()
recommend_singers = serializers.SerializerMethodField()
recommend_activitys = serializers.SerializerMethodField()
sounds = serializers.SerializerMethodField()
photos = serializers.SerializerMethodField()
activity = serializers.SerializerMethodField()
class Meta:
model = models.UserHasTidings
fields = "__all__"
def get_auther(self,obj):
return UserListSerializer(models.Users.objects.filter(id=obj.user_id).first(),many=False).data
def get_recommend_singers(self,obj):
user_ids = list(models.TidingsHasContents.objects.filter(tidings_id=obj.id,type=1).values_list('value',flat=True))
return UserListSerializer(models.Users.objects.filter(id__in=user_ids,status=1,deleted_at=None).all(),many=True).data
def get_recommend_activitys(self,obj):
activity_ids = list(models.TidingsHasContents.objects.filter(tidings_id=obj.id,type=2).values_list('value',flat=True))
return TidingsActivity(models.Activitys.objects.filter(id__in=activity_ids,status=1,deleted_at=None).all(),many=True).data
def get_sounds(self,obj):
return list(models.TidingsHasContents.objects.filter(tidings_id=obj.id,type=3).order_by('created_at').values_list('value',flat=True))
def get_photos(self,obj):
return list(models.TidingsHasContents.objects.filter(tidings_id=obj.id,type=4).order_by('created_at').values_list('value',flat=True))
def get_activity(self, obj):
return TidingsActivity(models.Activitys.objects.filter(id=obj.activity_id).first(), many=False).data
class CommunityTidingsSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()
recommend_singers = serializers.SerializerMethodField()
recommend_activitys = serializers.SerializerMethodField()
sounds = serializers.SerializerMethodField()
photos = serializers.SerializerMethodField()
like_count = serializers.SerializerMethodField()
unlike_count = serializers.SerializerMethodField()
is_like = serializers.SerializerMethodField()
is_unlike = serializers.SerializerMethodField()
activity = serializers.SerializerMethodField()
chat_count = serializers.SerializerMethodField()
is_chat = serializers.SerializerMethodField()
user_id = serializers.SerializerMethodField()
comment_count = serializers.SerializerMethodField()
# comments = serializers.SerializerMethodField()
class Meta:
model = models.UserHasTidings
fields = "__all__"
def get_is_chat(self,obj):
user_id = self.context['user_id']
return models.TidingsHasChat.objects.filter(user_id=user_id,tidings_id=obj.id,).exists()
def get_chat_count(self,obj):
return models.TidingsHasChat.objects.filter(tidings_id=obj.id).values('user_id').count()
def get_activity(self, obj):
if obj.activity_id:
return TidingsActivity(models.Activitys.objects.filter(id=obj.activity_id).first(), many=False).data
else:
return None
def get_user(self,obj):
return TidingsUserSerializer(models.Users.objects.filter(id=obj.user_id).first(),many=False).data
def get_recommend_singers(self,obj):
user_ids = list(models.TidingsHasContents.objects.filter(tidings_id=obj.id,type=1).values_list('value',flat=True))
return TidingsUserSerializer(models.Users.objects.filter(id__in=user_ids,status=1,deleted_at=None).all(),many=True).data
def get_recommend_activitys(self,obj):
activity_ids = list(models.TidingsHasContents.objects.filter(tidings_id=obj.id,type=2).values_list('value',flat=True))
return TidingsActivity(models.Activitys.objects.filter(id__in=activity_ids,deleted_at=None).all(),many=True).data
def get_sounds(self,obj):
return list(models.TidingsHasContents.objects.filter(tidings_id=obj.id,type=3).order_by('created_at').values_list('value',flat=True))
def get_photos(self,obj):
return list(models.TidingsHasContents.objects.filter(tidings_id=obj.id,type=4).order_by('created_at').values_list('value',flat=True))
def get_like_count(self,obj):
return models.TidingsHasInteracts.objects.filter(type=1,type_id=obj.id,status=1,deleted_at=None).count()
def get_is_like(self, obj):
user_id = self.context['user_id']
return models.TidingsHasInteracts.objects.filter(type=1, type_id=obj.id, status=1, user_id =user_id ,deleted_at=None).exists()
def get_unlike_count(self,obj):
return models.TidingsHasInteracts.objects.filter(type=1,type_id=obj.id,status=2,deleted_at=None).count()
def get_is_unlike(self, obj):
user_id = self.context['user_id']
return models.TidingsHasInteracts.objects.filter(type=1, type_id=obj.id, status=2, user_id =user_id ,deleted_at=None).exists()
def get_user_id(self,obj):
return obj.user_id
def get_comment_count(self,obj):
return models.TidingsHasComments.objects.filter(tidings_id=obj.id,deleted_at=None).count()
#
# def get_comments(self,obj):
# queryset = models.TidingsHasComments.objects.filter(tidings_id=obj.id,deleted_at=None).order_by('created_at')[:3]
# return TidingsHasCommentsSerializer(queryset,many=True).data
class TidingsSeleteActivitySerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
view_count = serializers.SerializerMethodField()
submit_count = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = "__all__"
def get_view_count(self,obj):
return models.UserViewActivity.objects.filter(activity_id=obj.id,deleted_at=None).all().count()
def get_tags(self, obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_project(self, obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id,deleted_at=None,status=1).all(), many=True).data
def get_submit_count(self,obj):
return models.ActivityHasUsers.objects.filter(activity_id=obj.id,type="Submit",deleted_at=None).count()
class SystemMessageSerializer(serializers.ModelSerializer):
sender = serializers.SerializerMethodField()
class Meta:
model = models.UserMessages
fields = "__all__"
def get_sender(self,obj):
return TidingsUserSerializer(models.Users.objects.filter(id=obj.sender_id).first(),many=False).data
class CustomerUserSerializer(serializers.ModelSerializer):
info = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = ('id','nick_name','avatar','info','identity')
def get_info(self,obj):
return '使用中有任何问题,请咨询我:)'
class SingerCompleteSerializer(serializers.ModelSerializer):
tags = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
submit_info = serializers.SerializerMethodField()
copyright = serializers.SerializerMethodField()
class Meta:
model = models.Activitys
fields = ("id", "status", "is_official", "cover", "song_name", "created_at","match_at", "sub_title", "guide", "lyric","clip_lyric", "tags", "project","submit_info","copyright")
def get_tags(self, obj):
tags = models.ActivityHasTags.objects.filter(activity_id=obj.id, deleted_at=None).values_list('tag_id',
flat=True)
return SystemTagsSerializer(models.SystemTags.objects.filter(deleted_at=None).in_bulk(tags).values(), many=True,
fields=['id', 'name']).data
def get_project(self, obj):
return ProjectsSerializer(models.Projects.objects.filter(id=obj.project_id, deleted_at=None, status=1).all(),many=True).data
def get_submit_info(self, obj):
user_id = self.context['user_id']
return ActivitysHasUserSerializer(models.ActivityHasUsers.objects.filter(activity_id=obj.id, user_id=user_id, type="Submit",deleted_at=None).first(), many=False).data
def get_copyright(self,obj):
return SingerCompleteCopyrightSerializer(models.Users.objects.filter(id=obj.user_id).first(),many=False).data
class SingerCompleteCopyrightSerializer(serializers.ModelSerializer):
class Meta:
model = models.Users
fields = ('id','nick_name','real_name','avatar')
class SingerBusinessSerializer(serializers.ModelSerializer):
class Meta:
model = models.Users
fields = ('id','nick_name','real_name','avatar')
class ChatRelationSerializer(serializers.ModelSerializer):
is_invite = serializers.SerializerMethodField()
identity = serializers.SerializerMethodField()
is_group_out = serializers.SerializerMethodField()
is_request = serializers.SerializerMethodField()
project_invite_info = serializers.SerializerMethodField()
project_out_info = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = ('id','is_invite','identity','is_group_out','is_request','project_invite_info','project_out_info')
def get_is_invite(self,obj):
return models.GorupInvites.objects.filter(invite_id=self.context['receiver_id'],user_id=self.context['sender']['id'],status=1,type=1).exists()
def get_identity(self,obj):
identity = ''
is_relation = models.Users.objects.filter(id=self.context['sender']['id'], business_id=self.context['receiver_id']).exists()
if is_relation:
identity = '我的队长'
is_relation = models.Users.objects.filter(id=self.context['receiver_id'], business_id=self.context['sender']['id']).exists()
if is_relation:
identity = '我的队员'
return identity
def get_is_group_out(self,obj):
query = models.GroupHasMembers.objects.filter(member_id=self.context['sender']['id'], role=1, deleted_at=None).first()
group_id = query.group_id if query else 0
return models.GroupHasMembers.objects.filter(member_id=self.context['receiver_id'], group_id=group_id, status=2,deleted_at=None).exists()
def get_is_request(self,obj):
return models.GorupInvites.objects.filter(invite_id=self.context['sender']['id'],user_id=self.context['receiver_id'],type=2,status=1).exists()
def get_project_invite_info(self,obj):
project_ids = list(models.ProjectHasMembers.objects.filter(user_id=self.context['sender']['id'], invite_id=self.context['receiver_id'], status=0, deleted_at=None).values_list('project_id', flat=True))
projects = models.Projects.objects.filter(id__in=project_ids, status=1, deleted_at=None).values('id','name')
if len(project_ids) > 0:
id = projects[0]['id']
name = projects[0]['name']
else:
id = 0
name = ''
return {"id":id,"name":name,"count":len(projects)}
def get_project_out_info(self,obj):
query = models.ProjectHasMembers.objects.filter(user_id=self.context['receiver_id'], status=3,deleted_at=None).last()
if query:
project_id = query.project_id
master_ids = list(models.UserHasProjects.objects.filter(project_id=project_id).values_list('user_id',flat=True))
if self.context['sender']['id'] in master_ids:
is_project_out = True
name = models.Projects.objects.filter(id=project_id).first().name
id = project_id
else:
is_project_out = False
name = ''
id = 0
else:
is_project_out = False
name = ''
id = 0
project_query = models.SystemConfig.objects.filter(identifier='VnyE3PTXOUPDEb4WZLBjM').first()
limit_count = project_query.content if project_query else 7
project_out_info = {"is_out": is_project_out, "limit_count": limit_count,"name":name,'id':id}
return project_out_info
class ChatAgentSerializer(serializers.ModelSerializer):
business = serializers.SerializerMethodField()
isfirst_agentchat = serializers.SerializerMethodField()
chat_mode = serializers.SerializerMethodField()
sender_chat_mode = serializers.SerializerMethodField()
class Meta:
model = models.Users
fields = ('id', 'nick_name', 'real_name', 'avatar','chat_mode','sender_chat_mode','business','isfirst_agentchat')
def get_business(self,obj):
if obj.business_id:return SingerBusinessSerializer(models.Users.objects.filter(id=obj.business_id).first(),many=False).data
else:return None
def get_isfirst_agentchat(self,obj):
send_id = self.context['send_id']
return not models.UserChatAgentRecords.objects.filter(send_id=send_id,user_id=obj.id,business_id=obj.business_id).exists()
def get_chat_mode(self,obj):
send_id = self.context['send_id']
if send_id == obj.business_id:return 0 #如果是推荐人和歌手私聊不限制聊天
else:return obj.chat_mode
def get_sender_chat_mode(self,obj):
send_id = self.context['send_id']
if send_id == obj.business_id: return 0 # 如果是推荐人和歌手私聊不限制聊天
return models.Users.objects.filter(id=send_id).first().chat_mode
class TidingsHasCommentsSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()
reply_to_user = serializers.SerializerMethodField()
class Meta:
model = models.TidingsHasComments
fields = ('id', 'tidings_id', 'user_id', 'content', 'created_at','user','reply_to_user')
def get_user(self,obj):
return SingerBusinessSerializer(models.Users.objects.filter(id=obj.user_id).first(),many=False).data
def get_reply_to_user(self,obj):
reply_user = models.TidingsHasComments.objects.filter(id=obj.parent_id).first()
if reply_user:reply_user_id = reply_user.user_id
else:return None
return SingerBusinessSerializer(models.Users.objects.filter(id=reply_user_id).first(),many=False).data
\ No newline at end of file
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.2,user-scalable=no" />
<title>分享</title>
<!-- <link rel="stylesheet" href="style/style.css">-->
<style>
* {
margin: 0px;
padding: 0px;
}
/*默认640下,按着设计图25号字体*/
body {
font-size: 0.25rem;
font-family: Microsoft YaHei, SimHei, SimSun;
background: #F7F7F7;
box-sizing: border-box;
}
html {
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
ol,
ul,
li {
list-style: none;
}
table {
border-collapse: collapse;
}
h1,
h2,
h3,
h4,
h5,
h6,
small {
font-size: 100%;
font-weight: normal
}
input[type=button] {
-webkit-appearance: none;
/*去除iphone input默认样式*/
}
input::-ms-clear {
display: none;
}
div {
box-sizing: border-box;
}
a,
a:hover {
text-decoration: none;
color: white;
}
.call {
color: #319de6;
text-decoration: none;
}
/*设置输入提示字体*/
::-webkit-input-placeholder {
color: #fff;
}
::-moz-placeholder {
color: #fff;
}
:-moz-placeholder {
color: #fff;
}
input:-ms-input-placeholder,
textarea:-ms-input-placeholder {
color: #ffffff;
}
/* 清除浮动 */
.clearfix:before,
.clearfix:after {
content: "";
display: table;
}
.clearfix:after {
clear: both;
overflow: hidden;
}
.clearfix {
zoom: 1;
/* for ie6 & ie7 */
}
.clear {
clear: both;
display: block;
}
body {
width: 100vw;
font-family: PingFang SC, PingFang SC-Medium;
}
.conBox {
z-index: 2;
width: 100vw;
display: flex;
flex-direction: column;
align-items: center;
background: #242521;
padding-bottom: 2.76rem;
}
.imgBox{
display: flex;
flex-direction: column;
margin-top: 1.04rem;
}
.img1{
width: 7.5rem;
height: 9.46rem;
}
.img2{
width: 7.5rem;
height: 7.46rem;
}
.img3{
width: 7.5rem;
height: 10.38rem;
}
.logoBox {
height: 1.04rem;
display: flex;
align-items: center;
position: fixed;
width: 100%;
top: 0;
left: 0;
z-index: 9;
padding-left: 0.38rem;
padding-right: 0.38rem;
background: #fff;
}
.logo {
height: 0.64rem;
width: 0.64rem;
}
.name {
margin-right: auto;
color: #333;
font-size: 0.32rem;
font-weight: 500;
margin-left: 0.12rem;
}
.btn {
width: 1.4rem;
height: 0.56rem;
background: linear-gradient(91deg, #ff9100 0%, #ff5100 100%);
border-radius: 1.2rem;
font-size: 0.24rem;
display: flex;
align-items: center;
justify-content: center;
}
.openApp {
width: 5.32rem;
height: 0.8rem;
color: #FFFFFF;
z-index: 2;
font-size: 0.28rem;
background: linear-gradient(90deg, #ff5100 0%, #ff9100 100%);
border-radius: 2rem;
position: fixed;
bottom: 0.96rem;
display: flex;
align-items: center;
justify-content: center;
}
.openDiv {
width: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
margin-top: 0.48rem;
}
.openP {
font-size: 0.32rem;
color: #fff;
}
</style>
<!-- <script src="js/jquery-3.6.0.min.js"></script>-->
<script>
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.6.0",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0<t&&t-1 in e)}S.fn=S.prototype={jquery:f,constructor:S,length:0,toArray:function(){return s.call(this)},get:function(e){return null==e?s.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=S.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return S.each(this,e)},map:function(n){return this.pushStack(S.map(this,function(e,t){return n.call(e,t,e)}))},slice:function(){return this.pushStack(s.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(S.grep(this,function(e,t){return(t+1)%2}))},odd:function(){return this.pushStack(S.grep(this,function(e,t){return t%2}))},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(0<=n&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:u,sort:t.sort,splice:t.splice},S.extend=S.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||m(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)r=e[t],"__proto__"!==t&&a!==r&&(l&&r&&(S.isPlainObject(r)||(i=Array.isArray(r)))?(n=a[t],o=i&&!Array.isArray(n)?[]:i||S.isPlainObject(n)?n:{},i=!1,a[t]=S.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},S.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==o.call(e))&&(!(t=r(e))||"function"==typeof(n=v.call(t,"constructor")&&t.constructor)&&a.call(n)===l)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e,t,n){b(e,{nonce:t&&t.nonce},n)},each:function(e,t){var n,r=0;if(p(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},makeArray:function(e,t){var n=t||[];return null!=e&&(p(Object(e))?S.merge(n,"string"==typeof e?[e]:e):u.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:i.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r=[],i=0,o=e.length,a=!n;i<o;i++)!t(e[i],i)!==a&&r.push(e[i]);return r},map:function(e,t,n){var r,i,o=0,a=[];if(p(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&a.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&a.push(i);return g(a)},guid:1,support:y}),"function"==typeof Symbol&&(S.fn[Symbol.iterator]=t[Symbol.iterator]),S.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){n["[object "+t+"]"]=t.toLowerCase()});var d=function(n){var e,d,b,o,i,h,f,g,w,u,l,T,C,a,E,v,s,c,y,S="sizzle"+1*new Date,p=n.document,k=0,r=0,m=ue(),x=ue(),A=ue(),N=ue(),j=function(e,t){return e===t&&(l=!0),0},D={}.hasOwnProperty,t=[],q=t.pop,L=t.push,H=t.push,O=t.slice,P=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},R="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",I="(?:\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",W="\\["+M+"*("+I+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+I+"))|)"+M+"*\\]",F=":("+I+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+W+")*)|.*)\\)|)",B=new RegExp(M+"+","g"),$=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),_=new RegExp("^"+M+"*,"+M+"*"),z=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="<a id='"+S+"'></a><select id='"+S+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},j=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0<se(t,C,null,[e]).length},se.contains=function(e,t){return(e.ownerDocument||e)!=C&&T(e),y(e,t)},se.attr=function(e,t){(e.ownerDocument||e)!=C&&T(e);var n=b.attrHandle[t.toLowerCase()],r=n&&D.call(b.attrHandle,t.toLowerCase())?n(e,t,!E):void 0;return void 0!==r?r:d.attributes||!E?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},se.escape=function(e){return(e+"").replace(re,ie)},se.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},se.uniqueSort=function(e){var t,n=[],r=0,i=0;if(l=!d.detectDuplicates,u=!d.sortStable&&e.slice(0),e.sort(j),l){while(t=e[i++])t===e[i]&&(r=n.push(i));while(r--)e.splice(n[r],1)}return u=null,e},o=se.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else while(t=e[r++])n+=o(t);return n},(b=se.selectors={cacheLength:50,createPseudo:le,match:G,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1<t.indexOf(i):"$="===r?i&&t.slice(-i.length)===i:"~="===r?-1<(" "+t.replace(B," ")+" ").indexOf(i):"|="===r&&(t===i||t.slice(0,i.length+1)===i+"-"))}},CHILD:function(h,e,t,g,v){var y="nth"!==h.slice(0,3),m="last"!==h.slice(-4),x="of-type"===e;return 1===g&&0===v?function(e){return!!e.parentNode}:function(e,t,n){var r,i,o,a,s,u,l=y!==m?"nextSibling":"previousSibling",c=e.parentNode,f=x&&e.nodeName.toLowerCase(),p=!n&&!x,d=!1;if(c){if(y){while(l){a=e;while(a=a[l])if(x?a.nodeName.toLowerCase()===f:1===a.nodeType)return!1;u=l="only"===h&&!u&&"nextSibling"}return!0}if(u=[m?c.firstChild:c.lastChild],m&&p){d=(s=(r=(i=(o=(a=c)[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===k&&r[1])&&r[2],a=s&&c.childNodes[s];while(a=++s&&a&&a[l]||(d=s=0)||u.pop())if(1===a.nodeType&&++d&&a===e){i[h]=[k,s,d];break}}else if(p&&(d=s=(r=(i=(o=(a=e)[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===k&&r[1]),!1===d)while(a=++s&&a&&a[l]||(d=s=0)||u.pop())if((x?a.nodeName.toLowerCase()===f:1===a.nodeType)&&++d&&(p&&((i=(o=a[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]=[k,d]),a===e))break;return(d-=v)===g||d%g==0&&0<=d/g}}},PSEUDO:function(e,o){var t,a=b.pseudos[e]||b.setFilters[e.toLowerCase()]||se.error("unsupported pseudo: "+e);return a[S]?a(o):1<a.length?(t=[e,e,"",o],b.setFilters.hasOwnProperty(e.toLowerCase())?le(function(e,t){var n,r=a(e,o),i=r.length;while(i--)e[n=P(e,r[i])]=!(t[n]=r[i])}):function(e){return a(e,0,t)}):a}},pseudos:{not:le(function(e){var r=[],i=[],s=f(e.replace($,"$1"));return s[S]?le(function(e,t,n,r){var i,o=s(e,null,r,[]),a=e.length;while(a--)(i=o[a])&&(e[a]=!(t[a]=i))}):function(e,t,n){return r[0]=e,s(r,null,n,i),r[0]=null,!i.pop()}}),has:le(function(t){return function(e){return 0<se(t,e).length}}),contains:le(function(t){return t=t.replace(te,ne),function(e){return-1<(e.textContent||o(e)).indexOf(t)}}),lang:le(function(n){return V.test(n||"")||se.error("unsupported lang: "+n),n=n.replace(te,ne).toLowerCase(),function(e){var t;do{if(t=E?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return(t=t.toLowerCase())===n||0===t.indexOf(n+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var t=n.location&&n.location.hash;return t&&t.slice(1)===e.id},root:function(e){return e===a},focus:function(e){return e===C.activeElement&&(!C.hasFocus||C.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:ge(!1),disabled:ge(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!b.pseudos.empty(e)},header:function(e){return J.test(e.nodeName)},input:function(e){return Q.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:ve(function(){return[0]}),last:ve(function(e,t){return[t-1]}),eq:ve(function(e,t,n){return[n<0?n+t:n]}),even:ve(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:ve(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:ve(function(e,t,n){for(var r=n<0?n+t:t<n?t:n;0<=--r;)e.push(r);return e}),gt:ve(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=b.pseudos.eq,{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})b.pseudos[e]=de(e);for(e in{submit:!0,reset:!0})b.pseudos[e]=he(e);function me(){}function xe(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function be(s,e,t){var u=e.dir,l=e.next,c=l||u,f=t&&"parentNode"===c,p=r++;return e.first?function(e,t,n){while(e=e[u])if(1===e.nodeType||f)return s(e,t,n);return!1}:function(e,t,n){var r,i,o,a=[k,p];if(n){while(e=e[u])if((1===e.nodeType||f)&&s(e,t,n))return!0}else while(e=e[u])if(1===e.nodeType||f)if(i=(o=e[S]||(e[S]={}))[e.uniqueID]||(o[e.uniqueID]={}),l&&l===e.nodeName.toLowerCase())e=e[u]||e;else{if((r=i[c])&&r[0]===k&&r[1]===p)return a[2]=r[2];if((i[c]=a)[2]=s(e,t,n))return!0}return!1}}function we(i){return 1<i.length?function(e,t,n){var r=i.length;while(r--)if(!i[r](e,t,n))return!1;return!0}:i[0]}function Te(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;s<u;s++)(o=e[s])&&(n&&!n(o,r,i)||(a.push(o),l&&t.push(s)));return a}function Ce(d,h,g,v,y,e){return v&&!v[S]&&(v=Ce(v)),y&&!y[S]&&(y=Ce(y,e)),le(function(e,t,n,r){var i,o,a,s=[],u=[],l=t.length,c=e||function(e,t,n){for(var r=0,i=t.length;r<i;r++)se(e,t[r],n);return n}(h||"*",n.nodeType?[n]:n,[]),f=!d||!e&&h?c:Te(c,s,d,n,r),p=g?y||(e?d:l||v)?[]:t:f;if(g&&g(f,p,n,r),v){i=Te(p,u),v(i,[],n,r),o=i.length;while(o--)(a=i[o])&&(p[u[o]]=!(f[u[o]]=a))}if(e){if(y||d){if(y){i=[],o=p.length;while(o--)(a=p[o])&&i.push(f[o]=a);y(null,p=[],i,r)}o=p.length;while(o--)(a=p[o])&&-1<(i=y?P(e,a):s[o])&&(e[i]=!(t[i]=a))}}else p=Te(p===t?p.splice(l,p.length):p),y?y(null,t,p,r):H.apply(t,p)})}function Ee(e){for(var i,t,n,r=e.length,o=b.relative[e[0].type],a=o||b.relative[" "],s=o?1:0,u=be(function(e){return e===i},a,!0),l=be(function(e){return-1<P(i,e)},a,!0),c=[function(e,t,n){var r=!o&&(n||t!==w)||((i=t).nodeType?u(e,t,n):l(e,t,n));return i=null,r}];s<r;s++)if(t=b.relative[e[s].type])c=[be(we(c),t)];else{if((t=b.filter[e[s].type].apply(null,e[s].matches))[S]){for(n=++s;n<r;n++)if(b.relative[e[n].type])break;return Ce(1<s&&we(c),1<s&&xe(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace($,"$1"),t,s<n&&Ee(e.slice(s,n)),n<r&&Ee(e=e.slice(n)),n<r&&xe(e))}c.push(t)}return we(c)}return me.prototype=b.filters=b.pseudos,b.setFilters=new me,h=se.tokenize=function(e,t){var n,r,i,o,a,s,u,l=x[e+" "];if(l)return t?0:l.slice(0);a=e,s=[],u=b.preFilter;while(a){for(o in n&&!(r=_.exec(a))||(r&&(a=a.slice(r[0].length)||a),s.push(i=[])),n=!1,(r=z.exec(a))&&(n=r.shift(),i.push({value:n,type:r[0].replace($," ")}),a=a.slice(n.length)),b.filter)!(r=G[o].exec(a))||u[o]&&!(r=u[o](r))||(n=r.shift(),i.push({value:n,type:o,matches:r}),a=a.slice(n.length));if(!n)break}return t?a.length:a?se.error(e):x(e,s).slice(0)},f=se.compile=function(e,t){var n,v,y,m,x,r,i=[],o=[],a=A[e+" "];if(!a){t||(t=h(e)),n=t.length;while(n--)(a=Ee(t[n]))[S]?i.push(a):o.push(a);(a=A(e,(v=o,m=0<(y=i).length,x=0<v.length,r=function(e,t,n,r,i){var o,a,s,u=0,l="0",c=e&&[],f=[],p=w,d=e||x&&b.find.TAG("*",i),h=k+=null==p?1:Math.random()||.1,g=d.length;for(i&&(w=t==C||t||i);l!==g&&null!=(o=d[l]);l++){if(x&&o){a=0,t||o.ownerDocument==C||(T(o),n=!E);while(s=v[a++])if(s(o,t||C,n)){r.push(o);break}i&&(k=h)}m&&((o=!s&&o)&&u--,e&&c.push(o))}if(u+=l,m&&l!==u){a=0;while(s=y[a++])s(c,f,t,n);if(e){if(0<u)while(l--)c[l]||f[l]||(f[l]=q.call(r));f=Te(f)}H.apply(r,f),i&&!e&&0<f.length&&1<u+y.length&&se.uniqueSort(r)}return i&&(k=h,w=p),c},m?le(r):r))).selector=e}return a},g=se.select=function(e,t,n,r){var i,o,a,s,u,l="function"==typeof e&&e,c=!r&&h(e=l.selector||e);if(n=n||[],1===c.length){if(2<(o=c[0]=c[0].slice(0)).length&&"ID"===(a=o[0]).type&&9===t.nodeType&&E&&b.relative[o[1].type]){if(!(t=(b.find.ID(a.matches[0].replace(te,ne),t)||[])[0]))return n;l&&(t=t.parentNode),e=e.slice(o.shift().value.length)}i=G.needsContext.test(e)?0:o.length;while(i--){if(a=o[i],b.relative[s=a.type])break;if((u=b.find[s])&&(r=u(a.matches[0].replace(te,ne),ee.test(o[0].type)&&ye(t.parentNode)||t))){if(o.splice(i,1),!(e=r.length&&xe(o)))return H.apply(n,r),n;break}}}return(l||f(e,c))(r,t,!E,n,!t||ee.test(e)&&ye(t.parentNode)||t),n},d.sortStable=S.split("").sort(j).join("")===S,d.detectDuplicates=!!l,T(),d.sortDetached=ce(function(e){return 1&e.compareDocumentPosition(C.createElement("fieldset"))}),ce(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),d.attributes&&ce(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ce(function(e){return null==e.getAttribute("disabled")})||fe(R,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),se}(C);S.find=d,S.expr=d.selectors,S.expr[":"]=S.expr.pseudos,S.uniqueSort=S.unique=d.uniqueSort,S.text=d.getText,S.isXMLDoc=d.isXML,S.contains=d.contains,S.escapeSelector=d.escape;var h=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&S(e).is(n))break;r.push(e)}return r},T=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},k=S.expr.match.needsContext;function A(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var N=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1<i.call(n,e)!==r}):S.filter(n,e,r)}S.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?S.find.matchesSelector(r,e)?[r]:[]:S.find.matches(e,S.grep(t,function(e){return 1===e.nodeType}))},S.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(S(e).filter(function(){for(t=0;t<r;t++)if(S.contains(i[t],this))return!0}));for(n=this.pushStack([]),t=0;t<r;t++)S.find(e,i[t],n);return 1<r?S.uniqueSort(n):n},filter:function(e){return this.pushStack(j(this,e||[],!1))},not:function(e){return this.pushStack(j(this,e||[],!0))},is:function(e){return!!j(this,"string"==typeof e&&k.test(e)?S(e):e||[],!1).length}});var D,q=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||D,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,D=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e<n;e++)if(S.contains(this,t[e]))return!0})},closest:function(e,t){var n,r=0,i=this.length,o=[],a="string"!=typeof e&&S(e);if(!k.test(e))for(;r<i;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?-1<a.index(n):1===n.nodeType&&S.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(1<o.length?S.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?i.call(S(e),this[0]):i.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(S.uniqueSort(S.merge(this.get(),S(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),S.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return h(e,"parentNode")},parentsUntil:function(e,t,n){return h(e,"parentNode",n)},next:function(e){return O(e,"nextSibling")},prev:function(e){return O(e,"previousSibling")},nextAll:function(e){return h(e,"nextSibling")},prevAll:function(e){return h(e,"previousSibling")},nextUntil:function(e,t,n){return h(e,"nextSibling",n)},prevUntil:function(e,t,n){return h(e,"previousSibling",n)},siblings:function(e){return T((e.parentNode||{}).firstChild,e)},children:function(e){return T(e.firstChild)},contents:function(e){return null!=e.contentDocument&&r(e.contentDocument)?e.contentDocument:(A(e,"template")&&(e=e.content||e),S.merge([],e.childNodes))}},function(r,i){S.fn[r]=function(e,t){var n=S.map(this,i,e);return"Until"!==r.slice(-5)&&(t=e),t&&"string"==typeof t&&(n=S.filter(t,n)),1<this.length&&(H[r]||S.uniqueSort(n),L.test(r)&&n.reverse()),this.pushStack(n)}});var P=/[^\x20\t\r\n\f]+/g;function R(e){return e}function M(e){throw e}function I(e,t,n,r){var i;try{e&&m(i=e.promise)?i.call(e).done(t).fail(n):e&&m(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}S.Callbacks=function(r){var e,n;r="string"==typeof r?(e=r,n={},S.each(e.match(P)||[],function(e,t){n[t]=!0}),n):S.extend({},r);var i,t,o,a,s=[],u=[],l=-1,c=function(){for(a=a||r.once,o=i=!0;u.length;l=-1){t=u.shift();while(++l<s.length)!1===s[l].apply(t[0],t[1])&&r.stopOnFalse&&(l=s.length,t=!1)}r.memory||(t=!1),i=!1,a&&(s=t?[]:"")},f={add:function(){return s&&(t&&!i&&(l=s.length-1,u.push(t)),function n(e){S.each(e,function(e,t){m(t)?r.unique&&f.has(t)||s.push(t):t&&t.length&&"string"!==w(t)&&n(t)})}(arguments),t&&!i&&c()),this},remove:function(){return S.each(arguments,function(e,t){var n;while(-1<(n=S.inArray(t,s,n)))s.splice(n,1),n<=l&&l--}),this},has:function(e){return e?-1<S.inArray(e,s):0<s.length},empty:function(){return s&&(s=[]),this},disable:function(){return a=u=[],s=t="",this},disabled:function(){return!s},lock:function(){return a=u=[],t||i||(s=t=""),this},locked:function(){return!!a},fireWith:function(e,t){return a||(t=[e,(t=t||[]).slice?t.slice():t],u.push(t),i||c()),this},fire:function(){return f.fireWith(this,arguments),this},fired:function(){return!!o}};return f},S.extend({Deferred:function(e){var o=[["notify","progress",S.Callbacks("memory"),S.Callbacks("memory"),2],["resolve","done",S.Callbacks("once memory"),S.Callbacks("once memory"),0,"resolved"],["reject","fail",S.Callbacks("once memory"),S.Callbacks("once memory"),1,"rejected"]],i="pending",a={state:function(){return i},always:function(){return s.done(arguments).fail(arguments),this},"catch":function(e){return a.then(null,e)},pipe:function(){var i=arguments;return S.Deferred(function(r){S.each(o,function(e,t){var n=m(i[t[4]])&&i[t[4]];s[t[1]](function(){var e=n&&n.apply(this,arguments);e&&m(e.promise)?e.promise().progress(r.notify).done(r.resolve).fail(r.reject):r[t[0]+"With"](this,n?[e]:arguments)})}),i=null}).promise()},then:function(t,n,r){var u=0;function l(i,o,a,s){return function(){var n=this,r=arguments,e=function(){var e,t;if(!(i<u)){if((e=a.apply(n,r))===o.promise())throw new TypeError("Thenable self-resolution");t=e&&("object"==typeof e||"function"==typeof e)&&e.then,m(t)?s?t.call(e,l(u,o,R,s),l(u,o,M,s)):(u++,t.call(e,l(u,o,R,s),l(u,o,M,s),l(u,o,R,o.notifyWith))):(a!==R&&(n=void 0,r=[e]),(s||o.resolveWith)(n,r))}},t=s?e:function(){try{e()}catch(e){S.Deferred.exceptionHook&&S.Deferred.exceptionHook(e,t.stackTrace),u<=i+1&&(a!==M&&(n=void 0,r=[e]),o.rejectWith(n,r))}};i?t():(S.Deferred.getStackHook&&(t.stackTrace=S.Deferred.getStackHook()),C.setTimeout(t))}}return S.Deferred(function(e){o[0][3].add(l(0,e,m(r)?r:R,e.notifyWith)),o[1][3].add(l(0,e,m(t)?t:R)),o[2][3].add(l(0,e,m(n)?n:M))}).promise()},promise:function(e){return null!=e?S.extend(e,a):a}},s={};return S.each(o,function(e,t){var n=t[2],r=t[5];a[t[1]]=n.add,r&&n.add(function(){i=r},o[3-e][2].disable,o[3-e][3].disable,o[0][2].lock,o[0][3].lock),n.add(t[3].fire),s[t[0]]=function(){return s[t[0]+"With"](this===s?void 0:this,arguments),this},s[t[0]+"With"]=n.fireWith}),a.promise(s),e&&e.call(s,s),s},when:function(e){var n=arguments.length,t=n,r=Array(t),i=s.call(arguments),o=S.Deferred(),a=function(t){return function(e){r[t]=this,i[t]=1<arguments.length?s.call(arguments):e,--n||o.resolveWith(r,i)}};if(n<=1&&(I(e,o.done(a(t)).resolve,o.reject,!n),"pending"===o.state()||m(i[t]&&i[t].then)))return o.then();while(t--)I(i[t],a(t),o.reject);return o.promise()}});var W=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;S.Deferred.exceptionHook=function(e,t){C.console&&C.console.warn&&e&&W.test(e.name)&&C.console.warn("jQuery.Deferred exception: "+e.message,e.stack,t)},S.readyException=function(e){C.setTimeout(function(){throw e})};var F=S.Deferred();function B(){E.removeEventListener("DOMContentLoaded",B),C.removeEventListener("load",B),S.ready()}S.fn.ready=function(e){return F.then(e)["catch"](function(e){S.readyException(e)}),this},S.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--S.readyWait:S.isReady)||(S.isReady=!0)!==e&&0<--S.readyWait||F.resolveWith(E,[S])}}),S.ready.then=F.then,"complete"===E.readyState||"loading"!==E.readyState&&!E.documentElement.doScroll?C.setTimeout(S.ready):(E.addEventListener("DOMContentLoaded",B),C.addEventListener("load",B));var $=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===w(n))for(s in i=!0,n)$(e,t,s,n[s],!0,o,a);else if(void 0!==r&&(i=!0,m(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(S(e),n)})),t))for(;s<u;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},_=/^-ms-/,z=/-([a-z])/g;function U(e,t){return t.toUpperCase()}function X(e){return e.replace(_,"ms-").replace(z,U)}var V=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};function G(){this.expando=S.expando+G.uid++}G.uid=1,G.prototype={cache:function(e){var t=e[this.expando];return t||(t={},V(e)&&(e.nodeType?e[this.expando]=t:Object.defineProperty(e,this.expando,{value:t,configurable:!0}))),t},set:function(e,t,n){var r,i=this.cache(e);if("string"==typeof t)i[X(t)]=n;else for(r in t)i[X(r)]=t[r];return i},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][X(t)]},access:function(e,t,n){return void 0===t||t&&"string"==typeof t&&void 0===n?this.get(e,t):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,r=e[this.expando];if(void 0!==r){if(void 0!==t){n=(t=Array.isArray(t)?t.map(X):(t=X(t))in r?[t]:t.match(P)||[]).length;while(n--)delete r[t[n]]}(void 0===t||S.isEmptyObject(r))&&(e.nodeType?e[this.expando]=void 0:delete e[this.expando])}},hasData:function(e){var t=e[this.expando];return void 0!==t&&!S.isEmptyObject(t)}};var Y=new G,Q=new G,J=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,K=/[A-Z]/g;function Z(e,t,n){var r,i;if(void 0===n&&1===e.nodeType)if(r="data-"+t.replace(K,"-$&").toLowerCase(),"string"==typeof(n=e.getAttribute(r))){try{n="true"===(i=n)||"false"!==i&&("null"===i?null:i===+i+""?+i:J.test(i)?JSON.parse(i):i)}catch(e){}Q.set(e,t,n)}else n=void 0;return n}S.extend({hasData:function(e){return Q.hasData(e)||Y.hasData(e)},data:function(e,t,n){return Q.access(e,t,n)},removeData:function(e,t){Q.remove(e,t)},_data:function(e,t,n){return Y.access(e,t,n)},_removeData:function(e,t){Y.remove(e,t)}}),S.fn.extend({data:function(n,e){var t,r,i,o=this[0],a=o&&o.attributes;if(void 0===n){if(this.length&&(i=Q.get(o),1===o.nodeType&&!Y.get(o,"hasDataAttrs"))){t=a.length;while(t--)a[t]&&0===(r=a[t].name).indexOf("data-")&&(r=X(r.slice(5)),Z(o,r,i[r]));Y.set(o,"hasDataAttrs",!0)}return i}return"object"==typeof n?this.each(function(){Q.set(this,n)}):$(this,function(e){var t;if(o&&void 0===e)return void 0!==(t=Q.get(o,n))?t:void 0!==(t=Z(o,n))?t:void 0;this.each(function(){Q.set(this,n,e)})},null,e,1<arguments.length,null,!0)},removeData:function(e){return this.each(function(){Q.remove(this,e)})}}),S.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=Y.get(e,t),n&&(!r||Array.isArray(n)?r=Y.access(e,t,S.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=S.queue(e,t),r=n.length,i=n.shift(),o=S._queueHooks(e,t);"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,function(){S.dequeue(e,t)},o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return Y.get(e,n)||Y.access(e,n,{empty:S.Callbacks("once memory").add(function(){Y.remove(e,[t+"queue",n])})})}}),S.fn.extend({queue:function(t,n){var e=2;return"string"!=typeof t&&(n=t,t="fx",e--),arguments.length<e?S.queue(this[0],t):void 0===n?this:this.each(function(){var e=S.queue(this,t,n);S._queueHooks(this,t),"fx"===t&&"inprogress"!==e[0]&&S.dequeue(this,t)})},dequeue:function(e){return this.each(function(){S.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=S.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=void 0),e=e||"fx";while(a--)(n=Y.get(o[a],e+"queueHooks"))&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var ee=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,te=new RegExp("^(?:([+-])=|)("+ee+")([a-z%]*)$","i"),ne=["Top","Right","Bottom","Left"],re=E.documentElement,ie=function(e){return S.contains(e.ownerDocument,e)},oe={composed:!0};re.getRootNode&&(ie=function(e){return S.contains(e.ownerDocument,e)||e.getRootNode(oe)===e.ownerDocument});var ae=function(e,t){return"none"===(e=t||e).style.display||""===e.style.display&&ie(e)&&"none"===S.css(e,"display")};function se(e,t,n,r){var i,o,a=20,s=r?function(){return r.cur()}:function(){return S.css(e,t,"")},u=s(),l=n&&n[3]||(S.cssNumber[t]?"":"px"),c=e.nodeType&&(S.cssNumber[t]||"px"!==l&&+u)&&te.exec(S.css(e,t));if(c&&c[3]!==l){u/=2,l=l||c[3],c=+u||1;while(a--)S.style(e,t,c+l),(1-o)*(1-(o=s()/u||.5))<=0&&(a=0),c/=o;c*=2,S.style(e,t,c+l),n=n||[]}return n&&(c=+c||+u||0,i=n[1]?c+(n[1]+1)*n[2]:+n[2],r&&(r.unit=l,r.start=c,r.end=i)),i}var ue={};function le(e,t){for(var n,r,i,o,a,s,u,l=[],c=0,f=e.length;c<f;c++)(r=e[c]).style&&(n=r.style.display,t?("none"===n&&(l[c]=Y.get(r,"display")||null,l[c]||(r.style.display="")),""===r.style.display&&ae(r)&&(l[c]=(u=a=o=void 0,a=(i=r).ownerDocument,s=i.nodeName,(u=ue[s])||(o=a.body.appendChild(a.createElement(s)),u=S.css(o,"display"),o.parentNode.removeChild(o),"none"===u&&(u="block"),ue[s]=u)))):"none"!==n&&(l[c]="none",Y.set(r,"display",n)));for(c=0;c<f;c++)null!=l[c]&&(e[c].style.display=l[c]);return e}S.fn.extend({show:function(){return le(this,!0)},hide:function(){return le(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){ae(this)?S(this).show():S(this).hide()})}});var ce,fe,pe=/^(?:checkbox|radio)$/i,de=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="<textarea>x</textarea>",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="<option></option>",y.option=!!ce.lastChild;var ge={thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n<r;n++)Y.set(e[n],"globalEval",!t||Y.get(t[n],"globalEval"))}ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td,y.option||(ge.optgroup=ge.option=[1,"<select multiple='multiple'>","</select>"]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d<h;d++)if((o=e[d])||0===o)if("object"===w(o))S.merge(p,o.nodeType?[o]:o);else if(me.test(o)){a=a||f.appendChild(t.createElement("div")),s=(de.exec(o)||["",""])[1].toLowerCase(),u=ge[s]||ge._default,a.innerHTML=u[1]+S.htmlPrefilter(o)+u[2],c=u[0];while(c--)a=a.lastChild;S.merge(p,a.childNodes),(a=f.firstChild).textContent=""}else p.push(t.createTextNode(o));f.textContent="",d=0;while(o=p[d++])if(r&&-1<S.inArray(o,r))i&&i.push(o);else if(l=ie(o),a=ve(f.appendChild(o),"script"),l&&ye(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}var be=/^([^.]*)(?:\.(.+)|)/;function we(){return!0}function Te(){return!1}function Ce(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ee(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ee(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Te;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return S().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=S.guid++)),e.each(function(){S.event.add(this,t,i,r,n)})}function Se(e,i,o){o?(Y.set(e,i,!1),S.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Y.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(S.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Y.set(this,i,r),t=o(this,i),this[i](),r!==(n=Y.get(this,i))||t?Y.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n&&n.value}else r.length&&(Y.set(this,i,{value:S.event.trigger(S.extend(r[0],S.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Y.get(e,i)&&S.event.add(e,i,we)}S.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Y.get(t);if(V(t)){n.handler&&(n=(o=n).handler,i=o.selector),i&&S.find.matchesSelector(re,i),n.guid||(n.guid=S.guid++),(u=v.events)||(u=v.events=Object.create(null)),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof S&&S.event.triggered!==e.type?S.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(P)||[""]).length;while(l--)d=g=(s=be.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=S.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=S.event.special[d]||{},c=S.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&S.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),S.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Y.hasData(e)&&Y.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(P)||[""]).length;while(l--)if(d=g=(s=be.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=S.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||S.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)S.event.remove(e,d+t[l],n,r,!0);S.isEmptyObject(u)&&Y.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=new Array(arguments.length),u=S.event.fix(e),l=(Y.get(this,"events")||Object.create(null))[u.type]||[],c=S.event.special[u.type]||{};for(s[0]=u,t=1;t<arguments.length;t++)s[t]=arguments[t];if(u.delegateTarget=this,!c.preDispatch||!1!==c.preDispatch.call(this,u)){a=S.event.handlers.call(this,u,l),t=0;while((i=a[t++])&&!u.isPropagationStopped()){u.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!u.isImmediatePropagationStopped())u.rnamespace&&!1!==o.namespace&&!u.rnamespace.test(o.namespace)||(u.handleObj=o,u.data=o.data,void 0!==(r=((S.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,s))&&!1===(u.result=r)&&(u.preventDefault(),u.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,u),u.result}},handlers:function(e,t){var n,r,i,o,a,s=[],u=t.delegateCount,l=e.target;if(u&&l.nodeType&&!("click"===e.type&&1<=e.button))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n<u;n++)void 0===a[i=(r=t[n]).selector+" "]&&(a[i]=r.needsContext?-1<S(i,this).index(l):S.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u<t.length&&s.push({elem:l,handlers:t.slice(u)}),s},addProp:function(t,e){Object.defineProperty(S.Event.prototype,t,{enumerable:!0,configurable:!0,get:m(e)?function(){if(this.originalEvent)return e(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[t]},set:function(e){Object.defineProperty(this,t,{enumerable:!0,configurable:!0,writable:!0,value:e})}})},fix:function(e){return e[S.expando]?e:new S.Event(e)},special:{load:{noBubble:!0},click:{setup:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&Se(t,"click",we),!1},trigger:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&Se(t,"click"),!0},_default:function(e){var t=e.target;return pe.test(t.type)&&t.click&&A(t,"input")&&Y.get(t,"click")||A(t,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},S.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},S.Event=function(e,t){if(!(this instanceof S.Event))return new S.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?we:Te,this.target=e.target&&3===e.target.nodeType?e.target.parentNode:e.target,this.currentTarget=e.currentTarget,this.relatedTarget=e.relatedTarget):this.type=e,t&&S.extend(this,t),this.timeStamp=e&&e.timeStamp||Date.now(),this[S.expando]=!0},S.Event.prototype={constructor:S.Event,isDefaultPrevented:Te,isPropagationStopped:Te,isImmediatePropagationStopped:Te,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=we,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=we,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=we,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},S.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,code:!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:!0},S.event.addProp),S.each({focus:"focusin",blur:"focusout"},function(e,t){S.event.special[e]={setup:function(){return Se(this,e,Ce),!1},trigger:function(){return Se(this,e),!0},_default:function(){return!0},delegateType:t}}),S.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,i){S.event.special[e]={delegateType:i,bindType:i,handle:function(e){var t,n=e.relatedTarget,r=e.handleObj;return n&&(n===this||S.contains(this,n))||(e.type=r.origType,t=r.handler.apply(this,arguments),e.type=i),t}}}),S.fn.extend({on:function(e,t,n,r){return Ee(this,e,t,n,r)},one:function(e,t,n,r){return Ee(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,S(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return!1!==t&&"function"!=typeof t||(n=t,t=void 0),!1===n&&(n=Te),this.each(function(){S.event.remove(this,e,n,t)})}});var ke=/<script|<style|<link/i,Ae=/checked\s*(?:[^=]|=\s*.checked.)/i,Ne=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function je(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function qe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n<r;n++)S.event.add(t,i,s[i][n]);Q.hasData(e)&&(o=Q.access(e),a=S.extend({},o),Q.set(t,a))}}function He(n,r,i,o){r=g(r);var e,t,a,s,u,l,c=0,f=n.length,p=f-1,d=r[0],h=m(d);if(h||1<f&&"string"==typeof d&&!y.checkClone&&Ae.test(d))return n.each(function(e){var t=n.eq(e);h&&(r[0]=d.call(this,e,t.html())),He(t,r,i,o)});if(f&&(t=(e=xe(r,n[0].ownerDocument,!1,n,o)).firstChild,1===e.childNodes.length&&(e=t),t||o)){for(s=(a=S.map(ve(e,"script"),De)).length;c<f;c++)u=e,c!==p&&(u=S.clone(u,!0,!0),s&&S.merge(a,ve(u,"script"))),i.call(n[c],u,c);if(s)for(l=a[a.length-1].ownerDocument,S.map(a,qe),c=0;c<s;c++)u=a[c],he.test(u.type||"")&&!Y.access(u,"globalEval")&&S.contains(l,u)&&(u.src&&"module"!==(u.type||"").toLowerCase()?S._evalUrl&&!u.noModule&&S._evalUrl(u.src,{nonce:u.nonce||u.getAttribute("nonce")},l):b(u.textContent.replace(Ne,""),u,l))}return n}function Oe(e,t,n){for(var r,i=t?S.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||S.cleanData(ve(r)),r.parentNode&&(n&&ie(r)&&ye(ve(r,"script")),r.parentNode.removeChild(r));return e}S.extend({htmlPrefilter:function(e){return e},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=ie(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||S.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r<i;r++)s=o[r],u=a[r],void 0,"input"===(l=u.nodeName.toLowerCase())&&pe.test(s.type)?u.checked=s.checked:"input"!==l&&"textarea"!==l||(u.defaultValue=s.defaultValue);if(t)if(n)for(o=o||ve(e),a=a||ve(c),r=0,i=o.length;r<i;r++)Le(o[r],a[r]);else Le(e,c);return 0<(a=ve(c,"script")).length&&ye(a,!f&&ve(e,"script")),c},cleanData:function(e){for(var t,n,r,i=S.event.special,o=0;void 0!==(n=e[o]);o++)if(V(n)){if(t=n[Y.expando]){if(t.events)for(r in t.events)i[r]?S.event.remove(n,r):S.removeEvent(n,r,t.handle);n[Y.expando]=void 0}n[Q.expando]&&(n[Q.expando]=void 0)}}}),S.fn.extend({detach:function(e){return Oe(this,e,!0)},remove:function(e){return Oe(this,e)},text:function(e){return $(this,function(e){return void 0===e?S.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return He(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||je(this,e).appendChild(e)})},prepend:function(){return He(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=je(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return He(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return He(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(S.cleanData(ve(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return S.clone(this,e,t)})},html:function(e){return $(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!ke.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=S.htmlPrefilter(e);try{for(;n<r;n++)1===(t=this[n]||{}).nodeType&&(S.cleanData(ve(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var n=[];return He(this,arguments,function(e){var t=this.parentNode;S.inArray(this,n)<0&&(S.cleanData(ve(this)),t&&t.replaceChild(e,this))},n)}}),S.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,a){S.fn[e]=function(e){for(var t,n=[],r=S(e),i=r.length-1,o=0;o<=i;o++)t=o===i?this:this.clone(!0),S(r[o])[a](t),u.apply(n,t.get());return this.pushStack(n)}});var Pe=new RegExp("^("+ee+")(?!px)[a-z%]+$","i"),Re=function(e){var t=e.ownerDocument.defaultView;return t&&t.opener||(t=C),t.getComputedStyle(e)},Me=function(e,t,n){var r,i,o={};for(i in t)o[i]=e.style[i],e.style[i]=t[i];for(i in r=n.call(e),t)e.style[i]=o[i];return r},Ie=new RegExp(ne.join("|"),"i");function We(e,t,n){var r,i,o,a,s=e.style;return(n=n||Re(e))&&(""!==(a=n.getPropertyValue(t)||n[t])||ie(e)||(a=S.style(e,t)),!y.pixelBoxStyles()&&Pe.test(a)&&Ie.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0!==a?a+"":a}function Fe(e,t){return{get:function(){if(!e())return(this.get=t).apply(this,arguments);delete this.get}}}!function(){function e(){if(l){u.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",l.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",re.appendChild(u).appendChild(l);var e=C.getComputedStyle(l);n="1%"!==e.top,s=12===t(e.marginLeft),l.style.right="60%",o=36===t(e.right),r=36===t(e.width),l.style.position="absolute",i=12===t(l.offsetWidth/3),re.removeChild(u),l=null}}function t(e){return Math.round(parseFloat(e))}var n,r,i,o,a,s,u=E.createElement("div"),l=E.createElement("div");l.style&&(l.style.backgroundClip="content-box",l.cloneNode(!0).style.backgroundClip="",y.clearCloneStyle="content-box"===l.style.backgroundClip,S.extend(y,{boxSizingReliable:function(){return e(),r},pixelBoxStyles:function(){return e(),o},pixelPosition:function(){return e(),n},reliableMarginLeft:function(){return e(),s},scrollboxSize:function(){return e(),i},reliableTrDimensions:function(){var e,t,n,r;return null==a&&(e=E.createElement("table"),t=E.createElement("tr"),n=E.createElement("div"),e.style.cssText="position:absolute;left:-11111px;border-collapse:separate",t.style.cssText="border:1px solid",t.style.height="1px",n.style.height="9px",n.style.display="block",re.appendChild(e).appendChild(t).appendChild(n),r=C.getComputedStyle(t),a=parseInt(r.height,10)+parseInt(r.borderTopWidth,10)+parseInt(r.borderBottomWidth,10)===t.offsetHeight,re.removeChild(e)),a}}))}();var Be=["Webkit","Moz","ms"],$e=E.createElement("div").style,_e={};function ze(e){var t=S.cssProps[e]||_e[e];return t||(e in $e?e:_e[e]=function(e){var t=e[0].toUpperCase()+e.slice(1),n=Be.length;while(n--)if((e=Be[n]+t)in $e)return e}(e)||e)}var Ue=/^(none|table(?!-c[ea]).+)/,Xe=/^--/,Ve={position:"absolute",visibility:"hidden",display:"block"},Ge={letterSpacing:"0",fontWeight:"400"};function Ye(e,t,n){var r=te.exec(t);return r?Math.max(0,r[2]-(n||0))+(r[3]||"px"):t}function Qe(e,t,n,r,i,o){var a="width"===t?1:0,s=0,u=0;if(n===(r?"border":"content"))return 0;for(;a<4;a+=2)"margin"===n&&(u+=S.css(e,n+ne[a],!0,i)),r?("content"===n&&(u-=S.css(e,"padding"+ne[a],!0,i)),"margin"!==n&&(u-=S.css(e,"border"+ne[a]+"Width",!0,i))):(u+=S.css(e,"padding"+ne[a],!0,i),"padding"!==n?u+=S.css(e,"border"+ne[a]+"Width",!0,i):s+=S.css(e,"border"+ne[a]+"Width",!0,i));return!r&&0<=o&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))||0),u}function Je(e,t,n){var r=Re(e),i=(!y.boxSizingReliable()||n)&&"border-box"===S.css(e,"boxSizing",!1,r),o=i,a=We(e,t,r),s="offset"+t[0].toUpperCase()+t.slice(1);if(Pe.test(a)){if(!n)return a;a="auto"}return(!y.boxSizingReliable()&&i||!y.reliableTrDimensions()&&A(e,"tr")||"auto"===a||!parseFloat(a)&&"inline"===S.css(e,"display",!1,r))&&e.getClientRects().length&&(i="border-box"===S.css(e,"boxSizing",!1,r),(o=s in e)&&(a=e[s])),(a=parseFloat(a)||0)+Qe(e,t,n||(i?"border":"content"),o,r,a)+"px"}function Ke(e,t,n,r,i){return new Ke.prototype.init(e,t,n,r,i)}S.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=We(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=X(t),u=Xe.test(t),l=e.style;if(u||(t=ze(s)),a=S.cssHooks[t]||S.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"===(o=typeof n)&&(i=te.exec(n))&&i[1]&&(n=se(e,t,i),o="number"),null!=n&&n==n&&("number"!==o||u||(n+=i&&i[3]||(S.cssNumber[s]?"":"px")),y.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=X(t);return Xe.test(t)||(t=ze(s)),(a=S.cssHooks[t]||S.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=We(e,t,r)),"normal"===i&&t in Ge&&(i=Ge[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),S.each(["height","width"],function(e,u){S.cssHooks[u]={get:function(e,t,n){if(t)return!Ue.test(S.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?Je(e,u,n):Me(e,Ve,function(){return Je(e,u,n)})},set:function(e,t,n){var r,i=Re(e),o=!y.scrollboxSize()&&"absolute"===i.position,a=(o||n)&&"border-box"===S.css(e,"boxSizing",!1,i),s=n?Qe(e,u,n,a,i):0;return a&&o&&(s-=Math.ceil(e["offset"+u[0].toUpperCase()+u.slice(1)]-parseFloat(i[u])-Qe(e,u,"border",!1,i)-.5)),s&&(r=te.exec(t))&&"px"!==(r[3]||"px")&&(e.style[u]=t,t=S.css(e,u)),Ye(0,t,s)}}}),S.cssHooks.marginLeft=Fe(y.reliableMarginLeft,function(e,t){if(t)return(parseFloat(We(e,"marginLeft"))||e.getBoundingClientRect().left-Me(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),S.each({margin:"",padding:"",border:"Width"},function(i,o){S.cssHooks[i+o]={expand:function(e){for(var t=0,n={},r="string"==typeof e?e.split(" "):[e];t<4;t++)n[i+ne[t]+o]=r[t]||r[t-2]||r[0];return n}},"margin"!==i&&(S.cssHooks[i+o].set=Ye)}),S.fn.extend({css:function(e,t){return $(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=Re(e),i=t.length;a<i;a++)o[t[a]]=S.css(e,t[a],!1,r);return o}return void 0!==n?S.style(e,t,n):S.css(e,t)},e,t,1<arguments.length)}}),((S.Tween=Ke).prototype={constructor:Ke,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||S.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(S.cssNumber[n]?"":"px")},cur:function(){var e=Ke.propHooks[this.prop];return e&&e.get?e.get(this):Ke.propHooks._default.get(this)},run:function(e){var t,n=Ke.propHooks[this.prop];return this.options.duration?this.pos=t=S.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Ke.propHooks._default.set(this),this}}).init.prototype=Ke.prototype,(Ke.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=S.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){S.fx.step[e.prop]?S.fx.step[e.prop](e):1!==e.elem.nodeType||!S.cssHooks[e.prop]&&null==e.elem.style[ze(e.prop)]?e.elem[e.prop]=e.now:S.style(e.elem,e.prop,e.now+e.unit)}}}).scrollTop=Ke.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},S.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},S.fx=Ke.prototype.init,S.fx.step={};var Ze,et,tt,nt,rt=/^(?:toggle|show|hide)$/,it=/queueHooks$/;function ot(){et&&(!1===E.hidden&&C.requestAnimationFrame?C.requestAnimationFrame(ot):C.setTimeout(ot,S.fx.interval),S.fx.tick())}function at(){return C.setTimeout(function(){Ze=void 0}),Ze=Date.now()}function st(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=ne[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function ut(e,t,n){for(var r,i=(lt.tweeners[t]||[]).concat(lt.tweeners["*"]),o=0,a=i.length;o<a;o++)if(r=i[o].call(n,t,e))return r}function lt(o,e,t){var n,a,r=0,i=lt.prefilters.length,s=S.Deferred().always(function(){delete u.elem}),u=function(){if(a)return!1;for(var e=Ze||at(),t=Math.max(0,l.startTime+l.duration-e),n=1-(t/l.duration||0),r=0,i=l.tweens.length;r<i;r++)l.tweens[r].run(n);return s.notifyWith(o,[l,n,t]),n<1&&i?t:(i||s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l]),!1)},l=s.promise({elem:o,props:S.extend({},e),opts:S.extend(!0,{specialEasing:{},easing:S.easing._default},t),originalProperties:e,originalOptions:t,startTime:Ze||at(),duration:t.duration,tweens:[],createTween:function(e,t){var n=S.Tween(o,l.opts,e,t,l.opts.specialEasing[e]||l.opts.easing);return l.tweens.push(n),n},stop:function(e){var t=0,n=e?l.tweens.length:0;if(a)return this;for(a=!0;t<n;t++)l.tweens[t].run(1);return e?(s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l,e])):s.rejectWith(o,[l,e]),this}}),c=l.props;for(!function(e,t){var n,r,i,o,a;for(n in e)if(i=t[r=X(n)],o=e[n],Array.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),(a=S.cssHooks[r])&&"expand"in a)for(n in o=a.expand(o),delete e[r],o)n in e||(e[n]=o[n],t[n]=i);else t[r]=i}(c,l.opts.specialEasing);r<i;r++)if(n=lt.prefilters[r].call(l,o,c,l.opts))return m(n.stop)&&(S._queueHooks(l.elem,l.opts.queue).stop=n.stop.bind(n)),n;return S.map(c,ut,l),m(l.opts.start)&&l.opts.start.call(o,l),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always),S.fx.timer(S.extend(u,{elem:o,anim:l,queue:l.opts.queue})),l}S.Animation=S.extend(lt,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return se(n.elem,e,te.exec(t),n),n}]},tweener:function(e,t){m(e)?(t=e,e=["*"]):e=e.match(P);for(var n,r=0,i=e.length;r<i;r++)n=e[r],lt.tweeners[n]=lt.tweeners[n]||[],lt.tweeners[n].unshift(t)},prefilters:[function(e,t,n){var r,i,o,a,s,u,l,c,f="width"in t||"height"in t,p=this,d={},h=e.style,g=e.nodeType&&ae(e),v=Y.get(e,"fxshow");for(r in n.queue||(null==(a=S._queueHooks(e,"fx")).unqueued&&(a.unqueued=0,s=a.empty.fire,a.empty.fire=function(){a.unqueued||s()}),a.unqueued++,p.always(function(){p.always(function(){a.unqueued--,S.queue(e,"fx").length||a.empty.fire()})})),t)if(i=t[r],rt.test(i)){if(delete t[r],o=o||"toggle"===i,i===(g?"hide":"show")){if("show"!==i||!v||void 0===v[r])continue;g=!0}d[r]=v&&v[r]||S.style(e,r)}if((u=!S.isEmptyObject(t))||!S.isEmptyObject(d))for(r in f&&1===e.nodeType&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],null==(l=v&&v.display)&&(l=Y.get(e,"display")),"none"===(c=S.css(e,"display"))&&(l?c=l:(le([e],!0),l=e.style.display||l,c=S.css(e,"display"),le([e]))),("inline"===c||"inline-block"===c&&null!=l)&&"none"===S.css(e,"float")&&(u||(p.done(function(){h.display=l}),null==l&&(c=h.display,l="none"===c?"":c)),h.display="inline-block")),n.overflow&&(h.overflow="hidden",p.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]})),u=!1,d)u||(v?"hidden"in v&&(g=v.hidden):v=Y.access(e,"fxshow",{display:l}),o&&(v.hidden=!g),g&&le([e],!0),p.done(function(){for(r in g||le([e]),Y.remove(e,"fxshow"),d)S.style(e,r,d[r])})),u=ut(g?v[r]:0,r,p),r in v||(v[r]=u.start,g&&(u.end=u.start,u.start=0))}],prefilter:function(e,t){t?lt.prefilters.unshift(e):lt.prefilters.push(e)}}),S.speed=function(e,t,n){var r=e&&"object"==typeof e?S.extend({},e):{complete:n||!n&&t||m(e)&&e,duration:e,easing:n&&t||t&&!m(t)&&t};return S.fx.off?r.duration=0:"number"!=typeof r.duration&&(r.duration in S.fx.speeds?r.duration=S.fx.speeds[r.duration]:r.duration=S.fx.speeds._default),null!=r.queue&&!0!==r.queue||(r.queue="fx"),r.old=r.complete,r.complete=function(){m(r.old)&&r.old.call(this),r.queue&&S.dequeue(this,r.queue)},r},S.fn.extend({fadeTo:function(e,t,n,r){return this.filter(ae).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(t,e,n,r){var i=S.isEmptyObject(t),o=S.speed(e,n,r),a=function(){var e=lt(this,S.extend({},t),o);(i||Y.get(this,"finish"))&&e.stop(!0)};return a.finish=a,i||!1===o.queue?this.each(a):this.queue(o.queue,a)},stop:function(i,e,o){var a=function(e){var t=e.stop;delete e.stop,t(o)};return"string"!=typeof i&&(o=e,e=i,i=void 0),e&&this.queue(i||"fx",[]),this.each(function(){var e=!0,t=null!=i&&i+"queueHooks",n=S.timers,r=Y.get(this);if(t)r[t]&&r[t].stop&&a(r[t]);else for(t in r)r[t]&&r[t].stop&&it.test(t)&&a(r[t]);for(t=n.length;t--;)n[t].elem!==this||null!=i&&n[t].queue!==i||(n[t].anim.stop(o),e=!1,n.splice(t,1));!e&&o||S.dequeue(this,i)})},finish:function(a){return!1!==a&&(a=a||"fx"),this.each(function(){var e,t=Y.get(this),n=t[a+"queue"],r=t[a+"queueHooks"],i=S.timers,o=n?n.length:0;for(t.finish=!0,S.queue(this,a,[]),r&&r.stop&&r.stop.call(this,!0),e=i.length;e--;)i[e].elem===this&&i[e].queue===a&&(i[e].anim.stop(!0),i.splice(e,1));for(e=0;e<o;e++)n[e]&&n[e].finish&&n[e].finish.call(this);delete t.finish})}}),S.each(["toggle","show","hide"],function(e,r){var i=S.fn[r];S.fn[r]=function(e,t,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(st(r,!0),e,t,n)}}),S.each({slideDown:st("show"),slideUp:st("hide"),slideToggle:st("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,r){S.fn[e]=function(e,t,n){return this.animate(r,e,t,n)}}),S.timers=[],S.fx.tick=function(){var e,t=0,n=S.timers;for(Ze=Date.now();t<n.length;t++)(e=n[t])()||n[t]!==e||n.splice(t--,1);n.length||S.fx.stop(),Ze=void 0},S.fx.timer=function(e){S.timers.push(e),S.fx.start()},S.fx.interval=13,S.fx.start=function(){et||(et=!0,ot())},S.fx.stop=function(){et=null},S.fx.speeds={slow:600,fast:200,_default:400},S.fn.delay=function(r,e){return r=S.fx&&S.fx.speeds[r]||r,e=e||"fx",this.queue(e,function(e,t){var n=C.setTimeout(e,r);t.stop=function(){C.clearTimeout(n)}})},tt=E.createElement("input"),nt=E.createElement("select").appendChild(E.createElement("option")),tt.type="checkbox",y.checkOn=""!==tt.value,y.optSelected=nt.selected,(tt=E.createElement("input")).value="t",tt.type="radio",y.radioValue="t"===tt.value;var ct,ft=S.expr.attrHandle;S.fn.extend({attr:function(e,t){return $(this,S.attr,e,t,1<arguments.length)},removeAttr:function(e){return this.each(function(){S.removeAttr(this,e)})}}),S.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?S.prop(e,t,n):(1===o&&S.isXMLDoc(e)||(i=S.attrHooks[t.toLowerCase()]||(S.expr.match.bool.test(t)?ct:void 0)),void 0!==n?null===n?void S.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=S.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!y.radioValue&&"radio"===t&&A(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(P);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),ct={set:function(e,t,n){return!1===t?S.removeAttr(e,n):e.setAttribute(n,n),n}},S.each(S.expr.match.bool.source.match(/\w+/g),function(e,t){var a=ft[t]||S.find.attr;ft[t]=function(e,t,n){var r,i,o=t.toLowerCase();return n||(i=ft[o],ft[o]=r,r=null!=a(e,t,n)?o:null,ft[o]=i),r}});var pt=/^(?:input|select|textarea|button)$/i,dt=/^(?:a|area)$/i;function ht(e){return(e.match(P)||[]).join(" ")}function gt(e){return e.getAttribute&&e.getAttribute("class")||""}function vt(e){return Array.isArray(e)?e:"string"==typeof e&&e.match(P)||[]}S.fn.extend({prop:function(e,t){return $(this,S.prop,e,t,1<arguments.length)},removeProp:function(e){return this.each(function(){delete this[S.propFix[e]||e]})}}),S.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&S.isXMLDoc(e)||(t=S.propFix[t]||t,i=S.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=S.find.attr(e,"tabindex");return t?parseInt(t,10):pt.test(e.nodeName)||dt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),y.optSelected||(S.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),S.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){S.propFix[this.toLowerCase()]=this}),S.fn.extend({addClass:function(t){var e,n,r,i,o,a,s,u=0;if(m(t))return this.each(function(e){S(this).addClass(t.call(this,e,gt(this)))});if((e=vt(t)).length)while(n=this[u++])if(i=gt(n),r=1===n.nodeType&&" "+ht(i)+" "){a=0;while(o=e[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=ht(r))&&n.setAttribute("class",s)}return this},removeClass:function(t){var e,n,r,i,o,a,s,u=0;if(m(t))return this.each(function(e){S(this).removeClass(t.call(this,e,gt(this)))});if(!arguments.length)return this.attr("class","");if((e=vt(t)).length)while(n=this[u++])if(i=gt(n),r=1===n.nodeType&&" "+ht(i)+" "){a=0;while(o=e[a++])while(-1<r.indexOf(" "+o+" "))r=r.replace(" "+o+" "," ");i!==(s=ht(r))&&n.setAttribute("class",s)}return this},toggleClass:function(i,t){var o=typeof i,a="string"===o||Array.isArray(i);return"boolean"==typeof t&&a?t?this.addClass(i):this.removeClass(i):m(i)?this.each(function(e){S(this).toggleClass(i.call(this,e,gt(this),t),t)}):this.each(function(){var e,t,n,r;if(a){t=0,n=S(this),r=vt(i);while(e=r[t++])n.hasClass(e)?n.removeClass(e):n.addClass(e)}else void 0!==i&&"boolean"!==o||((e=gt(this))&&Y.set(this,"__className__",e),this.setAttribute&&this.setAttribute("class",e||!1===i?"":Y.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&-1<(" "+ht(gt(n))+" ").indexOf(t))return!0;return!1}});var yt=/\r/g;S.fn.extend({val:function(n){var r,e,i,t=this[0];return arguments.length?(i=m(n),this.each(function(e){var t;1===this.nodeType&&(null==(t=i?n.call(this,e,S(this).val()):n)?t="":"number"==typeof t?t+="":Array.isArray(t)&&(t=S.map(t,function(e){return null==e?"":e+""})),(r=S.valHooks[this.type]||S.valHooks[this.nodeName.toLowerCase()])&&"set"in r&&void 0!==r.set(this,t,"value")||(this.value=t))})):t?(r=S.valHooks[t.type]||S.valHooks[t.nodeName.toLowerCase()])&&"get"in r&&void 0!==(e=r.get(t,"value"))?e:"string"==typeof(e=t.value)?e.replace(yt,""):null==e?"":e:void 0}}),S.extend({valHooks:{option:{get:function(e){var t=S.find.attr(e,"value");return null!=t?t:ht(S.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r<u;r++)if(((n=i[r]).selected||r===o)&&!n.disabled&&(!n.parentNode.disabled||!A(n.parentNode,"optgroup"))){if(t=S(n).val(),a)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=S.makeArray(t),a=i.length;while(a--)((r=i[a]).selected=-1<S.inArray(S.valHooks.option.get(r),o))&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),S.each(["radio","checkbox"],function(){S.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=-1<S.inArray(S(e).val(),t)}},y.checkOn||(S.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),y.focusin="onfocusin"in C;var mt=/^(?:focusinfocus|focusoutblur)$/,xt=function(e){e.stopPropagation()};S.extend(S.event,{trigger:function(e,t,n,r){var i,o,a,s,u,l,c,f,p=[n||E],d=v.call(e,"type")?e.type:e,h=v.call(e,"namespace")?e.namespace.split("."):[];if(o=f=a=n=n||E,3!==n.nodeType&&8!==n.nodeType&&!mt.test(d+S.event.triggered)&&(-1<d.indexOf(".")&&(d=(h=d.split(".")).shift(),h.sort()),u=d.indexOf(":")<0&&"on"+d,(e=e[S.expando]?e:new S.Event(d,"object"==typeof e&&e)).isTrigger=r?2:3,e.namespace=h.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=n),t=null==t?[e]:S.makeArray(t,[e]),c=S.event.special[d]||{},r||!c.trigger||!1!==c.trigger.apply(n,t))){if(!r&&!c.noBubble&&!x(n)){for(s=c.delegateType||d,mt.test(s+d)||(o=o.parentNode);o;o=o.parentNode)p.push(o),a=o;a===(n.ownerDocument||E)&&p.push(a.defaultView||a.parentWindow||C)}i=0;while((o=p[i++])&&!e.isPropagationStopped())f=o,e.type=1<i?s:c.bindType||d,(l=(Y.get(o,"events")||Object.create(null))[e.type]&&Y.get(o,"handle"))&&l.apply(o,t),(l=u&&o[u])&&l.apply&&V(o)&&(e.result=l.apply(o,t),!1===e.result&&e.preventDefault());return e.type=d,r||e.isDefaultPrevented()||c._default&&!1!==c._default.apply(p.pop(),t)||!V(n)||u&&m(n[d])&&!x(n)&&((a=n[u])&&(n[u]=null),S.event.triggered=d,e.isPropagationStopped()&&f.addEventListener(d,xt),n[d](),e.isPropagationStopped()&&f.removeEventListener(d,xt),S.event.triggered=void 0,a&&(n[u]=a)),e.result}},simulate:function(e,t,n){var r=S.extend(new S.Event,n,{type:e,isSimulated:!0});S.event.trigger(r,null,t)}}),S.fn.extend({trigger:function(e,t){return this.each(function(){S.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return S.event.trigger(e,t,n,!0)}}),y.focusin||S.each({focus:"focusin",blur:"focusout"},function(n,r){var i=function(e){S.event.simulate(r,e.target,S.event.fix(e))};S.event.special[r]={setup:function(){var e=this.ownerDocument||this.document||this,t=Y.access(e,r);t||e.addEventListener(n,i,!0),Y.access(e,r,(t||0)+1)},teardown:function(){var e=this.ownerDocument||this.document||this,t=Y.access(e,r)-1;t?Y.access(e,r,t):(e.removeEventListener(n,i,!0),Y.remove(e,r))}}});var bt=C.location,wt={guid:Date.now()},Tt=/\?/;S.parseXML=function(e){var t,n;if(!e||"string"!=typeof e)return null;try{t=(new C.DOMParser).parseFromString(e,"text/xml")}catch(e){}return n=t&&t.getElementsByTagName("parsererror")[0],t&&!n||S.error("Invalid XML: "+(n?S.map(n.childNodes,function(e){return e.textContent}).join("\n"):e)),t};var Ct=/\[\]$/,Et=/\r?\n/g,St=/^(?:submit|button|image|reset|file)$/i,kt=/^(?:input|select|textarea|keygen)/i;function At(n,e,r,i){var t;if(Array.isArray(e))S.each(e,function(e,t){r||Ct.test(n)?i(n,t):At(n+"["+("object"==typeof t&&null!=t?e:"")+"]",t,r,i)});else if(r||"object"!==w(e))i(n,e);else for(t in e)At(n+"["+t+"]",e[t],r,i)}S.param=function(e,t){var n,r=[],i=function(e,t){var n=m(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(null==e)return"";if(Array.isArray(e)||e.jquery&&!S.isPlainObject(e))S.each(e,function(){i(this.name,this.value)});else for(n in e)At(n,e[n],t,i);return r.join("&")},S.fn.extend({serialize:function(){return S.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=S.prop(this,"elements");return e?S.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!S(this).is(":disabled")&&kt.test(this.nodeName)&&!St.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=S(this).val();return null==n?null:Array.isArray(n)?S.map(n,function(e){return{name:t.name,value:e.replace(Et,"\r\n")}}):{name:t.name,value:n.replace(Et,"\r\n")}}).get()}});var Nt=/%20/g,jt=/#.*$/,Dt=/([?&])_=[^&]*/,qt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Lt=/^(?:GET|HEAD)$/,Ht=/^\/\//,Ot={},Pt={},Rt="*/".concat("*"),Mt=E.createElement("a");function It(o){return function(e,t){"string"!=typeof e&&(t=e,e="*");var n,r=0,i=e.toLowerCase().match(P)||[];if(m(t))while(n=i[r++])"+"===n[0]?(n=n.slice(1)||"*",(o[n]=o[n]||[]).unshift(t)):(o[n]=o[n]||[]).push(t)}}function Wt(t,i,o,a){var s={},u=t===Pt;function l(e){var r;return s[e]=!0,S.each(t[e]||[],function(e,t){var n=t(i,o,a);return"string"!=typeof n||u||s[n]?u?!(r=n):void 0:(i.dataTypes.unshift(n),l(n),!1)}),r}return l(i.dataTypes[0])||!s["*"]&&l("*")}function Ft(e,t){var n,r,i=S.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&S.extend(!0,e,r),e}Mt.href=bt.href,S.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:bt.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(bt.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Rt,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":S.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Ft(Ft(e,S.ajaxSettings),t):Ft(S.ajaxSettings,e)},ajaxPrefilter:It(Ot),ajaxTransport:It(Pt),ajax:function(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var c,f,p,n,d,r,h,g,i,o,v=S.ajaxSetup({},t),y=v.context||v,m=v.context&&(y.nodeType||y.jquery)?S(y):S.event,x=S.Deferred(),b=S.Callbacks("once memory"),w=v.statusCode||{},a={},s={},u="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(h){if(!n){n={};while(t=qt.exec(p))n[t[1].toLowerCase()+" "]=(n[t[1].toLowerCase()+" "]||[]).concat(t[2])}t=n[e.toLowerCase()+" "]}return null==t?null:t.join(", ")},getAllResponseHeaders:function(){return h?p:null},setRequestHeader:function(e,t){return null==h&&(e=s[e.toLowerCase()]=s[e.toLowerCase()]||e,a[e]=t),this},overrideMimeType:function(e){return null==h&&(v.mimeType=e),this},statusCode:function(e){var t;if(e)if(h)T.always(e[T.status]);else for(t in e)w[t]=[w[t],e[t]];return this},abort:function(e){var t=e||u;return c&&c.abort(t),l(0,t),this}};if(x.promise(T),v.url=((e||v.url||bt.href)+"").replace(Ht,bt.protocol+"//"),v.type=t.method||t.type||v.method||v.type,v.dataTypes=(v.dataType||"*").toLowerCase().match(P)||[""],null==v.crossDomain){r=E.createElement("a");try{r.href=v.url,r.href=r.href,v.crossDomain=Mt.protocol+"//"+Mt.host!=r.protocol+"//"+r.host}catch(e){v.crossDomain=!0}}if(v.data&&v.processData&&"string"!=typeof v.data&&(v.data=S.param(v.data,v.traditional)),Wt(Ot,v,t,T),h)return T;for(i in(g=S.event&&v.global)&&0==S.active++&&S.event.trigger("ajaxStart"),v.type=v.type.toUpperCase(),v.hasContent=!Lt.test(v.type),f=v.url.replace(jt,""),v.hasContent?v.data&&v.processData&&0===(v.contentType||"").indexOf("application/x-www-form-urlencoded")&&(v.data=v.data.replace(Nt,"+")):(o=v.url.slice(f.length),v.data&&(v.processData||"string"==typeof v.data)&&(f+=(Tt.test(f)?"&":"?")+v.data,delete v.data),!1===v.cache&&(f=f.replace(Dt,"$1"),o=(Tt.test(f)?"&":"?")+"_="+wt.guid+++o),v.url=f+o),v.ifModified&&(S.lastModified[f]&&T.setRequestHeader("If-Modified-Since",S.lastModified[f]),S.etag[f]&&T.setRequestHeader("If-None-Match",S.etag[f])),(v.data&&v.hasContent&&!1!==v.contentType||t.contentType)&&T.setRequestHeader("Content-Type",v.contentType),T.setRequestHeader("Accept",v.dataTypes[0]&&v.accepts[v.dataTypes[0]]?v.accepts[v.dataTypes[0]]+("*"!==v.dataTypes[0]?", "+Rt+"; q=0.01":""):v.accepts["*"]),v.headers)T.setRequestHeader(i,v.headers[i]);if(v.beforeSend&&(!1===v.beforeSend.call(y,T,v)||h))return T.abort();if(u="abort",b.add(v.complete),T.done(v.success),T.fail(v.error),c=Wt(Pt,v,t,T)){if(T.readyState=1,g&&m.trigger("ajaxSend",[T,v]),h)return T;v.async&&0<v.timeout&&(d=C.setTimeout(function(){T.abort("timeout")},v.timeout));try{h=!1,c.send(a,l)}catch(e){if(h)throw e;l(-1,e)}}else l(-1,"No Transport");function l(e,t,n,r){var i,o,a,s,u,l=t;h||(h=!0,d&&C.clearTimeout(d),c=void 0,p=r||"",T.readyState=0<e?4:0,i=200<=e&&e<300||304===e,n&&(s=function(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}(v,T,n)),!i&&-1<S.inArray("script",v.dataTypes)&&S.inArray("json",v.dataTypes)<0&&(v.converters["text script"]=function(){}),s=function(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}(v,s,T,i),i?(v.ifModified&&((u=T.getResponseHeader("Last-Modified"))&&(S.lastModified[f]=u),(u=T.getResponseHeader("etag"))&&(S.etag[f]=u)),204===e||"HEAD"===v.type?l="nocontent":304===e?l="notmodified":(l=s.state,o=s.data,i=!(a=s.error))):(a=l,!e&&l||(l="error",e<0&&(e=0))),T.status=e,T.statusText=(t||l)+"",i?x.resolveWith(y,[o,l,T]):x.rejectWith(y,[T,l,a]),T.statusCode(w),w=void 0,g&&m.trigger(i?"ajaxSuccess":"ajaxError",[T,v,i?o:a]),b.fireWith(y,[T,l]),g&&(m.trigger("ajaxComplete",[T,v]),--S.active||S.event.trigger("ajaxStop")))}return T},getJSON:function(e,t,n){return S.get(e,t,n,"json")},getScript:function(e,t){return S.get(e,void 0,t,"script")}}),S.each(["get","post"],function(e,i){S[i]=function(e,t,n,r){return m(t)&&(r=r||n,n=t,t=void 0),S.ajax(S.extend({url:e,type:i,dataType:r,data:t,success:n},S.isPlainObject(e)&&e))}}),S.ajaxPrefilter(function(e){var t;for(t in e.headers)"content-type"===t.toLowerCase()&&(e.contentType=e.headers[t]||"")}),S._evalUrl=function(e,t,n){return S.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(e){S.globalEval(e,t,n)}})},S.fn.extend({wrapAll:function(e){var t;return this[0]&&(m(e)&&(e=e.call(this[0])),t=S(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(n){return m(n)?this.each(function(e){S(this).wrapInner(n.call(this,e))}):this.each(function(){var e=S(this),t=e.contents();t.length?t.wrapAll(n):e.append(n)})},wrap:function(t){var n=m(t);return this.each(function(e){S(this).wrapAll(n?t.call(this,e):t)})},unwrap:function(e){return this.parent(e).not("body").each(function(){S(this).replaceWith(this.childNodes)}),this}}),S.expr.pseudos.hidden=function(e){return!S.expr.pseudos.visible(e)},S.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},S.ajaxSettings.xhr=function(){try{return new C.XMLHttpRequest}catch(e){}};var Bt={0:200,1223:204},$t=S.ajaxSettings.xhr();y.cors=!!$t&&"withCredentials"in $t,y.ajax=$t=!!$t,S.ajaxTransport(function(i){var o,a;if(y.cors||$t&&!i.crossDomain)return{send:function(e,t){var n,r=i.xhr();if(r.open(i.type,i.url,i.async,i.username,i.password),i.xhrFields)for(n in i.xhrFields)r[n]=i.xhrFields[n];for(n in i.mimeType&&r.overrideMimeType&&r.overrideMimeType(i.mimeType),i.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest"),e)r.setRequestHeader(n,e[n]);o=function(e){return function(){o&&(o=a=r.onload=r.onerror=r.onabort=r.ontimeout=r.onreadystatechange=null,"abort"===e?r.abort():"error"===e?"number"!=typeof r.status?t(0,"error"):t(r.status,r.statusText):t(Bt[r.status]||r.status,r.statusText,"text"!==(r.responseType||"text")||"string"!=typeof r.responseText?{binary:r.response}:{text:r.responseText},r.getAllResponseHeaders()))}},r.onload=o(),a=r.onerror=r.ontimeout=o("error"),void 0!==r.onabort?r.onabort=a:r.onreadystatechange=function(){4===r.readyState&&C.setTimeout(function(){o&&a()})},o=o("abort");try{r.send(i.hasContent&&i.data||null)}catch(e){if(o)throw e}},abort:function(){o&&o()}}}),S.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),S.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return S.globalEval(e),e}}}),S.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),S.ajaxTransport("script",function(n){var r,i;if(n.crossDomain||n.scriptAttrs)return{send:function(e,t){r=S("<script>").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var _t,zt=[],Ut=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=zt.pop()||S.expando+"_"+wt.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Ut.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ut.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Ut,"$1"+r):!1!==e.jsonp&&(e.url+=(Tt.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,zt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((_t=E.implementation.createHTMLDocument("").body).innerHTML="<form></form><form></form>",2===_t.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1<s&&(r=ht(e.slice(s)),e=e.slice(0,s)),m(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),0<a.length&&S.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?S("<div>").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=Fe(y.pixelPosition,function(e,t){if(t)return t=We(e,n),Pe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0<arguments.length?this.on(n,null,e,t):this.trigger(n)}});var Xt=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;S.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),m(e))return r=s.call(arguments,2),(i=function(){return e.apply(t||this,r.concat(s.call(arguments)))}).guid=e.guid=e.guid||S.guid++,i},S.holdReady=function(e){e?S.readyWait++:S.ready(!0)},S.isArray=Array.isArray,S.parseJSON=JSON.parse,S.nodeName=A,S.isFunction=m,S.isWindow=x,S.camelCase=X,S.type=w,S.now=Date.now,S.isNumeric=function(e){var t=S.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},S.trim=function(e){return null==e?"":(e+"").replace(Xt,"")},"function"==typeof define&&define.amd&&define("jquery",[],function(){return S});var Vt=C.jQuery,Gt=C.$;return S.noConflict=function(e){return C.$===S&&(C.$=Gt),e&&C.jQuery===S&&(C.jQuery=Vt),S},"undefined"==typeof e&&(C.jQuery=C.$=S),S});
</script>
<!-- <script src="js/s.js"></script>-->
<script>
(function (doc, win) {
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function () {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
</script>
</head>
<body>
<div class="conBox">
<div class="logoBox">
<img class="logo" src="https://hisin.oss-cn-hangzhou.aliyuncs.com/image/logo/logo.png">
<span class="name">独家好歌,征集歌手</span>
<a class="btn" onclick="submitFn()">打开</a>
</div>
<div class="imgBox">
<img class="img1" src="https://hisin.oss-cn-hangzhou.aliyuncs.com/image/logo/shareapp/1.png">
<img class="img2" src="https://hisin.oss-cn-hangzhou.aliyuncs.com/image/logo/shareapp/2.png">
<img class="img3" src="https://hisin.oss-cn-hangzhou.aliyuncs.com/image/logo/shareapp/3.png">
</div>
<div class="openApp" onclick="submitFn()" >打开APP</div>
</div>
<!-- <script src="js/d.js"></script>-->
<script>
function submitFn() {
//判断浏览器
var u = navigator.userAgent;
var d = new Date();
var t0 = d.getTime();
if(u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {
//Android 向安卓同事索要链接
if(openApp('hikoon.tech://hising/index')) {
openApp('hikoon.tech://hising/index');
} else {
//由于打开需要1~2秒,利用这个时间差来处理--打开app后,返回h5页面会出现页面变成app下载页面,影响用户体验
var delay = setInterval(function() {
var d = new Date();
var t1 = d.getTime();
if(t1 - t0 < 3000 && t1 - t0 > 2000) {
// alert('检测到未安装,请下载APP');
window.location.href = "https://a.app.qq.com/o/simple.jsp?pkgname=com.hikoon.hising";
}
if(t1 - t0 >= 3000) {
clearInterval(delay);
}
}, 1000);
}
} else if(u.indexOf('iPhone') > -1) {
//ios直接跳转到下载商店
window.location.href = "https://apps.apple.com/us/app/%E6%B5%B7%E6%98%9F%E8%AF%95%E5%94%B1/id1636460395";
}else{
}
};
function openApp(src) {
// 通过iframe的方式试图打开APP,如果能正常打开,会直接切换到APP,并自动阻止a标签的默认行为
// 否则打开a标签的href链接
var ifr = document.createElement('iframe');
ifr.src = src;
ifr.style.display = 'none';
document.body.appendChild(ifr);
window.setTimeout(function() {
document.body.removeChild(ifr);
}, 2000);
}
</script>
</body>
</html>
File mode changed
This diff could not be displayed because it is too large.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta name="generator" content="Aspose.Words for .NET 15.1.0.0" /><title></title>
</head>
<body style="padding:50px;">
<div style="line-height: 48px;">
<p style="background-color:#ffffff; margin:0pt; orphans:0; text-align:center; widows:0"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">“海星试唱”微信小程序/APP</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">用户协议</span></p><p style="background-color:#ffffff; margin:0pt; orphans:0; text-align:justify; widows:0"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">欢迎使用“海星试唱”微信小程序/APP软件及服务!</span></p><p style="background-color:#ffffff; margin:0pt; orphans:0; text-align:justify; widows:0"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">为使用“海星试唱”微信小程序/APP软件(以下简称</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">本软件</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">)及服务,你应当阅读并遵守《“海星试唱”微信小程序/APP</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">用户协议</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">》(以下简称</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">本协议</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span><span style="background-color:#ffffff; color:#333333; font-family:Calibri; font-size:12pt; font-weight:bold">&#xa0;</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">。请你务必审慎阅读、充分理解各条款内容,特别是免除或者限制责任的条款,并选择接受或不接受。限制、免责条款可能以加粗等形式提示你注意。</span></p><p style="background-color:#ffffff; margin:0pt; orphans:0; text-align:justify; widows:0"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">除非你已阅读并接受本协议所有条款,否则你无权下载、安装或使用本软件及相关服务。你的下载、安装、使用、注册、登录等行为即视为你已阅读并同意上述协议的约束。</span></p><p style="background-color:#ffffff; margin:0pt; orphans:0; text-align:justify; widows:0"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">如果你未满</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">18</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">周岁,请在法定监护人的陪同下阅读本协议及上述其他协议,并特别注意未成年人使用条款。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">&#xa0;</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">1. 接受条款</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">本软件</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">根据以下服务条款为您提供服务。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">这些条款包括本软件</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">可能不断发布的关于本服务的相关协议、业务指引和规则</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">以及版权声明</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">等内容。上述内容一经正式发布,即为本协议不可分割的组成部分,你同样应当遵守</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">2. 服务说明</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">目前向合法注册用户提供</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">在线试听歌曲小样、在线试唱歌曲小样、自主上传试唱音频文件等</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">服务(以下简称“本服务”),您可以在</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal"></span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:47:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">选择在线</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">录制并保存上传自己的</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:47:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">试唱</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:47:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">音频</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal"></span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal"></span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:47:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">选择以邮件方式获取对应试唱伴奏等资料后</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:48:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">在线下</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal"></span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:48:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">自行</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">通过其他硬件录制的</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:49:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">试唱</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">音频上传至</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">。除非本使用协议另有其它明示规定,增加或强化目前本服务的任何新功能,包括所推出的新产品,均受到本使用协议之规范。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">您了解并同意,本服务仅依其当前所呈现的状况提供,对于任何用户信息或个人化设定之时效、删除、传递错误、未予储存或其它任何问题,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">均不承担任何责任。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">保留不经事先通知为维修保养、升级或其它目的暂停本服务任何部分的权利,并无需承担任何责任。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:51:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">对于您</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:52:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">使用本软件服务</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:56:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">获取的试唱资料</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:30:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">(包括但不限于歌词、伴奏、音频等)</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:56:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:56:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">/或您</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:52:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">录制的试唱音</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:08:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:52:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:52:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:56:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:52:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:56:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:57:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:53:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:09:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">个人试唱录制使用</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:09:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:09:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">并仅能</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:53:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">上传至本软件</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:53:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:53:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">未经</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:54:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱平台书面同意</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:55:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:55:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">您不得</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:57:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">泄露给任何第三方或</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:55:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">发布在任何</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:55:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">其他</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:55:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">平台</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:55:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:13:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">本软件试唱资料及您使用</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:14:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">试唱资料制作的</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:57:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">全部</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:58:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">音乐作品</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:58:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">/录音</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:08:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">录像</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:58:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">制品</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:08:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">/视听作品</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:58:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:59:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">完整著作权和邻接权均归属于北京海葵科技有限公司</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:04:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">(以下简称“海葵”)</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:59:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">或其指定的第三方</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:30:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">,您不得抄袭</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:31:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">、模仿或提前泄露在短视频或音乐平台</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:30:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">,也不可在未取得</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:31:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海葵书面</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:30:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">许可的情况下翻唱、二次创作</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T14:59:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">。如因您未按规定使用本软件内的试唱资料</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:00:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:00:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">/或您</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:00:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">录制的试唱音</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:08:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:00:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:00:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">,海葵或其指定的第三方有权</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:02:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">要求您赔偿</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:04:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">因此造成的一切直接损失、间接损失(包括但不限于</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:05:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">词曲成本、软件运营成本、</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:04:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海葵支付的差旅费、律师费、公证费、诉讼/仲裁费、保全费、鉴定费等)</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:05:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold"></span></ins></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">3. 遵守法律</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:normal">您同意遵守中华人民共和国相关法律法规的所有规定,并对以任何方式使用本服务的任何行为及其结果承担全部责任。如您的行为违反国家法律和法规的任何规定,有可能构成犯罪的,将被追究刑事责任,并由您承担全部法律责任。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">同时如果</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">有理由认为您的任何行为,包括但不限于您的任何言论和其它行为违反或可能违反国家法律和法规的任何规定,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">可在任何时候不经任何事先通知终止向您提供服务并删除相关言论、音视频等内容,并无需承担任何责任。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">未成年人用户及其监护人理解并确认,如您违反法律法规、本协议内容,则您及您的监护人应依照法律法规承担因此而导致的全部法律责任。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">4. 您的注册义务</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">您注册成功后,本产品将为您提供一个帐号(下称“帐号”)。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">您在申请使用本产品服务时,应当向我们提供真实、准确的个人资料,以完成实名认证;您应确保开通本服务所提供的姓名</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">、所属公司</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">等信息为本人所有,并授权我们通过依法成立的合法采集机构或认证机构对您所提供的信息的真实性和有效性进行认证。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">如个人资料有任何变动,您须及时在本产品中予以更新。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">为了能使用本服务全部功能,您同意以下事项:依本服务注册提示请您填写正确的</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:17:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">姓名、身份证号码、个人</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:17:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">实名</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">手机号、密码和艺名</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:17:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">等信息</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">,并确保今后更新的手机号、艺名、头像等资料的有效性和合法性。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">若您提供任何违法、不道德或</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">认为不适合在</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">上展示的资料</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:15:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">或使用他人信息</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:16:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">进行注册</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">;或者</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">有理由怀疑你的资料属于程序或恶意操作,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">有权暂停或终止您的帐号,并拒绝您于现在和未来使用本服务之全部或任何部分。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">您理解并承诺,您所设置的</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">不得违反国家法律法规及“</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">”的相关规则,您的</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt"></span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">名称、头像等注册信息及其他个人信息中不得出现违法和不良信息,未经他人许可不得用他人名义(包括但不限于冒用他人姓名、名称、字号、头像等或采取其他足以让人引起混淆的方式)开设</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">,不得恶意注册</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">(包括但不限于频繁注册、批量注册</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">等行为)。您在</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">注册及使用过程中需遵守相关法律法规,不得实施任何侵害国家利益、损害其他公民合法权益,有害社会道德风尚的行为。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">有权对您提交的注册信息进行审核。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="color:#333333; font-family:楷体; font-size:12pt">&#xa0;</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">5. 用户帐号、密码及安全</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">完成本服务的注册程序并成功注册之后,您可使用您的手机号和验证码,Email和密码,登录到您在</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">的帐号(下称“帐号”)。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">保护您的帐号安全,是您的责任。您应对所有使用您的密码及帐号(包括他人使用您的密码及帐号)的活动负完全的责任。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">您同意:</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">1)您的</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号遭到未获授权的使用,或者发生其它任何安全问题时,您将立即通知</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt"></span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">2)如果您未保管好自己的帐号和密码,因此而产生的任何损失或损害,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">不承担任何责任;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">3)</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">每个用户都要对其帐号中的所有行为和事件负全责。如果因您未保管好自己的帐号和密码而对您、</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">或第三方造成的损害,您将负全部责任。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt"></span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">故意或者重大过失导致的损害除外;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">4)</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">如用户在申请开通服务后连续六个月未实际使用,则</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">有权回收用户</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:06:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">帐号使用权</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt"></span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">5)</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:07:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">每个用户仅能注册一个帐号,帐号所有权属于海星试唱平台所有,用户拥有使用权。</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">您在“</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">”中的注册</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">仅限于您本人使用,未经</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">书面同意,禁止以任何形式赠与、借用、出租、转让、售卖或以其他方式许可他人使用该</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">。如果</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">发现或者有合理理由认为使用者并非</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">初始注册人,为保障</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">安全,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">有权立即暂停或终止向该注册</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">提供服务,并有权永久禁用该</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">。同时我们非常重视对未成年人个人信息的保护,未成年用户在填写个人信息时,请加强个人保护意识并谨慎对待,并应在取得监护人的同意以及在监护人指导下正确使用本软件及相关服务。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">6. </span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">用户隐私政策</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">您提供的登记资料及</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">保留的有关您的若干其它资料将受到中国有关隐私的法律和本公司《用户隐私政策》之规范。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">7. 提供者之责任</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">根据有关法律法规,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">在此郑重提请您注意,</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:38:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">除本软件提供之试唱资料外</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:38:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt"></span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">任何经由本服务而发布、上传的文字、资讯、资料、音频、视频、照片、图形、视讯、信息或其它资料(以下简称“内容 ”),无论系公开还是私下传送,均由内容提供者承担责任。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">仅为用户提供内容存储空间,无法控制经由本服务传送之内容,因此不保证内容的正确性、完整性、合法性或品质。您已预知使用本服务时,可能会接触到令人不快、不适当或令人厌恶之内容。在任何情况下,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">均不为任何内容负责,但</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">有权依法停止传输任何前述内容并采取相应行动,包括但不限于暂停用户使用本服务的全部或部分,删除相关内容,保存有关记录,并向有关机关报告。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">用户在录音时,如果使用其他的配乐、伴奏、照片等可能涉及第三方版权及其他权利的内容配合录制并上传,则用户需要确认对该配乐和伴奏、照片等享有相应使用权,否则</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">可删除您上传的内容。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">8. 用户行为</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">用户同意将不会利用本服务进行任何违法或不正当的活动,包括但不限于下列行为:</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">1)发布或以其它方式传送含有下列内容之一的信息:</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 反对宪法所确定的基本原则的;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 危害国家安全,泄露国家秘密,颠覆国家政权,破坏国家统一的;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 损害国家荣誉和利益的;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 煽动民族仇恨、民族歧视、破坏民族团结的;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 破坏国家宗教政策,宣扬邪教和封建迷信的;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 散布谣言,扰乱社会秩序,破坏社会稳定的;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 散布淫秽、色情、赌博、暴力、凶杀、恐怖或者教唆犯罪的;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 侮辱或者诽谤他人,侵害他人合法权利的;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 含有虚假、诈骗、有害、胁迫、侵害他人隐私、骚扰、侵害、中伤、粗俗、猥亵、或其它道德上令人反感的内容;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 含有中国法律、法规、规章、条例以及任何具有法律效力之规范所限制或禁止的其它内容的;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 含有</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">认为不适合在</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">展示的内容;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">2)以任何方式危害他人的合法权益;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">3)冒充其他任何人或机构,或以虚伪不实的方式陈述或谎称与任何人或机构有关;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">4)将依据任何法律或合约或法定关系(例如由于雇佣关系和依据保密合约所得知或揭露之内部资料、专属及机密资料)知悉但无权传送之任何内容加以发布、发送电子邮件或以其它方式传送;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">5)将侵害他人著作权、专利权、商标权、商业秘密、或其它专属权利(以下简称“专属权利”)之内容加以发布或以其它方式传送;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">6)将任何广告信函、促销资料、垃圾邮件、滥发信件、连锁信件、直销或其它任何形式的劝诱资料加以发布、发送或以其它方式传送;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">7)将设计目的在于干扰、破坏或限制任何计算机软件、硬件或通讯设备功能之计算机病毒(包括但不限于木马程序(trojan horses)、蠕虫(worms)、定时炸弹、删除蝇(cancelbots)(以下简称“病毒”)或其它计算机代码、档案和程序之任何资料,加以发布、发送或以其它方式传送;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">8)干扰或破坏本服务或与本服务相连线之服务器和网络,或违反任何关于本服务连线网络之规定、程序、政策或规范;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">9)跟踪、人肉搜索或以其它方式骚扰他人;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">10)故意或非故意地违反任何适用的当地、国家法律,以及任何具有法律效力的规则;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">11)未经合法授权而截获、篡改、收集、储存或删除他人个人信息、站内邮件或其它数据资料,或将获知的此类资料用于任何非法或不正当目的。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">12)含有任何下列损害未成年人身心健康和合法权益的行为和内容:</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 涉及未成年人色情低俗的内容;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 涉及侵害未成年人身体/财产/人格/隐私的行为;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 涉及未成年人不当行为的内容;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 涉及毒害未成年人身心健康和价值观的内容;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 涉及过度消费未成年人的内容;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 其他危害未成年人生命、财产、健康的行为和内容。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">您已认可</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">未对用户的使用行为进行全面控制,您使用任何内容时,包括依赖前述内容之正确性、完整性、合法性、或实用性时,您同意将自行加以判断并承担所有风险,而不依赖于</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">。但</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">依其自行之考虑,拒绝和删除可经由本服务提供之违反本条款的或其它引起</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">反感的任何内容。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">您了解并同意,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">依据法律法规的要求,或基于诚信为了以下目的或在合理必要范围内,认定必须将内容加以保存或揭露时,得加以保存或揭露:</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">a)遵守法律程序;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">b)执行本使用协议;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">c)回应任何第三人提出的权利主张;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">d)保护</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">、其用户及公众之权利、财产或个人安全;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">e)其它</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">认为有必要的情况。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#ff0000; font-family:楷体; font-size:12pt; font-weight:bold">9.</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:33:00'"><span style="background-color:#ffffff; color:#ff0000; font-family:楷体; font-size:12pt; font-weight:bold">权利声明</span></ins></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:33:00'"><span style="background-color:#ffffff; color:#ff0000; font-family:楷体; font-size:12pt; font-weight:bold">本软件的一切知识产权,以及与本软件相关的所有信息内容,包括但不限于:文字表述及其组合、图标、图饰、图像、图表、色彩、界面设计、版面框架、有关数据、附加程序、印刷材料或电子文档等均为海葵公司所有,受著作权法和国际著作权条约以及其他知识产权法律法规的保护。</span></ins></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">1</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">0</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">. 违约处理</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">1)针对您违反本协议或其他服务条款的行为,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">有权自行独立判断并视情况采取预先警示、拒绝发布、立即停止传输信息、删除评论、音频、视频、音视频等内容、短期禁止发言、限制</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">部分或者全部功能直至终止提供服务、永久关闭</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">等措施。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">有权公告处理结果,且有权根据实际情况决定是否恢复相关</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T15:25:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">帐号</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">的使用。对涉嫌违反法律法规、涉嫌违法犯罪的行为,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">将保存有关记录,并有权依法向有关主管部门报告、配合有关主管部门调查、向公安机关报案等。对已删除内容</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">有权不予恢复。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">2)因您违反本协议或其他服务条款规定,引起第三方投诉或诉讼索赔的,您应当自行处理并承担可能因此产生的全部法律责任。因您的违法或违约等行为导致</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">及其关联方、控制公司、继承公司向任何第三方赔偿或遭受国家机关处罚的,您还应足额赔偿</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">及其关联方、控制公司、继承公司因此遭受的全部损失。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">3)公司尊重并保护您及他人的知识产权、名誉权、姓名权、隐私权等合法权益。您保证,在使用“</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">”软件及相关服务时上传的文字、图片、视频、音频等不侵犯任何第三方的知识产权、名誉权、姓名权、隐私权等权利及合法权益。否则,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">有权在收到权利方或者相关方通知的情况下移除该涉嫌侵权内容。针对第三方提出的全部权利主张,您应自行处理并承担可能因此产生的全部法律责任;如因您的侵权行为导致</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">及其关联方、控制公司、继承公司遭受损失的(包括但不限于经济、商誉等损失),您还应足额赔偿</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">及其关联方、控制公司、继承公司遭受的全部损失。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">1</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">1</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">. 复制、拷贝、出售、转售等的规定</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">您同意不对本服务任何部分或本服务所使用或获得的内容,进行复制、拷贝、出售、转售或用于任何其它商业目的。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">1</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">2</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">. 关于使用及储存之一般措施</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">您承认关于本服务的使用</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">有权制订一般措施及限制,包含但不限于本服务将保留所发布内容或其它发布内容之最长期间,以及一定期间内您使用本服务之次数上限(及每次使用时间之上限)。通过本服务发布或传送之任何信息、通讯资料和其它内容,如被删除或未予储存,您同意</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">毋须承担任何责任。您也同意,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">有权依其自行之考虑,不论通知与否,随时变更这些一般措施及限制。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">1</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">3</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">. 服务之修改</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">有权于任何时间暂时或永久修改或终止本服务(或其任何部分),且无论通知与否。您同意对于本服务所作的任何修改、暂停或终止,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">对您和任何第三人均无需承担任何责任。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">1</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">4</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">. 终止服务</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">您同意</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">基于其自行之考虑,因任何理由,包含但不限于缺乏使用,或</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">认为您已经违反本使用协议的文字及精神,终止您的帐号或本服务之使用(或服务之任何部分),并将您在本服务内任何内容加以移除并删除。您同意依本使用协议任何规定提供之本服务,无需进行事先通知即可中断或终止,您承认并同意,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">可立即关闭或删除您的帐号及您帐号中所有相关信息及文件,及/或禁止继续使用前述文件或本服务。此外,您同意若本服务之使用被中断或终止或您的帐号及相关信息和文件被关闭或删除,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">对您或任何第三人均不承担任何责任。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">1</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">5</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">. </span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">之专属权利</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">您了解并同意,本服务及本服务所使用之相关软件(以下简称“软件”)含有受到相关知识产权及其它法律保护之专有保密资料。您也了解并同意,经由本服务向您呈现</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">歌曲、歌词、专辑封面图片</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">内容,亦受到著作权、商标权、服务商标、专利权或其它专属权利之法律保护。未经</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt"></span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:41:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海葵</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">明示授权,您不得修改、出租、出借、出售、散布本服务或软件之任何部份或全部,或据以制作衍生著作,或使用擅自修改后的软件,包括但不限于为了未经授权而使用本服务之目的。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">仅授予您个人、不可移转及非专属之使用权,使您得于单机计算机使用其软件之目的码,但您不得(并不得允许任何第三人)复制、修改、创作衍生著作、进行还原工程、反向组译,或以其它方式发现原始码,或出售、转让、再授权或提供软件设定担保,或以其它方式移转软件之任何权利。您同意将通过由</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">所提供的界面而非任何其它途径使用本服务。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">1</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">6</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">. 担保与保证</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">您明确了解并同意∶</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">1)本使用协议的任何规定不会免除</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">对造成您人身伤害的、或因故意或重大过失造成您财产损失的任何责任;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">2)您使用本服务之风险由您个人负担。本服务系依“现状”及“现有”基础提供。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">对“服务”、“资料”或“产品”不提供任何明示或默示的担保或保证,包含但不限于商业适售性、特定目的之适用性及未侵害他人权利等担保或保证;</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">对于因“服务”、“资料”或“产品”所生之任何直接、间接、附带的或因此而导致之衍生性损失不承担任何责任。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">3)</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">不保证以下事项∶</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 本服务将符合您的要求;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 本服务将不受干扰、及时提供、安全可靠或不会出错;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 使用本服务取得之结果正确可靠;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">* 您经由本服务购买或取得之任何产品、服务、资讯或其它信息将符合您的期望;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">4)是否使用本服务下载或取得任何资料应由您自行考虑且自负风险,因任何资料之下载而导致的您电脑系统之任何损坏或数据流失等后果,由您自行承担;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">5)您自</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">或经由本服务取得的任何建议或信息,无论是书面或口头形式,除非本使用协议有明确规定,将不构成本使用协议以外之任何保证。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">17</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">. 责任限制</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">您明确了解并同意,基于以下原因而造成的,包括但不限于经济利益、信誉、应用、数据损失或其它无形损失,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">不承担任何直接、间接、连带、特别、衍生性或惩罚性赔偿责任:</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">1)本服务之使用或无法使用;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">2)为替换从或通过本服务购买或取得之任何商品、数据、信息、服务,收到的讯息,或缔结之交易而发生的成本;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">3)您的传输或数据遭到未获授权的存取或变造;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">4)任何第三方在本服务中所作之声明或行为;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">5)与本服务相关的其它事宜,但本使用协议有明确规定的除外;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">6)第三方以任何方式发布或投递欺诈性信息,或诱导用户受到经济损失,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">不承担任何责任。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">18</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">. </span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">商标信息</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">网、</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">以及其它</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">注册商标、标志及产品、服务名称,均为</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">公司之商标(以下简称“</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">标记”)。未经</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">事先书面同意,您同意不将</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">标记以任何方式展示或使用或作其它处理,或表示您有权展示、使用或另行处理</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">标记。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">19</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">. 知识产权之保护</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">尊重他人的任何权利(包括知识产权),同时也要求我们的使用者也尊重他人之权利。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">在适当情况下,可自行决定终止侵害或违反他人权利之使用者的帐号并有权删除相关内容。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">如果您对他人的知识产权造成了侵害,</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">将依国家法律法规的规定,或在适当的情形下,将依其服务条款或其相关规范性规定,删除特定内容或以至终止您对账户的使用并有权删除相关内容。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">若您认为您的作品的著作权遭到侵害或您的知识产权被侵犯,根据《信息网络传播权保护条例》的规定,您需及时向</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">联系并提供详实的举证材料。或请到中华人民共和国国家版权局下载《要求删除或断开链接侵权网络内容的通知》(下称“删除通知”)的示范格式,如果您不明白“删除通知”的内容,请登录中华人民共和国国家版权局查看《要求删除或断开链接侵权网络内容的通知》填写说明。</span></p><p style="background-color:#ffffff; margin:0pt; text-align:justify"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">2</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">0</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">. 一般条款</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">1</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">)本使用协议及您与</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">之关系,均受到中华人民共和国法律管辖。</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">您与</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">就本服务、本使用协议或其它有关事项发生的争议,应首先友好协商解决,协商不成时应提请</span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:47:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt; font-weight:bold">湖北省武汉市硚口区有管辖权的人民法院裁决</span></ins><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt"></span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">2</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt"></span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">未行使或执行本使用协议任何权利或规定,不构成对前述权利或权利之放弃;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">3</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">)倘本使用协议之任何规定因与中华人民共和国法律抵触而无效,您依然同意应依照法律,努力使该规定所反映之当事人意向具备效力,且本使用协议其它规定仍应具有完整的效力及效果;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">4</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">)本使用协议之标题仅供方便而设,不具任何法律或契约效果;</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">5</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">) 只要您登录了</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">,就代表您接受任何以上所有协议。</span><br /><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">6</span><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt"></span><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:49:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">海星试唱</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:48:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">有权随时根据有关法律、法规的变化以及公司经营状况和经营策略的调整等修改本协议,并随附于新版本软件。当发生有关争议时,以最新的协议</span></ins><ins style="-aw-revision-author:'FZ'; -aw-revision-datetime:'2022-05-07T16:48:00'"><span style="background-color:#ffffff; color:#333333; font-family:楷体; font-size:12pt">文本为准。如果不同意改动的内容,用户可以自行删除本软件。如果用户继续使用本软件,则视为您接受本协议的变动。</span></ins></p></div><div class="cnzz" style="display: none;">
<script src="https://s23.cnzz.com/z_stat.php?id=1277655852&web_id=1277655852" language="JavaScript"></script>
</div>
<div class="docpe" style="position: absolute;color: white;margin-left:-450;">
<a target="_blank" href="http://www.docpe.com">档铺网——在线文档免费处理</a>
</div>
</body>
</html>
\ No newline at end of file
# -*-coding:utf-8 -*-
import os
import requests
from pydub import AudioSegment
from django.core.cache import caches
import time, random, json
import base64
import hashlib
from Crypto.Cipher import AES
from Crypto import Random
appid = "wx0f3844b1458ccfb9"
secret = "f9fa09c6cf3b4db19906d876d9c64755"
def split_mp3():
new_name = './static/out444.mp3'
use_name = './static/12345.mp3'
input_music = AudioSegment.from_mp3(use_name)
# 截取音频后31000毫秒 = 31秒
output_music = input_music[31000:]
# 保存音频,指定音频比特率为64k
output_music.export(new_name, bitrate="64k")
print(new_name + '完成!')
def WeChatApi(code):
appid = "wx0f3844b1458ccfb9"
secret = "f9fa09c6cf3b4db19906d876d9c64755"
parmas = {
'appid': appid,
'secret': secret,
'js_code': code,
'grant_type': 'authorization_code'
}
url = 'https://api.weixin.qq.com/sns/jscode2session'
r = requests.get(url, params=parmas).json()
print (r)
try:
return r['openid'],r['unionid']
except:
return None,None
def get_access_toke():
url = 'https://api.weixin.qq.com/cgi-bin/token'
parmas = {
"grant_type":"client_credential",
"appid":appid,
"secret":secret
}
r = requests.get(url,params=parmas).json()
print (r)
def WxPushInfo(data):
nickname = data['nickname']
result = data['result']
remarks = data['remarks']
touser = data['touser']
access_token = data['access_token']
url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={}'.format(access_token)
postdata = {
"touser":touser,
"template_id":"B0s4RIurXwoegzK4tLWNU_H-xB2kUIE_E_ft5Ur6Auk",
"data":{
"name10":{"value":nickname},
"phrase5":{"value":result},
"thing11":{"value":remarks}
}
}
r = requests.post(url, json=postdata).json()
print(r)
def GetWxToken():
token = caches['default'].get('wx_access_token')
if not token:
appid = "wx0f3844b1458ccfb9"
secret = "f9fa09c6cf3b4db19906d876d9c64755"
url = 'https://api.weixin.qq.com/cgi-bin/token'
parmas = {
"grant_type":"client_credential",
"appid":appid,
"secret":secret
}
r = requests.get(url,params=parmas).json()
caches['default'].add('wx_access_token', r['access_token'] , r['expires_in']) #expires_in
return r['access_token']
else:
return token
def Test(data):
import hashlib
channel = 'register_audit_channel'
open_id = data['open_id']
url = 'http://hi-sing-admin-dev.hikoon.com/api/provider/wechat/pushSubscribeMessage'
md5_str = channel + open_id + 'tb0iwb7TE9TIbkG8iFsxldrHJRFdeP1g'
hl = hashlib.md5()
hl.update(md5_str.encode(encoding='utf8'))
secret = hl.hexdigest()
data = {
'secret': secret,
'channel': channel,
'open_id': open_id,
'data': data['data']
}
r = requests.post(url,json=data).json()
print (r)
def test():
import requests
url = "127.0.0.1:8000/api/register"
payload = {
"nick_name": "🍹🐼💑",
"real_name": "魏晗13457",
"phone": "17780983939",
"email": "17qwe111@qq.com",
"origin_type": "Other",
"remarks": "黄辉浩",
"role": "SystemUser",
"password": "112358ys",
"confirm_password": "112358ys",
"sms_code": 123456,
"vx_code":"051vPN000xA8EN1rW2100URGiX3vPN0t"
}
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, json=payload)
print(response.text)
def toMp3():
import os
path = './static/'
file = '1234.m4a'
os.system("ffmpeg -i "+ path+file+ " " + path+ ".mp3" )
class JPush():
def __init__(self):
self.app_key = '860a3d4ecfaf3c38eb539c4e'
self.master_secret = 'df208c0eb485ed3ab3b18ff2'
def https_request(self, body, url, content_type=None, version=None, params=None):
https = requests.Session()
https.auth = (self.app_key,self.master_secret)
headers = {}
headers['user-agent'] = 'jpush-api-python-client'
headers['connection'] = 'keep-alive'
headers['content-type'] = 'application/json;charset:utf-8'
response = https.request('POST', url, data=body, params=params, headers=headers)
print (response.text)
print (dict(json.loads(response.content), **{'status_code': response.status_code}))
return dict(json.loads(response.content), **{'status_code': response.status_code})
def push_params_v3(self,title,content, receiver_value=None,content_type=None, extras=None, platform="ios,android"):
sendno = int(random.randint(1, 999))
payload = dict()
payload['platform'] = platform
payload['audience'] = {
"alias": receiver_value
}
payload["inapp_message"] = {"inapp_message": False}
payload['notification'] = {
"android": {"alert": content,"badge_add_num": 1,"alternate_alert": "","style": 0,"category": "","priority": 0,"title": title,"intent": {"url": ""},"alert_type": 7, "alternate_title": "", "extras": extras },
"ios": {"alert": content, "sound": "default", "extras": extras},
}
payload['options'] = {"apns_production": False, "time_to_live": 86400, 'sendno': sendno,
"third_party_channel":{
"xiaomi": {"importance":"NORMAL","distribution":"secondary_push","distribution_fcm":"secondary_fcm_push"},
"huawei": {"importance": "NORMAL"},
# "honor": {"importance": "NORMAL"},
# "meizu": {"importance": "NORMAL"},
"oppo": {"importance": "NORMAL"},
"vivo": {"importance": "NORMAL"},
}
}
return payload
def jpush_v3(self, data):
payload = self.push_params_v3(title=data['title'],content=data['content'],content_type=data['content_type'],receiver_value=data['receiver_value'],extras=data['extras'])
body = json.dumps(payload)
return self.https_request(body, "https://api.jpush.cn/v3/push", 'application/json', version=1)
def get_alias():
url = 'https://device.jpush.cn/v3/aliases/test189'
token = str(base64.b64encode(b'860a3d4ecfaf3c38eb539c4e:df208c0eb485ed3ab3b18ff2'),'utf-8')
print (token)
headers = {
'Authorization': 'Basic {}'.format(token),
'Accept': 'application / json'
}
resp = requests.get(url,headers=headers).text
print (resp)
def remove_alias():
url = 'https://device.jpush.cn/v3/aliases/test189'
token = str(base64.b64encode(b'860a3d4ecfaf3c38eb539c4e:df208c0eb485ed3ab3b18ff2'), 'utf-8')
headers = {
'Authorization': 'Basic {}'.format(token),
'Accept': 'application / json'
}
data = {
"registration_ids":{"remove": ["121c83f760d835d731c"]}
}
resp = requests.post(url,headers=headers,json=data).text
print (resp)
def Msg_Push_Server(data):
secret = 'hNA32TZVxFGL9xv526Yg74XSNcutM3DiqfktZcHq0084jI6o2VetEjAndY8zlNTP'
p = '{channel}&{data}&{secret}&{time}'.format(channel=data['channel'],data=data['data'],secret=secret,time=data['time']).encode()
p = base64.b64encode(p)
hl = hashlib.md5()
hl.update(p)
sign = hl.hexdigest()
data['sign'] = sign
data['data'] = json.loads(data['data'])
url = "https://hi-sing-admin-dev.hikoon.com/api/provider"
resp = requests.request('POST',url,json=data).text
if __name__ == '__main__':
# data = {"title":"标题","content":"测试推送","content_type":"text","receiver_value":['test189'],"extras":{"type":"","value":""}}
# JPush().jpush_v3(data)
# TLSSigAPIv2.main()
# get_alias()
# remove_alias()
data = {"channel":"ActivityPublish","data":'{"activityId":69}',"time":int(time.time())}
Msg_Push_Server(data)
#-*-coding:utf-8 -*-
import logging
from django import forms
from rest_framework import serializers
def error_message(obj):
return list(obj.errors.values())[0][0]
class LoginVerify(serializers.Serializer):
phone = serializers.CharField(allow_blank=False,error_messages={"blank":"账号不能为空","required": "缺少必填参数phone"})
password = serializers.CharField(allow_blank=False,error_messages={"blank":"密码不能为空","required": "缺少必填参数password"})
class V2LoginVerify(serializers.Serializer):
phone = serializers.CharField(allow_null=False,error_messages={"blank":"账号不能为空","required": "缺少必填参数phone"})
sms_code = serializers.IntegerField(allow_null=False,error_messages={"blank":"验证码不能为空","required": "缺少必填参数sms_code","invalid":"验证码只能是数字"})
class SendVerify(serializers.Serializer):
phone = serializers.CharField(allow_blank=False,error_messages={"blank":"手机号不能为空","required": "缺少必填参数phone"})
class v2SendVerify(serializers.Serializer):
phone = serializers.CharField(allow_blank=False,error_messages={"blank":"手机号不能为空","required": "缺少必填参数phone"})
area_code = serializers.IntegerField(allow_null=False,error_messages={'invalid':'area_code数据格式错误',"blank":"区号不能为空","required": "缺少必填参数area_code"})
class SingerRegister(forms.Form):
nick_name = forms.CharField(min_length=2,max_length=16,error_messages={"min_length":"昵称最小长度为2","max_length":"昵称最大长度为16","required": "昵称不能为空"})
real_name = forms.CharField(error_messages={"required": "真名不能为空"})
email = forms.EmailField(error_messages={"required": "邮箱不能为空", "invalid": "邮箱格式错误"})
password = forms.CharField(error_messages={"required": "密码不能为空"})
confirm_password = forms.CharField(error_messages={"required": "重复密码不能为空"})
phone = forms.CharField(max_length=11,min_length=11,error_messages={"required": "手机号不能为空","max_length":"手机号码长度不正确","min_length":"手机号码长度不正确"})
sms_code = forms.IntegerField(error_messages={"required": "验证码不能为空","invalid":"验证码只能是数字"})
role = forms.CharField(error_messages={"required": "角色身份不能为空"})
# vx_code = forms.CharField(error_messages={"required": "vx_code不能为空"})
is_referee = forms.IntegerField(error_messages={"required": "推荐人不能为空"})
province = forms.CharField(error_messages={"required": "所在省不能为空"})
city = forms.CharField(error_messages={"required": "所在省不能为空"})
is_push = forms.IntegerField(error_messages={"required": "is_push不能为空"})
class V2SingerRegister(forms.Form):
nick_name = forms.CharField(min_length=2,max_length=16,error_messages={"min_length":"昵称最小长度为2","max_length":"昵称最大长度为16","required": "昵称不能为空"})
real_name = forms.CharField(error_messages={"required": "真名不能为空"})
email = forms.EmailField(error_messages={"required": "邮箱不能为空", "invalid": "邮箱格式错误"})
area_code = forms.IntegerField(error_messages={'invalid':'area_code数据格式错误',"required": "缺少必填参数area_code"})
phone = forms.CharField(error_messages={"required": "手机号不能为空"})
sms_code = forms.IntegerField(error_messages={"required": "验证码不能为空","invalid":"验证码只能是数字"})
role = forms.CharField(error_messages={"required": "角色身份不能为空"})
is_referee = forms.IntegerField(error_messages={"required": "推荐人不能为空"})
class V3UserRegister(forms.Form):
nick_name = forms.CharField(min_length=2, max_length=16,error_messages={"min_length": "昵称最小长度为2", "max_length": "昵称最大长度为16","required": "昵称不能为空"})
real_name = forms.CharField(error_messages={"required": "真名不能为空"})
email = forms.EmailField(error_messages={"required": "邮箱不能为空", "invalid": "邮箱格式错误"})
area_code = forms.IntegerField(error_messages={"required": "缺少必填参数area_code",'invalid':'area_code数据格式错误'})
phone = forms.CharField(error_messages={"required": "手机号不能为空"})
sms_code = forms.IntegerField(error_messages={"required": "验证码不能为空", "invalid": "验证码只能是数字"})
class BusinessRegister(forms.Form):
nick_name = forms.CharField(min_length=2,max_length=16,error_messages={"min_length":"昵称最小长度为2","max_length":"昵称最大长度为16","required": "昵称不能为空"})
real_name = forms.CharField(error_messages={"required": "真名不能为空"})
email = forms.EmailField(error_messages={"required": "邮箱不能为空", "invalid": "邮箱格式错误"})
password = forms.CharField(error_messages={"required": "密码不能为空"})
confirm_password = forms.CharField(error_messages={"required": "重复密码不能为空"})
phone = forms.CharField(max_length=11,min_length=11,error_messages={"required": "手机号不能为空","max_length":"手机号码长度不正确","min_length":"手机号码长度不正确"})
sms_code = forms.IntegerField(error_messages={"required": "验证码不能为空","invalid":"验证码只能是数字"})
role = forms.CharField(error_messages={"required": "角色身份不能为空"})
is_push = forms.IntegerField(error_messages={"required": "is_push不能为空"})
# vx_code = forms.CharField(error_messages={"required": "vx_code不能为空"})
company = forms.CharField(error_messages={"required": "所在公司不能为空"})
class V2BusinessRegister(forms.Form):
nick_name = forms.CharField(min_length=2,max_length=16,error_messages={"min_length":"昵称最小长度为2","max_length":"昵称最大长度为16","required": "昵称不能为空"})
real_name = forms.CharField(error_messages={"required": "真名不能为空"})
email = forms.EmailField(error_messages={"required": "邮箱不能为空", "invalid": "邮箱格式错误"})
area_code = forms.IntegerField(error_messages={'invalid':'area_code数据格式错误',"required": "缺少必填参数area_code"})
phone = forms.CharField(error_messages={"required": "手机号不能为空"})
sms_code = forms.IntegerField(error_messages={"required": "验证码不能为空","invalid":"验证码只能是数字"})
role = forms.CharField(error_messages={"required": "角色身份不能为空"})
company = forms.CharField(error_messages={"required": "所在公司不能为空"})
class bind_verification(forms.Form):
vx_code = forms.CharField(error_messages={"required": "vx_code不能为空"})
class reset_verification(forms.Form):
password = forms.CharField(error_messages={"required": "密码不能为空"})
confirm_password = forms.CharField(error_messages={"required": "重复密码不能为空"})
phone = forms.CharField(max_length=11,min_length=11,error_messages={"required": "手机号不能为空","max_length":"手机号码长度不正确","min_length":"手机号码长度不正确"})
sms_code = forms.IntegerField(error_messages={"required": "验证码不能为空","invalid":"验证码只能是数字"})
class examine_verification(forms.Form):
examine_id = forms.IntegerField(error_messages={"required": "待审核用户id不能为空"})
examine_status = forms.IntegerField(error_messages={"required": "审核状态不能为空"})
class view_activity_verification(forms.Form):
activity_id = forms.CharField(error_messages={"required": "活动id不能为空"})
class update_user_verification(forms.Form):
avatar = forms.CharField(error_messages={"required": "头像不能为空"})
class update_submit_verification(forms.Form):
activity_id = forms.CharField(error_messages={"required": "活动id不能为空"})
has_id = forms.CharField(error_messages={"required": "关联id不能为空不能为空"})
class singer_submit_examine_verification(forms.Form):
nick_name = forms.CharField(error_messages={"required": "昵称不能为空"})
real_name = forms.CharField(error_messages={"required": "真名不能为空"})
is_referee = forms.IntegerField(error_messages={"required": "推荐人不能为空"})
province = forms.CharField(error_messages={"required": "所在省不能为空"})
city = forms.CharField(error_messages={"required": "所在省不能为空"})
class v2_singer_submit_examine_verification(forms.Form):
nick_name = forms.CharField(error_messages={"required": "缺少必填参数nick_name"})
real_name = forms.CharField(error_messages={"required": "缺少必填参数real_name"})
email = forms.CharField(error_messages={"required": "缺少必填参数email"})
# business_id = forms.CharField(error_messages={"required": "缺少必填参数business_id"})
is_referee = forms.IntegerField(error_messages={"required": "缺少必填参数is_referee"})
class business_submit_examine_verification(forms.Form):
nick_name = forms.CharField(error_messages={"required": "昵称不能为空"})
real_name = forms.CharField(error_messages={"required": "真名不能为空"})
company = forms.CharField(error_messages={"required": "所在公司不能为空"})
class v2_business_submit_examine_verification(forms.Form):
nick_name = forms.CharField(error_messages={"required": "缺少必填参数nick_name"})
real_name = forms.CharField(error_messages={"required": "缺少必填参数real_name"})
email = forms.CharField(error_messages={"required": "缺少必填参数email"})
company = forms.CharField(error_messages={"required": "缺少必填参数company"})
class user_tags_verification(forms.Form):
tags = forms.CharField(error_messages={"required": "标签不能为空"})
class online_save_verification(forms.Form):
activity_id = forms.CharField(error_messages={"required": "活动id不能为空"})
person_url = forms.CharField(error_messages={"required": "人声不能为空"})
bg_url = forms.CharField(error_messages={"required": "混响程度 不能为空"})
bg_volume = forms.FloatField(error_messages={"required": "伴奏音调不能为空"})
person_volume = forms.FloatField(error_messages={"required": "人声音量不能为空"})
offset = forms.IntegerField(error_messages={"required": "偏移量不能为空"})
mix_type = forms.IntegerField(min_value=0,max_value=3,error_messages={"required": "混响程度 不能为空","min_value":"mix_type的值在0-3之间","max_value":"mix_type的值在0-3之间"})
demo_url = forms.CharField()
class mixin_previews(forms.Form):
activity_id = forms.CharField(error_messages={"required": "活动id不能为空"})
person_url = forms.CharField(error_messages={"required": "人声不能为空"})
bg_url = forms.CharField(error_messages={"required": "混响程度 不能为空"})
bg_volume = forms.FloatField(error_messages={"required": "伴奏音调不能为空"})
person_volume = forms.FloatField(error_messages={"required": "人声音量不能为空"})
offset = forms.IntegerField(error_messages={"required": "偏移量不能为空"})
mix_type = forms.IntegerField(min_value=0,max_value=3,error_messages={"required": "混响程度 不能为空","min_value":"mix_type的值在0-3之间","max_value":"mix_type的值在0-3之间"})
class part_mixin_previews(forms.Form):
activity_id = forms.CharField(error_messages={"required": "活动id不能为空"})
person_url = forms.CharField(error_messages={"required": "人声不能为空"})
bg_url = forms.CharField(error_messages={"required": "混响程度 不能为空"})
bg_volume = forms.FloatField(error_messages={"required": "伴奏音调不能为空"})
person_volume = forms.FloatField(error_messages={"required": "人声音量不能为空"})
offset = forms.IntegerField(error_messages={"required": "偏移量不能为空"})
mix_type = forms.IntegerField(min_value=0,max_value=3,error_messages={"required": "混响程度 不能为空","min_value":"mix_type的值在0-3之间","max_value":"mix_type的值在0-3之间"})
start_time = forms.FloatField(error_messages={"required": "片段开始时间不能为空"})
end_time = forms.FloatField(error_messages={"required": "片段结束时间不能为空"})
class mixin_check(forms.Form):
id = forms.IntegerField(error_messages={"required": "id不能为空"})
class aoto_submit(forms.Form):
url = forms.CharField(error_messages={"required": "url不能为空"})
activity_id = forms.CharField(error_messages={"required": "activity_id不能为空"})
type = forms.CharField(required=False, initial='Submit')
def clean_type(self):
value = self.cleaned_data.get('type', 'Submit')
if not value:
value = 'Submit'
elif value not in ['Submit','Save']:
raise forms.ValidationError('type 必须是Submit或者Save')
return value
class join_activity(forms.Form):
activity_id = forms.CharField(error_messages={"required": "缺少必要参数activity_id"})
join_type = forms.CharField(error_messages={"required": "缺少必要参数join_type"})
sing_type = forms.CharField(error_messages={"required": "缺少必要参数sing_type"})
url = forms.CharField(error_messages={"required": "缺少必要参数url"})
class collection(forms.Form):
activity_id = forms.CharField(error_messages={"required": "活动id不能为空"})
class singer_update(forms.Form):
singer_id = forms.CharField(error_messages={"required": "歌手id不能为空"})
rate = forms.CharField(error_messages={"required": "分成模式不能为空"})
company = forms.CharField(error_messages={"required": "经纪公司不能为空"})
class singer_updatev2(forms.Form):
singer_id = forms.CharField(error_messages={"required": "歌手id不能为空"})
# rate = forms.CharField(error_messages={"required": "分成模式不能为空"})
# company = forms.CharField(error_messages={"required": "经纪公司不能为空"})
chat_mode = forms.IntegerField(min_value=0,max_value=1,error_messages={"min_value":"值在0-1之间","max_value":"值在0-1之间","required": "缺少chat_mode参数"})
is_all = forms.IntegerField(min_value=0,max_value=1,error_messages={"min_value":"值在0-1之间","max_value":"值在0-1之间","required": "缺少is_all参数"})
class user_activity_unlike(forms.Form):
activity_id = forms.CharField(error_messages={"required": "活动id不能为空"})
class WechatAuth(forms.Form):
vx_code = forms.CharField(error_messages={"required": "缺少必要参数vx_code"})
platform = forms.CharField(error_messages={"required": "缺少必要参数platform"})
class EditorVerify(forms.Form):
field = forms.CharField(error_messages={"required": "缺少必要参数field"})
value = forms.CharField(error_messages={"required": "缺少必要参数value"})
class ConfirmSingerVerify(forms.Form):
activity_id = forms.IntegerField(error_messages={"required": "缺少必要参数activity_id"})
singer_id = forms.CharField(error_messages={"required": "缺少必要参数singer_id"})
status = forms.IntegerField(max_value=2,min_value=1,error_messages={"required": "缺少必要参数status","max_value":"最大值是2","min_value":"最小值是1"})
class ChangePhoneVrify(forms.Form):
phone = forms.CharField(error_messages={"required": "缺少必要参数phone"})
sms_code = forms.IntegerField(error_messages={"required": "缺少必要参数sms_code","invalid":"验证码只能是数字"})
area_code = forms.IntegerField(error_messages={'invalid':'area_code数据格式错误',"required": "缺少必填参数area_code"})
class PushNotifications(forms.Form):
title = forms.CharField(error_messages={"required": "缺少必要参数title"})
content = forms.CharField(error_messages={"required": "缺少必要参数content"})
receivers = forms.JSONField(error_messages={"required": "缺少必要参数receivers"})
class UserSound(serializers.Serializer):
tags = serializers.JSONField(allow_null=True,error_messages={"required": "缺少必要参数tags"})
sound_url = serializers.CharField(allow_blank=True, error_messages={"required": "缺少必要参数sound_url"})
class CreataFollow(serializers.Serializer):
following_id = serializers.IntegerField(error_messages={"required": "缺少必要参数following_id"})
class EditorUser(serializers.Serializer):
avatar = serializers.CharField(required=False)
cover = serializers.CharField(required=False)
nick_name = serializers.CharField(required=False,allow_blank=False, min_length=2,max_length=16,error_messages={"blank":"昵称不能为空","min_length":"长度不能小于2","max_length":"长度不能大于16"})
sex = serializers.IntegerField(required=False,min_value=0,max_value=2,error_messages={'invalid':'sex数据格式错误',"min_value": "参数范围在0-2之间","max_value": "参数范围在0-2之间"})
intro = serializers.CharField(required=False,allow_blank=True)
art_tag = serializers.JSONField(required=False)
style_tag = serializers.JSONField(required=False)
company = serializers.CharField(required=False,allow_blank=True)
province = serializers.CharField(required=False)
city = serializers.CharField(required=False)
class SplitAudio(serializers.Serializer):
activity_id = serializers.IntegerField(error_messages={"required": "缺少必要参数activity_id"})
status = serializers.IntegerField(error_messages={"required": "缺少必要参数status"})
class TidingsVerify(serializers.Serializer):
title = serializers.CharField(required=False,allow_blank=True, max_length=1000,error_messages={"max_length":"长度不能超过1000"})
activity_ids = serializers.ListField(required=False,allow_null=True)
singer_ids = serializers.ListField(required=False,allow_null=True)
sounds = serializers.ListField(required=False,allow_null=True)
photos = serializers.ListField(required=False,max_length=3,allow_null=True,error_messages={"max_length":"长度不能超过3"})
type = serializers.IntegerField(max_value=4,min_value=1 ,error_messages={"min_value":"type值范围在1~4","max_value":"type值范围在1~4","required":"缺少必要参数type"})
class TidingsLimitVerify(serializers.Serializer):
tidings_id = serializers.IntegerField(error_messages={"required": "缺少必要参数tidings_id"})
status = serializers.IntegerField(error_messages={"required": "缺少必要参数status"})
class TidingsReportVerify(serializers.Serializer):
tidings_id = serializers.IntegerField(required=False,default=0,error_messages={"required": "缺少必要参数tidings_id"})
reason = serializers.CharField(max_length=100,error_messages={"required": "缺少必要参数reason","max_length":"长度不能超过100","blank":"reason不能为空"})
class TidingsRecordUserVerify(serializers.Serializer):
tidings_id = serializers.ListField(error_messages={"required": "缺少必要参数tidings_id"})
class TidingsInteractsVerify(serializers.Serializer):
type = serializers.IntegerField(min_value=1,max_value=4,error_messages={"min_value":"type值范围在1~4","max_value":"type值范围在1~4","required": "缺少必要参数type"})
type_id = serializers.IntegerField(error_messages={"required": "缺少必要参数type_id"})
status = serializers.IntegerField(min_value=1,max_value=2,error_messages={"min_value":"status值范围在1~2","max_value":"status值范围在1~2","required": "缺少必要参数status"})
class TidingsDeleteVerify(serializers.Serializer):
tidings_id = serializers.IntegerField(error_messages={"required": "缺少必要参数tidings_id"})
class InteractsDeleteVerify(serializers.Serializer):
type = serializers.IntegerField(min_value=1,max_value=4,error_messages={"min_value":"type值范围在1~4","max_value":"type值范围在1~4","required": "缺少必要参数type"})
type_id = serializers.IntegerField(error_messages={"required": "缺少必要参数type_id"})
status = serializers.IntegerField(min_value=1,max_value=2,error_messages={"min_value":"status值范围在1~2","max_value":"status值范围在1~2","required": "缺少必要参数status"})
class ShareUsersVerify(serializers.Serializer):
activity_id = serializers.IntegerField(error_messages={"required": "缺少必要参数activity_id"})
share_id = serializers.IntegerField(required=False)
class TidingsChatVerify(serializers.Serializer):
tidings_id = serializers.IntegerField(error_messages={"required": "缺少必要参数tidings_id"})
class UnlikeTidingsVerify(serializers.Serializer):
tidings_id = serializers.IntegerField(error_messages={"required": "缺少必要参数tidings_id"})
class ChatAgentRecordVerify(serializers.Serializer):
user_id = serializers.IntegerField(error_messages={"required": "缺少必要参数user_id"})
class PushTidingsCommentsVerify(serializers.Serializer):
tidings_id = serializers.IntegerField(error_messages={"required": "缺少必要参数tidings_id"})
content = serializers.CharField(max_length=200,error_messages={"max_length":"评论字数超过限制","blank":"评论不能为空","required": "缺少必要参数content"})
class DeleCommentsVerify(serializers.Serializer):
comment_id = serializers.IntegerField(error_messages={"required": "缺少必要参数comment_id"})
class AvtivitysPriceVerification(serializers.Serializer):
activity_id = serializers.IntegerField(error_messages={"required": "缺少必要参数activity_id"})
value = serializers.JSONField(error_messages={"required": "缺少必要参数value",'invalid':'value是json数据类型'})
is_deduct = serializers.IntegerField(min_value=0,max_value=1,error_messages={"required": "缺少必要参数is_deduct","min_value":"is_deduct值范围在0~1","max_value":"is_deduct值范围在0~1"})
is_talk = serializers.IntegerField(min_value=0,max_value=1,error_messages={"required": "缺少必要参数is_talk","min_value":"is_talk值范围在0~1","max_value":"is_talk值范围在0~1"})
address_id = serializers.IntegerField(error_messages={"required": "缺少必要参数address_id"})
is_accept_address = serializers.IntegerField(min_value=0,max_value=1,error_messages={"required": "缺少必要参数is_accept_address","min_value":"is_accept_address值范围在0~1","max_value":"is_accept_address值范围在0~1"})
class SubmitPriceVerification(serializers.Serializer):
value = serializers.JSONField(error_messages={"required": "缺少必要参数value",'invalid':'value是json数据类型'})
is_deduct = serializers.IntegerField(min_value=0,max_value=1,error_messages={"required": "缺少必要参数is_deduct","min_value":"is_deduct值范围在0~1","max_value":"is_deduct值范围在0~1"})
is_talk = serializers.IntegerField(min_value=0,max_value=1,error_messages={"required": "缺少必要参数is_talk","min_value":"is_talk值范围在0~1","max_value":"is_talk值范围在0~1"})
address_id = serializers.IntegerField(error_messages={"required": "缺少必要参数address_id"})
is_accept_address = serializers.IntegerField(min_value=0,max_value=1,error_messages={"required": "缺少必要参数is_accept_address","min_value":"is_accept_address值范围在0~1","max_value":"is_accept_address值范围在0~1"})
# Create your views here\
import datetime
from api import models
from HisinApi import settings
from django.conf import settings
from django.http import JsonResponse
from django.contrib.auth import get_user_model
import jwt
from django.forms.models import model_to_dict
from rest_framework.pagination import PageNumberPagination
from HisinApi.settings import OSS_BASE_FILE,OSS_ENDPOINT,OSS_ID,OSS_KEY,OSS_BUKET
import json
import oss2
import random
import uuid
import librosa
import pydub
import matplotlib.pyplot as plt
import soundfile
import numpy as np
import time
import threading
import requests
from django.core.cache import caches
import hashlib
from django.utils import timezone
from api.loggin import logger
import base64
from django_redis import get_redis_connection
import os,shutil
from django.db import transaction
import jieba
from api import schedules
from django.db import close_old_connections
UserModel = get_user_model()
#定义拆分文件线程最大数量
sem = threading.Semaphore(4)
con = get_redis_connection("default")
def rate_limit(seconds=10):
def decorator(view):
def wrapper(request, *args, **kwargs):
now = time.time()
logger.info('session:{}'.format(request.session.items()))
request_time = request.session.get('request_time', 0)
interval_time = int(now - request_time)
logger.info("now:{},request_time:{}".format(now,request_time))
logger.info('interval_time:{}'.format(interval_time))
if interval_time < seconds:
request.session['request_time'] = time.time()
return JsonResponse(ResponseFactory(code=400,message="访问频繁,请稍后再试",data=None,status='fail'))
else:
request.session['request_time'] = time.time()
return view(request, *args, **kwargs)
return wrapper
return decorator
def upload_image(file):
"""
! 上传单张图片
:param file: b字节文件
:return: 若成功返回图片路径,若不成功返回空
"""
auth = oss2.Auth(OSS_ID, OSS_KEY)
bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUKET)
number = uuid.uuid4()
date = time.strftime("%Y-%m-%d", time.localtime())
base_fil_name = 'image/' + date + '/' + str(number) + '.jpg'
file_name = OSS_BASE_FILE + base_fil_name
headers = dict()
headers["x-oss-storage-class"] = "Standard"
headers["x-oss-object-acl"] = oss2.OBJECT_ACL_PUBLIC_READ_WRITE
res = bucket.put_object(base_fil_name, file,headers=headers)
if res.status == 200:
return file_name
else:
return False
def upload_audio(file):
"""
! 上传单张图片
:param file: b字节文件
:return: 若成功返回图片路径,若不成功返回空
"""
auth = oss2.Auth(OSS_ID, OSS_KEY)
bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUKET)
number = uuid.uuid4()
date = time.strftime("%Y-%m-%d", time.localtime())
base_fil_name = 'mp3/'+date+'/' + str(number) + '.mp3'
file_name = OSS_BASE_FILE+ base_fil_name
headers = dict()
headers["x-oss-storage-class"] = "Standard"
headers["x-oss-object-acl"] = oss2.OBJECT_ACL_PUBLIC_READ_WRITE
res = bucket.put_object(base_fil_name, file,headers=headers)
if res.status == 200:
return file_name
else:
return False
def auto_upload_audio(file,file_type):
"""
! 上传单张图片
:param file: b字节文件
:return: 若成功返回图片路径,若不成功返回空
"""
auth = oss2.Auth(OSS_ID, OSS_KEY)
bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUKET)
number = uuid.uuid4()
date = time.strftime("%Y-%m-%d", time.localtime())
# file_type = file.name.split('.')[1]
# base_fil_name = 'mp3/'+date+'/' + str(number) + '.'+ file_type
base_fil_name = 'mp3/'+date+'/' + str(number) + '.' + file_type
file_name = OSS_BASE_FILE+ base_fil_name
headers = dict()
headers["x-oss-storage-class"] = "Standard"
headers["x-oss-object-acl"] = oss2.OBJECT_ACL_PUBLIC_READ_WRITE
res = bucket.put_object(base_fil_name, file,headers=headers)
if res.status == 200:
# return file_name,file_type
return file_name
else:
return False
class PageNumberPagination(PageNumberPagination):
page_size = 10
page_size_query_param = 'size'
page_query_param = 'page'
max_page_size = None
def ResponseFactory(code,message,data,status):
return {'code':code,'message':message,'data':data,'status':status}
def AuthPermissionRequired():
"""
权限认证
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
try:
auth = request.META.get('HTTP_AUTHORIZATION').split()
except AttributeError:
return JsonResponse(ResponseFactory(code=401,message="无身份验证头",data=None,status='fail'))
# 用户通过API获取数据验证流程
if auth[0].lower() == 'token':
try:
dict = jwt.decode(auth[1], settings.SECRET_KEY, algorithms=['HS256'])
user_id = dict.get('data').get('id')
env = dict.get('data').get('env')
except jwt.ExpiredSignatureError:
return JsonResponse(ResponseFactory(code=401, message="身份验证过期", data=None, status='fail'))
except jwt.InvalidTokenError:
return JsonResponse(ResponseFactory(code=401, message="无效的身份验证", data=None, status='fail'))
except Exception as e:
return JsonResponse(ResponseFactory(code=401, message="无效的身份验证", data=None, status='fail'))
try:
if settings.ENV != env:
return JsonResponse(ResponseFactory(code=401, message="用户不存在", data=None, status='fail'))
user = UserModel.objects.get(id=user_id,deleted_at=None)
# 更新用户登录时间,由于登录入口比较多,登录时间难以维护,统一到这里维护
UserModel.objects.filter(id=user_id, deleted_at=None).update(last_login = timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
# 积分
user_point_record(user_id, type='Login')
if user.status == 0:
return JsonResponse(ResponseFactory(code=401, message="用户已被禁用", data=None, status='fail'))
except UserModel.DoesNotExist:
return JsonResponse(ResponseFactory(code=401, message="用户不存在", data=None, status='fail'))
else:
return JsonResponse(ResponseFactory(code=401, message="不支持此类验证", data=None, status='fail'))
return view_func(request, *args, **kwargs)
return _wrapped_view
return decorator
def get_user_info(requests):
auth = requests.META.get('HTTP_AUTHORIZATION').split()
userId = jwt.decode(auth[1], settings.SECRET_KEY, algorithms=['HS256'])['data']['id']
user = model_to_dict(models.Users.objects.get(id=userId))
if user['business']:user['business_id'] = user['business']
else:user['business_id'] = 0
del user['password']
return user
def object_to_json(obj):
return dict([(kk, obj.__dict__[kk]) for kk in obj.__dict__.keys() if kk != "_state"])
class ChangeAudio():
def __init__(self,file,base_path,type):
#### 文件变调
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
self.fs = 44100
self.outPath = base_path+"/out"
self.wav_data, self.sr = librosa.load(file, sr=22050, mono=False)
self.type = type
def change_step(self,step):
with sem:
y_third = librosa.effects.pitch_shift(self.wav_data, self.sr, n_steps=step)
stereo = y_third.transpose()
_outpath = self.outPath+self.type+str(step)+'.wav'
soundfile.write(_outpath, stereo, self.sr)
sound = pydub.AudioSegment.from_wav(_outpath)
sound.export(self.outPath+self.type+str(step) + '.mp3', format="mp3")
def WeChatApi(code):
appid = "wx0f3844b1458ccfb9"
secret = "f9fa09c6cf3b4db19906d876d9c64755"
parmas = {
'appid': appid,
'secret': secret,
'js_code': code,
'grant_type': 'authorization_code'
}
url = 'https://api.weixin.qq.com/sns/jscode2session'
r = requests.get(url, params=parmas).json()
try:
return r['openid'],r['unionid']
except:
return None,None
def AppWechatApi(code):
appid = 'wx78893f93dbc3a231'
secret = 'd709febdd41d0c966cc24bb9d93e2626'
url = 'https://api.weixin.qq.com/sns/oauth2/access_token'
parmas = {
'appid': appid,
'secret': secret,
'code': code,
'grant_type': 'authorization_code'
}
r = requests.get(url, params=parmas).json()
try:
return r['openid'], r['unionid']
except:
return None, None
def GetWxToken():
token = caches['default'].get('wx_access_token')
if not token:
appid = "wx0f3844b1458ccfb9"
secret = "f9fa09c6cf3b4db19906d876d9c64755"
url = 'https://api.weixin.qq.com/cgi-bin/token'
parmas = {
"grant_type":"client_credential",
"appid":appid,
"secret":secret
}
r = requests.get(url,params=parmas).json()
caches['default'].add('wx_access_token', r['access_token'] ,6000) #expires_in
return r['access_token']
else:
return token
def pushSubscribeMessage(data):
channel = data['channel']
open_ids = data['open_id']
if settings.ENV == 'pro':
url = 'https://hi-sing-admin.hikoon.com/api/provider/wechat/pushSubscribeMessage'
else:
url = 'https://hi-sing-admin-dev.hikoon.com/api/provider/wechat/pushSubscribeMessage'
md5_str = channel + ''.join(open_ids) + 'tb0iwb7TE9TIbkG8iFsxldrHJRFdeP1g'
hl = hashlib.md5()
hl.update(md5_str.encode(encoding='utf8'))
secret = hl.hexdigest()
data = {
'secret': secret,
'channel': channel,
'open_ids': open_ids,
'data': data['data']
}
requests.post(url,json=data).json()
def createMessage(data):
message_list = []
for receiver in data['receivers']:
obj = models.UserMessages(
title = data.get('title',''),
content=data.get('content', ''),
sender_id = data.get('sender_id'),
receiver_id = receiver,
activity_id = data.get('activity_id',0),
type = data.get('type'),
is_read = 0,
is_bind = data.get('is_bind',0),
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
)
message_list.append(obj)
models.UserMessages.objects.bulk_create(message_list)
def get_oss_file(url):
"""[文件]
内网访问oss资源
:return:
"""
if settings.ENV == 'pro':
url = url.replace(settings.OSS_BASE_FILE,settings.OSS_INTERNAL)
return requests.get(url, verify=False).content
def deleteMessage(data):
models.UserMessages.objects.filter(sender_id=data['sender_id'],activity_id=data['activity_id'],type=data['type'],is_read=0).update(deleted_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
def user_point_record(user_id,type,singer_id=0,activity_id=0):
"""
:param user_id:
:param type:
:return:
"""
rules = {
'Login':[1,None],
'Listen':[None,None],
'SubmitPart':[5,None],
'SubmitFull':[2,None],
'Confirm':[None,None],
'ShareSong':[3,None],
'BindSinger': [None,20],
'SingerSubmitPart': [10, None],
'SingerSubmitFull': [6, None],
'SingerConfirm': [None, None],
'Subscribe': [1, 1],
'AutoSubmit' :[2,None],
'SingerAutoSubmit':[6, None]
}
pointItem = rules.get(type,'')
if pointItem:
#一天内积分次数
today = datetime.date.today().strftime('%Y-%m-%d')
oneday_count = models.UserPoints.objects.filter(type=type,user_id=user_id,created_at__gte=today).count()
history_count = models.UserPoints.objects.filter(type=type,user_id=user_id).count()
is_history = pointItem[1] == None or pointItem[1] > history_count
is_one = pointItem[0] == None or pointItem[0] > oneday_count
is_singer = not singer_id or not models.UserPoints.objects.filter(type=type, user_id=user_id,singer_id=singer_id,activity_id=activity_id)
is_activity = not activity_id or not models.UserPoints.objects.filter(type=type, user_id=user_id,activity_id=activity_id,singer_id=singer_id)
if is_one and is_history and is_singer and is_activity:
models.UserPoints.objects.create(
type = type,
user_id = user_id,
singer_id = singer_id,
activity_id = activity_id,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
)
class JPush():
"""
极光推送
"""
def __init__(self):
self.app_key = settings.J_APP_KEY
self.master_secret = settings.J_MASTER_SECRET
def https_request(self, body, url, content_type=None, version=None, params=None):
https = requests.Session()
https.auth = (self.app_key,self.master_secret)
headers = {}
headers['user-agent'] = 'jpush-api-python-client'
headers['connection'] = 'keep-alive'
headers['content-type'] = 'application/json;charset:utf-8'
response = https.request('POST', url, data=body, params=params, headers=headers)
logger.info(dict(json.loads(response.content), **{'status_code': response.status_code}))
return dict(json.loads(response.content), **{'status_code': response.status_code})
def push_params_v3(self,title,content, receiver_value=None,content_type=None, extras=None, platform="ios,android"):
sendno = int(random.randint(999, 999999))
payload = dict()
payload['platform'] = platform
if settings.ENV == 'dev':
receiver_value = list('test'+str(i) for i in receiver_value)
apns_production = False
else:
apns_production = True
payload['audience'] = {
"alias": receiver_value
}
payload['notification'] = {
"android": {"alert": content, "badge_add_num": 1, "alternate_alert": "", "style": 0, "category": "",
"priority": 0, "title": title, "intent": {"url": ""}, "alert_type": 7, "alternate_title": "",
"extras": extras},
"ios": {"alert": {"body": content,"title": title}, "sound": "default", "extras": extras},
}
payload['options'] = {"apns_production": apns_production, "time_to_live": 86400 * 3, 'sendno': sendno,
"third_party_channel":{
"xiaomi": {"importance":"NORMAL"},
"huawei": {"importance": "NORMAL"},
"honor": {"importance": "NORMAL"},
"meizu": {"importance": "NORMAL"},
"oppo": {"importance": "NORMAL"},
"vivo": {"importance": "NORMAL"},
}
}
logger.info(payload)
return payload
def jpush_v3(self, data):
payload = self.push_params_v3(title=data['title'],content=data['content'],content_type=data['content_type'],receiver_value=data['receiver_value'],extras=data['extras'])
body = json.dumps(payload)
return self.https_request(body, "https://api.jpush.cn/v3/push", 'application/json', version=1)
def Msg_Push_Server(data):
secret = settings.YJ_SECRET
p = '{channel}&{data}&{secret}&{time}'.format(channel=data['channel'],data=data['data'],secret=secret,time=data['time']).encode()
p = base64.b64encode(p)
hl = hashlib.md5()
hl.update(p)
sign = hl.hexdigest()
data['sign'] = sign
data['data'] = json.loads(data['data'])
logger.info("推送参数:{}".format(str(data)))
if settings.ENV == 'pro':
url = 'https://hi-sing-admin.hikoon.com/api/provider'
else:
url = 'https://hi-sing-admin-dev.hikoon.com/api/provider'
resp = requests.post(url,json=data).text
logger.info("推送结果:{}".format(str(resp)))
def remove_alias_device(alias):
try:
if settings.ENV == 'dev':
alias ='test' + str(alias)
#获取设备
url = 'https://device.jpush.cn/v3/aliases/{}'.format(alias)
m_str = bytes('{}:{}'.format(settings.J_APP_KEY,settings.J_MASTER_SECRET), 'utf-8')
token = str(base64.b64encode(m_str), 'utf-8')
headers = {
'Authorization': 'Basic {}'.format(token),
'Accept': 'application / json'
}
resp = requests.get(url, headers=headers).json()
try:
registration_ids = resp['registration_ids']
except:
registration_ids = []
#删除设备
headers = {
'Authorization': 'Basic {}'.format(token),
'Accept': 'application / json'
}
data = {
"registration_ids": {"remove":registration_ids }
}
requests.post(url, headers=headers, json=data)
except Exception as e:
print (e)
def upload_oss(file,activity_id,type,name):
"""上传到oss,地址存入mysql"""
with open(file,'rb') as f:
data = f.read()
f.close()
url = upload_audio(data)
return url
def run_split_audio(activity_id, activity_status,push_date):
"""
:param activity_id:
:param activity_status:
:param push_date:
:return:
拆分物料
"""
# 文件目录定义
t = str(int(time.time())) + str(random.randint(0, 100000))
base_path = "./api/static/{}".format(t)
os.mkdir(base_path)
try:
# 下载活动物料
close_old_connections()
activitys = models.Activitys.objects.filter(id=activity_id).first()
guide_file = requests.get(activitys.guide, verify=False).content
accompany_file = requests.get(activitys.karaoke, verify=False).content
f1 = base_path + '/guide.mp3'
f2 = base_path + '/accompany.mp3'
# #保存上传文件
with open(f1, "wb") as ff:
ff.write(guide_file)
ff.close()
with open(f2, "wb") as fff:
fff.write(accompany_file)
fff.close()
guide_split_audio = ChangeAudio(file=f1, base_path=base_path, type='GuideDinging')
acc_split_audio = ChangeAudio(file=f2, base_path=base_path, type='Accompany')
for i in range(-3, 4):
guide_split_audio.change_step(i)
for i in range(-3, 4):
acc_split_audio.change_step(i)
# 上传文件到OSS,地址保存至数据库
types = ['GuideDinging', 'Accompany']
activitymaterials_obj_list = []
for type in types:
for name in range(-3, 4):
file = base_path + '/out' + type + str(name) + '.mp3'
url = upload_oss(file, activity_id, type, name)
am_obj = models.ActivityMaterials(
activity_id=activity_id,
type=type,
url=url,
tone=name,
created_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
)
activitymaterials_obj_list.append(am_obj)
try:
close_old_connections()
with transaction.atomic():
# 判断是否已存在数据
is_exists = models.ActivityMaterials.objects.filter(activity_id=activity_id,
deleted_at=None).exists()
if is_exists:
# 先删掉之前的拆分物料
models.ActivityMaterials.objects.filter(activity_id=activity_id).delete()
models.ActivityMaterials.objects.bulk_create(activitymaterials_obj_list)
# 改变活动状态
models.Activitys.objects.filter(id=activity_id).update(status=activity_status,
updated_at=timezone.now().strftime(
"%Y-%m-%d %H:%M:%S"))
con.rpop('split_audio_queue')
# 触发消息推送
data = {"channel": "ActivityPublish", "data": '{"activityId":' + str(activity_id) + '}',
"time": int(time.time())}
Msg_Push_Server(data)
except Exception as e:
logger.info('数据准备完成,同步数据库失败:{}'.format(e))
# 删除拆分的文件
shutil.rmtree(base_path)
except Exception as e:
# 删除拆分的文件
shutil.rmtree(base_path)
logger.info('avtivity_split_error:{}'.format(e))
#如果超过1天处理失败,则归为处理失败
now = (datetime.datetime.now() + datetime.timedelta(days = -1)).strftime("%Y-%m-%d %H:%M:%S")
if now > push_date:
models.Activitys.objects.filter(id=activity_id).update(status=4, updated_at=timezone.now().strftime("%Y-%m-%d %H:%M:%S"))
# 队列去掉数据
con.rpop('split_audio_queue')
time.sleep(5)
def senstive_word_check(text):
with open('./api/static/min_word.txt','rb') as f:
senstive_word = f.read().decode("utf-8").replace('\r', '')
f.close()
jieba.load_userdict('./api/static/min_word.txt')
word_list = jieba.lcut(text)
senstive_word_list = senstive_word.split('\n')
for word in word_list:
if word in senstive_word_list:return True
else:pass
return False
def user_permission(id):
"""返回用户试听,试唱权限"""
permission = list()
#检测是否在试唱白名单
singobj = models.SystemConfig.objects.filter(identifier='Jy-zgPbcSXSGnvHIx8moq', status=1,deleted_at=None).first()
if singobj:
if str(id) in singobj.content.split(','):
permission.append(2)
tags = list(models.UserTagRelations.objects.filter(user_id=id, type=4).values_list('tag_id', flat=True))
if len(tags) == 0: return permission
expands = models.SystemTags.objects.filter(id__in=tags, deleted_at=None).values_list('expand', flat=True)
for expand in expands:
permission = permission + expand['permission']
return permission
def push_relation():
users = models.Users.objects.filter(deleted_at=None).all()
for user in users:
if user.business_id:
#创建群组
models.Groups.objects.update_or_create(defaults = {'created_at':timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
'updated_at':timezone.now().strftime("%Y-%m-%d %H:%M:%S")}, user_id=user.business_id,deleted_at=None)
#加入群
group_id = models.Groups.objects.filter(user_id=user.business_id).first().id
#团长入群
models.GroupHasMembers.objects.update_or_create(group_id=group_id,member_id=user.business_id,deleted_at=None, defaults={"role":1,"created_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S"),"updated_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S")})
#成员入群
models.GroupHasMembers.objects.update_or_create(group_id=group_id,member_id=user.id, deleted_at=None,defaults={"created_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S"),"updated_at":timezone.now().strftime("%Y-%m-%d %H:%M:%S")})
#
# # #异步开启定时任务:活动拆分
def startJob():
while True:
try:
if con.llen("split_audio_queue") > 0:
last_index = con.llen("split_audio_queue") - 1
item = eval(con.lindex('split_audio_queue',last_index))
run_split_audio(item['id'],item['status'],item['time'])
else:
time.sleep(5)
except Exception as e:
time.sleep(60)
logger.info('拆分异常:{}'.format(e))
t = threading.Thread(target=startJob)
t.setDaemon(True)
t.start()
# 异步开启定时任务:厂牌确认时间统计
t1 = threading.Thread(target=schedules.run)
t1.setDaemon(True)
t1.start()
# t1 = threading.Thread(target=push_relation)
# t1.setDaemon(True)
# t1.start()
\ No newline at end of file
File mode changed
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HisinApi.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
aliyun-python-sdk-core==2.13.35
aliyun-python-sdk-kms==2.15.0
django==3.2.12
django-redis-cache==3.0.1
django-rest-jwt==0.1.46
djangorestframework==3.13.1
djangorestframework-jwt==1.11.0
gevent==21.1.2
mysql-connector-python==8.0.18
oss2==2.14.0
PyJWT==2.7.0
PyMySQL==0.10.1
redis==3.5.3
requests==2.25.0
django-ratelimit==3.0.1
librosa==0.9.1
pydub==0.25.1
pyroomacoustics==0.7.3
eyed3==0.9.6
jieba==0.42.1
twilio==8.2.0
django_redis
matplotlib
schedule