OSDN Git Service

fix status double counting bug.
[rec10/rec10-git.git] / rec10 / trunk / src / dbMySQL.py
1 #!/usr/bin/python
2 # coding: UTF-8
3 # Rec10 TS Recording Tools
4 # Copyright (C) 2009 Yukikaze
5 import MySQLdb
6 import dbSQLite
7
8 class DB_MySQL:
9     dbname = ""
10     dbhost = ""
11     dbusr = ""
12     dbpasswd = ""
13     dbport = 0
14     def __init__(self, dbname, user, passwd, host="localhost", port=3306):
15         self.dbname = dbname
16         self.dbhost = host
17         self.dbusr = user
18         self.dbpasswd = passwd
19         self.dbport = port
20         try:
21             con = MySQLdb.connect(user=user, passwd=passwd)
22             cur = con.cursor()
23             cur.execute('CREATE DATABASE ' + dbname + " DEFAULT CHARACTER SET utf8")
24             cur.close()
25             con.close()
26         except:
27             ""
28         db = self.connect_db()
29         try:
30             db[1].execute('\
31             CREATE TABLE rectime \
32             (\
33             id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,\
34             type VARCHAR(20),\
35             chtxt VARCHAR(20),\
36             title VARCHAR(100),\
37             btime DATETIME,\
38             etime DATETIME,\
39             deltatime VARCHAR(5),\
40             deltaday VARCHAR(5),\
41             opt VARCHAR(20),\
42             UNIQUE uni (type,chtxt,title,btime,deltaday)\
43             )')
44         except:
45             ""
46         self.new_tv("")
47         self.new_ch("")
48         self.close_db(db)
49     def connect_db(self):
50         """
51         dbへの接続
52         """
53         con = MySQLdb.connect(db=self.dbname, host=self.dbhost, port=self.dbport, user=self.dbusr, passwd=self.dbpasswd, charset="utf8")
54         cur = con.cursor()
55         cur.execute('set names utf8;')
56         return [con, cur]
57     def close_db(self, db):
58         db[1].close()
59         db[0].close()
60     def new_chdata(self):
61         db = self.connect_db()
62         try:
63             db[1].execute('drop table chdata')
64         except:
65             ""
66         try:
67             db[1].execute('\
68             CREATE TABLE chdata \
69             (\
70             bctype VARCHAR(15),\
71             ontv VARCHAR(30) PRIMARY KEY,\
72             chtxt VARCHAR(15),\
73             ch VARCHAR(20),\
74             csch VARCHAR(20),\
75             updatetime DATETIME,\
76             status TINYINT\
77             )')
78         except:
79             ""
80         self.close_db(db)
81     def add_chdata(self, bctype, ontv, chtxt, ch, csch, updatetime):
82         db = self.connect_db()
83         db[1].execute('\
84         INSERT INTO chdata \
85         VALUES (%s,%s,%s,%s,%s,%s,%s)', \
86                       (bctype, ontv, chtxt, ch, csch, updatetime, "1"))
87         self.close_db(db)
88     def select_by_ontv_chdata(self, ontv):
89         db = self.connect_db()
90         dbexe = db[1].execute("\
91         SELECT bctype,ontv,chtxt,ch,csch,updatetime \
92         FROM chdata \
93         WHERE ontv = %s", \
94                               (ontv,))
95         ret = []
96         dls = []
97         if dbexe > 0:
98             dls = db[1].fetchall()
99         self.close_db(db)
100         for dl in dls:
101             r = list(dl)
102             r[5] = r[5].strftime("%Y-%m-%d %H:%M:%S")
103             ret.append(r)
104         return ret
105     def select_by_chtxt_chdata(self, chtxt):
106         db = self.connect_db()
107         dbexe = db[1].execute("\
108         SELECT bctype,ontv,chtxt,ch,csch,updatetime \
109         FROM chdata \
110         WHERE chtxt = %s", \
111                               (chtxt,))
112         ret = []
113         dls = []
114         if dbexe > 0:
115             dls = db[1].fetchall()
116         self.close_db(db)
117         for dl in dls:
118             r = list(dl)
119             r[5] = r[5].strftime("%Y-%m-%d %H:%M:%S")
120             ret.append(r)
121         return ret
122     def select_by_bctype_chdata(self, bctype):
123         db = self.connect_db()
124         dbexe = db[1].execute("\
125         SELECT bctype,ontv,chtxt,ch,csch,updatetime,status \
126         FROM chdata \
127         WHERE bctype = %s", \
128                               (bctype,))
129         ret = []
130         dls = []
131         if dbexe > 0:
132             dls = db[1].fetchall()
133         self.close_db(db)
134         for dl in dls:
135             #print dl
136             r = list(dl)
137             r[5] = r[5].strftime("%Y-%m-%d %H:%M:%S")
138             r[6] = str(r[6])
139             ret.append(r)
140         return ret
141     def select_by_ch_chdata(self, ch):
142         db = self.connect_db()
143         dbexe = db[1].execute("\
144         SELECT \
145         bctype,ontv,chtxt,ch,csch,updatetime \
146         FROM chdata \
147         WHERE ch = %s", \
148                               (ch,))
149         ret = []
150         dls = []
151         if dbexe > 0:
152             dls = db[1].fetchall()
153         self.close_db(db)
154         for dl in dls:
155             r = list(dl)
156             r[5] = r[5].strftime("%Y-%m-%d %H:%M:%S")
157             ret.append(r)
158         return ret
159     def select_all_chdata(self):
160         db = self.connect_db()
161         dbexe = db[1].execute("\
162         SELECT bctype,ontv,chtxt,ch,csch,updatetime \
163         FROM chdata \
164         ")
165         ret = []
166         dls = []
167         if dbexe > 0:
168             dls = db[1].fetchall()
169         self.close_db(db)
170         for dl in dls:
171             r = list(dl)
172             r[5] = r[5].strftime("%Y-%m-%d %H:%M:%S")
173             ret.append(r)
174         return ret
175     def select_get_update_chdata(self, dhour):
176         db = self.connect_db()
177         dbexe = db[1].execute("SELECT bctype,chtxt,status FROM chdata \
178         WHERE \
179         ( \
180         updatetime < DATE_SUB(now(),INTERVAL " + dhour + " HOUR) \
181         AND \
182         status = 1 \
183         ) \
184         OR \
185         status > 1 \
186         ORDER BY status DESC")
187         ret = []
188         #print dbexe
189         if dbexe > 0:
190             ret = db[1].fetchall()
191         self.close_db(db)
192         return ret
193     def update_by_bctype_chdata(self, bctype):
194         db = self.connect_db()
195         db[1].execute("\
196         UPDATE chdata \
197         SET \
198         updatetime=now() , \
199         status = 1 \
200         WHERE bctype = %s", (bctype,))
201         self.close_db(db)
202     def update_by_bctype_and_chtxt_chdata(self, bctype, chtxt):
203         db = self.connect_db()
204         db[1].execute("\
205         UPDATE chdata \
206         SET \
207         updatetime=now() , \
208         status = 1\
209         WHERE bctype = %s AND chtxt = %s", (bctype, chtxt))
210         self.close_db(db)
211     def update_status_by_bctype_chdata(self, bctype, status):
212         db = self.connect_db()
213         db[1].execute("\
214         UPDATE chdata \
215         SET \
216         status=%s \
217         WHERE bctype = %s", \
218                       (status, bctype)\
219                       )
220         self.close_db(db)
221     def add_rectime(self, type="", chtxt="", title="", btime="", etime="", deltatime="", deltaday="", opt=""):
222         db = self.connect_db()
223         db[1].execute('\
224         INSERT IGNORE into rectime \
225         (type,chtxt,title,btime,etime,deltatime,deltaday,opt) \
226         values (%s,%s,%s,%s,%s,%s,%s,%s)', \
227                       (type, chtxt, title, btime, etime, deltatime, deltaday, opt))
228         ##db.commit()
229         self.close_db(db)
230     def del_rectime(self, type="", title="", chtxt="", btime=""):
231         """
232
233         """
234         db = self.connect_db()
235         db[1].execute("\
236         DELETE FROM rectime \
237         WHERE type = %s AND title = %s AND chtxt = %s AND btime = %s", \
238                       (type, title, chtxt, btime))
239         #db.commit()
240         self.close_db(db)
241     def select_all_rectime(self):
242         db = self.connect_db()
243         recdata = []
244         dbr = db[1].execute("\
245         SELECT type, chtxt, title, btime, etime, deltatime ,deltaday ,opt \
246         FROM rectime")
247         dbl = db[1].fetchall()
248         self.close_db(db)
249         if dbr > 0:
250             for typet, chtxt, title, btime, etime, deltatime, deltaday, opt in dbl:
251                 ret = {}
252                 ret['type'] = typet
253                 ret['chtxt'] = chtxt
254                 ret['title'] = title.encode('utf-8')
255                 btime = btime.strftime("%Y-%m-%d %H:%M:%S")
256                 etime = etime.strftime("%Y-%m-%d %H:%M:%S")
257                 ret['btime'] = btime
258                 ret['etime'] = etime
259                 ret['opt'] = opt
260                 ret['deltatime'] = ""
261                 ret['deltaday'] = ""
262                 if deltatime == None:
263                     deltatime = "3"
264                 if deltaday == None:
265                     deltaday = "7"
266                 if typet == 'key':
267                     ret['deltatime'] = deltatime
268                 elif typet == 'keyevery':
269                     ret['deltatime'] = deltatime
270                     ret['deltaday'] = deltaday
271                 recdata.append(ret)
272         self.close_db(db)
273         return recdata
274     def select_bytime_rectime(self, dminutes):
275         db = self.connect_db()
276         recdatum = []
277         #dbr=db[1].execute("SELECT type, chtxt, title, btime, etime, deltatime ,deltaday ,opt FROM rectime WHERE btime < DATE_SUB(now(),INTERVAL "+dminutes+" MINUTE ) AND btime > DATE_ADD(now(),INTERVAL "+dminutes+" MINUTE )")
278         dbr = db[1].execute("SELECT \
279         type, chtxt, title, btime, etime, deltatime ,deltaday ,opt \
280         FROM rectime \
281         WHERE btime BETWEEN DATE_SUB(now(),INTERVAL " + dminutes + " MINUTE ) AND \
282         DATE_ADD(now(),INTERVAL " + dminutes + " MINUTE )")
283         dbl = db[1].fetchall()
284         self.close_db(db)
285         #print dbl
286         if dbr > 0:
287             for typet, chtxt, title, btime, etime, deltatime, deltaday, opt in dbl:
288                 ret = {}
289                 ret['type'] = typet
290                 ret['chtxt'] = chtxt
291                 ret['title'] = title.encode('utf-8')
292                 btime = btime.strftime("%Y-%m-%d %H:%M:%S")
293                 etime = etime.strftime("%Y-%m-%d %H:%M:%S")
294                 ret['btime'] = btime
295                 ret['etime'] = etime
296                 ret['opt'] = opt
297                 if deltatime == None or deltatime == "":
298                     deltatime = "3"
299                 if deltaday == None or deltaday == "":
300                     deltaday = "7"
301                 if typet == 'key':
302                     ret['deltatime'] = deltatime
303                 elif typet == 'keyevery':
304                     ret['deltatime'] = deltatime
305                     ret['deltaday'] = deltaday
306                 recdatum.append(ret)
307         return recdatum
308     def delete_old_rectime(self, dhour):
309         db = self.connect_db()
310         db[1].execute("\
311         DELETE FROM rectime \
312         WHERE \
313         btime < DATE_SUB(now(),INTERVAL " + dhour + " HOUR )")
314         #db.commit()
315         self.close_db(db)
316     def new_status(self):
317         db = self.connect_db()
318         try:
319             db[1].execute("\
320             CREATE TABLE status \
321             (\
322             ts2avi TINYINT DEFAULT 0,\
323             terec TINYINT DEFAULT 0,\
324             bscsrec TINYINT DEFAULT 0,\
325             b252ts TINYINT DEFAULT 0\
326             )")
327             db[1].execute("INSERT IGNORE into status VALUE (0,0,0,0)")
328         except:
329             ""
330
331         self.close_db(db)
332     def select_all_status(self):
333         db = self.connect_db()
334         dbexe = db[1].execute("\
335         SELECT ts2avi,terec,bscsrec,b252ts \
336         FROM status \
337         ")
338         ret = []
339         dls = []
340         if dbexe > 0:
341             dls = db[1].fetchall()
342         self.close_db(db)
343         for dl in dls:
344             r = list(dl)
345             r[0]=str(r[0])
346             r[1]=str(r[1])
347             r[2]=str(r[2])
348             r[3]=str(r[3])
349             ret.append(r)
350         return ret
351         self.close_db(db)
352     def change_ts2avi_status(self,i):
353         """
354         statuをiだけ増減する
355         iはint
356         """
357         db = self.connect_db()
358         db[1].execute("\
359         UPDATE status SET ts2avi=ts2avi+%s",i)
360         self.close_db(db)
361     def change_terec_status(self,i):
362         """
363         statuをiだけ増減する
364         iはint
365         """
366         db = self.connect_db()
367         db[1].execute("\
368         UPDATE status SET terec=terec+%s",i)
369         self.close_db(db)
370     def change_bscsrec_status(self,i):
371         """
372         statuをiだけ増減する
373         iはint
374         """
375         db = self.connect_db()
376         db[1].execute("\
377         UPDATE status SET bscsrec=bscsrec+%s",i)
378         self.close_db(db)
379     def change_b252ts_status(self,i):
380         """
381         statuをiだけ増減する
382         iはint
383         """
384         db = self.connect_db()
385         db[1].execute("\
386         UPDATE status SET b252ts=b252ts+%s",i)
387         self.close_db(db)
388     def new_tv(self, bctype):
389         db = self.connect_db()
390         try:
391             db[1].execute("\
392             DELETE FROM tv \
393             WHERE bctype = %s", \
394                           (bctype,))
395         except:
396             ""
397         try:
398             db[1].execute("\
399             CREATE TABLE tv \
400             (\
401             bctype VARCHAR(20),\
402             channel VARCHAR(100) NOT NULL,\
403             start VARCHAR(30),\
404             stop  VARCHAR(30),\
405             title VARCHAR(100),\
406             exp VARCHAR(200),\
407             category VARCHAR(100),\
408             UNIQUE unitv(bctype,channel,start,stop,title)\
409             )")
410         except:
411             ""
412         #db.commit()
413         self.close_db(db)
414     def add_tv(self, bctype, channel, start, stop, title, desc, category):
415         db = self.connect_db()
416         db[1].execute('\
417         INSERT IGNORE INTO tv \
418         VALUES (%s,%s,%s,%s,%s,%s,%s)', \
419                       (bctype, channel, start, stop, title, desc, category))
420         #db.commit()
421         self.close_db(db)
422     def add_multi_tv(self, tvlists):
423         """
424         tvlists is (bctype,channel,start,stop,title,desc,category) lists.
425         """
426         db = self.connect_db()
427         db[1].executemany('\
428         INSERT IGNORE INTO tv \
429         (bctype,channel,start,stop,title,exp,category) \
430         values(%s,%s,%s,%s,%s,%s,%s)', \
431                           tvlists)
432         #db.commit()
433         self.close_db(db)
434         
435
436     def select_by_time_ngram_tv(self, btime, etime, chtxt):
437         db = self.connect_db()
438         dbexe = "\
439         SELECT \
440         chdata.chtxt,title,start,stop \
441         FROM tv \
442         INNER JOIN chdata \
443         WHERE chdata.ontv=tv.channel \
444         AND \
445         start >= %s \
446         AND \
447         start <= %s \
448         AND \
449         chdata.chtxt=%s"
450         dbcmd = db[1].execute(dbexe, (btime, etime, chtxt))
451         retall = []
452         if dbcmd > 0:
453             retall = db[1].fetchall()
454         self.close_db(db)
455         return retall
456     def new_ch(self, bctype):
457         db = self.connect_db()
458         try:
459             db[1].execute("DELETE FROM ch WHERE bctype = %s", (bctype,))
460         except:
461             ""
462         try:
463             db[1].execute('\
464             CREATE TABLE ch \
465             (\
466             bctype VARCHAR(20),\
467             channel VARCHAR(20) NOT NULL,\
468             display VARCHAR(100),\
469             UNIQUE unich(bctype,channel)\
470             )')
471         except:
472             ""
473         #db.commit()
474         self.close_db(db)
475     def add_ch(self, bctype, channel, display):
476         db = self.connect_db()
477         db[1].execute('INSERT IGNORE INTO ch VALUES (%s,%s,%s)', (bctype, channel, display))
478         #db.commit()
479         self.close_db(db)
480     def add_multi_ch(self, chlists):
481         """
482         chlists is (bctype,channel,display) lists
483         """
484         db = self.connect_db()
485         db[1].executemany('INSERT IGNORE INTO ch VALUES (%s,%s,%s)', chlists)
486         self.close_db(db)
487     def import_from_SQLite(self, dbpath):
488         dbb = dbSQLite.DB_SQLite(dbpath)
489         dbl = dbb.select_all_rectime()
490         for db in dbl:
491             self.add_rectime(db['type'], db['chtxt'], db['title'], db['btime'], db['etime'], db['deltatime'], db['deltaday'], db['opt'])
492