-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
318 lines (253 loc) · 11.3 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import json
import sqlite3
import sys
from twisted.internet.protocol import Protocol, Factory, ServerFactory
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
from datetime import datetime
import netifaces as ni
class CsharpProtocol(Protocol):
def connectionMade(self):
print("C# baglandı")
def dataReceived(self, data):
self.data_json = self.getJson(data)
komut = self.data_json["komut"]
if komut == "getRowIdS":
dataToGo = bytes(json.dumps([{"count": self.getCount(), "rowIdS": self.getRowId()}]) + "\n", "utf-8")
self.transport.write(dataToGo)
elif komut == "check":
dataToGo = bytes("ok" + "\n", "utf-8")
self.transport.write(dataToGo)
elif komut == "ekle":
self.duyuruEkle(self.data_dict["kullanici"], self.data_dict["baslik"], self.data_dict["duyuru"],
self.data_dict["giris_tarih"], self.data_dict["cikis_tarih"], self.data_dict["duyuru_tur"])
dataToGo = bytes(json.dumps([{"status": "ok"}]) + "\n", "utf-8")
if self.data_dict["duyuru_tur"] == "aktif":
self.factory.broadcast(json.dumps({"duyuruCheck": True}))
self.transport.write(dataToGo)
elif komut == "yenile":
self.reqRowId = int(self.data_dict["rowid"])
dataToGo = bytes(json.dumps(self.yenileDuyuru(self.reqRowId)) + "\n", "utf-8")
self.transport.write(dataToGo)
elif komut == "sil":
self.duyuruSil(self.data_dict["rowid"])
dataToGo = bytes(json.dumps([{"status": "ok"}]) + "\n", "utf-8")
if self.data_dict["tur"] == "aktif":
self.factory.broadcast(json.dumps({"duyuruCheck": True}))
self.transport.write(dataToGo)
elif komut == "yolla":
msg = "{} from {}".format(self.data_dict["msg"], self.peer)
self.factory.broadcast(msg)
elif komut == "setAyarlar":
self.ayarGuncelle(self.data_dict["sayfaArkaPlan"], self.data_dict["duyuruArkaPlan"],
self.data_dict["metinRengi"],
self.data_dict["metinFontu"], self.data_dict["donusSure"])
dataToGo = bytes(json.dumps([{"status": "ok"}]) + "\n", "utf-8")
self.transport.write(dataToGo)
self.factory.broadcast(json.dumps({"ayarCheck": True}))
elif komut == "getAyarlar":
dataToGo = bytes(json.dumps({"ayarlar": self.getAyarlar()}) + "\n", "utf-8")
#self.factory.broadcast("yeniAyar")
self.transport.write(dataToGo)
def connectionLost(self, reason):
print(reason)
def getJson(self, data):
self.data_dict = str(data, "utf-8")
self.data_dict = json.loads(self.data_dict)
return self.data_dict
def getAyarlar(self):
try:
conn = sqlite3.connect('duyuruDB.db')
c = conn.cursor()
c.execute('SELECT * FROM ayarlar')
row = c.fetchone()
rowsList = [row[0], row[1], row[2], row[3], row[4]]
# dataToGO = bytes(json.dumps(rowsListed) + "\n", "utf-8")
return rowsList
except sqlite3.OperationalError:
print("Operational Error:", sys.exc_info()[1])
def ayarGuncelle(self, sayfaArkaRenk, duyuruArkaRenk, metinRenk, metinFont, interval):
try:
conn = sqlite3.connect('duyuruDB.db')
c = conn.cursor()
c.execute('DELETE FROM ayarlar')
c.execute('INSERT INTO ayarlar VALUES (?, ?, ?, ?, ?)',
[sayfaArkaRenk, duyuruArkaRenk, metinRenk, metinFont, interval])
conn.commit()
conn.close()
except sqlite3.OperationalError:
print("Operational Error:", sys.exc_info()[1])
def duyuruEkle(self, kullanici, baslik, duyuru, giris_tarih, cikis_tarih, duyuru_tur):
# DUYURU EKLEME
try:
conn = sqlite3.connect('duyuruDB.db')
c = conn.cursor()
c.execute('INSERT INTO duyuru VALUES (?, ?, ?, ?, ?, ? )',
[kullanici, baslik, duyuru, giris_tarih, cikis_tarih, duyuru_tur])
conn.commit()
conn.close()
except sqlite3.OperationalError:
print("Operational Error:", sys.exc_info()[1])
def yenileDuyuru(self, reqRowId):
# tablonun son halini alıp, json a cevirip, sonra byte a ceviriyor.
#PATLAYACAK MUHTEMELEN VERI SILININCE...
try:
conn = sqlite3.connect('duyuruDB.db')
c = conn.cursor()
c.execute('SELECT rowid, * FROM duyuru WHERE rowid = (?)', [reqRowId])
rows = c.fetchall()
rowsListed = [{"rowid": row[0], "kullanici": row[1], "baslik": row[2], "duyuru": row[3],
"giris_tarih": row[4], "cikis_tarih": row[5], "duyuru_tur": row[6]} for row in rows]
#dataToGO = bytes(json.dumps(rowsListed) + "\n", "utf-8")
return rowsListed
except sqlite3.OperationalError:
print("Operational Error:", sys.exc_info()[1])
def duyuruSil(self, reqRowId):
try:
conn = sqlite3.connect('duyuruDB.db')
c = conn.cursor()
c.execute('DELETE FROM duyuru WHERE rowid = (?)', [reqRowId])
conn.commit()
conn.close()
except sqlite3.OperationalError:
print("Operational Error:", sys.exc_info()[1])
def getCount(self):
conn = sqlite3.connect('duyuruDB.db')
c = conn.cursor()
c.execute('SELECT count(*) FROM duyuru')
count = c.fetchone()
return [count[0]]
def getRowId(self):
conn = sqlite3.connect('duyuruDB.db')
c = conn.cursor()
c.execute('SELECT rowid FROM duyuru')
rowIdS = c.fetchall()
rowIdS = [k[0] for k in rowIdS]
return rowIdS
class ClientHtmlProtocol(WebSocketServerProtocol):
def onOpen(self):
#if len(self.factory.clients) != 0:
# self.factory.clients = []
self.factory.register(self)
def onMessage(self, payload, isBinary):
komut = payload.decode('utf8')
if komut == "aktif":
duyurular = self.aktifDuyurular()
duyurular = json.dumps({"duyurular": duyurular})
self.sendMessage(duyurular.encode('utf8'))
#self.factory.broadcast(duyurular)
elif komut == "ayarlar":
#burdaki ve yukardaki broadcast birden fazla client.html bagladıgımız zaman sacmaliyor. daha sonra düzelt buraları
#şimdilik tek bir client.html e izin ver.
ayarlar = self.getAyarlar()
ayarlar = json.dumps({"ayarlar": ayarlar})
self.sendMessage(ayarlar.encode('utf8'))
#self.factory.broadcast(ayarlar)
elif komut == "ip":
addr = self.getIp();
addr = json.dumps({"ip": addr})
self.sendMessage(addr.encode('utf8'))
def getIp(self):
return ni.ifaddresses('{DB2FCC38-FA39-4FAA-9E4C-EECB32FB6D9E}')[2][0]['addr']
def connectionLost(self, reason):
WebSocketServerProtocol.connectionLost(self, reason)
print("Losing my mind")
self.factory.unregister(self)
def getAyarlar(self):
try:
conn = sqlite3.connect('duyuruDB.db')
c = conn.cursor()
c.execute('SELECT * FROM ayarlar')
row = c.fetchone()
rowsList = [row[0], row[1], row[2], row[3], row[4]]
# dataToGO = bytes(json.dumps(rowsListed) + "\n", "utf-8")
return rowsList
except sqlite3.OperationalError:
print("Operational Error:", sys.exc_info()[1])
def aktifDuyurular(self):
conn = sqlite3.connect('duyuruDB.db')
c = conn.cursor()
c.execute('SELECT * FROM duyuru WHERE duyuru_tur = (?)', ['aktif'])
rows = c.fetchall()
rowsListed = [row[2] for row in rows]
return rowsListed
class BroadcastServerFactory(WebSocketServerFactory):
"""
Gelen tüm mesajları bağlı olan tüm clientlara yollayan Broadcast Server
"""
clients = []
def __init__(self, url):
WebSocketServerFactory.__init__(self, url)
# self.clients = []
self.veriGüncelle()
def register(self, client):
if not client in self.clients:
print("registered client {}".format(client.peer))
self.clients.append(client)
def unregister(self, client):
if client in self.clients:
print("unregistered client {}".format(client.peer))
self.clients.remove(client)
def broadcast(self, msg):
if len(self.clients) != 0:
print("broadcasting message '{}' ..".format(msg))
for c in self.clients:
c.sendMessage(msg.encode('utf8'))
print("message sent to {}".format(c.peer))
def veriGüncelle(self):
try:
conn = sqlite3.connect('duyuruDB.db')
c = conn.cursor()
c.execute('SELECT rowid, * FROM duyuru')
rows = c.fetchall()
aktifHaleGelecekDuyurular = []
silinecekDuyurular = []
for row in rows:
giris_tarih = datetime.strptime(row[4], "%d.%m.%Y")
cikis_tarih = datetime.strptime(row[5], "%d.%m.%Y")
if row[6] == "plan":
if giris_tarih <= datetime.now():
aktifHaleGelecekDuyurular.append(row[0])
print("'{0}' aktif hale gelecek. rowId = {1}".format(row[3], row[0]))
if datetime.now() > cikis_tarih:
silinecekDuyurular.append(row[0])
print("'{0}' silinecek. rowId = {1}".format(row[3], row[0]))
self.duyuruGüncelAktif(aktifHaleGelecekDuyurular)
self.duyuruGuncelSil(silinecekDuyurular)
except sqlite3.OperationalError:
print("Operational Error:", sys.exc_info()[1])
def duyuruGuncelSil(self, rowsList):
try:
conn = sqlite3.connect('duyuruDB.db')
c = conn.cursor()
for rowId in rowsList:
c.execute('DELETE FROM duyuru WHERE rowid = (?)', [rowId])
print("{0} rowID li duyuru silindi".format(rowId))
conn.commit()
conn.close()
except sqlite3.OperationalError:
print("Operational Error:", sys.exc_info()[1])
def duyuruGüncelAktif(self, rowsList):
try:
conn = sqlite3.connect('duyuruDB.db')
c = conn.cursor()
for rowId in rowsList:
c.execute('UPDATE duyuru SET duyuru_tur = (?) WHERE rowid = (?)', ['aktif', rowId])
print("{0} rowID li duyuru aktif hale geldi".format(rowId))
conn.commit()
conn.close()
except sqlite3.OperationalError:
print("Operational Error:", sys.exc_info()[1])
def main():
import sys
from twisted.python import log
from twisted.internet import reactor
log.startLogging(sys.stdout)
csharpFactory = BroadcastServerFactory(u"ws://127.0.0.1:9000")
csharpFactory.protocol = CsharpProtocol
clientHtmlFactory = BroadcastServerFactory(u"ws://127.0.0.1:9001")
clientHtmlFactory.protocol = ClientHtmlProtocol
reactor.listenTCP(9000, csharpFactory)
reactor.listenTCP(9001, clientHtmlFactory)
reactor.run()
if __name__ == '__main__':
main()