OSDN Git Service

detail corrected
[pybbs/pybbs.git] / index.py
index 0f2071b..d40928a 100755 (executable)
--- a/index.py
+++ b/index.py
@@ -1,14 +1,18 @@
 
 import os.path
-import shutil,copy
-import tornado.auth
+import shutil,re
 import tornado.escape
 import tornado.web
-import tornado.wsgi
-import wsgiref.simple_server
+import tornado.httpserver
+import tornado.ioloop
+import tornado.options
+from tornado.options import define,options
 from tinydb import TinyDB,Query,where
 from tinydb.operations import delete
 from datetime import datetime
+import json
+
+define('port',default=8000,help='run on the given port',type=int)
 
 class BaseHandler(tornado.web.RequestHandler):
     def get_current_user(self):
@@ -32,6 +36,16 @@ class IndexHandler(BaseHandler):
             else:
                 raise tornado.web.HTTPError(404)
                 return
+        key = self.get_argument('key','')
+        if key:
+            table = self.application.db.table(dbname)
+            rec = table.get(where('number') == int(key))
+            if rec:
+                self.render('article.htm',record=rec)
+                return
+            else:
+                raise tornado.web.HTTPError(404)
+                return
         i = params['count']      
         na = tornado.escape.url_unescape(self.get_cookie("username",u"誰かさん"))
         pos = self.application.gpos(dbname,page)
@@ -120,25 +134,40 @@ class RegistHandler(tornado.web.RequestHandler):
         if self.application.collection(dbname) == False:
             raise tornado.web.HTTPError(404)
             return
+        self.database = dbname
         rec = self.application.db.get(where('kinds') == 'conf')
         words = rec['bad_words']
         out = rec['out_words']
-        na = self.get_argument('name',u'誰かさん')
-        sub = self.get_argument('title',u'タイトルなし')
-        com = self.get_argument('comment')
+        na = self.get_argument('name')
+        sub = self.get_argument('title')
+        com = self.get_argument('comment',None,False)
         text = ''
         i = 0
+        url = []
         error = ''
         for word in out:
             if word in com:
                 error = error + u'禁止ワード.'
                 break
         for line in com.splitlines(True):
+            if error != '':
+                break
             for word in words:
                 if word in line.lower():
                     error = error + u'タグ違反.('+word+')'       
-            i += len(line)
+            i += len(line)   
+            obj = re.finditer('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', line)
+            for x in obj:
+                if x.group() not in url:
+                    url.append(x.group())
+            if re.match(' ',line):
+                line = line.replace(' ',' ',1)
             text = text+'<p>'+self.link(line)+'<br></p>'
+        s = ''
+        for x in url:
+            s = s+'<tr><td><a class=livepreview target=_blank href={0}>{0}</a></td></tr>'.format(x)
+        if s:
+            text = text+'<table><tr><td>検出URL:</td></tr>'+s+'</table>'
         pw = self.get_argument('password')
         if i == 0:
             error = error + u'本文がありません.'
@@ -151,6 +180,8 @@ class RegistHandler(tornado.web.RequestHandler):
             item = sorted(article.all(),key=lambda x: x['number'])[len(article)-1]
             no = item['number']+1
         if error == '':
+            if not na:
+                na = u'誰かさん'
             s = datetime.now()
             reg = {'number':no,'name':na,'title':sub,'comment':text,'raw':com,'password':pw,'date':s.strftime('%Y/%m/%d %H:%M')}
             article.insert(reg)
@@ -160,30 +191,16 @@ class RegistHandler(tornado.web.RequestHandler):
             self.render('regist.htm',content=error)
     
     def link(self,command):
-        y = ''
         i = 0
         text = ''
-        for x in command.split():
-            if (y == '>>')and(x.isdecimal() == True):
-                s = '<a href=#'+x+'>'+x+'</a>'
-                while -1 < command.find(x,i):
-                    j = command.find(x,i)
-                    tmp = command[i:j]
-                    i = j+len(x)
-                    k = tmp.rsplit(None,1)
-                    if ((len(k) > 1)and(k[1] == y))or(k[0] == y):
-                        text = text+tmp+s                                                                       
-                        break
-                    else:
-                        text = text+tmp+x                        
-            y = x    
-        if text == '':
-            return command
+        obj = re.finditer('>>[0-9]+',command)
+        for x in obj:
+            s = '<a class=minpreview data-preview-url=/{0}?key={1} href=/{0}#{1}>>>{1}</a>'.format(self.database,x.group()[2:])
+            text = text+command[i:x.start()]+s
+            i = x.end()
         else:
-            if len(command) > i:
-                return text+command[i:]
-            else:
-                return text
+            text = text+command[i:]
+        return text
     
 class AdminHandler(BaseHandler):
     @tornado.web.authenticated               
@@ -309,10 +326,48 @@ class FooterModule(tornado.web.UIModule):
     def render(self,number,url,link):
         return self.render_string('modules/footer.htm',index=number,url=url,link=link)
     
+class HeadlineApi(tornado.web.RequestHandler):
+    def get(self):
+        response = {}
+        for x in self.application.db.tables():
+            if x != '_default':
+                response[x] = self.get_data(x)           
+        self.write(json.dumps(response,ensure_ascii=False))
+    
+    def get_data(self,dbname):
+        table = self.application.db.table(dbname)
+        i = len(table)
+        if i == 0:
+            return {}
+        else:
+            rec = sorted(table.all(),key=lambda x: x['number'])[i-1]
+            return {'number':rec['number'],'title':rec['title'],'name':rec['name'],'comment':rec['raw'][0:19]}
+        
+class ArticleApi(tornado.web.RequestHandler):
+    def get(self,dbname,number):
+        if self.application.collection(dbname) == True:
+            table = self.application.db.table(dbname)
+            response = table.get(where('number') == int(number))
+            if response == None:
+                response = {}
+            else:
+                del response['comment']
+            self.write(json.dumps(response,ensure_ascii=False))
+        else:
+            tornado.web.HTTPError(404)
+    
+    def post(self,dbname):
+        name = self.get_argument('name',u'誰かさん')
+        title = self.get_argument('title',u'タイトルなし')
+        comment = self.get_argument('comment')
+        table = self.application.db.table(dbname)
+        table.insert({'name':name,'title':title,'comment':comment})
+        
 class Application(tornado.web.Application):    
     def __init__(self):
         self.db = TinyDB(st.json)
         handlers = [(r'/',NaviHandler),(r'/login',LoginHandler),(r'/logout',LogoutHandler),(r'/title',TitleHandler),
+                    (r'/headline/api',HeadlineApi),(r'/read/api/([a-zA-Z0-9_]+)/([0-9]+)',ArticleApi),(r'/write/api/([a-zA-Z0-9_]+)',ArticleApi),
                     (r'/([a-zA-Z0-9_]+)',IndexHandler),(r'/([a-zA-Z0-9_]+)/([0-9]+)/',IndexHandler),
                     (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),
                     (r'/([a-zA-Z0-9_]+)/search',SearchHandler),(r'/([a-zA-Z0-9_]+)/regist',RegistHandler)]
@@ -321,7 +376,7 @@ class Application(tornado.web.Application):
                         'ui_modules':{'Footer':FooterModule},
                         'cookie_secret':'bZJc2sWbQLKos6GkHn/VB9oXwQt8SOROkRvJ5/xJ89E=',
                         'xsrf_cookies':True,
-                        #'debug':True,
+                        'debug':True,
                         'login_url':'/login'
                         }
         tornado.web.Application.__init__(self,handlers,**settings)
@@ -346,7 +401,8 @@ class static():
     bak = 'static/db/bak.json'
 
 st = static()
-app = tornado.wsgi.WSGIAdapter(Application())
 if __name__ == '__main__':
-    server = wsgiref.simple_server.make_server('',8888,app)
-    server.serve_forever()
+    tornado.options.parse_command_line()
+    http_server = tornado.httpserver.HTTPServer(Application())
+    http_server.listen(options.port)
+    tornado.ioloop.IOLoop.instance().start()