OSDN Git Service

0fcb4da032746067a8e08a5f26bffb1b977be892
[chatyl/chatyl.git] / Talk.py
1 # -*- coding: UTF-8 -*-
2 import wx
3 import datetime
4 import pymongo
5 from pymongo_pubsub import Publisher
6 from pymongo_pubsub import Subscriber
7 import thread
8 import simplejson as json
9 from time import sleep
10 import urllib2
11 class myapp(wx.Frame):
12     def OnClose(self,evt):
13        #re = redis.Redis(host='pub-redis-19834.us-east-1-4.5.ec2.garantiadata.com',port=19834,password='22842218')
14        #re.delete(un_g + '-' + username)
15        try:
16            s = urllib2.urlopen("http://chat-tyl.coding.io/read_cache.php?name="+ un_g + "-" + username +"&del=OK&check=NO").read()
17        except urllib2.HTTPError,e:
18           print e.code
19        self.Destroy()
20     def __init__(self, parent, id,title,user_name,un,addcon):
21         wx.Frame.__init__(self,parent,id,title,wx.DefaultPosition,wx.Size(400,300))
22         global username
23         username=user_name
24         self.bkg = wx.Panel(self,-1)
25         global un_g
26         un_g=un
27         self.tshow = wx.TextCtrl(self.bkg,style = wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY|wx.TE_RICH2|wx.TE_LINEWRAP)
28         self.tinput = wx.TextCtrl(self.bkg,style = wx.TE_PROCESS_ENTER)
29         self.tinput.Bind(wx.EVT_TEXT_ENTER,self.btaction)
30         self.bt = wx.Button(self.bkg,label = _("Send"))      
31         self.box1 = wx.BoxSizer()
32         self.box1.Add(self.tinput,proportion = 1,flag = wx.EXPAND)
33         self.box1.Add(self.bt,proportion = 0)        
34         self.box2 = wx.BoxSizer(wx.VERTICAL)
35         self.box2.Add(self.tshow,flag = wx.EXPAND|wx.ALL,border = 5,proportion = 1)     
36         self.box2.Add(self.box1,flag = wx.EXPAND|wx.LEFT|wx.BOTTOM|wx.RIGHT\
37         ,border = 5,proportion = 0)        
38         self.bkg.SetSizer(self.box2)
39         if addcon != "":
40             now = datetime.datetime.now()
41             self.tshow.SetDefaultStyle(wx.TextAttr("BLUE"))
42             self.tshow.AppendText(_("User:")+now.strftime('%Y-%m-%d %H:%M:%S')+"\n")       
43             self.tshow.SetDefaultStyle(wx.TextAttr("BLACK"))
44             self.tshow.AppendText(addcon + "\n")
45         self.Bind(wx.EVT_CLOSE, self.OnClose)
46         self.bt.Bind(wx.EVT_BUTTON,self.btaction)        
47         thread.start_new_thread(self.receive, ())
48         self.Show()
49     def btaction(self,evt):
50         global content
51         content = self.tinput.GetValue()
52         if content == "":
53              wx.MessageBox(_('Please Enter the text'), _('Try it again'),
54                      wx.OK | wx.ICON_ERROR)
55         else:
56             now = datetime.datetime.now()
57             self.tshow.SetDefaultStyle(wx.TextAttr("GREEN"))
58             self.tshow.AppendText(_("I:")+now.strftime('%Y-%m-%d %H:%M:%S')+"\n")
59             self.tshow.SetDefaultStyle(wx.TextAttr("BLACK"))
60             self.tshow.AppendText(self.tinput.GetValue() + "\n")
61             thread.start_new_thread(self.send, ())
62             self.tinput.SetValue("")
63     def put_text(self,data): 
64                text_json= json.loads(data['message'])
65                if text_json['type'] == 'p2pchat-in-line':
66                            now = datetime.datetime.now()
67                            self.tshow.SetDefaultStyle(wx.TextAttr("BLUE"))
68                            wx.CallAfter(self.tshow.AppendText, _("User:")+text_json['time']+"\n")
69                            sleep(0.1)
70                            self.tshow.SetDefaultStyle(wx.TextAttr("BLACK"))
71                            wx.CallAfter(self.tshow.AppendText, text_json['content'] + "\n")
72     def receive(self):
73        try:
74            s = urllib2.urlopen("http://chat-tyl.coding.io/read_cache.php?name="+ un_g + "-" + username +"&txt=OK&del=NO&check=NO").read()
75        except urllib2.HTTPError,e:
76           print e.code
77        connection = pymongo.MongoClient('mongodb://tyl:22842218@ds051738.mongolab.com:51738/tylchat?authMechanism=SCRAM-SHA-1').get_default_database()
78        i = 1
79        while (i == 1):
80              subscriber = Subscriber(connection, un_g,callback=self.put_text ,
81                       matching={'send': username})
82              subscriber.listen()
83     def send(self): 
84         connection = pymongo.MongoClient('mongodb://tyl:22842218@ds051738.mongolab.com:51738/tylchat?authMechanism=SCRAM-SHA-1').get_default_database()
85         #database = connection.tylchat_collection.pubsub_db
86         publisher = Publisher(connection, username)
87         try:
88             s = urllib2.urlopen("http://chat-tyl.coding.io/read_cache.php?name="+ username + "-" + un_g +"&del=NO&check=OK").read()
89         except urllib2.HTTPError,e:
90            print e.code
91         now = datetime.datetime.now()
92         if s == "":
93              send_dic = {
94              'type': 'info-in-line',
95              'send': un_g,
96              'user' : username,
97              'time': now.strftime('%Y-%m-%d %H:%M:%S'),
98              'content': content 
99              }
100              user = json.dumps(send_dic)
101              publisher.push({'message': user, 'send': 'info-chat'})
102         else:
103              send_dic = {
104              'type': 'p2pchat-in-line',
105              'content': content ,
106              'time': now.strftime('%Y-%m-%d %H:%M:%S')
107              }
108              user = json.dumps(send_dic)
109              publisher.push({'message': user, 'send': un_g})          
110 #if __name__ == '__main__':
111     #app = myapp()
112     #app.MainLoop()