-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutils.py
executable file
·176 lines (140 loc) · 5.42 KB
/
utils.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
import json
import os
import time
import urllib
import tempfile
import multiprocessing
import sys, traceback
from multiprocessing.pool import ThreadPool
from datetime import date
from datetime import datetime
import threading
from vk.exceptions import VkAPIError
from twocaptchaapi import TwoCaptchaApi
import psutil
def load_json(filename):
try:
data = json.load(open(filename))
except:
return None
return data
def pretty_dump(data):
return json.dumps(data, indent=4, separators=(',', ': '),ensure_ascii=False).encode('utf8')
def RateLimited(maxPerSecond):
minInterval = 1.0 / float(maxPerSecond)
def decorate(func):
lastTimeCalled = [0.0]
def rateLimitedFunction(*args,**kargs):
elapsed = time.clock() - lastTimeCalled[0]
leftToWait = minInterval - elapsed
if leftToWait>0:
time.sleep(leftToWait)
ret = func(*args,**kargs)
lastTimeCalled[0] = time.clock()
return ret
return rateLimitedFunction
return decorate
rated_lock = multiprocessing.Lock()
json_lock = multiprocessing.Lock()
rated_queue = multiprocessing.Queue()
_2captcha_api = None
@RateLimited(2.5)
def set_event():
try:
rated_lock.release()
except ValueError:
pass
def rl_dispatch():
set_event()
while True:
rated_queue.get()
set_event();
def run_ratelimit_dispatcher():
p = multiprocessing.Process(target=rl_dispatch)
p.start()
def init_2captcha(api_key):
global _2captcha_api
_2captcha_api = TwoCaptchaApi(api_key)
cerror = 0
def solve_capthca(cfile):
with open(cfile, 'rb') as captcha_file:
captcha = _2captcha_api.solve(captcha_file)
res = captcha.await_result()
return res, captcha
manager = multiprocessing.Manager()
mmap = manager.dict({})
def read_minfo(method):
json = load_json("./files/minfo.json")
if json:
return str(json.get(method,"no method info"))
else:
return "no info at all"
def update_minfo(method, type, incr):
with json_lock:
json = load_json("./files/minfo.json")
if not json:
json = {"method":{"type":incr}}
else:
mmap = json.get(method, {})
mmap[type] = mmap.get(type,0)+incr
json[method] = mmap
open("./files/minfo.json","w").write(pretty_dump(json))
def info_string(method, val ):
return datetime.now().strftime('%H:%M:%S') + "\t" + method + "\t" + str(os.getpid()) +"\t" + val + "\t"+read_minfo(method) +"\t"+str(threading.active_count())+"\n"
no_captcha = multiprocessing.Event()
no_captcha.set()
def rated_operation(operation, args):
global cerror
current_captcha = None
rated_lock.acquire()
rated_queue.put("Can unlock")
this_captcha = False
with open("api_history","a") as file:
while True:
try:
process = psutil.Process(os.getpid())
print time.time(), operation._method_name, process.memory_info().rss, process.memory_info().rss/1024.0/1024.0, cerror, threading.active_count()
if not this_captcha and not no_captcha.is_set(): #captcha in progress, wait
no_captcha.wait()
ret = operation(**args)
update_minfo(operation._method_name, "success", 1)
if args.get("captcha_key", None):
update_minfo(operation._method_name, "capthca_ok", 1)
file.write(info_string(operation._method_name, "CAPTCHA OK [{}]; balance [{}]".format(args.get("captcha_key",None),_2captcha_api.get_balance())))
else:
file.write(info_string(operation._method_name, "OK"))
no_captcha.set()
return ret
except VkAPIError as e:
if e.code == 14:
if not _2captcha_api:
raise
this_captcha = True
no_captcha.clear()
if current_captcha:
current_captcha.report_bad()
temp_name = next(tempfile._get_candidate_names())
temp_name = "./files/{}.jpg".format(temp_name)
urllib.urlretrieve (e.captcha_img, temp_name)
try:
print "solving captcha ...",
res,current_captcha = solve_capthca(temp_name)
print "ok"
except:
print "Somthing bad in capthca solving"
continue
print "Solved captcha: ",res
update_minfo(operation._method_name, "captcha", 1)
args.update({"captcha_sid":e.captcha_sid,"captcha_key":res})
continue
if e.code == 6:
print "------- To many req for sec, throttling", e
time.sleep(1)
update_minfo(operation._method_name, "throttle", 1)
file.write(info_string(operation._method_name, "THROTTLE"))
continue
else:
update_minfo(operation._method_name, "error", 1)
file.write(info_string(operation._method_name, str(e)))
no_captcha.set()
raise