-
Notifications
You must be signed in to change notification settings - Fork 0
/
grab_ticket.py
278 lines (262 loc) · 10.1 KB
/
grab_ticket.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
#!/usr/bin/python
# coding=utf-8
import os
import re
import sys
import time
import thread
import random
import urllib, urllib2
from svmutil import *
from datetime import datetime
from aubio import source, pitch
from cookielib import CookieJar
from threading import Thread
HOP_SIZE = 512
FRAME_SIZE = 2048
SIMPLE_RATE = 8000
FEATURE_SIZE = 8
PITCH_METHOD = 'yinfft'
INIT_URL = 'http://railway.hinet.net/check_ctno1.jsp'
CTNO_JS_URL = 'http://railway.hinet.net/ctno1.js'
CTNO_HTM_URL = 'http://railway.hinet.net/ctno1.htm'
IMAGE_URL = 'http://railway.hinet.net/ImageOut.jsp?pageRandom=%.16f'
AUDIO_URL = 'http://railway.hinet.net/PronounceRandonNumber.do?pageRandom=%.16f'
ORDER_URL = 'http://railway.hinet.net/order_no1.jsp'
def read_arguments():
if len(sys.argv) == 2:
return int(sys.argv[1]), True
elif len(sys.argv) == 3:
return int(sys.argv[1]), int(sys.argv[2]) == 1
return 1, True
def rand_user_agent():
user_agents = [
'Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)',
'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; GTB7.4; InfoPath.2; SV1; .NET CLR 3.3.69573; WOW64; en-US)',
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2',
'Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11',
'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.45 Safari/535.19'
]
return random.choice(user_agents)
def get_pitches(filename):
pitches = []
s = source(filename, SIMPLE_RATE, HOP_SIZE)
p = pitch(PITCH_METHOD, FRAME_SIZE, HOP_SIZE, SIMPLE_RATE)
while True:
samples, read = s()
pit = p(samples)[0]
pitches += [pit]
if read < HOP_SIZE: break
return pitches
def split_pitches(pitches):
zero_count = -1
char_pitches = []
for i in range(len(pitches)):
if pitches[i] != 0 and zero_count >= 0 and zero_count <= 3:
zero_count = 0
char_pitches[len(char_pitches) - 1] += [pitches[i]]
elif pitches[i] != 0:
zero_count = 0
char_pitches.append([pitches[i]])
elif zero_count >= 0:
zero_count += 1
return char_pitches
def char_pitches_to_string(char_pitches):
string = ''
for i in range(len(char_pitches)):
labels = [0.0]
data = [{}]
for j in range(len(char_pitches[i]), FEATURE_SIZE):
char_pitches[i].append(0)
for j in range(len(char_pitches[i])):
data[0][j+1] = char_pitches[i][j]
p_labels, p_acc, p_vals = svm_predict(labels, data, model, '-q')
string += str(int(p_labels[0]))
return string
def input_params():
params = {
'person_id': '', 'from_station': '', 'to_station': '',
'getin_date': '', 'train_no': '', 'order_qty_str': '0',
't_order_qty_str': '0', 'n_order_qty_str': '0', 'd_order_qty_str': '0',
'b_order_qty_str': '0', 'z_order_qty_str': '0', 'returnTicket': '0'
}
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
htm_resp = opener.open(urllib2.Request(CTNO_HTM_URL)).read()
htm_resp = htm_resp.decode('big5').encode('utf-8')
js_resp = opener.open(urllib2.Request(CTNO_JS_URL)).read()
js_resp = js_resp
# person_id
params['person_id'] = raw_input('請輸入身分證字號: ').capitalize()
if not re.match('^[A-Z][12][0-9]{8}$', params['person_id']):
print '身分證字號格式錯誤.'
return None
table = "10987654932210898765431320"
check_sum = int(table[ord(params['person_id'][0])-65]) + int(params['person_id'][9])
for i in range(1, 9): check_sum += int(params['person_id'][i]) * (9 - i)
if check_sum % 10 != 0:
print '身分證字號驗證失敗.'
return None
# from_station
params['from_station'] = raw_input('請輸入起站代碼(台北:100): ')
if not re.match('[0-9]{3}$', params['from_station']):
print '起站代碼格式錯誤.'
return None
from_station_obj = re.search('%s-([^<]+)' % params['from_station'], htm_resp)
if from_station_obj == None:
print '起站代碼驗證失敗.'
return None
# to_station
params['to_station'] = raw_input('請輸入到站代碼(花蓮:051): ')
if not re.match('[0-9]{3}$', params['to_station']):
print '到站代碼格式錯誤.'
return None
to_station_obj = re.search('%s-([^<]+)' % params['to_station'], htm_resp)
if to_station_obj == None:
print '到站代碼驗證失敗.'
return None
# getin_date
params['getin_date'] = raw_input('請輸入乘車日期(xxxx/xx/xx): ')
if not re.match('^(19|20)[0-9]{2}\/(0[0-9]|1[0-2])\/([0-2][0-9]|3[0-1])$', params['getin_date']):
print '乘車日期格式錯誤.'
return None
diff_days = abs(datetime.now().date() - datetime.strptime(params['getin_date'][:10], '%Y/%m/%d').date()).days
params['getin_date'] = '%s-%d' % (params['getin_date'][:10], diff_days)
# train_no
params['train_no'] = raw_input('請輸入車次代碼: ')
if not re.match('[0-9]+', params['train_no']):
print '車次代碼格式錯誤.'
return None
# train_box_data
has_box = {'n': False, 'd': False, 't': False, 'b': False, 'z': False}
map_box = {' ': 'n', 'D': 'd', '5': 't', 'B': 'b', 'Z': 'z'}
train_box_data = re.search('[0-9]{6}%s *([^"]+)' % params['train_no'], js_resp)
if train_box_data == None:
train_box_data = []
else:
train_box_data = train_box_data.group(1)
for i in range(len(train_box_data)):
if train_box_data[i] in map_box:
has_box[map_box[train_box_data[i]]] = True
if has_box['d'] or has_box['b'] or has_box['z']:
has_box['t'] = False
has_box_message = {'n': '一般車廂', 'd': '商務車廂', 'b': '兩鐵車廂', 'z': '桌型座位'}
for key, value in has_box.iteritems():
if value:
params['%s_order_qty_str' % key] = raw_input('請輸入%s張數: ' % has_box_message[key])
elif has_box['t']:
params['t_order_qty_str'] = raw_input('請輸入訂票張數: ')
else:
params['order_qty_str'] = raw_input('請輸入訂票張數: ')
total = 0
has_box = ['', 'n_', 'd_', 't_', 'b_', 'z_']
for i in range(len(has_box)):
if not re.match('[0-9]+', params['%sorder_qty_str' % has_box[i]]):
print '訂票張數格式錯誤.'
return None
else:
total += int(params['%sorder_qty_str' % has_box[i]])
if total < 1 or total > 6:
print '訂票張數有誤(總張數至少一張且至多六張).'
return None
params['order_qty_str'] = str(total)
return params
def save_data(opener, headers, url, output):
headers['referer'] = INIT_URL
data = opener.open(urllib2.Request(url, None, headers)).read()
if len(output) > 0:
f = open(output, 'wb')
f.write(data)
def init_session(opener, params):
global ORDER_URL
headers = {'referer': CTNO_HTM_URL, 'User-Agent': rand_user_agent()}
resp = opener.open(urllib2.Request(INIT_URL, urllib.urlencode(params), headers)).read()
resp = resp.decode('big5').encode('utf-8')
tmp_params = params
new_params = re.findall('input name="([^"]+)[^v]+value="([^"]+)', resp)
for i in range(len(new_params)):
params[new_params[i][0]] = new_params[i][1]
if not 'getin_date' in params:
ORDER_URL = 'http://railway.hinet.net/%s.jsp'% re.search('action="([^.]+)', resp).group(1)
return tmp_params, headers
diff_days = abs(datetime.now().date() - datetime.strptime(params['getin_date'][:10], '%Y/%m/%d').date()).days
params['getin_date'] = '%s-%d' % (params['getin_date'][:10], diff_days)
ORDER_URL = 'http://railway.hinet.net/%s.jsp'% re.search('action="([^.]+)', resp).group(1)
print ORDER_URL
return params, headers
def buy_ticket(opener, params, headers, lock, thread_id):
rand = random.random()
stamp = int(time.time() * 1000)
save_data(opener, headers, IMAGE_URL % rand, '')
save_data(opener, headers, AUDIO_URL % rand, 'Temp/%d_%d.wav' % (thread_id, stamp))
params['randInput'] = char_pitches_to_string(split_pitches(get_pitches('Temp/%d_%d.wav' % (thread_id, stamp))))
os.remove('Temp/%d_%d.wav' % (thread_id, stamp))
# print params['randInput']
headers['referer'] = INIT_URL;
resp = opener.open(urllib2.Request('%s?%s' % (ORDER_URL, urllib.urlencode(params)), None, headers)).read()
resp = resp.decode('big5').encode('utf-8')
message = re.search('spanOrderCode[^>]+>([0-9]+)', resp)
if message != None:
lock.acquire()
print '%d: 您的車票已訂到. 電腦代碼: %s, 身分證字號: %s' % (thread_id, message.group(1), params['person_id'])
lock.release()
return True
message = re.search('<strong>([^<]+)<\/strong>', resp)
if message == None:
lock.acquire()
if resp.find('對不起,車票已訂完') != -1:
print '%d: 對不起,車票已訂完, 重試中 ...' % thread_id
else:
print '%d: 發生其餘未知的錯誤(EX:購票超過6張) ...' % thread_id
lock.release()
return False
lock.acquire()
print '%d: %s 重試中 ...' % (thread_id, message.group(1))
lock.release()
return False
def grab_ticket(params, wait, lock, thread_id):
global stop
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
buy_params, headers = init_session(opener, params)
while stop == False and buy_params == None:
cj.clear()
buy_params, headers = init_session(opener, params)
# wait
wait_time = (23 * 60 + 30) * 60 + 45
while stop == False and wait == True:
now_time = datetime.now()
current_time = (now_time.hour * 60 + now_time.minute) * 60 + now_time.second
if current_time >= wait_time:
cj.clear()
buy_params, headers = init_session(opener, params)
break
# start
while stop == False and buy_ticket(opener, buy_params, headers, lock, thread_id) == False:
diff_days = abs(datetime.now().date() - datetime.strptime(buy_params['getin_date'][:10], '%Y/%m/%d').date()).days
buy_params['getin_date'] = '%s-%d' % (buy_params['getin_date'][:10], diff_days)
time.sleep(3)
stop = True
thread.exit()
def main():
global model, stop
thread_count, wait = read_arguments()
model = svm_load_model('Data/svm.model')
df_params = input_params()
print
stop = False
threads = []
lock = thread.allocate_lock()
for i in range(thread_count):
threads.append(Thread(target = grab_ticket, args = (df_params, wait, lock, i + 1,)))
threads[i].start()
try:
while True:
for t in threads:
t.join(1)
except KeyboardInterrupt:
stop = True
exit()
if __name__ == '__main__':
main()