-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.py
150 lines (108 loc) · 2.75 KB
/
user.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
from time import time, sleep
class User():
_priority= 1
def __init__(s, gl, se, con, addr):
gl.all_priorities+= s._priority
s.gl= gl
s.se= se
s.con= con
s.ip, s.port= addr
def recvb(s, amount):
recived= b""
while amount:
priority= s._priority/ s.gl.all_priorities
max_download= int(s.se.global_download_limit* priority)
if max_download <= amount:
to_download= max_download
amount-= max_download
else:
to_download= amount
amount= 0
recived+= s.con.recv(to_download)
sleep(to_download/ max_download)
return recived
def sendallb(s, data):
while data:
priority= s._priority/ s.gl.all_priorities
max_upload= int(s.se.global_upload_limit* priority)
to_upload= data[:max_upload]
data= data[max_upload:]
s.con.sendall(to_upload)
sleep(len(to_upload)/ max_upload)
def recive_header(s):
start= time()
data= b""
while 1:
if start+s.se.time_to_recive_header < time():
raise TimeoutError("header not sent in time")
remains= s.se.header_maxlen - len(data)
bit= s.recvb(1)
data+= bit
if data.endswith(b"\r\n"):
del start
del remains
del bit
data= data[:-2]
break
data= data.decode()#decode error
header= data.split(" ")
del data
if len(header)!=3:
raise ValueError("header's format is bad")
s.meth, s.url, s.proto= header#... da opravq url-a i dekodiraneto
def recive_body(s):
start= time()
data= b""
while 1:
if start+s.se.time_to_recive_body < time():
raise TimeoutError("body not sent in time")
remains= s.se.body_maxlen- len(data)
if remains<=0:
raise ValueError("body is too long")
frame= s.recvb(remains)
data+= frame
if data.endswith(b"\r\n\r\n"):
del start
del remains
del frame
data= data[:-4]
break
data= data.decode()#decode error
body= {}
for line in data.split("\r\n"):
if ": " in line:
ind= line.index(": ")
key= line[:ind]
value= line[ind+2:]
body[key]= value
del data
coo= {}
if "Cookie" in body:
for line in body["Cookie"].split("; "):
if "=" in line:
ind= line.index("=")
key= line[:ind]
value= line[ind+1:]
coo[key]= value
else:
coo[line]= ""
del body["Cookie"]
s.body= body
s.coo= coo
def send_file(s, dir):
f= open(dir, "rb")
while 1:
chunk= s.se.file_sending_chunk
to_send= f.read(chunk)
if to_send==b"":
break
s.sendallb(to_send)
if len(to_send)< chunk:
break
f.close()
def change_priotiry(s, new):
change= new- s._priority
s.gl.all_priorities+= change
s._priority= new
def __del__(s):
s.gl.all_priorities-= s._priority