Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/backend.py
blob: b019a0cba9e856bf254cc0492c6b4f72c3d57f57 (plain)
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
import os
import sqlite3
import random
import sys
from sugar.activity import activity
from xmlio import Xmlio
from path import path
import subprocess

import traceback

random.seed()

global debug_info
debug_info = True

'''
Handles pysqlite Interaction: query("SELECT..."), commit("UPDATE...")
'''
class Question:
    imgfn = u''
    sndfn = u''
    map = u''
    cat = 0
    subcat = 0
    lang = 1    # 1 = English
    text = u''
    answer = u''
    answer_link = ''
    
class Database:

    db_filename = "main.db"
    cur = '';
    con = '';
    
    def __init__(self):
        pass

    def query(self, q):
        dataList = []
        try:
            self.cur.execute(q)
        except:
            # If DB connection get's lost on Activity-Startup, then Reset
            print 'query reset=', q
            self.con = sqlite3.connect(self.db_fn)
            self.cur = self.con.cursor()
            self.cur.execute("-- types unicode")
            try:
                self.cur.execute(q)
            except:
                print 'execute failed', q
                        
        data = self.cur.fetchall()
        #if data:
            #print 'data', len(data)
        #else:
            #print 'data = None'
        if data: dataList = [list(row) for row in data]
        #print 'dbmgr return dataList', len(dataList)
        return dataList

    def commit(self, q):
        try:
            self.cur.execute(q)
        except:
            # If DB connection get's lost on Activity-Startup, then Reset
            print 'execute reset=', q
            self.con = sqlite3.connect(self.db_fn)
            self.cur = self.con.cursor()
            self.cur.execute("-- types unicode")
            self.cur.execute(q)
            
        try:
            self.con.commit()
        except:
            print 'failure on commit'
        
    def load(self, services):   
        # Init DB
        db = os.path.join(activity.get_activity_root(), "data")
        fullname = os.path.join(db, self.db_filename)
        self.db_fn = fullname
        #for testing, remove db
        #subprocess.call("rm -rf " + fullname, shell=True)
        if os.path.isfile(fullname):
            self.con = sqlite3.connect(fullname)
            self.cur = self.con.cursor()
            self.cur.execute("-- types unicode")
        else:
            # Check for Database Setup
            self.con = sqlite3.connect(fullname)
            self.cur = self.con.cursor()
            self.cur.execute("-- types unicode")
            # Create image, sound folders
            self.imagepath = os.path.join(db,'image')
            subprocess.call("mkdir -p " + self.imagepath, shell=True)
            self.soundpath = os.path.join(db,'sound')
            subprocess.call("mkdir -p " + self.soundpath, shell=True)
            # Setup New Database
            self.cur.execute("CREATE TABLE 'categories' ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'text' TEXT);")
            self.cur.execute("CREATE TABLE 'questions' ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'prompt' TEXT, 'response' TEXT, 'image_fn' TEXT, 'sound_fn' TEXT, 'map' TEXT, 'answer_link' VARCHAR ( 1024 ));")
            self.cur.execute("CREATE TABLE 'Leitner' ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'question_id' INT, 'count_found' INT, 'count notfound' INT, 'box' INT, 'time' INT, 'day' INT);")
            self.cur.execute("CREATE TABLE 'catlink' ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'parent_id' INT, 'child_id' INT);") 
            self.cur.execute("CREATE TABLE 'quizlink' ('id' INTEGER PRIMARY KEY AUTOINCREMENT, 'quiz_id' INT, 'question_id' INT);")  

            # Add questions, quizzes from builtins
            self.load_builtins()
            
            self.con.commit()
                
            print "* database created"
                     
        if debug_info: print "- database loaded"
        return True

    #loads preinstalled quizzes from activity-bundle/imagequiz_library into db
    def load_builtins(self):         
        self.builtins = path(activity.get_bundle_path()) / 'imagequiz_library'
        categorypaths = self.builtins.listdir()
        categories = []
        for categorypath in categorypaths:
            categories.append(categorypath.name)
        categories.sort()
        
        for quiz in categories:
             if not (quiz == 'image' or quiz == 'sound'):
                 #create category entry in db
                 self.cat_id = self.add_cat(path(quiz).namebase)
                 if 'xml' in path(quiz).name:
                     self.add_questions_xml(quiz)
                 else:
                     self.add_questions_csv(quiz)

    def add_questions_xml(self, quizname):
        quiztree = Xmlio(path(self.builtins) / quizname)
        quiz = quiztree.getroot()
        question = Question()
        #what we need to do:
        for card in quiz:
           question.prompt = card.findtext('question')
           question.response = card.findtext('answer')
           if card.find('answer').findtext('image'):
               question.imgfn = card.find('answer').findtext('image')
           else:
               question.imgfn = ""
           if card.find('question').findtext('sound'):
               question.sndfn = card.find('question').findtext('sound')
           else:
               question.sndfn = ""
           question.map = ""
           question.answer_link = ""
           self.add_question(question)
           if question.imgfn and len(question.imgfn) > 0:
               srcpath = path(self.builtins) / 'image' / question.imgfn
               dstpath = path(self.imagepath) / question.imgfn
               if srcpath.exists():
                   path.copy(srcpath,dstpath)
           if question.sndfn and len(question.sndfn) > 0:
               srcpath = path(self.builtins) / 'sound' / question.sndfn
               dstpath = path(self.soundpath) / question.sndfn
               if srcpath.exists():
                   path.copy(srcpath,dstpath)
                   
    def add_questions_csv(self, quiz):
        question = Question()
        csvquiz = open(path(self.builtins) / quiz)
        csvtext = csvquiz.read()
        csvquiz.close()

        questions = csvtext.split(";;;<br>")
        for q in questions:
            csv = q.split(";;")
            if len(csv) < 2:
                #no more questions
                return
            question.prompt = csv[1].replace("'", "")
            question.response = csv[4].replace("'", "")
            question.imgfn = "%s" % (csv[0])
            question.sndfn = ""
            question.map = csv[2]	
            if len(csv) > 5:
                question.answer_link = csv[5].replace("'", "")
            else:
                question.answer_link = ""
            self.add_question(question)
            #copy resources to resource folders
            if question.imgfn and len(question.imgfn) > 0:
                srcpath = path(self.builtins) / 'image' / question.imgfn
                dstpath = path(self.imagepath) / question.imgfn
                if srcpath.exists():
                    path.copy(srcpath,dstpath)
            if question.sndfn and len(question.sndfn) > 0:
                srcpath = path(self.builtins) / 'sound' / question.sndfn
                dstpath = path(self.soundpath) / question.sndfn
                if srcpath.exists():
                    path.copy(srcpath,dstpath)
        
    def add_cat(self, cat_namebase):
        # returns new cat_id
        # Category exists?
        q = u"SELECT count(*) FROM categories WHERE text='%s'" % (cat_namebase)
        res = self.query(q)
        if res[0][0] == 0:
            # No, insert
            q = u"INSERT INTO categories (text) VALUES ('%s')" % (cat_namebase)
            self.commit(q)
        q = u"SELECT id FROM categories WHERE text='%s'" % (cat_namebase)
        res = self.query(q)
        id = res[0][0]        
        return id;


    def add_question(self, question):
       
        if len(question.answer_link) > 0:
            question.answer_link = question.answer_link.replace("'", '"')

        # Insert Question
        q = u'INSERT INTO questions (prompt, response, image_fn, sound_fn, map, answer_link) VALUES ("%s", "%s", "%s", "%s", "%s", "%s")' % (question.prompt, question.response, question.imgfn, question.sndfn,  question.map, question.answer_link)
        self.commit(q)

        # Get Question_ID of last question inserted
        question_id = self.cur.lastrowid
            
        # Link question to quiz
        q = u"INSERT INTO quizlink (quiz_id, question_id) VALUES (%i, %i)" % (self.cat_id, question_id)
        self.commit(q)

        return True
          
''' 
Main Game Backend (Kernel)
'''

class Kernel:   
    services = []
    def __init__(self):
                pass
        
    def load(self, s):
        pass
        
    def add_service(self, descriptor, function):
        print "* registering service:",descriptor,
        self.services.append([descriptor, function])
        print "... ok"
            
    def start_service(self, descriptor, params=False):
        for s in self.services:
            if s[0] == descriptor: 
                print "* starting service:",s[0],"(",params,")"

                try: 
                    print s[1](params)
                except:
                    try: 
                        print s[1]()
                    except: 
                        print "! starting service %s failed" % s[0]
                        traceback.print_exc()
    def hex2rgb(hex): 
        if hex[0:1] == '#': hex = hex[1:]; 
        return (hex2dec(hex[:2]), hex2dec(hex[2:4]), hex2dec(hex[4:6]))

''' 
 Class PluginManager: 
 ====================
 This class loads the plugins and hooks in the services
 (Loads all .py files from plugin_dir/ not starting with _)
    - plugin1.py will be loaded
    - _plugin1.py will not be loaded
 Usage:
    plugger = PluginManager()
    plugger.load_plugins()
    plugger.debug()
'''
def empty(): pass

class PluginManager:
    plugins = []
    plugin_dir = 'plugins'
        
    services = ''
    
    def __init__(self):
        pass 
        
    def load(self, services):
        self.services = services
        if debug_info: print "- plugger loaded"
    
    def load_plugins(self):
        filenames = os.listdir(self.plugin_dir)
        for fn in filenames:
            # All .py files not starting with _
            if fn[-3:] == '.py' and fn[:1] != '_':
                # Extract File without Extension
                plugin_fn = os.path.splitext(fn)[0]
                
                # Import
                p = __import__(os.path.join(self.plugin_dir, plugin_fn))
                self.plugins.append(p)
                

                if debug_info: 
                    try:
                        print "- plugin import:", p.__PLUGIN_NAME__
                    except:
                        print "no plugin name for ", plugin_fn
                
                p.__SERVICES__ = self.services
                                    
                try: p.load()
                except: traceback.print_exc()

    def close_plugins(self):
        for p in self.plugins:
            try: p.close()
            except: traceback.print_exc()
        
    def debug(self):
        print "Activated Plugins:"
        for p in self.plugins:
            print "-", p.__PLUGIN_NAME__