Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
最终版
  • Loading branch information
suzxzd committed Jun 19, 2024
1 parent 40fdf25 commit 75e8675
Show file tree
Hide file tree
Showing 26 changed files with 478 additions and 179 deletions.
7 changes: 1 addition & 6 deletions .idea/MQTT.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 1 addition & 4 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file modified main/__pycache__/mysql.cpython-310.pyc
Binary file not shown.
Binary file modified main/__pycache__/mysql.cpython-311.pyc
Binary file not shown.
8 changes: 6 additions & 2 deletions main/client/Client.py
Expand Up @@ -62,6 +62,7 @@ def clientStart(self):#启动进程,使用threading(python自带进程管理
class Register(Client):
def __init__(self,userName,userPwd):
super().__init__(userName,userPwd)
self.flag=False #标志注册是否成功
self.clientStart()
self.publishRegister()

Expand All @@ -84,6 +85,7 @@ def on_message(self,client, userdata, msg):#接受数据
if code==0:
print(message)
if code==1:
self.flag=True #成功了更新
print(message)
return data

Expand All @@ -99,6 +101,7 @@ def publishRegister(self):
class Login(Client):
def __init__(self,userName,userPwd):
super().__init__(userName,userPwd)
self.flag=False
self.clientStart()
self.publishLogin()

Expand All @@ -120,6 +123,7 @@ def on_message(self,client, userdata, msg):#接受数据
if code==0: #表示登入失败
print(message)
if code==1: #表示登入成功
self.flag=True
print(message)
return data

Expand Down Expand Up @@ -154,7 +158,7 @@ def on_message(self, client, userdata, msg): # 接受数据

messages = eval(msg.payload.decode('utf-8'))
# 读取数据
self.messages=messages #存到类中
self.messages=messages #返回一个字典的列表,['id':id,'senderID':senderID,'message':message]存到类中
print(messages)


Expand Down Expand Up @@ -301,7 +305,7 @@ def reset_password(self, answer, new_password):

####################################################################
def main():

SendMessage("1234","1234")



Expand Down
Binary file modified main/config/__pycache__/config.cpython-310.pyc
Binary file not shown.
Binary file modified main/config/__pycache__/config.cpython-311.pyc
Binary file not shown.
11 changes: 7 additions & 4 deletions main/mysql.py
Expand Up @@ -33,6 +33,7 @@ class ChatModel(BaseModel):
message = TextField()
senderId=BigIntegerField()
time = DateTimeField(default=datetime.datetime.now)
senderName=CharField(max_length=64)
class Meta:
db_table = 'chat'

Expand All @@ -49,7 +50,7 @@ class CreateTable:
@staticmethod
def create():
db.connect()
db.create_tables([UserModel, ChatModel,LikeModel])
db.create_tables([UserModel, ChatModel,LikeModel,SecurityQuestionModel])



Expand Down Expand Up @@ -121,7 +122,8 @@ def getAllManage():
'id': chat.id,
'message': chat.message,
'senderId': chat.senderId,
'time': chat.time
'time': chat.time,
'senderName':chat.senderName
}
chat_list.append(chat_data)
return chat_list
Expand All @@ -130,9 +132,9 @@ def getAllManage():
return None

@staticmethod
def AddChat(message,senderId):
def AddChat(message,senderId,senderName):
try:
ChatModel.insert(message=message,senderId=senderId).execute()
ChatModel.insert(message=message,senderId=senderId,senderName=senderName).execute()
return True
except Exception as error:
print(error)
Expand Down Expand Up @@ -243,3 +245,4 @@ def reset_password(user_name, new_password):
print(f"发生错误: {error}")
return False

CreateTable.create()
112 changes: 77 additions & 35 deletions main/server/Server.py
Expand Up @@ -146,45 +146,89 @@ def __init__(self):
super().__init__()
self.serverStart()


def on_connect(self, client, userdata, flags, rc):
if rc == 0:
print("Connected successfully")
client.subscribe('like')
client.subscribe('login') # 订阅 login 主题
else:
print("Failed to connect, return code %d\n", rc)

def on_message(self, client, userdata, msg):
data = eval(msg.payload.decode('utf-8'))
messageId = data.get('message_id')
returnTopic = data.get('returnTopic')
print("Publishing to topic:", returnTopic)
self.like_message(messageId, returnTopic)
def like_message(self, messageId, returnTopic):
like_count = LikeManage.like_message(messageId)
if like_count is not None:
data = {'code': 1, 'like_count': like_count}
self.client.publish(returnTopic, str(data).encode(), 1)
else:
data = {'code': 0, 'message': '点赞失败'}
self.client.publish(returnTopic, str(data).encode(), 1)




class SecurityServer(Server):
def __init__(self):
super().__init__()
self.serverStart()

def on_connect(self, client, userdata, flags, rc):
if rc == 0:
print("连接成功")
client.subscribe('set_security_question')
client.subscribe('request_security_question',)
client.subscribe('verify_security_answer')
else:
print("连接失败,返回码 %d\n", rc)

def on_message(self, client, userdata, msg):
# 规定传入数据均为dict的形式
if msg.topic == 'like':
data = eval(msg.payload.decode('utf-8'))
messageId = data.get('message_id')
returnTopic = data.get('return_topic')

if not messageId:
print("Invalid message format")
return


# 更新点赞数量
new_count = LikeManage.like_message(messageId)

if new_count is None:
print(f"Failed to update like count for message ID: {messageId}")
return

print(f'处理并新的点赞计数成功')
# 此处可以输出最高点赞的消息ID
try:
top_message_id = LikeModel.select().order_by(LikeModel.count.desc()).get()
if top_message_id:
print(f'Top liked message ID: {top_message_id}')
else:
print('No top liked message found.')
except Exception as e:
print(f"Error retrieving top liked message: {e}")
data = eval(msg.payload.decode('utf-8'))
if msg.topic == 'set_security_question':
user_name = data.get('userName')
question = data.get('question')
answer = data.get('answer')
returnTopic = data.get('returnTopic')
success = SecurityQuestionManage.set_security_question(user_name, question, answer)
if success == True:
code = 1
else:
code = 0
data = {
'action': 'set_question',
'code': code
}
client.publish(returnTopic, str(data).encode(), 1)

elif msg.topic == 'request_security_question':
user_name = data.get('userName')
returnTopic = data.get('returnTopic')

user = UserModel.get(UserModel.name == user_name)
security_question = SecurityQuestionModel.get(SecurityQuestionModel.user_id == user.id)
data = {
'action': 'request_question',
'question': security_question.question
}
client.publish(returnTopic, str(data).encode(), 1)

elif msg.topic == 'verify_security_answer':
user_name = data.get('userName')
answer = data.get('answer')
newPassword = data.get('new_password')
returnTopic = data.get('returnTopic')
success = SecurityQuestionManage.verify_security_answer(user_name, answer, newPassword)
if success: code = 1
else: code = 0
data = {
'action': 'verify_security_answer',
'code': code
}
client.publish(returnTopic, str(data).encode(), 1)

###################################################################################
#jia yikun
class ChatSave(Server):
Expand All @@ -206,15 +250,15 @@ def on_message(self, client, userdata, msg):
data = eval(msg.payload.decode('utf-8'))
message = data.get('message')
userName = data.get('userName')
print(data)
returnTopic = data.get('returnTopic')
user=UserManage.chackName(userName)
if user == None:
data = {'code': 0, 'message': "消息发送失败,找不到用户"}
self.client.publish(returnTopic, str(data).encode(), 1)
else:
print('new_message ',user.id,':', message)
chat = ChatManage()
if chat.AddChat(message, user.id):
if ChatManage.AddChat(message, user.id,userName):
data = {'code': 1, 'message': "消息发送成功"}
self.client.publish(returnTopic, str(data).encode(), 1)
else:
Expand All @@ -241,8 +285,6 @@ def on_message(self, client, userdata, msg):
returnTopic = data.get('returnTopic')
chat = ChatManage()
payload = str(chat.getAllManage())
print('历史消息为:')
print(payload)
return self.client.publish(returnTopic, payload=payload, qos=2, retain=False)


Expand All @@ -254,6 +296,6 @@ def main():
b=Login() #进程2,处理登入
c=Like() #进程3,处理点赞
d=ChatAll() #进程4,处理所有消息
e=ChatSave() #进程5,处理消息报存
e=ChatSave() #进程5,处理消息保存

main()
75 changes: 75 additions & 0 deletions requirements.txt
@@ -0,0 +1,75 @@
appnope==0.1.4
asgiref==3.7.2
asttokens==2.4.1
attrs==23.2.0
backcall @ file:///home/ktietz/src/ci/backcall_1611930011877/work
beautifulsoup4==4.12.3
bleach==6.1.0
Brotli @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_38mvgltu8c/croots/recipe/brotli-split_1659616064542/work
certifi==2023.11.17
charset-normalizer==3.3.2
colorama @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_100_k35lkb/croot/colorama_1672386539781/work
decorator @ file:///opt/conda/conda-bld/decorator_1643638310831/work
defusedxml @ file:///tmp/build/80754af9/defusedxml_1615228127516/work
Django==4.2
django-cors-headers==4.3.1
django-filter==24.2
djangorestframework==3.14.0
djangorestframework-simplejwt==5.3.1
docopt @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_5alx0ctp1q/croots/recipe/docopt_1663662430075/work
et-xmlfile==1.1.0
executing==2.0.1
fastjsonschema==2.19.1
gunicorn==22.0.0
idna==3.6
ipython==8.12.3
jedi==0.19.1
Jinja2==3.1.3
jsonschema==4.21.1
jsonschema-specifications==2023.12.1
jupyter_client==8.6.1
jupyter_core==5.7.2
jupyterlab_pygments==0.3.0
Markdown==3.6
MarkupSafe==2.1.5
matplotlib-inline @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_f6fdc0hldi/croots/recipe/matplotlib-inline_1662014472341/work
mistune==3.0.2
mysqlclient==2.2.4
nbclient==0.10.0
nbconvert==7.16.2
nbformat==5.10.3
openpyxl==3.1.2
packaging==24.0
paho-mqtt==2.1.0
pandocfilters==1.5.1
parso @ file:///opt/conda/conda-bld/parso_1641458642106/work
pexpect==4.9.0
pickleshare @ file:///tmp/build/80754af9/pickleshare_1606932040724/work
pipreqs==0.5.0
platformdirs==4.2.0
prompt-toolkit @ file:///private/var/folders/k1/30mswbxs7r1g6zwn8y4fyt500000gp/T/abs_c63v4kqjzr/croot/prompt-toolkit_1704404354115/work
ptyprocess==0.7.0
pure-eval==0.2.2
Pygments==2.17.2
PyJWT==2.8.0
PyMySQL==1.1.0
PySocks @ file:///Users/ktietz/ci_310/pysocks_1643961536721/work
python-dateutil==2.9.0.post0
pytz==2024.1
pyzmq @ file:///private/var/folders/k1/30mswbxs7r1g6zwn8y4fyt500000gp/T/abs_43pxpbos3z/croot/pyzmq_1705605108344/work
referencing==0.33.0
requests @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_b3tnputioh/croot/requests_1707355573919/work
rpds-py==0.18.0
six @ file:///tmp/build/80754af9/six_1644875935023/work
soupsieve @ file:///private/var/folders/k1/30mswbxs7r1g6zwn8y4fyt500000gp/T/abs_9798xzs_03/croot/soupsieve_1696347567192/work
sqlparse @ file:///private/var/folders/k1/30mswbxs7r1g6zwn8y4fyt500000gp/T/abs_16ptvrhamb/croot/sqlparse_1690901943673/work
stack-data==0.6.3
tinycss2 @ file:///private/var/folders/nz/j6p8yfhx1mv_0grj5xl4650h0000gp/T/abs_fcw5_i306t/croot/tinycss2_1668168825117/work
tornado==6.4
traitlets==5.14.2
typing_extensions==4.9.0
tzdata==2023.4
urllib3 @ file:///private/var/folders/k1/30mswbxs7r1g6zwn8y4fyt500000gp/T/abs_aff2m3lasf/croot/urllib3_1707770561896/work
wcwidth==0.2.13
webencodings==0.5.1
yarg==0.1.9
Binary file modified su/myproject/mqtt/__pycache__/__init__.cpython-310.pyc
Binary file not shown.
Binary file modified su/myproject/mqtt/__pycache__/forms.cpython-310.pyc
Binary file not shown.
Binary file modified su/myproject/mqtt/__pycache__/views.cpython-310.pyc
Binary file not shown.

0 comments on commit 75e8675

Please sign in to comment.