def update_rows(table_name, rows, values): """table_name - str rows - list of cortages(e.g. from select function) values - cortage !in the order of table columns! return True or False """ if len(rows): cort = _quick_cursor() conn = cort[0] cur = cort[1] d = _cortage_to_dictionary(table_name, values) vals = "" for i, j in d.items(): vals += str(i) + " = '" + str(j) + "', " vals = vals[:-2] ids = "" for c in rows: ids += "id = " + str(c[0]) + ", " ids = ids[:-2] if len(ids): sql_str = "UPDATE {} SET {} WHERE {};" sql_str = sql_str.format(table_name, vals, ids) req = cur.mogrify(sql_str) cur.execute(req) res = int(cur.statusmessage.replace("UPDATE ", "")) conn.commit() cur.close() conn.close() return res > 0 else: common.dbg_log("db.update_rows ids were empty") return False common.dbg_log("db.update_rows got None or Empty rows") return False
def cmp_solve(env, headers, cmp_id): cookies = _get_cookies(env) user_id = auth.is_logined(cookies) if user_id is not None: sql_str = 'id={}' sql_str = sql_str.format(cmp_id) rows = db.select('CMPS', sql_str) if rows: post_data = _get_post_data(env) format_a = 'answer-{}' sql_str = 'cmp_id={}' sql_str = sql_str.format(cmp_id) answers = ( (r[0], common.escape(post_data[format_a.format(r[0])][0])) for r in db.select('QUESTIONS', sql_str)) username = db.username_by_id(user_id) solver.save_answers(username, answers, cmp_id) headers.append(('Location', '/quiz/{}/results'.format(cmp_id))) else: err_msg = "User ID {} tried to solve non-existing cmp {}" err_msg = err_msg.format(str(user_id), str(cmp_id)) common.dbg_log(err_msg) return (ui.error_page({'error_msg': '404: Competition not found'}), '404 Not Found') else: headers.append(('Location', '/')) return ''
def insert(table_name, values): """Insert row in table table_name - str values - cortage, contains values to insert return id or None """ if values and len(values): cort = _quick_cursor() conn = cort[0] cur = cort[1] sql_str = "INSERT INTO {} VALUES (DEFAULT{});" sql_str = sql_str.format(table_name, _pack_str_args(values)) req = cur.mogrify(sql_str, values) cur.execute(req) conn.commit() d = _cortage_to_dictionary(table_name, values) vals = "" for i, j in d.items(): vals += str(i) + " = " vals += "'"+str(j)+"'" vals += " AND " vals = vals[:-5] rows = select(table_name, vals) res = int(rows[0][0]) cur.close() conn.close() return res common.dbg_log("db.insert got None or Empty values") return None
def remove_rows(table_name, rows): """Update and remove by given rows table_name - str return True or False """ if len(rows): cort = _quick_cursor() conn = cort[0] cur = cort[1] ids = "" for c in rows: ids += "id = " + str(c[0]) + " OR " ids = ids[:-4] if len(ids): sql_str = "DELETE FROM {} WHERE {};" sql_str = sql_str.format(table_name, ids) req = cur.mogrify(sql_str) cur.execute(req) res = int(cur.statusmessage.replace("DELETE ", "")) conn.commit() cur.close() conn.close() return res > 0 else: common.dbg_log("db.remove_rows ids were empty") return False common.dbg_log("db.remove_rows got None or Empty rows") return False
def onClick(self, controlID): try: if controlID == self.C_MAIN_LIST1 or controlID == self.C_MAIN_LIST2: selectedPos = self.ChannelList.getSelectedPosition() if selectedPos > 0: selectedItem = self.getControl(controlID).getSelectedItem() strChannelName = selectedItem.getLabel() strIconPath = selectedItem.getProperty('IconPath') strClientId = selectedItem.getProperty('ClientId') strUniqueId = selectedItem.getProperty('UniqueId') ClientName = self.DBC.get_pvr_client_name(strClientId) grow = self.DBC.get_id_group_row(self.isRadio) sub = ['tv','radio'] strPatch = 'pvr://channels/%s/%s/%s_%s.pvr' % (sub[int(self.isRadio)],str(grow[1]),ClientName,strUniqueId) xbmc.executebuiltin('Skin.SetString(%s,%s)' % ('%s.%s' % (self.SkinPropery, "Path",), strPatch.encode('utf-8'),)) xbmc.executebuiltin('Skin.SetString(%s,%s)' % ('%s.%s' % (self.SkinPropery, "Number",), strUniqueId,)) xbmc.executebuiltin('Skin.SetString(%s,%s)' % ('%s.%s' % (self.SkinPropery, "Label",), strChannelName,)) xbmc.executebuiltin('Skin.SetString(%s,%s)' % ('%s.%s' % (self.SkinPropery, "Icon",), strIconPath,)) xbmc.sleep(300) self.close() else: xbmc.executebuiltin('Skin.Reset(%s)' % '%s.%s' % (self.SkinPropery, "Path",)) xbmc.executebuiltin('Skin.Reset(%s)' % '%s.%s' % (self.SkinPropery, "Number",)) xbmc.executebuiltin('Skin.Reset(%s)' % '%s.%s' % (self.SkinPropery, "Label",)) xbmc.executebuiltin('Skin.Reset(%s)' % '%s.%s' % (self.SkinPropery, "Icon",)) xbmc.sleep(300) self.close() if controlID == self.C_MAIN_CANCEL_BUTTON1 or controlID == self.C_MAIN_CANCEL_BUTTON2: self.close() except Exception, e: common.dbg_log('SelectChannels::onClick', 'ERROR: (' + repr(e) + ')', common.logErorr)
def cmp_page(env, headers, cmp_id): cookies = _get_cookies(env) user_id = auth.is_logined(cookies) if user_id is not None: sql_str = 'id={}' sql_str = sql_str.format(cmp_id) rows = db.select('CMPS', sql_str) if rows and len(rows): row = rows[0] if common.is_user_solve_cmp(cmp_id, user_id): headers.append(('Location', '/quiz/{}/results'.format(cmp_id))) else: username = db.username_by_id(user_id) sql_str = 'cmp_id={}' sql_str = sql_str.format(cmp_id) questions = [(r[0], r[1]) for r in db.select('QUESTIONS', sql_str)] return ui.solve_page({ 'cmp_id': row[0], 'title': row[1], 'description': row[2], 'user_name': username, 'questions': questions}) else: err_msg = "User ID {} tried to solve non-existing cmp {}" err_msg = err_msg.format(str(user_id), str(cmp_id)) common.dbg_log(err_msg) return (ui.error_page({'error_msg': '404: Competition not found'}), '404 Not Found') else: headers.append(('Location', '/')) return ''
def get_channels_list(self, vIsRadio): try: idAGroup = self.get_id_group_row(vIsRadio) cur = self.DBconnect.cursor() sel_str = SELECT_CHANNELS % str(idAGroup[0]) return cur.execute(sel_str) except Exception, e: common.dbg_log('DBChannels::get_channels_list', 'ERROR: (' + repr(e) + ')', common.logErorr)
def get_id_group_row(self, vIsRadio): try: cur = self.DBconnect.cursor() sel_str = SELECT_ALL_CHANNELS_GROUP % str(vIsRadio) cur.execute(sel_str) return cur.fetchone() except Exception, e: common.dbg_log('DBChannels::get_id_group_row', 'ERROR: (' + repr(e) + ')', common.logErorr)
def __init__(self): try: self.dbTV = os.path.join(xbmc.translatePath("special://database"), common.NAME_TVDB) self.dbAddons = os.path.join(xbmc.translatePath("special://database"), common.NAME_ADDONSDB) self.dbEpg = os.path.join(xbmc.translatePath("special://database"), common.NAME_EPGDB) self.DBconnect = sqlite.connect(self.dbTV) except Exception, e: common.dbg_log('DBChannels::__init__', 'ERROR: (' + repr(e) + ')', common.logErorr)
def __init__(self, vIndex, vOName, vUName='', vIcon='', vCorrection=120): try: self.Index = vIndex self.OName = vOName self.UName = vUName self.Icon = vIcon self.Correction = vCorrection except Exception, e: common.dbg_log('channel::__init__', 'ERROR: (' + repr(e) + ')', common.logErorr)
def is_op(user_id): """Check, has user with given id OP rights or not user_id - int - user id return True or False """ row = db.select("USERS", "id=" + str(user_id) + "") if len(row) and len(row[0]): return row[0][4] common.dbg_log("User with id "+str(user_id)+" not found") return False
def __init__(self, vProgress): try: self.Progress = vProgress self.Channels = channel.channel_list() self.Programmes = programme.programme_list() self.CountDay = common.count_day self.FullDesc = common.full_desc self.XMLOut = common.xmltv_patch self.Channels.load_channels_from_settings() except Exception, e: common.dbg_log('parser::__init__', 'ERROR: (' + repr(e) + ')', common.logErorr)
def get_id_epg(self, vUChannelID): try: cur = self.DBconnect.cursor() sel_str = SELECT_CHANNEL_EPG % str(vUChannelID) cur.execute(sel_str) ret = cur.fetchone() id_epg = '' if ret: id_epg = str(ret[0]) return id_epg except Exception, e: common.dbg_log('DBChannels::get_id_epg', 'ERROR: (' + repr(e) + ')', common.logErorr)
def get_epg_data(self, vUChannelID, vCurTime): try: epgid = self.get_id_epg(vUChannelID) connect = sqlite.connect(self.dbEpg) cur = connect.cursor() sel_str = SELECT_EPG_DATA % (epgid, vCurTime, vCurTime) cur.execute(sel_str) data = cur.fetchone() if connect: connect.close() return data except Exception, e: common.dbg_log('DBChannels::get_epg_data', 'ERROR: (' + repr(e) + ')', common.logErorr)
def load_channels_from_settings(self): try: common.dbg_log('channel_list::load_channels_from_settings', 'enter_function') self.Data = [] set = settings.settings() xmldoc = set.parse() if xmldoc != None: category = xmldoc.getElementsByTagName('category') for node_cat in category: setting = node_cat.getElementsByTagName('setting') for node_set in setting : if 'id' in node_set.attributes.keys() and not node_set.getAttribute('id').find('channel_sep_'): offset = len('channel_sep_') index = node_set.getAttribute('id')[offset:] enabled = common.__addon__.getSetting('channel_enable_'+index) if enabled == 'true': oname = node_set.getAttribute('label') uname = common.__addon__.getSetting('channel_name_'+index) icon = common.__addon__.getSetting('channel_icon_'+index) chn = channel(index, oname, uname, icon, common.correction) self.Data.append(chn) common.dbg_log('channel_list::load_channels_from_settings', oname.encode('utf-8') + '(' + index + ')') common.dbg_log('channel_list::load_channels_from_settings', 'exit_function') except Exception, e: common.dbg_log('channel_list::load_channels_from_settings', 'ERROR: (' + repr(e) + ')', common.logErorr)
def new_cmp(env, headers): cookies = _get_cookies(env) user_id = auth.is_logined(cookies) if user_id is not None: if auth.is_op(user_id): return ui.create_cmp_page({'user_id': user_id}) else: err_msg = "User ID {} tried to create cmp without op" err_msg = err_msg.format(str(user_id)) common.dbg_log(err_msg) em = '403: You don\'t have permissions to create competition' return (ui.error_page({'error_msg': em}), '403 Forbidden') else: headers.append(('Location', '/')) return ''
def get_pvr_client_name(self, vClientID): try: connect = sqlite.connect(self.dbAddons) cur = connect.cursor() sel_str = SELECT_CLIENT_PVR % vClientID cur.execute(sel_str) data = cur.fetchone() pvr_client_name = '' if data: pvr_client_name = data[0] if connect: connect.close() return pvr_client_name except Exception, e: common.dbg_log('DBChannels::get_pvr_client_name', 'ERROR: (' + repr(e) + ')', common.logErorr)
def __init__(self, *args, **kwargs): try: xbmcgui.WindowXMLDialog.__init__(self) self.isRadio = kwargs.get("isradio") self.SkinPropery = kwargs.get("property") self.C_MAIN_HEADER=1 self.C_MAIN_LIST1=3 self.C_MAIN_LIST2=6 self.C_MAIN_OK_BUTTON=5 self.C_MAIN_CANCEL_BUTTON1=7 self.C_MAIN_CANCEL_BUTTON2=99 self.DBC = db.DBChannels() except Exception, e: common.dbg_log('SelectChannels::__init__', 'ERROR: (' + repr(e) + ')', common.logErorr)
def cmp_edit(env, headers, cmp_id): cookies = _get_cookies(env) user_id = auth.is_logined(cookies) if user_id is not None: cond = 'id={}'.format(cmp_id) cmp_rows = db.select('CMPS', cond) if cmp_rows: cmp_row = cmp_rows[0] if cmp_row[3] == user_id: title = cmp_row[1] description = cmp_row[2] cond = 'cmp_id={}'.format(cmp_id) tasks = db.select('QUESTIONS', cond) tcond = 'task_id={}' questions = [ ( task[0], task[1], '##'.join( answer[1] for answer in db.select('answers', tcond.format(task[0])) ) ) for task in tasks ] headers.append(('Location', '/quiz/{}/edit'.format(cmp_id))) return ui.cmp_edit({ 'cmp_id': cmp_id, 'title': title, 'description': description, 'user_id': user_id, 'questions': questions }) else: err_msg = "User ID {} tried to edit cmp {} without access" err_msg = err_msg.format(str(user_id), str(cmp_id)) common.dbg_log(err_msg) em = '403: You don\'t have permissions to edit this competition' return (ui.error_page({'error_msg': em}), '403 Forbidden') else: err_msg = "User ID {} tried to edit non-existing cmp {}" err_msg = err_msg.format(str(user_id), str(cmp_id)) common.dbg_log(err_msg) return (ui.error_page({'error_msg': '404: Competition not found'}), '404 Not Found') else: headers.append(('Location', '/')) return ''
def cmp_results(env, headers, cmp_id): cookies = _get_cookies(env) user_id = auth.is_logined(cookies) logineduid = user_id if user_id is not None: cond_f = 'id={}' cond = cond_f.format(cmp_id) rows = db.select('CMPS', cond) if rows: row = rows[0] qs = _get_query_data(env) is_cmp_author = False if 'uid' in qs: uid = int(qs['uid'][0]) if (uid != user_id) and (row[3] == user_id): user_id = uid is_cmp_author = True if common.is_user_solve_cmp(cmp_id, user_id): username = db.username_by_id(logineduid) cond_f = 'cmp_id={}' cond = cond_f.format(cmp_id) tasks = db.select('questions', cond) answers = common.user_answers_for_cmp(cmp_id, user_id) restuple = solver.is_cmp_right(cmp_id, answers) results = [ (task[0], task[1], ans[0], ans[3], res) for task, ans, res in zip(tasks, answers, restuple)] return ui.results_page({ 'cmp_id': row[0], 'title': row[1], 'description': row[2], 'user_name': username, 'results': results, 'is_cmp_author': is_cmp_author}) else: headers.append(('Location', '/quiz/{}'.format(cmp_id))) err_msg = "User ID {} tried to see result for non-solved cmp {}" err_msg = err_msg.format(str(user_id), str(cmp_id)) common.dbg_log(err_msg) else: err_msg = "User ID {} tried to view result for non-existing cmp {}" err_msg = err_msg.format(str(user_id), str(cmp_id)) common.dbg_log(err_msg) return (ui.error_page({'error_msg': '404: Competition not found'}), '404 Not Found') else: headers.append(('Location', '/')) return ''
def __init__(self, vChannelIdx, vStart, vTitle, vStop='', vDesc='', vFullDesc='', vCategoryLang1='', vCategoryLang2='', vDirectors='', vActors='', vDate='', vStarrating=''): try: self.ChannelIdx = vChannelIdx self.Start = vStart self.Stop = vStop self.Title = vTitle self.Desc = vDesc self.UrlDesc = '' self.FullDesc = vFullDesc self.CategoryLang1 = vCategoryLang1 self.CategoryLang2 = vCategoryLang2 self.Directors = vDirectors self.Actors = vActors self.Date = vDate self.Starrating = vStarrating except Exception, e: common.dbg_log('programme::__init__', 'ERROR: (' + repr(e) + ')', common.logErorr)
def choose_action(env, headers): """Works with paths. Selects, which page to show. return html - string """ paths = [([''], main_page), (['user', 'login'], login), (['user', 'logout'], logout), (['user', 'register'], register), (['dashboard'], dashboard), (['cmp', 'create'], new_cmp), (['quiz', 'create', 'questions'], new_questions), (['contest', 'create', 'tasks'], new_questions), (['quiz', 'create', 'save'], create_cmp), (['contest', 'create', 'save'], create_cmp), (['quiz', (int, 'cmp_id')], cmp_page), (['quiz', (int, 'cmp_id'), 'solve'], cmp_solve), (['quiz', (int, 'cmp_id'), 'results'], cmp_results), (['quiz', (int, 'cmp_id'), 'edit'], cmp_edit), (['quiz', (int, 'cmp_id'), 'edit', 'save'], cmp_edit_save), (['quiz', (int, 'cmp_id'), 'participants'], participants)] path = env['PATH_INFO'].split('/') path.remove('') for path_f in paths: if len(path) != len(path_f[0]): continue vardict = {} for i, j in enumerate(path_f[0]): if type(j) == tuple: try: vardict[j[1]] = j[0](path[i]) except ValueError: break elif j != path[i]: break else: try: return path_f[1](env, headers, **vardict) except Exception: common.dbg_log(traceback.format_exc()) return (ui.error_page({'error_msg': '500: Internal Server Error'}), '500 Internal Server Error') common.dbg_log("Page not found: "+str(env['PATH_INFO'])) return (ui.error_page({'error_msg': '404: Not found'}), '404 Not found')
def get_programme_for_url(self, vurl): try: common.dbg_log('programme_list::get_programme_for_url', 'enter_function') for prg in self.Data: if prg.UrlDesc == vurl: common.dbg_log('programme_list::get_programme_for_url', '*FOUND* exit_function') return prg common.dbg_log('programme_list::get_programme_for_url', '*NO FOUND* exit_function') return None except Exception, e: common.dbg_log('programme_list::get_programme_for_url', 'ERROR: (' + repr(e) + ')', common.logErorr) return None
def select(table_name, conditions): """Finds row, that conforms given condition. To be used by all modules. table_name - str conditions - str, read module description return list of cortages - rows """ if conditions and len(conditions): cort = _quick_cursor() conn = cort[0] cur = cort[1] sql_str = "SELECT * FROM {} WHERE {};" sql_str = sql_str.format(table_name, conditions) req = cur.mogrify(sql_str) cur.execute(req) row = cur.fetchall() cur.close() conn.close() return row else: common.dbg_log("db.select got None or Empty conditions") return []
def save_channels_to_settings(self, vxmldoc): try: common.dbg_log('channel_list::save_channels_to_settings', 'enter_function') category = vxmldoc.getElementsByTagName('category') for node_cat in category: setting = node_cat.getElementsByTagName('setting') for node_set in setting : if 'label' in node_set.attributes.keys() and '32011' in node_set.getAttribute('label'): for channel in self.Data: node1 = vxmldoc.createElement("setting") node1.setAttribute("id", 'channel_sep_' + channel.Index) node1.setAttribute("label", channel.OName) node1.setAttribute("type", 'lsep') node_cat.appendChild(node1) node2 = vxmldoc.createElement("setting") node2.setAttribute("id", 'channel_name_' + channel.Index) node2.setAttribute("label", '32013') node2.setAttribute("type", 'text') node2.setAttribute("default", channel.OName) node_cat.appendChild(node2) node3 = vxmldoc.createElement("setting") node3.setAttribute("id", 'channel_icon_' + channel.Index) node3.setAttribute("label", '32014') node3.setAttribute("type", 'text') node3.setAttribute("default", channel.Icon) node_cat.appendChild(node3) node4 = vxmldoc.createElement("setting") node4.setAttribute("id", 'channel_enable_' + channel.Index) node4.setAttribute("label", '32015') node4.setAttribute("type", 'bool') node4.setAttribute("default", 'false') node_cat.appendChild(node4) common.dbg_log('channel_list::save_channels_to_settings', 'exit_function') except Exception, e: common.dbg_log('channel_list::save_channels_to_settings', 'ERROR: (' + repr(e) + ')', common.logErorr)
def service_update_epg(): try: common.dbg_log('functions::service_update_epg', 'enter_function') if common.enable_service == 'true': week_day = datetime.date.today().isoweekday() cur_time = datetime.datetime.now().strftime('%H:%M') cur_date = datetime.datetime.now().strftime('%Y%m%d') if week_day == 1: enable_upd_week = common.enable_monday == 'true' elif week_day == 2: enable_upd_week = common.enable_tuesday == 'true' elif week_day == 3: enable_upd_week = common.enable_wednesday == 'true' elif week_day == 4: enable_upd_week = common.enable_thursday == 'true' elif week_day == 5: enable_upd_week = common.enable_friday == 'true' elif week_day == 6: enable_upd_week = common.enable_saturday == 'true' elif week_day == 7: enable_upd_week = common.enable_sunday == 'true' else: enable_upd_week = False enable_upd_time = common.run_time <= cur_time enable_upd_day = common.last_update != cur_date if enable_upd_time and enable_upd_week and enable_upd_day: save_xmltv() common.dbg_log('functions::service_update_epg', 'exit_function') except Exception, e: common.dbg_log('functions::service_update_epg', 'ERROR: (' + repr(e) + ')', common.logErorr)
def restore(self): try: common.dbg_log('settings::restore', 'enter_function') shutil.copyfile(self.SettingsFile + '_orig', self.SettingsFile) common.dbg_log('settings::restore', 'exit_function') except IOError as e: common.dbg_log('settings::restore', 'ERROR: (' + repr(e) + ')', common.logErorr)
def register(env, headers): post_data = _get_post_data(env) if ('password' in post_data) and ('username' in post_data): password = post_data['password'][0] username = post_data['username'][0] if auth.register(username, password) is None: error_msg = urllib.parse.quote('Registration failed') err_msg = "Guest tried to register '{}' and failed" err_msg = err_msg.format(str(username)) common.dbg_log(err_msg) location = '/?error_msg={}'.format(error_msg) headers.append(('Location', location)) else: auth.login(username, password, headers) headers.append(('Location', '/dashboard')) else: error_msg = urllib.parse.quote('Username or password is not given') location = '/?error_msg={}'.format(error_msg) headers.append(('Location', location)) return ''
def create(title, description, username, questions): """Create new competition questions - cortage of cortages EXAMPLE: ( ('Question1','Answer1'), ('Question2','Answer2', 'Answer22') ) return id or None """ check = cmp_exists(title) common.dbg_log(str(questions)) if check is None: user_id = db.id_by_username(username) cmp_id = db.insert('CMPS', (title, description, user_id, 0, 0)) for task in questions: task_id = db.insert('QUESTIONS', (task[0], cmp_id)) common.dbg_log(str(task_id)) for i in range(1, len(task)): db.insert('ANSWERS', (task[i], task_id, cmp_id)) return cmp_id else: return None
def cmp_edit_save(env, headers, cmp_id): cookies = _get_cookies(env) user_id = auth.is_logined(cookies) if user_id is not None: post_data = _get_post_data(env) cmp_rows = db.select('CMPS', 'id={}'.format(cmp_id)) if cmp_rows: cmp_row = cmp_rows[0] if cmp_row[3] == user_id: title = cmp_row[1] description = post_data['description'][0] format_q = 'question-{}' format_a = 'answer-{}' qnumber = len(db.select('QUESTIONS', 'cmp_id={}'.format(cmp_id))) tasks = [] for i in range(qnumber): answers = post_data[format_a.format(i)][0].split('##') answers = [common.escape(j) for j in answers if j] tasks.append( tuple( [common.escape(post_data[format_q.format(i)][0])] + answers )) creator.edit(cmp_id, title, description, tasks) headers.append(('Location', '/dashboard')) else: err_msg = "User ID {} tried to edit cmp {} without access" err_msg = err_msg.format(str(user_id), str(cmp_id)) common.dbg_log(err_msg) em = '403: You don\'t have permissions to edit this competition' return (ui.error_page({'error_msg': em}), '403 Forbidden') else: err_msg = "User ID {} tried to edit non-existing cmp {}" err_msg = err_msg.format(str(user_id), str(cmp_id)) common.dbg_log(err_msg) return (ui.error_page({'error_msg': '404: Competition not found'}), '404 Not Found') else: headers.append(('Location', '/')) return ''