OSDN Git Service

simplify many codes.
[rec10/rec10-git.git] / Rec10WEB / trunk / src / rec10web.py
index fb210a5..faf4101 100644 (file)
 # Rec10 TS Recording Tools
 # Copyright (C) 2009 Yukikaze
 import cgi
-import cgitb
-import sqlite3
+import cgitb;cgitb.enable()
+import rec10web_dbMySQL
+import rec10web_dbSQLite
 import os
+import re
 import datetime
-cgitb.enable()
-path=str(os.path.dirname(os.path.abspath(__file__)))+"/"
-dbpath=path+"ch.db"
-
+import rec10web_dbSQLite
+import ConfigParser
+import time
 
+path=str(os.path.dirname(os.path.abspath(__file__)))+"/"
+confp=ConfigParser.SafeConfigParser()
+Conf='config.ini'
+confp.read(path+Conf)
+global f
+f=cgi.FieldStorage()
+def getpath(string):
+    global confp
+    return confp.get('path',string)
+def getdbpath(string):
+    global confp
+    return confp.get('db',string)
+def getdb():
+    retdb=""
+    if getdbpath('db')=='MySQL':
+        dbn=getdbpath("mysql_dbname")
+        dbh=getdbpath("mysql_host")
+        dbu=getdbpath("mysql_user")
+        dbpwd=getdbpath("mysql_passwd")
+        dbport=int(getdbpath("mysql_port"))
+        retdb=rec10web_dbMySQL.DB_MySQL(dbname=dbn,host=dbh,user=dbu,passwd=dbpwd,port=dbport)
+    else:
+        retdb=rec10web_dbSQLite.DB_SQLite(dbpath)
+    return retdb
+def getRecDate():
+    dl=database.select_all_rectime()
+    recdata="id,type,chtxt,title,btime,etime,deltaday,opt\n"
+    #print dl
+    for d in dl:
+        id=d['id']
+        typet=d['type']
+        chtxt=d['chtxt']
+        title=d['title']
+        btime=d['btime']
+        etime=d['etime']
+        deltatime=d['deltatime']
+        deltaday=d['deltaday']
+        opt=d['opt']
+        if deltaday==None:
+            deltaday="なし"
+        elif deltaday=="":
+            deltaday="なし"
+        if opt==None:
+            opt="なし"
+        if typet=="res":
+            typet="一回予約"
+        elif typet=="key":
+            typet="検索予約"
+        elif typet=="keyevery":
+            typet="隔週予約"
+        elif typet=="res":
+            typet="録画最終"
+        elif typet=="grid":
+            typet="外部委託"
+        elif typet=="ts2avi":
+            typet="縁故予約"
+        elif typet=="b252ts":
+            typet="復号予約"
+        #print btime
+        btime=btime[5:16]
+        etime=etime[5:16]
+        btime=btime.replace("-","/")
+        etime=etime.replace("-","/")
+        if btime[0:5]==etime[0:5]:
+            etime=etime[6:]
+        s="\""+str(id)+"\",\""+typet+"\",\""+chtxt+"\",\""+title+"\",\""+btime+"\",\""+etime+"\",\""+deltaday+"\",\""+opt+"\"\n"
+        s=str(id)+","+typet+","+chtxt+","+title+","+btime+","+etime+","+deltaday+","+opt+"\n"
+        recdata=recdata+s
+    f=open(path+"/recdatum.csv","w")
+    f.write(recdata)
+    f.close()
+def getiEPGDate():
+    dl=database.select_all_iepg()
+    recdata="id,name,chtxt\n"
+    #print dl
+    s=""
+    for d in dl:
+        s=s+d[0]+","+d[1]+","+d[2]+"\n"
+    recdata=recdata+s
+    f=open(path+"/iepgdatum.csv","w")
+    f.write(recdata)
+    f.close()
 def getchtxt():
-    db=sqlite3.connect(dbpath)
+    dl=database.select_all_chdata()
     chopt=""
-    for bctype, ontv, chtxt, ch, csch ,updatetime in db.execute("SELECT bctype,ontv,chtxt,ch,csch,updatetime FROM chdata"):
+    for bctype, ontv, chtxt, ch, csch ,updatetime in dl:
         chdisplay=""
-        for bctype,channel,display in db.execute("SELECT bctype,channel,display FROM ch WHERE channel=\""+ontv+"\""):
+        for bctype,channel,display in database.select_by_ontv_ch(ontv):
             chdisplay=display
-        chopt=chopt+"<option  value="+chtxt+">"+display+"</option>\n                "
-    db.close()
+        if chdisplay!="":
+            chopt=chopt+"<option  value="+chtxt+">"+chdisplay+"</option>\n                "
     return chopt
+def edit_date(id):
+    ret=database.select_by_id_rectime(id)
+    return ret[0]
+def reserv_recday(keyword,chtxt,btime,etime,deltatime,opt,deltaday,day):
+    """
+    dayは月曜日を1日曜日を7とした数字
+    """
+    #bt=datetime.datetime.strptime(btime,"%Y-%m-%d %H:%M:%S")
+    #et=datetime.datetime.strptime(etime,"%Y-%m-%d %H:%M:%S")
+    bt=datetime.datetime(*time.strptime(btime,"%Y-%m-%d %H:%M:%S")[:-3])
+    et=datetime.datetime(*time.strptime(etime,"%Y-%m-%d %H:%M:%S")[:-3])
+    dt=int(day)-bt.isoweekday()
+    if dt<0:
+        dt=dt+7
+    dbt=bt+datetime.timedelta(days=dt)
+    det=et+datetime.timedelta(days=dt)
+    btime=dbt.strftime("%Y-%m-%d %H:%M:%S")
+    etime=det.strftime("%Y-%m-%d %H:%M:%S")
+    return reserv("keyevery",keyword,chtxt,btime,etime,deltatime,opt,"7")
 def reserv(type,keyword,chtxt,btime,etime,deltatime,opt,deltaday):
-    db=sqlite3.connect(dbpath)
-    recline="\""+type+"\",\""+chtxt+"\",\""+keyword+"\",datetime(\""+btime+"\"),datetime(\""+etime+"\"),\""+deltatime+"\",\""+opt+"\",\""+deltaday+"\""
-    #print recline
-    db.execute('insert into rectime ("type","chtxt","title","btime","etime","deltatime","opt","deltaday") values ('+recline+')')
-    db.commit()
-    db.close()
+    MaxT=2
+    MaxS=2
+    tsnum=count_schedule(btime,etime)
+    MaxT=MaxT-tsnum[0]
+    MaxS=MaxS-tsnum[1]
+    bctype=""
+    rett=""
+    bctypegetdb=database.select_by_chtxt_chdata(chtxt)
+    for bctypet,ontvt,chtxtt,cht,cscht,updatetimet in bctypegetdb:
+        bctype=bctypet
+    if (type=="rec") or (type=="res") or (type=="key") or (type=="keyevery"):
+        if bctype.find("cs")>-1:
+            MaxS=MaxS-1
+        elif bctype.find("bs")>-1:
+            MaxS=MaxS-1
+        elif bctype.find("te")>-1:
+            MaxT=MaxT-1
+    if MaxS>-1 and MaxT>-1:
+        database.add_rectime(type=type,chtxt=chtxt,title=keyword,btime=btime,etime=etime,deltatime=deltatime,deltaday=deltaday,opt=opt)
+    else:
+        rett="over"
+    return rett
+def count_schedule(btime,etime):
+    """
+    return rec num (int return[0]:TE /int return[1]:BS/CS)
+    """
+    def cmpare(x,y):
+        #xt=datetime.datetime(*time.strptime(x,"%Y-%m-%d %H:%M:%S")[:-3])
+        #yt=datetime.datetime(*time.strptime(y,"%Y-%m-%d %H:%M:%S")[:-3])
+        xt=x
+        yt=y
+        if xt>yt:
+            return -1
+        elif xt==yt:
+            return 0
+        else:
+            return 1
+    dls=database.schedule_rectime(btime,etime)
+    print dls
+    times=[]
+    btd=datetime.datetime(*time.strptime(btime,"%Y-%m-%d %H:%M:%S")[:-3])
+    etd=datetime.datetime(*time.strptime(etime,"%Y-%m-%d %H:%M:%S")[:-3])
+    for dl in dls:
+        dd1=datetime.datetime(*time.strptime(dl[4],"%Y-%m-%d %H:%M:%S")[:-3])
+        dd2=datetime.datetime(*time.strptime(dl[5],"%Y-%m-%d %H:%M:%S")[:-3])
+        if dd1<btd:
+            dd1=btd
+        if dd2>etd:
+            dd2=etd
+        times.append(dd1)
+        times.append(dd2)
+    print times
+    times=list(set(times))
+    print times
+    times.sort(cmpare)
+    times.reverse()
+    print times
+    retcount=[0,0]
+    for i in xrange(0, len(times)-2, 1):
+        bt1=times[i]
+        et1=times[i+1]
+        btime1=bt1.strftime("%Y-%m-%d %H:%M:%S")
+        etime1=et1.strftime("%Y-%m-%d %H:%M:%S")
+        ret1=database.count_schedule_rectime(btime1,etime1)
+        if retcount[0]<ret1[0]:
+            retcount[0]=ret1[0]
+        if retcount[1]<ret1[1]:
+            retcount[1]=ret1[1]
+    return retcount
+def change_reserv(id,type,keyword,chtxt,btime,etime,deltatime,opt,deltaday):
+    """
+    idはテキスト
+    """
+    MaxT=2
+    MaxS=2
+    tsnum=count_schedule(btime, etime)
+    MaxT=MaxT-tsnum[0]
+    MaxS=MaxS-tsnum[1]
+    bctype=""
+    rett=""
+    for dl in database.select_by_chtxt_chdata(chtxt):
+        bctype=dl[0]
+    if (type=="rec") or (type=="res") or (type=="key") or (type=="keyevery"):
+        if bctype.find("cs")>-1:
+            MaxS=MaxS-1
+        elif bctype.find("bs")>-1:
+            MaxS=MaxS-1
+        elif bctype.find("te")>-1:
+            MaxT=MaxT-1
+    if MaxS>-1 and MaxT>-1:
+        database.del_by_id_rectime(id)
+        database.add_rectime(type=type, chtxt=chtxt, title=keyword, btime=btime, etime=etime, deltatime=deltatime, deltaday=deltaday, opt=opt)
+    else:
+        rett="over"
+    return rett
 def station2chtxt(station):
-    db=sqlite3.connect(dbpath)
     ret=""
-    for bctype, ontv, chtxt, ch, csch ,updatetime in db.execute("SELECT bctype,ontv,chtxt,ch,csch,updatetime FROM chdata WHERE station=\""+station+"\""):
-        ret=chtxt
-    db.close()
+    #try:
+    database.new_iepg()
+    #except:
+    #    ""
+    sta=database.select_by_station_iepg(station)
+    if len(sta)>0:
+        ret=sta[0][1]
+    else:
+        ret="n\/a"
     return ret
 def readHtmlSrcSimple():
     f = open(path+'rswi.htm')
@@ -46,18 +242,101 @@ def readRecFinisSimple():
     ret=f.read()
     f.close()
     return ret
-f=cgi.FieldStorage()
-
+def readRecSchedule():
+    f = open(path+'schedule.htm')
+    ret=f.read()
+    f.close()
+    return ret
+def readiEPGadd():
+    f = open(path+'iepg_add.htm')
+    ret=f.read()
+    f.close()
+    return ret
+def readiEPGshow():
+    f = open(path+'iepg_show.htm')
+    ret=f.read()
+    f.close()
+    return ret
+def get_fin(string,refreshurl):
+    htmdate=readRecFinisSimple()
+    htmdate=htmdate.replace('<!--text_for_replace_fin//-->',string)
+    htmdate=htmdate.replace('<!--url_for_replace_fin//-->',refreshurl)
+    return htmdate
+def mode_iepg_add(station):
+    htmdate=readiEPGadd()
+    htmdate=htmdate.replace("<!--text_for_replace_chtxt_input//-->",getchtxt())
+    htmdate=htmdate.replace("<!--ch-value//-->","")
+    htmdate=htmdate.replace("<!--iepg_title-value//-->",station)
+    return htmdate
+def mode_iepg_fin():
+    s="epgデータの追加を完了しました。<br>\n録画を行う場合はもう一度おねがいします。<br>"
+    u="rec10web.py?exec=iepg-show"
+    return get_fin(s,u)
+def mode_iepg_show():
+    htmdate=readiEPGshow()
+    return htmdate
+def mode_iepg_del():
+    s="epgデータを削除しました。"
+    u="rec10web.py?exec=iepg-show"
+    return get_fin(s,u)
+def mode_iepg_del_miss():
+    s="epgデータの削除に失敗しました。"
+    u="rec10web.py?exec=iepg-show"
+    return get_fin(s,u)
+def mode_schedule():
+    htmdate=readRecSchedule()
+    return htmdate
+def mode_recfin():
+    s="予約が終了しました。移動します。"
+    u="rec10web.py?exec=schedule"
+    return get_fin(s,u)
+def mode_recover():
+    s="最大予約可能数を超えています"
+    u="rec10web.py?exec=schedule"
+    return get_fin(s,u)
+def mode_normal():
+    htmdate=readHtmlSrcSimple()
+    htmdate=htmdate.replace("<!--exec-value//-->","yes")
+def mode_edit():
+    editnum=exect.replace("edit:","")
+    htmdate= readHtmlSrcSimple()
+    iddata=edit_date(editnum)
+    htmdate=htmdate.replace("<!--text_for_replace_chtxt_input//-->",getchtxt())
+    htmdate=htmdate.replace("<!--ch-value//-->",iddata['chtxt'])
+    htmdate=htmdate.replace("<!--btime-value//-->",iddata['btime'])
+    htmdate=htmdate.replace("<!--etime-value//-->",iddata['etime'])
+    htmdate=htmdate.replace("<!--type-value//-->",iddata['type'])
+    htmdate=htmdate.replace("<!--ch-value//-->",iddata['chtxt'])
+    htmdate=htmdate.replace("<!--title-value//-->",iddata['title'])
+    htmdate=htmdate.replace("<!--size-value//-->",size)
+    htmdate=htmdate.replace("<!--opts-value//-->",iddata["opt"])
+    htmdate=htmdate.replace("<!--exec-value//-->","edit-exec:"+editnum)
+    return htmdate
+dbpath=path+"ch.db"
+database=getdb()
 btime=""
 etime=""
 title=""
 chtxt=""
 type="res"
 bt=""
+station_name=""
+mode=""
 ###ここからiEPG用の読み出し
+if f.getfirst('station_name'):
+    station=f.getfirst('station_name')
+    chtxt=station2chtxt(station)
+    if chtxt=="n\/a":
+        mode="iepg-add"
+        station_name=station
+        exect="iepg-add"
 if f.getfirst('station'):
     station=f.getfirst('station')
     chtxt=station2chtxt(station)
+    if chtxt=="n\/a":
+        mode="iepg-add"
+        station_name=station
+        exect="iepg-add"
 ###ここから外部からの読み出しの場合
 if f.getfirst('type'):
     type=f.getfirst('type')
@@ -67,25 +346,24 @@ if f.getfirst('chtxt'):
     chtxt=f.getfirst('chtxt')
 if f.getfirst('btime'):
     btime=f.getfirst('btime')
-    bt=datetime.datetime.strptime(btime,"%Y-%m-%d %H:%M:%S")
+    bt=datetime.datetime(*time.strptime(btime,"%Y-%m-%d %H:%M:%S")[:-3])
 if f.getfirst('etime'):
     etime=f.getfirst('etime')
-    et=datetime.datetime.strptime(etime,"%Y-%m-%d %H:%M:%S")
+    et=datetime.datetime(*time.strptime(etime,"%Y-%m-%d %H:%M:%S")[:-3])
     if bt !="":
         delt=et-bt
-        dt=delt.days*24*60+delt.seconds
+        dt=delt.days*24*60*60+delt.seconds
         if dt<0:
             dd=datetime.timedelta(days=1)
             et=et+dd
             etime=et.strftime("%Y-%m-%d %H:%M:%S")
-        if dt<-1*24*60+1:
+        if dt<-1*24*60*60:
             d1=datetime.datetime(bt.year,0,0)
             d2=datetime.datetime(bt.year+1,0,0)
             dd=d2-d1
             et=et+dd
             etime=et.strftime("%Y-%m-%d %H:%M:%S")
-        
-size=""
+size="S"
 if f.getfirst('size'):
     size=f.getfirst('size')
 opts=""
@@ -100,10 +378,21 @@ if f.getfirst('deltaday',""):
 exect=""
 if f.getfirst('exec',""):
     exect=f.getfirst('exec',"")
-    
-htmdate= readHtmlSrcSimple()
+if exect=="schedule":
+    mode="schedule"
+    getRecDate()
+elif re.search('edit:',exect):
+    mode="edit"
+elif exect=="iepg-add":
+    mode="iepg-add"
+elif exect=="iepg-show":
+    mode="iepg-show"
+elif exect=="iepg-add_yes":
+    mode="iepg-add-yes"
+elif exect=="iepg-del":
+    mode="iepg-del"
+htmdate= mode_normal()
 htmdate=htmdate.replace("<!--text_for_replace_chtxt_input//-->",getchtxt())
-
 htmdate=htmdate.replace("<!--btime-value//-->",btime)
 htmdate=htmdate.replace("<!--etime-value//-->",etime)
 htmdate=htmdate.replace("<!--type-value//-->",type)
@@ -111,12 +400,80 @@ htmdate=htmdate.replace("<!--ch-value//-->",chtxt)
 htmdate=htmdate.replace("<!--title-value//-->",title)
 htmdate=htmdate.replace("<!--size-value//-->",size)
 htmdate=htmdate.replace("<!--opts-value//-->",opts)
-
+#ここから曜日検索の設定
+if f.getfirst('type')=="keyday":
+    rett=""
+    dayt=f.getfirst('day_Mon')
+    if dayt:
+        rett=rett+reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
+    dayt=f.getfirst('day_Tue')
+    if dayt:
+        rett=rett+reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
+    dayt=f.getfirst('day_Wed')
+    if dayt:
+        rett=rett+reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
+    dayt=f.getfirst('day_Thu')
+    if dayt:
+        rett=rett+reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
+    dayt=f.getfirst('day_Fri')
+    if dayt:
+        rett=rett+reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
+    dayt=f.getfirst('day_Sat')
+    if dayt:
+        rett=rett+reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
+    dayt=f.getfirst('day_Sun')
+    if dayt:
+        rett=rett+reserv_recday(title, chtxt, btime, etime, deltahour, opts, deltaday, dayt)
+    if rett=="":
+        htmdate=mode_recfin()
+    else:
+        htmdate=mode_recover()
+    chtxt=""
+    exect=""
 if (chtxt != "")and(title != "")and(btime!="")and(etime!="")and(opts!="")and(exect=="yes"):
-    reserv(type, title, chtxt, btime, etime, deltahour, opts, deltaday)
-    htmdate=readRecFinisSimple()
+    restxt=reserv(type, title, chtxt, btime, etime, deltahour, opts, deltaday)
+    if restxt=="":
+        htmdate=mode_recfin()
+    elif restxt=="over":
+        htmdate=mode_recover()
+    exect=""
+if (chtxt != "")and(title != "")and(btime!="")and(etime!="")and(opts!="")and(re.search('edit-exec:',exect)):
+    editnum=exect.replace("edit-exec:","")
+    restxt=change_reserv(editnum,type, title, chtxt, btime, etime, deltahour, opts, deltaday)
+    if restxt=="":
+        htmdate=mode_recfin()
+    elif restxt=="over":
+        htmdate=mode_recover()
     exect=""
-#
+if mode=="schedule":
+    htmdate=mode_normal()
+elif mode=="edit":
+    htmdate=mode_edit()
+elif mode=="iepg-add":
+    htmdate=mode_iepg_add(station_name)
+elif mode=="iepg-add-yes":
+    try:
+        database.new_iepg()
+    except:
+        ""
+    if f.getfirst('iepg_station') and f.getfirst('iepg_chtxt'):
+        database.add_iepg(f.getfirst('iepg_station'),f.getfirst('iepg_chtxt'))
+    htmdate=mode_iepg_fin()
+elif mode=="iepg-show":
+    getiEPGDate()
+    htmdate=mode_iepg_show()
+elif mode=="iepg-del":
+    s=f.getfirst('iepgdelnum')
+    htmdate=""
+    try:
+        for st in s.split(","):
+            if st!="":
+                database.del_by_id_iepg(st)
+        htmdate=mode_iepg_del()
+    except:
+        htmdate=mode_iepg_del_miss()
+print "Content-Type: text/html"
 print htmdate
-
+#print exect
+#print mode