forked from pyload/pyload
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseBackend.py
More file actions
352 lines (283 loc) · 11.2 KB
/
DatabaseBackend.py
File metadata and controls
352 lines (283 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#!/usr/bin/env python
"""
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
@author: RaNaN
@author: mkaay
"""
from threading import Thread
from threading import Event
from os import remove
from os.path import exists
from shutil import move
from Queue import Queue
from traceback import print_exc
from module.utils import chmod
try:
from pysqlite2 import dbapi2 as sqlite3
except:
import sqlite3
DB_VERSION = 4
class style():
db = None
@classmethod
def setDB(cls, db):
cls.db = db
@classmethod
def inner(cls, f):
@staticmethod
def x(*args, **kwargs):
if cls.db:
return f(cls.db, *args, **kwargs)
return x
@classmethod
def queue(cls, f):
@staticmethod
def x(*args, **kwargs):
if cls.db:
return cls.db.queue(f, *args, **kwargs)
return x
@classmethod
def async(cls, f):
@staticmethod
def x(*args, **kwargs):
if cls.db:
return cls.db.async(f, *args, **kwargs)
return x
class DatabaseJob():
def __init__(self, f, *args, **kwargs):
self.done = Event()
self.f = f
self.args = args
self.kwargs = kwargs
self.result = None
self.exception = False
# import inspect
# self.frame = inspect.currentframe()
def __repr__(self):
from os.path import basename
frame = self.frame.f_back
output = ""
for i in range(5):
output += "\t%s:%s, %s\n" % (basename(frame.f_code.co_filename), frame.f_lineno, frame.f_code.co_name)
frame = frame.f_back
del frame
del self.frame
return "DataBase Job %s:%s\n%sResult: %s" % (self.f.__name__, self.args[1:], output, self.result)
def processJob(self):
try:
self.result = self.f(*self.args, **self.kwargs)
except Exception, e:
print_exc()
try:
print "Database Error @", self.f.__name__, self.args[1:], self.kwargs, e
except:
pass
self.exception = e
finally:
self.done.set()
def wait(self):
self.done.wait()
class DatabaseBackend(Thread):
subs = []
def __init__(self, core):
Thread.__init__(self)
self.setDaemon(True)
self.core = core
self.jobs = Queue()
self.setuplock = Event()
style.setDB(self)
def setup(self):
self.start()
self.setuplock.wait()
def run(self):
"""main loop, which executes commands"""
convert = self._checkVersion() #returns None or current version
self.conn = sqlite3.connect("files.db")
chmod("files.db", 0600)
self.c = self.conn.cursor() #compatibility
if convert is not None:
self._convertDB(convert)
self._createTables()
self._migrateUser()
self.conn.commit()
self.setuplock.set()
while True:
j = self.jobs.get()
if j == "quit":
self.c.close()
self.conn.close()
break
j.processJob()
@style.queue
def shutdown(self):
self.conn.commit()
self.jobs.put("quit")
def _checkVersion(self):
""" check db version and delete it if needed"""
if not exists("files.version"):
f = open("files.version", "wb")
f.write(str(DB_VERSION))
f.close()
return
f = open("files.version", "rb")
v = int(f.read().strip())
f.close()
if v < DB_VERSION:
if v < 2:
try:
self.manager.core.log.warning(_("Filedatabase was deleted due to incompatible version."))
except:
print "Filedatabase was deleted due to incompatible version."
remove("files.version")
move("files.db", "files.backup.db")
f = open("files.version", "wb")
f.write(str(DB_VERSION))
f.close()
return v
def _convertDB(self, v):
try:
getattr(self, "_convertV%i" % v)()
except:
try:
self.core.log.error(_("Filedatabase could NOT be converted."))
except:
print "Filedatabase could NOT be converted."
#--convert scripts start
def _convertV2(self):
self.c.execute('CREATE TABLE IF NOT EXISTS "storage" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "identifier" TEXT NOT NULL, "key" TEXT NOT NULL, "value" TEXT DEFAULT "")')
try:
self.manager.core.log.info(_("Database was converted from v2 to v3."))
except:
print "Database was converted from v2 to v3."
self._convertV3()
def _convertV3(self):
self.c.execute('CREATE TABLE IF NOT EXISTS "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "name" TEXT NOT NULL, "email" TEXT DEFAULT "" NOT NULL, "password" TEXT NOT NULL, "role" INTEGER DEFAULT 0 NOT NULL, "permission" INTEGER DEFAULT 0 NOT NULL, "template" TEXT DEFAULT "default" NOT NULL)')
try:
self.manager.core.log.info(_("Database was converted from v3 to v4."))
except:
print "Database was converted from v3 to v4."
#--convert scripts end
def _createTables(self):
"""create tables for database"""
self.c.execute('CREATE TABLE IF NOT EXISTS "packages" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "name" TEXT NOT NULL, "folder" TEXT, "password" TEXT DEFAULT "", "site" TEXT DEFAULT "", "queue" INTEGER DEFAULT 0 NOT NULL, "packageorder" INTEGER DEFAULT 0 NOT NULL)')
self.c.execute('CREATE TABLE IF NOT EXISTS "links" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "url" TEXT NOT NULL, "name" TEXT, "size" INTEGER DEFAULT 0 NOT NULL, "status" INTEGER DEFAULT 3 NOT NULL, "plugin" TEXT DEFAULT "BasePlugin" NOT NULL, "error" TEXT DEFAULT "", "linkorder" INTEGER DEFAULT 0 NOT NULL, "package" INTEGER DEFAULT 0 NOT NULL, FOREIGN KEY(package) REFERENCES packages(id))')
self.c.execute('CREATE INDEX IF NOT EXISTS "pIdIndex" ON links(package)')
self.c.execute('CREATE TABLE IF NOT EXISTS "storage" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "identifier" TEXT NOT NULL, "key" TEXT NOT NULL, "value" TEXT DEFAULT "")')
self.c.execute('CREATE TABLE IF NOT EXISTS "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "name" TEXT NOT NULL, "email" TEXT DEFAULT "" NOT NULL, "password" TEXT NOT NULL, "role" INTEGER DEFAULT 0 NOT NULL, "permission" INTEGER DEFAULT 0 NOT NULL, "template" TEXT DEFAULT "default" NOT NULL)')
self.c.execute('CREATE VIEW IF NOT EXISTS "pstats" AS \
SELECT p.id AS id, SUM(l.size) AS sizetotal, COUNT(l.id) AS linkstotal, linksdone, sizedone\
FROM packages p JOIN links l ON p.id = l.package LEFT OUTER JOIN\
(SELECT p.id AS id, COUNT(*) AS linksdone, SUM(l.size) AS sizedone \
FROM packages p JOIN links l ON p.id = l.package AND l.status in (0,4,13) GROUP BY p.id) s ON s.id = p.id \
GROUP BY p.id')
#try to lower ids
self.c.execute('SELECT max(id) FROM LINKS')
fid = self.c.fetchone()[0]
if fid:
fid = int(fid)
else:
fid = 0
self.c.execute('UPDATE SQLITE_SEQUENCE SET seq=? WHERE name=?', (fid, "links"))
self.c.execute('SELECT max(id) FROM packages')
pid = self.c.fetchone()[0]
if pid:
pid = int(pid)
else:
pid = 0
self.c.execute('UPDATE SQLITE_SEQUENCE SET seq=? WHERE name=?', (pid, "packages"))
self.c.execute('VACUUM')
def _migrateUser(self):
if exists("pyload.db"):
try:
self.core.log.info(_("Converting old Django DB"))
except:
print "Converting old Django DB"
conn = sqlite3.connect('pyload.db')
c = conn.cursor()
c.execute("SELECT username, password, email from auth_user WHERE is_superuser")
users = []
for r in c:
pw = r[1].split("$")
users.append((r[0], pw[1] + pw[2], r[2]))
c.close()
conn.close()
self.c.executemany("INSERT INTO users(name, password, email) VALUES (?, ?, ?)", users)
move("pyload.db", "pyload.old.db")
def createCursor(self):
return self.conn.cursor()
@style.async
def commit(self):
self.conn.commit()
@style.queue
def syncSave(self):
self.conn.commit()
@style.async
def rollback(self):
self.conn.rollback()
def async(self, f, *args, **kwargs):
args = (self, ) + args
job = DatabaseJob(f, *args, **kwargs)
self.jobs.put(job)
def queue(self, f, *args, **kwargs):
args = (self, ) + args
job = DatabaseJob(f, *args, **kwargs)
self.jobs.put(job)
job.wait()
return job.result
@classmethod
def registerSub(cls, klass):
cls.subs.append(klass)
@classmethod
def unregisterSub(cls, klass):
cls.subs.remove(klass)
def __getattr__(self, attr):
for sub in DatabaseBackend.subs:
if hasattr(sub, attr):
return getattr(sub, attr)
if __name__ == "__main__":
db = DatabaseBackend()
db.setup()
class Test():
@style.queue
def insert(db):
c = db.createCursor()
for i in range(1000):
c.execute("INSERT INTO storage (identifier, key, value) VALUES (?, ?, ?)", ("foo", i, "bar"))
@style.async
def insert2(db):
c = db.createCursor()
for i in range(1000*1000):
c.execute("INSERT INTO storage (identifier, key, value) VALUES (?, ?, ?)", ("foo", i, "bar"))
@style.queue
def select(db):
c = db.createCursor()
for i in range(10):
res = c.execute("SELECT value FROM storage WHERE identifier=? AND key=?", ("foo", i))
print res.fetchone()
@style.queue
def error(db):
c = db.createCursor()
print "a"
c.execute("SELECT myerror FROM storage WHERE identifier=? AND key=?", ("foo", i))
print "e"
db.registerSub(Test)
from time import time
start = time()
for i in range(100):
db.insert()
end = time()
print end-start
start = time()
db.insert2()
end = time()
print end-start
db.error()