Notes
Notes - notes.io |
import time
import hashlib
import random
import sys
import string
import threading
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBox, QDialog,
QGroupBox, QGridLayout, QVBoxLayout, QComboBox, QLabel
from PyQt5.QtCore import pyqtSlot
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
return IP
no_cipher = False
if(len(sys.argv) > 1):
if sys.argv[1] == "--no-cipher":
no_cipher = True
discovery_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
messaging_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
active_chat = None
HOST = '127.0.0.1'
discovery_port = 5000
messaging_port = 5001
own_name = ''
own_ip = get_ip()
tokens = own_ip.split('.')
own_prefix = tokens[0]+'.'+tokens[1]+'.'+tokens[2]
def random_string(size=33):
chars = 'abcdef' + string.digits
return ''.join(random.choice(chars) for _ in range(size))
class ChatConnection:
def __init__(self, ip):
self.ip = ip
self.name = None
self.cipher = None
self.lastDiscovered = None
self.messages = []
self.lock = threading.Lock()
def setName(self, name):
self.name = name
def updateCipher(self):
if no_cipher:
self.cipher = random_string().encode('ascii')
return
if not self.cipher:
self.cipher = random_string().encode('ascii')
else:
self.cipher = hashlib.md5(self.cipher).hexdigest().encode('ascii')
def chat_to_string(self):
chat = "Chat with " + self.name + ":n"
for msg in self.messages:
chat = chat + msg[0] + ": " + msg[1] + "n"
return chat
def incomingCipher(self, inc):
if no_cipher:
return True
if not self.cipher:
self.cipher = inc.encode('ascii')
return True
else:
if hashlib.md5(self.cipher).hexdigest().encode('ascii') == inc.encode('ascii'):
self.cipher = inc.encode('ascii')
return True
return False
def incoming_message(self, cipher, message):
if self.incomingCipher(cipher):
self.messages.append((self.name, message))
if active_chat is not None:
if active_chat.chat.ip == self.ip:
active_chat.setText()
else:
print("Invalid cipher received")
def send_message(self,msg):
try:
self.updateCipher()
message = own_ip + ";" + self.cipher.decode('ascii') + ";" + msg
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(0.1)
s.connect((self.ip, messaging_port ))
s.sendall(message.encode('ascii'))
self.messages.append((own_name, msg))
except Exception as ex:
print("Error occured while sending the message", ex)
return
def incoming_discovery(self, message):
fields = message.split(';')
if len(fields) != 5:
return
if fields[1] != self.ip:
return
if fields[3] != own_ip:
return
if fields[0] == '0':
self.name = fields[2]
self.send_discovery_response()
elif fields[0] == '1':
if self.lastDiscovered is None:
self.lastDiscovered = time.time()
else:
now = time.time()
if (now - self.lastDiscovered) < 5:
self.lastDiscovered = now
return
else:
self.lastDiscovered = now
self.name = fields[2]
pass
else:
return
def send_discovery_request(self):
request = "0;"+ own_ip +";" + own_name + ";" + self.ip + ";" +"unknown"
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(0.1)
s.connect((self.ip, discovery_port))
s.sendall(request.encode('ascii'))
except Exception as ex:
print("Couldn't send discovery request", ex)
return
def send_discovery_response(self):
response = "1;"+ own_ip +";" + own_name + ";" + self.ip + ";" + self.name
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((self.ip, discovery_port ))
s.sendall(response.encode('ascii'))
except:
print("Couldn't send discovery response")
return
chatList = []
for i in range(256):
chatList.append(ChatConnection(own_prefix + '.' + str(i)))
def send_discoveries_batch():
for i in range(256):
chatList[i].send_discovery_request()
def online_users():
active_users = []
for i in range(256):
if chatList[i].name is not None:
active_users.append(chatList[i])
return active_users
class DiscoveryListener(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
print('initializing discovery thread')
def run(self):
discovery_socket.bind((own_ip, discovery_port))
discovery_socket.listen()
while True:
conn, addr = discovery_socket.accept()
with conn:
message = ""
while True:
data = conn.recv(1024)
print(data)
if not data:
received_from = int(addr[0].split('.')[3])
self.discovered(message, received_from)
break
message = message + data.decode('ascii')
def discovered(self, message, postfix):
chat = chatList[postfix]
chat.lock.acquire()
chat.incoming_discovery(message)
chat.lock.release()
class MessageListener(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
print('initializing message receive thread')
def run(self):
messaging_socket.bind((own_ip, messaging_port))
messaging_socket.listen()
while True:
conn, addr = messaging_socket.accept()
with conn:
message = ""
while True:
data = conn.recv(1024)
if not data:
received_from = int(addr[0].split('.')[3])
self.received(message, received_from)
break
message = message + data.decode('ascii')
def received(self,message, postfix):
recv_tokens = message.split(';')
if int(postfix) != int(recv_tokens[0].split('.')[3]):
return
chat = chatList[int(postfix)]
chat.lock.acquire()
chat.incoming_message(recv_tokens[1],recv_tokens[2])
chat.lock.release()
class NameDialog(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 textbox - pythonspot.com'
self.left = 10
self.top = 10
self.width = 400
self.height = 140
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox
self.textbox = QLineEdit(self)
self.textbox.move(20, 20)
self.textbox.resize(280, 40)
# Create a button in the window
self.button = QPushButton('Set name', self)
self.button.move(20, 80)
# connect button to function on_click
self.button.clicked.connect(self.on_click)
self.show()
@pyqtSlot()
def on_click(self):
textboxValue = self.textbox.text()
global own_name
own_name= textboxValue
self.textbox.setText("Other ips are being discovered")
self.textbox.setDisabled(True)
self.button.setText("Waiting")
self.button.setDisabled(True)
QMessageBox.question(self, 'Press Ok to discover ips', "Your name: " + textboxValue +", Your ip: " + own_ip , QMessageBox.Ok,
QMessageBox.Ok)
send_discoveries_batch()
self.close()
class ChatDialog(QDialog):
def __init__(self, chat):
super().__init__()
self.title = 'Chat'
self.left = 10
self.top = 10
self.width = 640
self.height = 300
self.chat = chat
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.createGridLayout()
windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)
self.show()
def setText(self):
self.chatBox.setText(self.chat.chat_to_string())
def send_message(self):
self.chat.send_message(self.textbox.text())
self.setText()
def createGridLayout(self):
self.horizontalGroupBox = QGroupBox("Chat")
layout = QGridLayout()
layout.setRowStretch(0, 10)
layout.setRowStretch(1, 4)
self.chatBox = QLabel()
self.setText()
self.send_button = QPushButton("send")
self.send_button.clicked.connect(self.send_message)
self.textbox = QLineEdit(self)
layout.addWidget(self.chatBox)
layout.addWidget(self.textbox, 1, 0)
layout.addWidget(self.send_button, 1, 1)
self.horizontalGroupBox.setLayout(layout)
class App(QDialog):
def __init__(self):
super().__init__()
self.title = 'PyQt5 layout - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 100
self.userList = online_users()
self.selected_user = None
self.init_combo()
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.createGridLayout()
windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)
self.show()
def on_refresh(self):
self.layout.removeWidget(self.combo)
self.combo.deleteLater()
self.combo = None
self.layout.update()
self.init_combo()
self.layout.addWidget(self.combo,0,0)
self.layout.update()
def on_start(self):
currChat = chatList[int(self.selected_user)]
global active_chat
self.extra = ChatDialog(currChat)
active_chat = self.extra
self.extra.exec_()
def set_selected_ip(self,text):
self.selected_user = text.split(" ")[0].split(".")[3]
def init_combo(self):
self.combo = QComboBox(self)
self.userList = online_users()
for u in self.userList:
self.combo.addItem(u.ip + " " + u.name)
self.selected_user = self.userList[0].ip.split(".")[3]
self.combo.activated[str].connect(self.set_selected_ip)
def createGridLayout(self):
self.horizontalGroupBox = QGroupBox("Grid")
self.layout = QGridLayout()
self.layout.setColumnStretch(0, 10)
self.layout.setColumnStretch(1, 4)
refresh_button = QPushButton('Refresh List')
refresh_button.clicked.connect(self.on_refresh)
open_button = QPushButton('Open Chat')
open_button.clicked.connect(self.on_start)
self.layout.addWidget(refresh_button, 0, 1)
self.layout.addWidget(self.combo, 0, 0)
self.layout.addWidget(open_button, 1, 1)
self.horizontalGroupBox.setLayout(self.layout)
disc_thread = DiscoveryListener()
msg_thread = MessageListener()
msg_thread.start()
disc_thread.start()
app = QApplication(sys.argv)
ex = NameDialog()
app.exec_()
ex = App()
sys.exit(app.exec_())
|
Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...
With notes.io;
- * You can take a note from anywhere and any device with internet connection.
- * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
- * You can quickly share your contents without website, blog and e-mail.
- * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
- * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.
Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.
Easy: Notes.io doesn’t require installation. Just write and share note!
Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )
Free: Notes.io works for 12 years and has been free since the day it was started.
You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;
Email: [email protected]
Twitter: http://twitter.com/notesio
Instagram: http://instagram.com/notes.io
Facebook: http://facebook.com/notesio
Regards;
Notes.io Team