OSDN Git Service

you can add some urls
[pybbs/pybbs.git] / index.py
1
2 import os.path
3 import shutil,re
4 import tornado.escape
5 import tornado.web
6 import tornado.httpserver
7 import tornado.ioloop
8 import tornado.options
9 from tornado.options import define,options
10 from tinydb import TinyDB,Query,where
11 from tinydb.operations import delete
12 from datetime import datetime
13
14 define('port',default=8000,help='run on the given port',type=int)
15
16 class BaseHandler(tornado.web.RequestHandler):
17     def get_current_user(self):
18         user = self.get_secure_cookie('admin_user')
19         return tornado.escape.utf8(user)
20     
21     def set_current_user(self,username):
22         self.set_secure_cookie('admin_user',username)
23         
24     def clear_current_user(self):
25         self.clear_cookie('admin_user')
26
27 class IndexHandler(BaseHandler):
28     def get(self,dbname,page='0'):
29         params = self.application.db.get(where('kinds') == 'conf')
30         if params['mentenance'] == True:
31             self.render('mentenance.htm',title=params['title'],db=dbname)
32         if self.application.collection(dbname) == False:
33             if self.current_user == b'admin':
34                 self.application.db.table(dbname)
35             else:
36                 raise tornado.web.HTTPError(404)
37                 return
38         i = params['count']      
39         na = tornado.escape.url_unescape(self.get_cookie("username",u"誰かさん"))
40         pos = self.application.gpos(dbname,page)
41         table = self.application.db.table(dbname)
42         start = (pos-1)*i
43         if start < 0:
44             start = len(table)-i
45             if start < 0:
46                 start = 0
47         rec = sorted(table.all(),key=lambda x: x['number'])[start:start+i]
48         if len(table) >= 10*i:
49             self.render('modules/full.htm',position=pos,records=rec,data=params,db=dbname)
50             return
51         self.render('modules/index.htm',position=pos,records=rec,data=params,username=na,db=dbname)
52         
53 class LoginHandler(BaseHandler):
54     def get(self):
55         self.render('login.htm')
56         
57     def post(self):
58         pw = self.application.db.get(where('kinds') == 'conf')
59         if self.get_argument('password') == pw['password']:
60             self.set_current_user('admin')
61         dbname = self.get_argument('record')
62         self.redirect('/'+dbname+'/admin/0/')
63         
64 class LogoutHandler(BaseHandler):
65     def get(self):
66         self.clear_current_user()
67         self.redirect('/login')
68         
69 class NaviHandler(tornado.web.RequestHandler):
70     def get(self):
71         self.render('top.htm',coll=sorted(self.name()),full=self.full)
72         
73     def name(self):
74         for x in self.application.db.tables():
75             if x != '_default':
76                 yield x
77                 
78     def full(self,dbname):
79         if dbname in self.application.db.tables():
80             i = 10*self.application.db.get(where('kinds') == 'conf')['count']
81             table = self.application.db.table(dbname)
82             if len(table) >= i:
83                 return True
84         return False
85
86 class TitleHandler(NaviHandler):
87     def get(self):
88         rec = sorted(self.title(),key=lambda x: x['date2'])
89         self.render('title.htm',coll=rec,full=self.full)  
90         
91     def title(self):
92         for x in self.name():
93             item = {}
94             item['name'] = x
95             table = self.application.db.table(x)
96             i = len(table)
97             item['count'] = i            
98             if table.contains(where('number') == 1) == True:
99                 s = table.get(where('number') == 1)['title']
100             else:
101                 s = ''
102             item['title'] = s   
103             if i == 0:
104                 item['date'] = ''
105                 item['date2'] = 0
106             else:
107                 rec = sorted(table.all(),key=lambda k: k['number'])
108                 s = rec[i-1]['date']
109                 item['date'] = s
110                 i = datetime.strptime(s,'%Y/%m/%d %H:%M')
111                 year = datetime.now().year-i.year
112                 if year == 0:
113                     j = 800
114                 elif year == 1:
115                     j = 400
116                 else:
117                     j = 0
118                 item['date2'] = j+31*(i.month-1)+i.day
119             yield item
120         
121 class RegistHandler(tornado.web.RequestHandler):
122     def post(self,dbname):
123         if self.application.collection(dbname) == False:
124             raise tornado.web.HTTPError(404)
125             return
126         rec = self.application.db.get(where('kinds') == 'conf')
127         words = rec['bad_words']
128         out = rec['out_words']
129         na = self.get_argument('name',u'誰かさん')
130         sub = self.get_argument('title',u'タイトルなし')
131         com = self.get_argument('comment')
132         text = ''
133         i = 0
134         url = []
135         error = ''
136         for word in out:
137             if word in com:
138                 error = error + u'禁止ワード.'
139                 break
140         for line in com.splitlines(True):
141             if error != '':
142                 break
143             for word in words:
144                 if word in line.lower():
145                     error = error + u'タグ違反.('+word+')'       
146             i += len(line)   
147             obj = re.finditer('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', line)
148             for x in obj:
149                 if x.group() not in url:
150                     url.append(x.group())
151             if re.match(' ',line):
152                 line = line.replace(' ','&nbsp;',1)
153             text = text+'<p>'+self.link(line)+'<br></p>'
154         s = ''
155         for x in url:
156             s = s+'<tr><td><a class=livepreview target=_blank href={0}>{0}</a></td></tr>'.format(x)
157         if s:
158             text = text+'<table><tr><td>検出URL:</td></tr>'+s+'</table>'
159         pw = self.get_argument('password')
160         if i == 0:
161             error = error + u'本文がありません.'
162         elif i > 1000:
163             error = error +u'文字数が1,000をこえました.'
164         article = self.application.db.table(dbname)
165         if len(article) == 0:
166             no = 1
167         else:
168             item = sorted(article.all(),key=lambda x: x['number'])[len(article)-1]
169             no = item['number']+1
170         if error == '':
171             s = datetime.now()
172             reg = {'number':no,'name':na,'title':sub,'comment':text,'raw':com,'password':pw,'date':s.strftime('%Y/%m/%d %H:%M')}
173             article.insert(reg)
174             self.set_cookie('username',tornado.escape.url_escape(na))
175             self.redirect('/'+dbname+'#article')
176         else:
177             self.render('regist.htm',content=error)
178     
179     def link(self,command):
180         y = ''
181         i = 0
182         text = ''
183         for x in command.split():
184             if (y == '>>')and(x.isdecimal() == True):
185                 s = '<a href=#'+x+'>'+x+'</a>'
186                 while -1 < command.find(x,i):
187                     j = command.find(x,i)
188                     tmp = command[i:j]
189                     i = j+len(x)
190                     k = tmp.rsplit(None,1)
191                     if ((len(k) > 1)and(k[1] == y))or(k[0] == y):
192                         text = text+tmp+s                                                                       
193                         break
194                     else:
195                         text = text+tmp+x                        
196             y = x    
197         if text == '':
198             return command
199         else:
200             if len(command) > i:
201                 return text+command[i:]
202             else:
203                 return text
204     
205 class AdminHandler(BaseHandler):
206     @tornado.web.authenticated               
207     def get(self,dbname,page='0'):
208         if dbname == '':
209             dbname = self.get_argument('record','')
210         if self.application.collection(dbname) == False:
211             raise tornado.web.HTTPError(404)
212             return
213         table = self.application.db.table(dbname) 
214         rec = sorted(table.all(),key=lambda x: x['number'])                   
215         mente = self.application.db.get(where('kinds') == 'conf')
216         if mente['mentenance'] == True:
217             check = 'checked=checked'
218         else:
219             check = ''
220         pos = self.application.gpos(dbname,page)
221         i = mente['count']
222         start = (pos-1)*i
223         if start < 0:
224             start = len(table)-i
225             if start < 0:
226                 start = 0
227         self.render('modules/admin.htm',position=pos,records=rec[start:start+i],mente=check,password=mente['password'],db=dbname)
228
229 class AdminConfHandler(BaseHandler):
230     @tornado.web.authenticated
231     def post(self,dbname,func):
232         if func == 'set':
233             param = self.application.db.get(where('kinds') == 'conf')['mentenance']
234             if self.get_argument('mente','') == 'on':
235                 mente = True
236                 if param != mente:
237                     self.store()
238             else:
239                 mente = False  
240                 if param != mente:
241                     self.restore()
242             word = self.get_argument('pass','')
243             if word == '':
244                 self.render('regist.htm',content='パスワードを設定してください')
245                 return
246             else:
247                 self.application.db.update({'mentenance':mente,'password':word},where('kinds') == 'conf')  
248         elif func == 'del':
249             table = self.application.db.table(dbname)
250             for x in self.get_arguments('item'):
251                 table.remove(where('number') == int(x))
252         self.redirect('/'+dbname+'/admin/0/')
253         
254     def store(self):
255         self.application.db.close()
256         shutil.copy(st.json,st.bak)
257         self.application.db = TinyDB(st.json)
258         
259     def restore(self):
260         database = self.application.db
261         bak = TinyDB(st.bak)
262         for x in database.tables():
263             if self.application.collection(x) == True:
264                 database.purge_table(x)
265                 if x in bak.tables():
266                     table = database.table(x)
267                     table.insert_multiple(bak.table(x).all())
268           
269 class UserHandler(tornado.web.RequestHandler):
270     def post(self,dbname):
271         num = self.get_argument('number')
272         if num.isdigit() == True:
273             num = int(num)
274             pas = self.get_argument('password')
275             table = self.application.db.table(dbname)
276             qwr = Query()
277             obj = table.get(qwr.number == num)
278             if obj and(obj['password'] == pas):
279                 table.remove(qwr.number == num)
280         self.redirect('/'+dbname)
281       
282 class SearchHandler(tornado.web.RequestHandler):       
283     def post(self,dbname):
284         self.word = tornado.escape.url_unescape(self.get_argument('word1'))
285         self.radiobox = self.get_argument('filter')
286         self.set_cookie('search',tornado.escape.url_escape(self.word))         
287         rec = sorted(self.search(dbname),key=lambda x: x['number'])
288         self.render('modules/search.htm',records=rec,word1=self.word,db=dbname)
289     
290     def get(self,dbname):
291         if self.application.collection(dbname) == False:
292             raise tornado.web.HTTPError(404)
293             return
294         word = self.get_cookie('search','')
295         word = tornado.escape.url_unescape(word)
296         self.render('modules/search.htm',records=[],word1=word,db=dbname)
297         
298     def search(self,dbname):
299         table = self.application.db.table(dbname)    
300         element = self.word.split()
301         if len(element) == 0:
302             element = ['']
303         while len(element) < 3:
304             element.append(element[0])
305         if self.radiobox == 'comment':
306             query = (Query().raw.search(element[0])) | (Query().raw.search(element[1])) | (Query().raw.search(element[2]))
307         else:
308             query = (Query().name == element[0]) | (Query().name == element[1]) | (Query().name == element[2])
309         if self.radiobox == 'comment':    
310             for x in table.search(query):
311                 com = ''
312                 for text in x['raw'].splitlines(True):                  
313                     for word in self.word.split():                        
314                         if text.find(word) > -1:
315                             com = com +'<p style=background-color:yellow>'+text+'<br></p>'  
316                             break                          
317                     else:
318                         com = com+'<p>'+text+'<br></p>'
319                 x['comment'] = com
320                 yield x       
321         else:
322             for x in table.search(query):
323                 yield x
324                                         
325 class FooterModule(tornado.web.UIModule):
326     def render(self,number,url,link):
327         return self.render_string('modules/footer.htm',index=number,url=url,link=link)
328     
329 class Application(tornado.web.Application):    
330     def __init__(self):
331         self.db = TinyDB(st.json)
332         handlers = [(r'/',NaviHandler),(r'/login',LoginHandler),(r'/logout',LogoutHandler),(r'/title',TitleHandler),
333                     (r'/([a-zA-Z0-9_]+)',IndexHandler),(r'/([a-zA-Z0-9_]+)/([0-9]+)/',IndexHandler),
334                     (r'/([a-zA-Z0-9_]+)/admin/([0-9]+)/',AdminHandler),(r'/([a-zA-Z0-9_]+)/admin/([a-z]+)/',AdminConfHandler),(r'/([a-zA-Z0-9_]+)/userdel',UserHandler),
335                     (r'/([a-zA-Z0-9_]+)/search',SearchHandler),(r'/([a-zA-Z0-9_]+)/regist',RegistHandler)]
336         settings = {'template_path':os.path.join(os.path.dirname(__file__),'pybbs'),
337                         'static_path':os.path.join(os.path.dirname(__file__),'static'),
338                         'ui_modules':{'Footer':FooterModule},
339                         'cookie_secret':'bZJc2sWbQLKos6GkHn/VB9oXwQt8SOROkRvJ5/xJ89E=',
340                         'xsrf_cookies':True,
341                         'debug':True,
342                         'login_url':'/login'
343                         }
344         tornado.web.Application.__init__(self,handlers,**settings)
345  
346     def gpos(self,dbname,page):
347         params = self.db.get(where('kinds') == 'conf')
348         pos = int(page)
349         if pos <= 0:
350             pos = 0
351         elif (pos-1)*params['count'] >= len(self.db.table(dbname)):
352             pos = 0
353         return pos
354     
355     def collection(self,name):
356         if name in self.db.tables():
357             return True
358         else:
359             return False
360
361 class static():
362     json = 'static/db/db.json'
363     bak = 'static/db/bak.json'
364
365 st = static()
366 if __name__ == '__main__':
367     tornado.options.parse_command_line()
368     http_server = tornado.httpserver.HTTPServer(Application())
369     http_server.listen(options.port)
370     tornado.ioloop.IOLoop.instance().start()