first updata

This commit is contained in:
2024-02-26 18:17:15 +08:00
commit 1ec018ca90
162 changed files with 123649 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
+15
View File
@@ -0,0 +1,15 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="2">
<item index="0" class="java.lang.String" itemvalue="revChatGPT" />
<item index="1" class="java.lang.String" itemvalue="discord.py" />
</list>
</value>
</option>
</inspection_tool>
</profile>
</component>
+6
View File
@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="jsmindmulti/settings.py" />
<option name="manageScript" value="$MODULE_DIR$/manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="migrations" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.10 (gafocus)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
</component>
</module>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (gafocus)" project-jdk-type="Python SDK" />
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/jsmindmulti.iml" filepath="$PROJECT_DIR$/.idea/jsmindmulti.iml" />
</modules>
</component>
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Binary file not shown.
+28
View File
@@ -0,0 +1,28 @@
from wordcloud import WordCloud
# python的可视化库,也是二级考试推荐的可视化库
import matplotlib.pyplot as plt
str=['齐天大圣','大圣','大圣','八戒','嫦娥']
#数组里面添加内容
str.append('玉兔')
str.append('女儿国')
str.append('牛魔王')
str.append('大圣')
str.append('土地公公')
str.append('小神仙')
str.append('八戒')
print(str)
#join 函数 用斜杆拼接词组mask =maskph,
#这里一定要join拼接一下 转成字符串
text_cut = '/'.join(str)
#看一下连接后的样子
#关键点 text_cut 是词云要处理的内容
print(text_cut)
wordcloud = WordCloud( background_color='white',font_path = 'msyh.ttc', width=1000, height=860, margin=2).generate(text_cut)
# 显示图片
plt.imshow(wordcloud)
plt.axis('off')
plt.show()
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+30
View File
@@ -0,0 +1,30 @@
"""
ASGI config for jsmindmulti 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/3.2/howto/deployment/asgi/
"""
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from server.websocket.routing import websocket_urlpatterns
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'jsmindmulti.settings')
application = ProtocolTypeRouter({
# http 请求
"http": get_asgi_application(),
# websocket 请求
# channels文档:https://channels.readthedocs.io/en/stable/tutorial/index.html
"websocket": AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
),
})
+179
View File
@@ -0,0 +1,179 @@
"""
Django settings for jsmindmulti project.
Generated by 'django-admin startproject' using Django 3.2.11.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os.path
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-92%z)%dv$x)-254f2ixp(ctnua4%^@=db&(ha4i-i2p2er(+^&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'server',
'server_auth',
'channels',
'django_filters' # 注册过滤
]
REST_FRAMEWORK = {
# 全局过滤
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination'
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# 指定websocket主路由的位置
ASGI_APPLICATION = 'jsmindmulti.asgi.application'
# 指定websocket CHANNEL_LAYERS
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer"
}
}
ROOT_URLCONF = 'jsmindmulti.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'static')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'jsmindmulti.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'jsmind',
'USER': 'root',
'PASSWORD': 'guoan123',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# 静态文件目录
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# AUTH_USER_MODEL为我们自定义的用户类
AUTH_USER_MODEL = "server_auth.MindUser"
# 自定义 登陆手段
AUTHENTICATION_BACKENDS = [
'server_auth.lib.auth.AuthBackend',
]
# session 设置
SESSION_COOKIE_AGE = 60 * 30 # 设置过期时间10分钟,默认为两周
SESSION_SAVE_EVERY_REQUEST = True
# 日志
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level': 'DEBUG',
},
}
}
+23
View File
@@ -0,0 +1,23 @@
"""jsmindmulti URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/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 django.conf.urls import url, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('server.urls'))
]
+16
View File
@@ -0,0 +1,16 @@
"""
WSGI config for jsmindmulti 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/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'jsmindmulti.settings')
application = get_wsgi_application()
+22
View File
@@ -0,0 +1,22 @@
#!/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', 'jsmindmulti.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()
+30
View File
@@ -0,0 +1,30 @@
asgiref==3.4.1
attrs==21.4.0
autobahn==21.11.1
Automat==20.2.0
cffi==1.15.0
channels==3.0.4
constantly==15.1.0
cryptography==36.0.1
daphne==3.0.2
Django==3.2.11
django-filter==21.1
djangorestframework==3.13.1
hyperlink==21.0.0
idna==3.3
incremental==21.3.0
mysqlclient==2.1.0
pyasn1==0.4.8
pyasn1-modules==0.2.8
pycparser==2.21
pyOpenSSL==21.0.0
pytz==2021.3
service-identity==21.1.0
six==1.16.0
sqlparse==0.4.2
Twisted==21.7.0
twisted-iocpsupport==1.0.2
txaio==21.2.1
typing_extensions==4.0.1
xmindparser==1.0.9
zope.interface==5.4.0
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class ServerConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'server'
+26
View File
@@ -0,0 +1,26 @@
import django_filters
from django_filters import rest_framework
from server.models import *
class CooperationMindFilter(django_filters.rest_framework.FilterSet):
"""
思维导图filter
"""
coop_mind_name = rest_framework.CharFilter(field_name='coop_mind_name', lookup_expr='icontains')
class Meta:
model = CooperationMind
fields = "__all__"
class CooperationMindShareFilter(django_filters.rest_framework.FilterSet):
"""
思维导图分享filter
"""
coop_mind_name = rest_framework.CharFilter(field_name='coop_mind_name', lookup_expr='icontains')
class Meta:
model = CooperationMindShare
fields = "__all__"
View File
Binary file not shown.
Binary file not shown.
+32
View File
@@ -0,0 +1,32 @@
from server.models import CooperationMindLog
import ast
from server.serializers import CooperationMindLogSerializer
class CooperationMindLogLib(object):
"""
操作日志
"""
def save_log(self, json_msg):
"""
保存操作日志
"""
if self.should_handle(json_msg):
# 避免json解析失败
json_msg = json_msg.replace(',null]', ']')
print(json_msg)
json_msg_dict = ast.literal_eval(json_msg)
log = CooperationMindLog(
coop_mind_id=json_msg_dict.get('coop_mind_id'),
log_uuid=json_msg_dict.get('log_uuid'),
log_content=json_msg,
client_uuid=json_msg_dict.get('client_uuid')
)
log.save()
return CooperationMindLogSerializer(log).data
return None
def should_handle(self, json_msg):
return 'coop_mind_id' in json_msg and 'select_node' not in json_msg
+18
View File
@@ -0,0 +1,18 @@
def get_context():
if QrContext.instance is None:
QrContext.instance = QrContext()
return QrContext.instance
class QrContext():
instance = None
all_obj = {}
def get(self, key):
return self.all_obj.get(key)
def add(self, key, v):
self.all_obj.update({key: v})
def remove(self, key):
del self.all_obj[key]
+115
View File
@@ -0,0 +1,115 @@
# Generated by Django 3.2.11 on 2024-02-12 17:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CooperationMind',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, verbose_name='修改时间')),
('coop_mind_name', models.CharField(max_length=128, verbose_name='脑图名称')),
('creator_user_id', models.BigIntegerField(default=0, verbose_name='创建人ID')),
('client_uuid', models.CharField(max_length=64, verbose_name='客户端ID')),
('snapshot_data', models.TextField(null=True, verbose_name='脑图数据')),
('mind_log_id', models.BigIntegerField(null=True, verbose_name='data对应的操作日志(cooperation_mind_log)ID')),
('data_format', models.CharField(max_length=32, verbose_name='数据格式化类型')),
('deleted', models.BooleanField(default=False, verbose_name='是否标记为软删除')),
],
options={
'verbose_name': '脑图表',
'db_table': 'cooperation_mind',
'ordering': ['-id'],
},
),
migrations.CreateModel(
name='CooperationMindStar',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, verbose_name='修改时间')),
('operator_user_id', models.BigIntegerField(verbose_name='收藏人')),
('coop_mind_name', models.CharField(max_length=128, verbose_name='脑图名称')),
('coop_mind', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='server.cooperationmind', verbose_name='脑图ID')),
],
options={
'verbose_name': '协作分享表',
'db_table': 'cooperation_mind_star',
},
),
migrations.CreateModel(
name='CooperationMindShare',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, verbose_name='修改时间')),
('coop_mind_name', models.CharField(max_length=128, verbose_name='脑图名称')),
('share_uuid', models.CharField(max_length=128, verbose_name='分享uuid')),
('share_uuid_hash', models.BigIntegerField(verbose_name='分享uuid_hash')),
('share_end_time', models.DateTimeField(null=True, verbose_name='分享有效期')),
('operator_user_id', models.BigIntegerField(verbose_name='分享操作人')),
('coop_mind', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='server.cooperationmind', verbose_name='脑图ID')),
],
options={
'verbose_name': '协作分享表',
'db_table': 'cooperation_mind_share',
},
),
migrations.CreateModel(
name='CooperationMindLog',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, verbose_name='修改时间')),
('log_uuid', models.CharField(max_length=64, verbose_name='操作UUID')),
('log_content', models.CharField(max_length=1024, verbose_name='操作内容')),
('operator_user_id', models.BigIntegerField(null=True, verbose_name='操作人')),
('operator_ip', models.CharField(max_length=32, verbose_name='操作人IP')),
('client_uuid', models.CharField(max_length=64, verbose_name='客户端ID')),
('coop_mind', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='server.cooperationmind', verbose_name='脑图ID')),
],
options={
'verbose_name': '操作日志表',
'db_table': 'cooperation_mind_log',
'ordering': ['id'],
},
),
migrations.AddIndex(
model_name='cooperationmind',
index=models.Index(fields=['creator_user_id'], name='cooperation_creator_b40e3b_idx'),
),
migrations.AddIndex(
model_name='cooperationmindstar',
index=models.Index(fields=['operator_user_id'], name='cooperation_operato_fae2a0_idx'),
),
migrations.AddIndex(
model_name='cooperationmindshare',
index=models.Index(fields=['share_uuid_hash'], name='cooperation_share_u_66be20_idx'),
),
migrations.AddIndex(
model_name='cooperationmindshare',
index=models.Index(fields=['operator_user_id'], name='cooperation_operato_f5cf97_idx'),
),
migrations.AddIndex(
model_name='cooperationmindlog',
index=models.Index(fields=['coop_mind_id'], name='cooperation_coop_mi_32e0df_idx'),
),
migrations.AddIndex(
model_name='cooperationmindlog',
index=models.Index(fields=['operator_user_id'], name='cooperation_operato_9d4daf_idx'),
),
migrations.AlterUniqueTogether(
name='cooperationmindlog',
unique_together={('coop_mind_id', 'log_uuid')},
),
]
@@ -0,0 +1,30 @@
# Generated by Django 3.2.11 on 2024-02-25 21:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('server', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='StudentandTercher',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('create_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')),
('update_time', models.DateTimeField(auto_now=True, verbose_name='修改时间')),
('class_id', models.CharField(max_length=128, verbose_name='课程id')),
('class_name', models.CharField(max_length=128, verbose_name='课程名称')),
('tercher_name', models.CharField(max_length=128, verbose_name='老师姓名')),
('add_time', models.DateTimeField(auto_now_add=True, verbose_name='添加时间')),
('class_info', models.CharField(max_length=128, verbose_name='课程信息')),
('class_status', models.CharField(max_length=128, verbose_name='课程状态')),
],
options={
'abstract': False,
},
),
]
View File
+104
View File
@@ -0,0 +1,104 @@
from django.db import models
class AbstractModel(models.Model):
id = models.AutoField(primary_key=True)
create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
class Meta:
abstract = True
# Create your models here.
class CooperationMind(AbstractModel):
"""
"""
coop_mind_name = models.CharField(verbose_name='脑图名称', max_length=128, null=False, blank=False)
creator_user_id = models.BigIntegerField(verbose_name='创建人ID', null=False, blank=False, default=0)
client_uuid = models.CharField(verbose_name='客户端ID', max_length=64, null=False, blank=False)
snapshot_data = models.TextField(verbose_name='脑图数据', null=True, )
mind_log_id = models.BigIntegerField(verbose_name='data对应的操作日志(cooperation_mind_log)ID', null=True, )
data_format = models.CharField(verbose_name='数据格式化类型', max_length=32, null=False, blank=False)
deleted = models.BooleanField(verbose_name='是否标记为软删除', default=False)
class Meta:
db_table = 'cooperation_mind'
ordering = ['-id']
indexes = [
models.Index(fields=['creator_user_id'])
]
verbose_name = "脑图表"
# Create your models here.
class CooperationMindLog(AbstractModel):
"""
操作日志表
"""
coop_mind = models.ForeignKey(to="CooperationMind", to_field="id", verbose_name="脑图ID", on_delete=models.CASCADE)
log_uuid = models.CharField(verbose_name='操作UUID', max_length=64, null=False, blank=False)
log_content = models.CharField(verbose_name='操作内容', max_length=1024, null=False, blank=False)
operator_user_id = models.BigIntegerField(verbose_name='操作人', null=True)
operator_ip = models.CharField(verbose_name='操作人IP', null=False, max_length=32)
client_uuid = models.CharField(verbose_name='客户端ID', max_length=64, null=False, blank=False)
class Meta:
db_table = 'cooperation_mind_log'
ordering = ['id']
unique_together = (("coop_mind_id", "log_uuid"),)
indexes = [
models.Index(fields=['coop_mind_id'], ),
models.Index(fields=['operator_user_id'], )
]
verbose_name = "操作日志表"
class CooperationMindShare(AbstractModel):
"""
分享记录表
"""
coop_mind = models.OneToOneField(to="CooperationMind", to_field="id", verbose_name="脑图ID", on_delete=models.CASCADE)
coop_mind_name = models.CharField(verbose_name='脑图名称', max_length=128, null=False, blank=False)
share_uuid = models.CharField(verbose_name='分享uuid', max_length=128, null=False, blank=False)
share_uuid_hash = models.BigIntegerField(verbose_name='分享uuid_hash', null=False, blank=False)
share_end_time = models.DateTimeField(verbose_name='分享有效期', null=True)
operator_user_id = models.BigIntegerField(verbose_name='分享操作人', null=False)
class Meta:
db_table = 'cooperation_mind_share'
indexes = [
models.Index(fields=['share_uuid_hash'], ),
models.Index(fields=['operator_user_id'], ),
]
verbose_name = "协作分享表"
class CooperationMindStar(AbstractModel):
"""
收藏记录表
"""
operator_user_id = models.BigIntegerField(verbose_name='收藏人', null=False)
coop_mind = models.ForeignKey(to="CooperationMind", to_field="id", verbose_name="脑图ID", on_delete=models.CASCADE)
coop_mind_name = models.CharField(verbose_name='脑图名称', max_length=128, null=False, blank=False)
# star_type = models.SmallIntegerField(verbose_name="收藏类型。1:根据主键收藏;2:根据分享收藏", null=False)
class Meta:
db_table = 'cooperation_mind_star'
indexes = [
models.Index(fields=['operator_user_id'], ),
]
verbose_name = "协作分享表"
class StudentandTercher(AbstractModel):
"""
学生和老师表与课程信息表
"""
class_id = models.CharField(verbose_name='课程id', max_length=128, null=False, blank=False)
class_name = models.CharField(verbose_name='课程名称', max_length=128, null=False, blank=False)
tercher_name = models.CharField(verbose_name='老师姓名', max_length=128, null=False, blank=False)
add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)
class_info = models.CharField(verbose_name='课程信息', max_length=128, null=False, blank=False)
class_status = models.CharField(verbose_name='课程状态', max_length=128, null=False, blank=False)
+19
View File
@@ -0,0 +1,19 @@
from rest_framework.pagination import PageNumberPagination
from server.util.constant_util import *
from rest_framework.response import Response
class DefaultNumberPagination(PageNumberPagination):
page_size = 1 # default page size
page_size_query_param = 'page_size' # ?page=xx&page_size=??
max_page_size = 50 # max page size
def get_paginated_response(self, data):
"""
重写返回值格式
"""
return Response({
'code': CODE_SUCCESS,
'count': self.page.paginator.count,
'results': data
})
+32
View File
@@ -0,0 +1,32 @@
from rest_framework import serializers
from server.models import *
class CooperationMindSerializer(serializers.ModelSerializer):
"""
思维导图序列
"""
class Meta:
model = CooperationMind
fields = '__all__' # 包含模型类的所有字段
class CooperationMindLogSerializer(serializers.ModelSerializer):
"""
思维导图日志序列
"""
class Meta:
model = CooperationMindLog
fields = "__all__"
class CooperationMindShareSerializer(serializers.ModelSerializer):
"""
思维导图分享序列
"""
class Meta:
model = CooperationMindShare
fields = "__all__"
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+43
View File
@@ -0,0 +1,43 @@
from django.urls import path
from server.views.mind_map import *
from server.views.jump import *
from server.views.user import *
from server.view_test import *
from server_auth.lib.auth import *
urlpatterns = [
# ---------------------------------------------------
path('test', test), #
# ---------------------------------------------------
path('', to_dashboard), # 跳转列表界面
path('2_d', to_detail), # 跳转详情界面
path('s_2_d', share_to_detail), # 从分享链接跳转详细界面
path('2_share', to_share), # 到分享界面
path('2_echart',to_echarts), # 到图标界面
path('chat_room',to_chat_room), # 到聊天室界面
path('reng_wu',to_rengwu), # 到任务界面
path('ke_cheng',to_kecheng), # 到课程界面
path('2_star', to_star), # 到收藏界面
path('2_recycle', to_recycle), # 回收站
path(r'jsmind_op', JsMindLogView.as_view()), # 更新快照,get日志操作
# ---------------------------------------------------
path('create', JsMindView.as_view()), # 创建思维导图
path('list', JsMindView.as_view()), # 查询思维导图
path('d', JsMindView.as_view()), # 获得导图详情
path('s_d', JsMindShareView.as_view()), # 获得导图详情
path('delete', JsMindView.as_view()), # 删除思维导图
path('delete_cancel', JsMindView.as_view()), # 思维导图恢复
path('share', JsMindShareView.as_view()), # 分享思维导图,查询等
path('star', JsMindStarView.as_view()), # 收藏思维导图
# ---------------------------------------------------
path('register', MindUserView.as_view()), # 用户注册
path('login', LoginView.as_view()), # 用户登录
path('logout', LogoutView.as_view()), # 用户登出
# ---------------------------------------------------
]
View File
Binary file not shown.
Binary file not shown.
+43
View File
@@ -0,0 +1,43 @@
CODE_SUCCESS = 0
CODE_FAILED = -1
DUPLICATE = 1
SNAPSHOT_JSON_DATA = """{
"id": "root",
"topic": "想法",
"children": [{"id": "guoan",
"topic": "guoan",
"direction": "left",
"expanded": true,
"children": [
{"id": "看法", "topic": "看法"},
{"id": "依据", "topic": "依据"},
{"id": "中立", "topic": "中立"},
{"id": "反对", "topic": "反对"}
]
},
{
"id": "组员1",
"topic": "组员1",
"direction": "right",
"expanded": true,
"children": [
{"id": "看法1", "topic": "看法"},
{"id": "依据1", "topic": "依据"},
{"id": "中立1", "topic": "中立"},
{"id": "反对1", "topic": "反对"}
]
},
{
"id": "组员2",
"topic": "组员2",
"direction": "lift",
"expanded": true,
"children": [
{"id": "看法2", "topic": "看法"},
{"id": "依据2", "topic": "依据"},
{"id": "中立2", "topic": "中立"},
{"id": "反对2", "topic": "反对"}
]
}
]}"""
+6
View File
@@ -0,0 +1,6 @@
from rest_framework.response import Response
from server.util.constant_util import *
def build_response(code=CODE_SUCCESS, msg='操作成功', data=''):
return Response({'code': code, 'msg': msg, 'data': data})
+12
View File
@@ -0,0 +1,12 @@
from django.http import HttpResponse
from server.lib.qr_context import get_context
def test(request):
uid = request.GET.get('uid')
print(uid)
qrContext = get_context()
consumer = qrContext.get(uid)
print(consumer)
consumer.sed_text('ppp')
return HttpResponse('success')
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+74
View File
@@ -0,0 +1,74 @@
from django.shortcuts import render
def to_dashboard(request):
"""
主界面
"""
param = {"page": "b9b101e"}
return render(request, "html/dashboard.html", param)
def to_share(request):
"""
分享页面
"""
param = {"page": "share"}
return render(request, "html/dashboard.html", param)
def to_echarts(request):
"""
图表页面
"""
param = {"page": "share"}
return render(request, "html/echats.html", param)
def to_chat_room(request):
"""
聊天室页面
"""
param = {"page": "chat_room"}
return render(request, "html/wechat_2.html", param)
def to_rengwu(request):
"""
聊天室页面
"""
param = {"page": "chat_room"}
return render(request, "html/rengwu.html", param)
def to_kecheng(request):
"""
聊天室页面
"""
param = {"page": "chat_room"}
return render(request, "html/kecheng.html", param)
def to_star(request):
"""
收藏页面
"""
param = {"page": "star"}
return render(request, "html/dashboard.html", param)
def to_recycle(request):
"""
回收站
"""
param = {"page": "recycle"}
return render(request, "html/dashboard.html", param)
def to_detail(request):
"""
详情页面
"""
param = {'id': request.GET.get('id')}
return render(request, "html/detail.html", param)
def share_to_detail(request):
"""
详情页面
"""
param = {'h': request.GET.get('h'), 'u': request.GET.get('u')}
return render(request, "html/detail.html", param)
+255
View File
@@ -0,0 +1,255 @@
import uuid
from datetime import datetime as dt
from django_filters.rest_framework import *
from rest_framework.generics import *
from rest_framework.views import APIView
from server.filters import *
from server.pagination import DefaultNumberPagination
from server.serializers import *
from server.util.constant_util import *
from server.util.mix_util import build_response
from server_auth.lib.auth import LoginRequiredJSONMixin
from django.db.models import Exists, OuterRef
class JsMindView(LoginRequiredJSONMixin, ListAPIView):
"""
思维导图view
"""
queryset = CooperationMind.objects.all()
serializer_class = CooperationMindSerializer
filter_backends = [DjangoFilterBackend]
filter_class = CooperationMindFilter
pagination_class = DefaultNumberPagination
def get(self, request, *args, **kwargs):
"""
查询思维导图
"""
pk = request.GET.get('id')
# 页面源
page_tag = request.GET.get('s_p')
user = request.user
if page_tag is None or user.id is None:
return build_response(code=CODE_FAILED, msg="参数错误")
print('list current user: %s' % user)
if pk is not None:
# 查询导图详细 查看用户是否有权限
sql = """
select * from cooperation_mind mind where id=%s and mind.creator_user_id=%s
union all select m1.* from cooperation_mind m1 join cooperation_mind_share sh on sh.coop_mind_id = m1.id where m1.id=%s and sh.operator_user_id =%s
union all select m1.* from cooperation_mind m1 join cooperation_mind_star st on st.coop_mind_id = m1.id where m1.id=%s and st.operator_user_id =%s
""" % (pk, user.id, pk, user.id, pk, user.id)
mind = CooperationMind.objects.raw(sql)
if len(mind) is None:
return build_response(code=CODE_FAILED, msg="无权限")
# 序列化
serializer = CooperationMindSerializer(mind[0])
return build_response(data=serializer.data)
# 查询列表
if 'b9b101e' == page_tag:
# 我的文件
self.queryset = CooperationMind.objects.filter(creator_user_id=user.id, deleted=0).values('id', 'coop_mind_name', "client_uuid", "data_format")
elif 'share' == page_tag:
# 我的分享
share = CooperationMindShare.objects.filter(coop_mind_id=OuterRef('id'), operator_user_id=user.id)
self.queryset = CooperationMind.objects.annotate(share_col=Exists(share), ).filter(share_col=1, deleted=0).values('id', 'coop_mind_name', "client_uuid", "data_format")
elif 'star' == page_tag:
# 我的收藏
star = CooperationMindStar.objects.filter(coop_mind_id=OuterRef('id'), operator_user_id=user.id)
self.queryset = CooperationMind.objects.annotate(star_col=Exists(star), ).filter(star_col=1, deleted=0).values('id', 'coop_mind_name', "client_uuid", "data_format")
elif 'recycle' == page_tag:
# 回收站
self.queryset = CooperationMind.objects.filter(creator_user_id=user.id, deleted=1).values('id', 'coop_mind_name', "client_uuid", "data_format")
else:
# 不返回数据
self.queryset = CooperationMind.objects.filter(creator_user_id=-100).values('id', 'coop_mind_name', "client_uuid", "data_format")
return self.list(request, *args, **kwargs)
def post(self, request):
"""
创建思维导图
"""
user = request.user
coop_mind_name = request.data.get('mind_name')
coop_mind_id = request.data.get('coop_mind_id')
op_type = request.data.get('op_type')
if op_type == "delete_cancel":
CooperationMind.objects.filter(id=coop_mind_id, creator_user_id=user.id).update(deleted=False)
return build_response()
else:
user = request.user
data_format = 'node_tree'
mind = CooperationMind(coop_mind_name=coop_mind_name, client_uuid='', mind_log_id=-1, creator_user_id=user.id, snapshot_data=SNAPSHOT_JSON_DATA, data_format=data_format)
mind.save()
return build_response(data=mind.id)
def delete(self, request):
# 删除
pk = request.POST.get('coop_mind_id')
source = request.POST.get('source')
user = request.user
res = None
if source == 'dashboard':
res = CooperationMind.objects.filter(id=pk, creator_user_id=user.id).update(deleted=True)
elif source == 'recycle':
res = CooperationMind.objects.filter(id=pk, creator_user_id=user.id).delete()
print(res)
return build_response(msg='删除成功')
# Create your views here.
class JsMindLogView(APIView):
"""
日志获取,快照保存
"""
def get(self, request):
"""
查询日志
"""
param = request.GET
coop_mind_id = param.get('coop_mind_id')
cooperation_mind_log_id = param.get('cooperation_mind_log_id')
query_set = CooperationMindLog.objects.filter(coop_mind_id=coop_mind_id, id__gt=cooperation_mind_log_id)
log_list = CooperationMindLogSerializer(query_set, many=True)
return build_response(data=log_list.data)
def post(self, request):
"""
更新保存快照
"""
post_body = request.POST
client_uuid = post_body.get('client_uuid')
type = post_body.get('type')
if 'snapshot' == type:
# 保存快照
coop_mind_id = post_body.get('coop_mind_id')
data = post_body.get('data')
coop_mind_log_id = post_body.get('coop_mind_log_id')
data_format = post_body.get('data_format')
CooperationMind.objects.filter(id=coop_mind_id, mind_log_id__lt=coop_mind_log_id).update(data_format=data_format, snapshot_data=data, mind_log_id=coop_mind_log_id, update_time=dt.now(), client_uuid=client_uuid)
return build_response()
class JsMindShareView(LoginRequiredJSONMixin, ListAPIView):
"""
思维导图分享view
"""
serializer_class = CooperationMindShareSerializer
filter_backends = [DjangoFilterBackend]
filter_class = CooperationMindShareFilter
pagination_class = DefaultNumberPagination
def get(self, request, *args, **kwargs):
"""
通过链接即uuid、hash获得分享的导图详情
"""
share_uuid_hash = request.GET.get('h')
share_uuid = request.GET.get('u')
coop_mind_id = request.GET.get('coop_mind_id')
user = request.user
if user.id is None:
return build_response(code=CODE_FAILED, msg="用户未登录")
#
if share_uuid_hash is not None and share_uuid is not None:
share = CooperationMindShare.objects.filter(share_uuid_hash=share_uuid_hash, share_uuid=share_uuid).first()
if share is None:
return build_response(code=CODE_FAILED, msg='分享不存在')
# 查询mind
mind = CooperationMind.objects.filter(id=share.coop_mind_id).first()
serializer = CooperationMindSerializer(mind)
return build_response(data=serializer.data)
elif coop_mind_id is not None:
# 获得分享链接
share = CooperationMindShare.objects.filter(operator_user_id=user.id, coop_mind_id=coop_mind_id).first()
if share is None:
return build_response(code=CODE_FAILED, msg='分享不存在')
serializer = CooperationMindShareSerializer(share)
return build_response(data=serializer.data)
else:
# 查询列表
self.queryset = CooperationMindShare.objects.filter(operator_user_id=user.id).all()
return self.list(request, *args, **kwargs)
def post(self, request):
"""
分享脑图功能,只有创建人能分享
"""
post_body = request.POST
id = post_body.get('id')
user = request.user
if id is None:
return build_response(code=CODE_FAILED, msg='参数错误')
mind = CooperationMind.objects.filter(id=id, creator_user_id=user.id).first()
if mind is None:
return build_response(code=CODE_FAILED, msg='导图不存在')
# 校验成功
share = CooperationMindShare.objects.filter(coop_mind_id=mind.id, operator_user_id=user.id).first()
if share is None:
uuid_str = str(uuid.uuid4()).replace('-', "")
share_uuid_hash = -1
share = CooperationMindShare(coop_mind_id=mind.id, coop_mind_name=mind.coop_mind_name, share_uuid=uuid_str, share_uuid_hash=share_uuid_hash, operator_user_id=user.id)
share.save()
return build_response(data={"u": uuid_str, "h": share_uuid_hash})
# 重复分享
return build_response(code=DUPLICATE, data={"u": share.share_uuid, "h": share.share_uuid_hash})
def delete(self, request):
"""
"""
post_body = request.POST
id = post_body.get('id')
user = request.user
if id is None:
return build_response(code=CODE_FAILED, msg='参数错误')
if user.id is None:
return build_response(code=CODE_FAILED, msg='用户未登录')
res = CooperationMindShare.objects.filter(coop_mind_id=id, operator_user_id=user.id).delete()
return build_response(msg="操作成功", data=res[0])
class JsMindStarView(LoginRequiredJSONMixin, ListAPIView):
"""
收藏
"""
def get(self, request, *args, **kwargs):
pass
def post(self, request):
user = request.user
post_body = request.POST
# 思维导图id
coop_mind_id = post_body.get('coop_mind_id')
if coop_mind_id is None:
return build_response(CODE_FAILED, msg="参数错误")
mind = CooperationMind.objects.filter(id=coop_mind_id).first()
if mind is None:
return build_response(CODE_FAILED, msg="导图不存在")
star = CooperationMindStar.objects.filter(operator_user_id=user.id, coop_mind_id=coop_mind_id).first()
if star is None:
star = CooperationMindStar(operator_user_id=user.id, coop_mind_id=coop_mind_id, coop_mind_name=mind.coop_mind_name)
star.save()
return build_response(msg="收藏成功")
def delete(self, request):
"""
取消收藏
"""
post_body = request.POST
user = request.user
coop_mind_id = post_body.get('coop_mind_id')
CooperationMindStar.objects.filter(operator_user_id=user.id, coop_mind_id=coop_mind_id).delete()
return build_response(msg="取消收藏,操作成功")
+25
View File
@@ -0,0 +1,25 @@
from django.http.response import JsonResponse
from rest_framework.views import APIView
from server.util.mix_util import build_response
from server_auth.models import MindUser
class MindUserView(APIView):
"""
用户注册
"""
def post(self, request):
data_dict = request.POST
user_name = data_dict.get('userName')
input_password = data_dict.get('inputPassword')
print('userName:%s,inputPassword:%s' % (user_name, input_password))
# 根据用户名查询 MindUser
db_user = MindUser.objects.filter(username=user_name).first()
if db_user is not None:
return build_response(code=-1, msg='用户名:%s 已经存在,请更换!' % user_name)
MindUser.objects.create_user(username=user_name, password=input_password, email='')
return JsonResponse({"code": 0, "msg": "注册成功,跳转登录界面中"})
View File
Binary file not shown.
+48
View File
@@ -0,0 +1,48 @@
import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from server.lib.coope_mind_lib import CooperationMindLogLib
class ChatConsumer(WebsocketConsumer):
log_lib = CooperationMindLogLib()
def connect(self):
self.room_group_name = 'chat%s' % bytes.decode(self.scope['query_string'])
# print(self.room_group_name)
# Join room group
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self, close_code):
# Leave room group
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
# Receive message from WebSocket
def receive(self, text_data):
# Send message to room group
log_dict = self.log_lib.save_log(text_data)
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
# chat_message 方法
'type': 'chat_message',
'message': text_data if log_dict is None else json.dumps(log_dict)
}
)
# Receive message from room group
def chat_message(self, event):
message = event['message']
# Send message to WebSocket
self.send(text_data=message)
+59
View File
@@ -0,0 +1,59 @@
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from server.lib.qr_context import get_context
# 获得一个环境变量
qrContext = get_context()
class QrConsumer(WebsocketConsumer):
"""
扫码进度websocket
"""
def connect(self):
self.room_group_name = 'qr%s' % bytes.decode(self.scope['query_string'])
self.channel_name = 'qr_cn%s' % bytes.decode(self.scope['query_string'])
print(self.room_group_name)
print(self.channel_name)
# Join room group
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
self.send(text_data=self.channel_name)
qrContext.add(self.channel_name, self)
def disconnect(self, close_code):
# Leave room group
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
qrContext.remove(self.channel_name)
print('close')
# Receive message from WebSocket
def receive(self, text_data=None, bytes_data=None):
# Send message to room group
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
# chat_message 方法
'type': 'chat_message',
'message': '成功获得二维码'
}
)
# Receive message from room group
def chat_message(self, event):
message = event['message']
# Send message to WebSocket
self.send(text_data=message)
def sed_text(self, text):
self.send(text_data=text)
+9
View File
@@ -0,0 +1,9 @@
from django.urls import re_path
from . import consumers
from . import consumers_qr
websocket_urlpatterns = [
re_path(r'ws/jsmind/$', consumers.ChatConsumer.as_asgi()),
re_path(r'ws/qr/$', consumers_qr.QrConsumer.as_asgi()),
]
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class ServerAuthConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'server_auth'
View File
Binary file not shown.
Binary file not shown.
+80
View File
@@ -0,0 +1,80 @@
from django import http
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend # 验证基类
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.urls import reverse
from rest_framework.views import APIView
from server.util.constant_util import *
from server.util.mix_util import build_response
class AuthBackend(ModelBackend):
"""
login 方法会调用该方法
"""
pass
# 重写验证方式
# def authenticate(self, request, username=None, password=None, **kwargs):
# user = MindUser.objects.get(id=1)
# if user is not None and user.check_password(password):
# return user
# 登录方式有多种
# 1、用户名密码登录:直接匹配数据库的用户名密码
# 2、微信扫码登录:1、生成带标记的二维码 2、用户扫码 3、微信通知服务器端 4、服务器校验是否有注册,如果没有注册则新增用户 5、服务器通知前端界面
# 3、手机号短信验证码登录 1、发送短信验证码 2、用户界面向服务器提交手机号和验证码 3、服务器请求短服务商 4、服务器校验是否有注册,如果没有注册则新增用户
class LoginView(APIView):
"""
"""
def post(self, request):
username = request.POST.get('username')
password = request.POST.get('password')
# django内置认证来校验登录用户
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
# 记住登录状态
login(request, user)
return build_response(msg='登录成功')
else:
return build_response(code=CODE_FAILED, msg='登录失败')
else:
return build_response(code=CODE_FAILED, msg='登录失败')
class LogoutView(APIView):
"""
注销
"""
def get(self, request):
logout(request)
return build_response(msg='注销成功')
def post(self, request):
logout(request)
return build_response(msg='注销成功')
class LoginRequiredJSONMixin(LoginRequiredMixin):
"""自定义LoginRequiredMixin
如果用户未登录,响应JSON,且状态码为400
"""
def handle_no_permission(self):
# return build_response(code=CODE_FAILED, msg='用户未登录!')
return http.JsonResponse({'code': CODE_FAILED, 'msg': '用户未登录'})
+46
View File
@@ -0,0 +1,46 @@
# Generated by Django 3.2.11 on 2022-06-29 08:18
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='MindUser',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('wx_openid', models.CharField(blank=True, max_length=64, null=True, verbose_name='微信openid')),
('wx_nick_name', models.CharField(blank=True, max_length=64, null=True, verbose_name='微信名称')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': '脑图用户表',
'db_table': 'mind_user',
'ordering': ['-id'],
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
View File
+15
View File
@@ -0,0 +1,15 @@
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class MindUser(AbstractUser):
# 继承了AbstractUser拥有的所有字段
# 自定义我们需要的字段
wx_openid = models.CharField(verbose_name='微信openid', max_length=64, null=True, blank=True)
wx_nick_name = models.CharField(verbose_name='微信名称', max_length=64, null=True, blank=True)
class Meta:
db_table = 'mind_user'
ordering = ['-id']
verbose_name = "脑图用户表"
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+9
View File
@@ -0,0 +1,9 @@
from django.shortcuts import render
# Create your views here.
def fetch_qr_code(request):
"""
获得二维码
"""
pass
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+325
View File
@@ -0,0 +1,325 @@
/*!
* Bootstrap Reboot v4.6.1 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
html {
font-family: sans-serif;
line-height: 1.15;
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
article, aside, figcaption, figure, footer, header, hgroup, main, nav, section {
display: block;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", "Liberation Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #212529;
text-align: left;
background-color: #fff;
}
[tabindex="-1"]:focus:not(:focus-visible) {
outline: 0 !important;
}
hr {
box-sizing: content-box;
height: 0;
overflow: visible;
}
h1, h2, h3, h4, h5, h6 {
margin-top: 0;
margin-bottom: 0.5rem;
}
p {
margin-top: 0;
margin-bottom: 1rem;
}
abbr[title],
abbr[data-original-title] {
text-decoration: underline;
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
cursor: help;
border-bottom: 0;
-webkit-text-decoration-skip-ink: none;
text-decoration-skip-ink: none;
}
address {
margin-bottom: 1rem;
font-style: normal;
line-height: inherit;
}
ol,
ul,
dl {
margin-top: 0;
margin-bottom: 1rem;
}
ol ol,
ul ul,
ol ul,
ul ol {
margin-bottom: 0;
}
dt {
font-weight: 700;
}
dd {
margin-bottom: .5rem;
margin-left: 0;
}
blockquote {
margin: 0 0 1rem;
}
b,
strong {
font-weight: bolder;
}
small {
font-size: 80%;
}
sub,
sup {
position: relative;
font-size: 75%;
line-height: 0;
vertical-align: baseline;
}
sub {
bottom: -.25em;
}
sup {
top: -.5em;
}
a {
color: #007bff;
text-decoration: none;
background-color: transparent;
}
a:hover {
color: #0056b3;
text-decoration: underline;
}
a:not([href]):not([class]) {
color: inherit;
text-decoration: none;
}
a:not([href]):not([class]):hover {
color: inherit;
text-decoration: none;
}
pre,
code,
kbd,
samp {
font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
font-size: 1em;
}
pre {
margin-top: 0;
margin-bottom: 1rem;
overflow: auto;
-ms-overflow-style: scrollbar;
}
figure {
margin: 0 0 1rem;
}
img {
vertical-align: middle;
border-style: none;
}
svg {
overflow: hidden;
vertical-align: middle;
}
table {
border-collapse: collapse;
}
caption {
padding-top: 0.75rem;
padding-bottom: 0.75rem;
color: #6c757d;
text-align: left;
caption-side: bottom;
}
th {
text-align: inherit;
text-align: -webkit-match-parent;
}
label {
display: inline-block;
margin-bottom: 0.5rem;
}
button {
border-radius: 0;
}
button:focus:not(:focus-visible) {
outline: 0;
}
input,
button,
select,
optgroup,
textarea {
margin: 0;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
button,
input {
overflow: visible;
}
button,
select {
text-transform: none;
}
[role="button"] {
cursor: pointer;
}
select {
word-wrap: normal;
}
button,
[type="button"],
[type="reset"],
[type="submit"] {
-webkit-appearance: button;
}
button:not(:disabled),
[type="button"]:not(:disabled),
[type="reset"]:not(:disabled),
[type="submit"]:not(:disabled) {
cursor: pointer;
}
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
padding: 0;
border-style: none;
}
input[type="radio"],
input[type="checkbox"] {
box-sizing: border-box;
padding: 0;
}
textarea {
overflow: auto;
resize: vertical;
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
display: block;
width: 100%;
max-width: 100%;
padding: 0;
margin-bottom: .5rem;
font-size: 1.5rem;
line-height: inherit;
color: inherit;
white-space: normal;
}
progress {
vertical-align: baseline;
}
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
[type="search"] {
outline-offset: -2px;
-webkit-appearance: none;
}
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-file-upload-button {
font: inherit;
-webkit-appearance: button;
}
output {
display: inline-block;
}
summary {
display: list-item;
cursor: pointer;
}
template {
display: none;
}
[hidden] {
display: none !important;
}
/*# sourceMappingURL=bootstrap-reboot.css.map */
File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More