1. Aleksey Frolov
  2. post_check

Commits

Aleksey Frolov  committed ecb946c

second version

  • Participants
  • Parent commits 6af06ac
  • Branches default

Comments (0)

Files changed (1)

File post_check

View file
 import time
 from thread import start_new_thread
 from cgi import escape
+import socket
+import traceback
 
-re_ERROR = re.compile(r'<P CLASS\="page_ERROR".*?>(.*?)<\/P>',re.I+re.M+re.S)
-re_INFO = re.compile(r'<P CLASS\="page_TITLE".*?>(.*?)<\/P>',re.I+re.M+re.S)
+re_ERROR = re.compile(r'<p class\="error".*?>(.*?)<\/p>',re.I+re.M+re.S)
+re_INFO = re.compile(r'<p class\="red".*?>(.*?)<\/p>',re.I+re.M+re.S)
 re_TABLE = re.compile(r'<table.*?>(.*?)<\/table>',re.I+re.M+re.S)
 re_TR = re.compile(r'<tr.*?>(.*?)<\/tr>',re.I+re.M+re.S)
 re_TD = re.compile(r'<td.*?>(.*?)<\/td>',re.I+re.M+re.S)
 
+socket.setdefaulttimeout(5)
+
 def mydir():
 	return os.path.abspath(os.path.dirname(__file__))
- 
+	
 DB_FN = mydir()+'/post.db'
 
 class EditPost:
 	def on_cancel(self, w):
 		self.win.destroy()
 		del self
- 
+	
 class Config:
 	def __init__(self):
 
 		self.win.add(self.vbox)
 		self.win.connect('delete-event', self.on_delete_event)
 
-		self.liststore = gtk.ListStore(int, str, gobject.TYPE_BOOLEAN, str, str, str)
+		self.liststore = gtk.ListStore(int, str, gobject.TYPE_BOOLEAN, str, str, str, gobject.TYPE_BOOLEAN)
 		self.treeview = gtk.TreeView(self.liststore)
 		self.tv_post_number = gtk.TreeViewColumn('Номер')
 		self.tv_post_enable = gtk.TreeViewColumn('Следить')
 		self.tv_post_state = gtk.TreeViewColumn('Статус')
 		self.tv_post_desc = gtk.TreeViewColumn('Описание')
 		self.tv_post_date = gtk.TreeViewColumn('Дата')
- 
+		
 		self.cr_text = gtk.CellRendererText()
 		self.cr_toggle = gtk.CellRendererToggle()
 		self.cr_toggle.set_property('activatable', True)
 		self.cr_toggle.connect('toggled', self.on_post_enable_toggled)		
- 
+		
 		self.treeview.append_column(self.tv_post_enable)
 		self.treeview.append_column(self.tv_post_number)
 		self.treeview.append_column(self.tv_post_date)
 		self.treeview.append_column(self.tv_post_desc)		
- 
+		
 		self.tv_post_enable.pack_start(self.cr_toggle, False)
 		self.tv_post_number.pack_start(self.cr_text, False)
 		self.tv_post_desc.pack_start(self.cr_text, True)
 		self.tv_post_date.pack_start(self.cr_text, False)
- 
+		
 		self.tv_post_enable.add_attribute(self.cr_toggle, "active", 2)
 		self.tv_post_number.set_attributes(self.cr_text, text=1)
 		self.tv_post_desc.set_attributes(self.cr_text, text=3)
 		self.tv_post_date.set_attributes(self.cr_text, text=4)
- 
-		self.treeview.set_search_column(0)
-		#self.tvcolumn.set_sort_column_id(2)
+		
+		self.treeview.set_search_column(0)		
 		self.treeview.set_reorderable(True)
 		self.vbox.add(self.treeview)
 		# - buttons ----------------
 		self.b_del.connect('clicked', self.on_delete)
 		self.hbox.add(self.b_add)
 		self.hbox.add(self.b_edit)
-		self.hbox.add(self.b_del)		
- 
+		self.hbox.add(self.b_del)
+		# - filter ----------------
+		self.receive_filter = self.liststore.filter_new()
+		self.receive_filter.set_visible_func(self.func_receive_filter)
+	
+	def func_receive_filter(self, model, iter):
+		return not model[iter][6]				
+		
 	def on_edit(self, w):
 		path, column = self.treeview.get_cursor()
 		if path != None:
-			post = EditPost(self, self.liststore)
- 
+			post = EditPost(self, self.liststore[path])
+		
 	def on_delete(self, w):		
 		path, column = self.treeview.get_cursor()
 		if path != None:
 			self.confirm = gtk.MessageDialog( parent=self.win, type=gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format='Уверен?' )
-			self.confirm.set_position( gtk.WIN_POS_CENTER )
-			self.confirm.connect( 'delete_event', gtk.main_quit)
+			self.confirm.set_position( gtk.WIN_POS_CENTER )			
 			responce = self.confirm.run()
 			self.confirm.destroy()
 			if responce == gtk.RESPONSE_YES:
-				self.db_cur.execute('delete from posts where id = ?', [ self.liststore[0] ])
+				self.db_cur.execute('delete from posts where id = ?', [ self.liststore[path][0] ])
 				self.db_con.commit()
-				self.liststore.remove(self.liststore.iter)				
+				self.liststore.remove(self.liststore[path].iter)				
+				
 	def add_post(self, num, desc):
-		data = [ None, num, 0, unicode(desc), str(datetime.datetime.now()), '' ]
-		self.db_cur.execute('insert into posts values (?, ?, ?, ?, ?, ?)', data)
+		data = [ None, num, True, unicode(desc), str(datetime.datetime.now()), 'Unknown please update', 0 ]
+		self.db_cur.execute('insert into posts values (?, ?, ?, ?, ?, ?, ?)', data)
 		self.db_con.commit()
 		self.db_cur.execute('select max(id) from posts')			
 		self.db_cur.execute( 'select * from posts where id = ?', self.db_cur.fetchone() )
 		self.db_con.commit()
 		model[1] = num
 		model[3] = desc
- 
+		
 	def on_add(self, w):
 		post = EditPost(self)
- 
+		
 	def on_post_enable_toggled(self, cell, path):
-		self.liststore[2] = not self.liststore[2]
-		self.db_cur.execute( 'update posts set enable = ? where id = ?', [ self.liststore[2], self.liststore[0] ] )
+		self.liststore[path][2] = not self.liststore[path][2]
+		self.db_cur.execute( 'update posts set enable = ? where id = ?', [ self.liststore[path][2], self.liststore[path][0] ] )
 		self.db_con.commit()
- 
+		
 	def on_delete_event(self, w, a):
 		self.win.hide()
 		return True
 		if os.path.exists(db):
 			self.db_con = sqlite3.connect(db)
 			self.db_cur = self.db_con.cursor()
+			self.db_con.text_factory = str			
+			try:
+				self.db_cur.execute('select receive from posts')
+			except:
+				print 'Update DB to new version'
+				self.db_cur.execute('alter table posts add column receive INTEGER')
 			self.db_cur.execute('select * from posts')
-			for i in self.db_cur.fetchall():
+			for i in self.db_cur.fetchall():				
 				self.liststore.append(i)
 		else:
 			self.db_con = sqlite3.connect(db)
 			self.db_cur = self.db_con.cursor()
-			self.db_cur.execute('create table posts (id INTEGER PRIMARY KEY ASC, number TEXT, enable INTEGER, desc TEXT, date TEXT, status TEXT)')
+			self.db_con.text_factory = str
+			self.db_cur.execute('create table posts (id INTEGER PRIMARY KEY ASC, number TEXT, enable INTEGER, desc TEXT, date TEXT, status TEXT, receive INTEGER)')
 
 class App:
 	def __init__(self):
 		# - UI --------------------
 		self.win = gtk.Window(gtk.WINDOW_TOPLEVEL)
 		self.win.set_position( gtk.WIN_POS_CENTER )
-		self.win.resize(600,350)		
+		self.win.resize(600,600)		
 		self.win.set_deletable(False)
-		self.win.set_title('Отслеживание РПО')		
+		self.win.set_title('Отслеживание РПО')
 		self.win.set_border_width(3)
 		self.win.connect('window-state-event', self.on_window_state)
 		# - menu ------------------
 		hbox = gtk.HBox()
 		hbox.set_size_request(0, 25)		
 		vbox.pack_start(hbox, expand=False)
-		b_update = gtk.Button('Обновить')
+		
+		#cb_receive = gtk.CheckButton('Принятые')
+		#ccb_receive.connect('toggled', self.on_show_receive)
+		#hbox.add(cb_receive)
+		
+		b_update = gtk.Button('Обновить', gtk.STOCK_REFRESH)
 		b_update.connect('clicked', self.on_update)
 		hbox.add(b_update)
+		
 		b_update_all = gtk.Button('Обновить все')
-		b_update_all.set_label('Обновить все')
 		b_update_all.connect('clicked', self.on_update_all)
 		hbox.add(b_update_all)
+		
+		b_add = gtk.Button('Удалить', gtk.STOCK_ADD)
+		b_add.connect('clicked', self.config.on_add)
+		hbox.add(b_add)		
+		
+		b_del = gtk.Button('Удалить', gtk.STOCK_DELETE)
+		b_del.connect('clicked', self.on_delete)
+		hbox.add(b_del)
+		
 		b_config = gtk.Button('Параметры', gtk.STOCK_PREFERENCES)
 		b_config.connect('clicked', self.on_config)
 		hbox.add(b_config)
+		
+		
 		b_quit = gtk.Button('Выйти',gtk.STOCK_QUIT)
 		b_quit.connect('clicked', self.quit)
 		hbox.add(b_quit)
+		
 		self.treeview = gtk.TreeView(self.config.liststore)
+		#self.treeview = gtk.TreeView(self.config.receive_filter)
+		
 		self.treeview.set_headers_visible(0)
 		self.treeview.set_rules_hint(1)
 		sw.add(self.treeview)
 		cr_text = gtk.CellRendererText()
+		cr_toggle = gtk.CellRendererToggle()
+		cr_toggle.set_property('activatable', True)
+		cr_toggle.connect('toggled', self.on_receive_toggle)
+		
 		tv_status = gtk.TreeViewColumn('Сатус', cr_text, markup=5)
+		tv_receive = gtk.TreeViewColumn('', cr_toggle)
+		tv_receive.add_attribute(cr_toggle, "active", 6)
+		tv_status.set_expand(True)	
+		
+		self.treeview.append_column(tv_receive)
 		self.treeview.append_column(tv_status)
+		
 		self.config.load()
 		start_new_thread(self.update_by_timer,())
- 
+
+	def on_delete(self, w):		
+		path, column = self.treeview.get_cursor()
+		if path != None:
+			confirm = gtk.MessageDialog( parent=self.win, type=gtk.MESSAGE_QUESTION, buttons=gtk.BUTTONS_YES_NO, message_format='Уверен?' )
+			confirm.set_position( gtk.WIN_POS_CENTER )			
+			responce = confirm.run()
+			confirm.destroy()
+			if responce == gtk.RESPONSE_YES:
+				self.config.db_cur.execute('delete from posts where id = ?', [ self.config.liststore[path][0] ])
+				self.config.db_con.commit()
+				self.config.liststore.remove(self.config.liststore[path].iter)
+	
+	def on_show_receive(self, btn):
+		if btn.get_active():
+			self.treeview.set_model(self.config.liststore)
+		else:
+			self.treeview.set_model(self.config.receive_filter)
+	
+	def on_receive_toggle(self, cell, path):
+		self.config.liststore[path][6] = not self.config.liststore[path][6]
+		self.config.db_cur.execute( 'update posts set receive = ? where id = ?', [ self.config.liststore[path][6], self.config.liststore[path][0] ] )
+		self.config.db_con.commit()
+	
+		
 	def on_window_state(self, w, e):		
 		if e.new_window_state == gtk.gdk.WINDOW_STATE_ICONIFIED:			
 			self.win.hide()
 			self.win.deiconify()
- 
+		
 	def update_by_timer(self):
 		while True:	
-			time.sleep(60*60*3) # auto update every 3 hours
+			time.sleep(60*60*4) # auto update every 3 hours
 			print 'Start auto update'
 			for i in self.config.liststore:
 				if i[2]:
 					self.update_model(i)
- 
+		
 	def on_update_all(self, w):
 		for i in self.config.liststore:
 			self.update_model( i )
 	def on_update(self, w):
 		path, column = self.treeview.get_cursor()
 		if path != None:
-			self.update_model( self.config.liststore )
- 
+			self.update_model( self.config.liststore[path] )
+		
 	def on_config(self, widget):
 		self.config.win.show_all()
 
 		else:
 			self.win.show()			
 			self.win.present()
- 
+		
 	def update_model(self, model):
 		print 'update', model[1]
-		query = { 'action':'search', 'barCodeSearchBtn':'?????', 'page':1, 'searchType':'barCode', 'show_form':'yes' }
-		query['barCode'] = model[1]
-		text = 'Ошибка связи'
+		query = { 
+			'ASP'		:'',	
+			'BarCode'	:model[1],
+			'CA'		:'',
+			'CDAY'		:'01',
+			'CMONTH'	:'09',
+			'CYEAR'		:'2011',
+			'DFROM'		:'',
+			'DTO'		:'',
+			'FORUMID'	:'',
+			'NAVCURPAGE':'',
+			'NEWSID'	:'',
+			'OP'		:'',
+			'PARENTID'	:'',
+			'PATHCUR'	:'rp/servise/ru/home/postuslug/trackingpo',
+			'PATHFROM'	:'',
+			'PATHPAGE'	:'RP/INDEX/RU/Home/Search',
+			'PATHWEB'	:'RP/INDEX/RU/Home',
+			'SEARCHTEXT':'',
+			'WHEREONOK'	:'',
+			'search1'	:'',
+			'searchAdd'	:'',
+			'searchsign':'1',
+		}		
+		
+		text = 'Неизвестная ошибка'
 		try:
-			status = urllib.urlopen( 'http://info.russianpost.ru/servlet/post_item', urllib.urlencode(query) ).read().decode('cp1251')			
+			try:
+				status = urllib.urlopen( 'http://www.russianpost.ru/resp_engine.aspx?Path=rp/servise/ru/home/postuslug/trackingpo', urllib.urlencode(query) ).read() #.decode('cp1251')
+				pass
+			except:
+				text = 'Ошибка связи'
+			#open('debug.txt','w').write(status)
+			#status = open('debug.txt').read()
 			errors = [ i.replace('<BR>','').replace('\n','') for i in re_ERROR.findall(status) ]
 			info = [ i.replace('<BR>','').replace('\n','') for i in re_INFO.findall(status) ]
 			table = re_TABLE.findall(status)
+			#10 - complete
+			#print 'Errors:', errors[0]
+			print len(table)
+			#print table[7]
 			if errors:
 				text = '<span background="red">'+'\n'.join(errors)+'</span>'
-			elif len(table) == 2:
+			elif len(table) == 9 or len(table) == 10:
 				text = ''
-				for i in  re_TR.findall( table[1] )[2:]:		
-					text+= ' '.join( [ j.replace(' ',' ') for j in re_TD.findall(i)[:5] ] ).strip() + '\n'
-				text = '<span background="green" foreground="black">'+text.strip()+'</span>'
+				for i in  re_TR.findall( table[8] )[2:]:		
+					text+= ' '.join( [ j.replace('&nbsp;',' ') for j in re_TD.findall(i)[:5] ] ).strip() + '\n'
+				text = re.sub('<.*?>','',text)
+				text = '<span background="green" foreground="black">'+text.strip()+'</span>'				
+				#print 'Update text:', text
 			else:
-				text = '<span background="yellow" foreground="black">'+escape( info[1].strip() )+'</span>'
- 
+				text = '<span background="yellow" foreground="black">'+escape( info[0].strip() )+'</span>'
+			
 		except Exception, e:
 			print 'Update error',model[1], e
+			print traceback.format_exc()
 		model[5] = u'<big><b>%s</b></big>\n<i>%s</i>\n<small>%s</small>' % (model[1], escape(model[3]), text )
-		#model<5> = u'<big><b>%s</b></big>\n<i>%s</i>\n%s\n<small>%s</small>' % (model[1], escape(model[3]), '-'*40, text )
+		#model[5] = u'<big><b>%s</b></big>\n<i>%s</i>\n%s\n<small>%s</small>' % (model[1], escape(model[3]), '-'*40, text )
 		db_con = sqlite3.connect(DB_FN)
 		db_cur = db_con.cursor()
+		db_con.text_factory = str
 		db_cur.execute('update posts set status = ? where id = ?', [ unicode(model[5]), model[0] ] )
 		db_con.commit()
 
 	app = App()	
 	app.win.show_all()
 	gtk.main()	
-