def changeNick(self, nick, initial=False): nick = nick.decode('utf-8', 'replace').encode('utf-8') if nick == '': nick = self.user if not initial and self.nick == nick: common.debug('trying to set the same nick') return if len(nick) > 129: # to avoid problems with utf-8 return oldNick = self.nick self.nick = nick #self.contactManager.setContactNick(self.user, self.nick) self.emit('self-nick-changed', oldNick, self.nick) self.socket.sendCommand("PRP", "MFN " + urllib.quote(nick)) if not initial: if self.rid != "":# self.affinityCache != '': soap.requests.update_profile(self.proxy, self.affinityCache, \ self.rid, common.escape(nick), \ common.escape(self.personalMessage), self.onNickChanged, oldNick)
def convert_file(source, target): target.parent.mkdir(parents=True, exist_ok=True) os.system(' '.join([ 'ffmpeg', '-i', quote(escape(source.as_posix())), quote(escape(target.as_posix())) ]))
def updateUUX(self): '''update personal message and current media''' pm = self.personalMessage cm = self.currentMedia pm = pm.decode('utf-8', 'replace').encode('utf-8') cm = cm.decode('utf-8', 'replace').encode('utf-8') self.socket.sendPayloadCommand('UUX', '', \ '<Data><PSM>' + common.escape(pm) + '</PSM>' + \ '<CurrentMedia>' + common.escape(cm) + '</CurrentMedia>' + \ '<MachineGuid></MachineGuid></Data>')
def set_metadata(data, artist, album, track): os.system(' '.join([ 'mid3v2', '-a', quote(escape(artist.metadata[Metakey.name])), '-A', quote(escape(album.metadata[Metakey.name])), '-t', quote(escape(track.metadata[Metakey.name])), '-y', quote(album.metadata[Metakey.year]), '-T', quote(f'{track.metadata[Metakey.index] + 1}/{len(album.subnodes)}'), quote(escape(target_path(data, artist, album, track).as_posix())) ]))
def changePersonalMessage(self, pm): '''change the personal message''' if self.personalMessage != pm: if len(pm) > 129: return oldPm = self.personalMessage self.personalMessage = pm self.updateUUX() #if self.affinityCache != '': soap.requests.update_profile(self.proxy, self.affinityCache, \ self.rid, common.escape(self.nick), \ common.escape(self.personalMessage), self.onPmChanged, oldPm) self.emit('self-personal-message-changed', self.user, pm) else: common.debug("duplicate pm")
def changePersonalMessage(self, pm): '''change the personal message''' if self.personalMessage != pm: if len(pm) > 129: return oldPm = self.personalMessage self.personalMessage = pm self.updateUUX() if self.affinityCache != '': soap.requests.update_profile(self.proxy, self.affinityCache, \ self.rid, common.escape(self.nick), \ common.escape(self.personalMessage), self.onPmChanged, oldPm) self.emit('self-personal-message-changed', self.user, pm) else: common.debug("duplicate pm")
def getContactPersonalMessage(self, email, escaped=False): email = email.lower() if self.contacts.has_key(email): if escaped: return common.escape(self.contacts[email].personalMessage) else: return self.contacts[email].personalMessage
def renameGroup(self, oldGroup, newGroup): '''rename a group from the group list''' if oldGroup == newGroup: common.debug('oldgroup and new group are the same') return if self.contactManager.getGroupId(newGroup) != None: common.debug('That group name is already in use') return gid = self.contactManager.getGroupId(oldGroup) if gid == None: common.debug('The specified group does not exist') return else: self.contactManager.renameGroup(gid, newGroup) group = self.contactManager.getGroup(gid) objOldGroup = ContactData.Group(oldGroup) self.emit('group-attr-changed', objOldGroup, group) request = SoapManager.SoapRequest( 'http://www.msn.com/webservices/AddressBook/ABGroupUpdate', \ 'omega.contacts.msn.com', 443, '/abservice/abservice.asmx', \ XmlTemplates.renameGroup % (gid, common.escape(newGroup)), \ self.onGroupRenamed, (oldGroup, newGroup)) SoapManager.put(request)
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 login(username, password, headers): """Log in user into his account(if it is his account) headers - dictionary return id or None """ username = common.escape(username) sql_str = "username='******'" sql_str = sql_str.format(username) user = db.select('USERS', sql_str) if user: user = user[0] pass_hash = _generate_hash(password, user[3]) if user[2] == pass_hash: session_id = None while (session_id is None) or db.select('SESSIONS', sql_str): session_id = _generate_string(256) sql_str = "session_id='{}'" sql_str = sql_str.format(session_id) td = datetime.timedelta(14) dt = datetime.datetime.today() dt = dt + td expires = common.utctime(dt) cookie = "session_id={}; expires={}; path=/" cookie = cookie.format(session_id, expires) headers.append(('Set-Cookie', cookie)) user_id = user[0] db.insert('SESSIONS', (session_id, user_id)) return user_id return None
def changeNick(self, nick, user='******', initial=False): '''change the nick, type can be Me or Normal''' nick = nick.decode('utf-8', 'replace').encode('utf-8') if user == 'Me': if not initial and self.nick == nick: common.debug('trying to set the same nick') return if len(nick) > 129: # to avoid problems with utf-8 return oldNick = self.nick self.nick = nick #self.contactManager.setContactNick(self.user, self.nick) self.emit('self-nick-changed', oldNick, self.nick) self.socket.sendCommand("PRP", "MFN " + urllib.quote(nick)) nick = common.escape(nick) if not initial: request = SoapManager.SoapRequest( 'http://www.msn.com/webservices/AddressBook/ABContactUpdate', \ 'omega.contacts.msn.com', 443, '/abservice/abservice.asmx', \ XmlTemplates.changeNick % (user, nick), \ self.onNickChanged, (self.user, oldNick)) else: # why this change the contact alias? # it's a good question, but remember to sign your # comments with --~~~~, like this: --dx [talk] 9/11 3:47 oldAlias = self.contactManager.getContactAlias(user) self.contactManager.setContactAlias(user, nick) contact = self.contactManager.getContact(user) self.emit('user-attr-changed', contact) contactID = str(self.contactManager.getContactId(user)) nick = str(common.escape(nick)) if not initial: request = SoapManager.SoapRequest( 'http://www.msn.com/webservices/AddressBook/ABContactUpdate', \ 'omega.contacts.msn.com', 443, '/abservice/abservice.asmx', \ str(XmlTemplates.renameContact % (contactID, nick)), \ self.onNickChanged, (user, oldAlias)) if not initial: SoapManager.put(request)
def cmp_exists(title): """Exists competition with given title or not. Returns id of found competition or None. return id or None """ title_full = "title='{}'" res = db.select('CMPS', title_full.format(common.escape(title))) return res[0][0] if res else None
def _handle_action_set_message(self, message): '''handle e3.Action.ACTION_SET_MESSAGE ''' self.socket.send_command('UUX', payload='<Data><PSM>' + \ common.escape(message) + '</PSM><CurrentMedia></CurrentMedia>' + \ '<MachineGuid></MachineGuid></Data>') e3.base.Worker._handle_action_set_message(self, message) Requester.SetProfile(self.session, contact.nick, message).start()
def passportAuth(self , hash): '''do the passport authenticaton, this is done connecting to loginnet.passport.com:443 and sending a XML message described on XmlTemplates.passport''' common.debug('PASSPORT begin', 'core') # unquote the hash ticket = urllib.unquote(hash).replace("," , "&") # replace the %s in the string body = XmlTemplates.passport%(self.user, common.escape(self.password), ticket) #create the headers headers = { \ "Accept" : "text/*" , \ "User-Agent" : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" , \ "Host" : "loginnet.passport.com" , \ "Content-Length" : str(len(body)) , \ "Connection" : "Keep-Alive" , \ "Cache-Control" : "no-cache" , \ } _server="loginnet.passport.com" _url="/RST.srf" succeeded = False for i in range(5): response = None lastError = None # send the SOAP request for i in range(3): try: conn = httplib.HTTPSConnection(_server,443) conn.request("POST", _url, body, headers) response = conn.getresponse() common.debug('%s %s'%(response.status, response.reason), \ 'core') break except Exception, e: lastError = e if response: data = response.read() else: raise common.AuthError, "Can't connect to HTTPS server: " + \ str(e) if data.find('<faultcode>psf:Redirect</faultcode>') > 0: _url = urlparse.urlparse(data.split('<psf:redirectUrl>')\ [ 1 ].split('</psf:redirectUrl>')[ 0 ]) # fixed according to # http://docs.python.org/lib/module-urlparse.html _server=_url[ 1 ] _url=_url[ 2 ] common.debug('Redirect to: %s %s' % (_server, _url), 'core') else: succeeded = True break
def getContactAlias(self, email, escaped=False): email = email.lower() if self.contacts.has_key(email): if escaped: return common.escape(self.contacts[email].alias) else: return self.contacts[email].alias else: return ''
def program(data): expr = data['text'].strip() if expr in ['', '-h', '--help', 'help']: return _help_msg escaped_expr = re.sub(_escape_pattern, '', expr.replace('^', '**')) try: ans = eval(escaped_expr, _globals, _locals) except: ans = _error_msg.format(escape(quote_plus(expr, ''))) else: if isinstance(ans, float): ans = '= {0:g}'.format(ans) else: ans = '= {0}'.format(ans) return '{0}\n{1}'.format(escape(expr), ans)
def program(data): expr = data['text'].strip() if expr in ['', '-h', '--help', 'help']: return _help_msg escaped_expr = re.sub(_escape_pattern, '', expr.replace('^', '**')) try: ans = eval(escaped_expr, _globals, _locals) except: ans = _error_msg.format(escape(quote_plus(expr,''))) else: if isinstance(ans, float): ans = '= {0:g}'.format(ans) else: ans = '= {0}'.format(ans) return '{0}\n{1}'.format(escape(expr), ans)
def _handle_action_set_media(self, message): '''handle Action.ACTION_SET_MEDIA ''' me = self.session.contacts.me self.socket.send_command('UUX', payload='<Data><PSM>' + \ '</PSM><CurrentMedia>' + \ common.escape(message) + '</CurrentMedia>' + \ '<MachineGuid></MachineGuid></Data>') e3.base.Worker._handle_action_set_media(self, message)
def get(name, *args): '''try to get a template from the template folder and return it, return None if not found''' name = os.path.join(TEMPLATE_FOLDER, name + '.xml') if os.access(name, os.R_OK): xml = file(name, 'r') template = xml.read() xml.close() return template % tuple([common.escape(x) for x in args]) return None
def getContactNick(self, email, escaped=False): email = email.lower() if self.contacts.has_key(email): nick = self.contacts[email].nick elif self.pendingNicks.has_key(email): nick = self.pendingNicks[email] else: nick = email if escaped: return common.escape(nick) else: return nick
def register(username, password): """Yay! New user to our site! Let's create his account. Must check user existance. return id or None """ username = common.escape(username) sql_str = "username='******'" sql_str = sql_str.format(username) if db.select('USERS', sql_str): return None salt = _generate_string(32) pass_hash = _generate_hash(password, salt) return db.insert('USERS', (username, pass_hash, salt, False))
def program(data): query, __, comment = data['text'].strip().partition(' ') if comment: comment += r'\n' arxiv_id = arxiv_re.search(query) if arxiv_id is None: return _error_msg arxiv_id = arxiv_id.group() entry = fetch_arxiv(id_list=arxiv_id).iterentries().next() if entry is None or entry.entry is None: return _error_msg output = _output_template.format(entry['key'], \ escape(re.sub(r'\s+', u' ', entry['title'], re.U)), \ escape(entry['first_author']), escape(comment)).encode('utf-8') payload = _payload_template.format(data['channel_id'], data['user_name'], \ output) return output, payload
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 ''
def create_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): post_data = _get_post_data(env) checks = ('title' in post_data) and ('description' in post_data) if checks and ('qnumber' in post_data): title = common.escape(post_data['title'][0]) description = common.escape(post_data['description'][0]) qnumber = int(common.escape(post_data['qnumber'][0])) format_q = 'question-{}' format_a = 'answer-{}' tasks = [] for i in range(qnumber): question_tpl = format_q.format(i) answer_tpl = format_a.format(i) if (answer_tpl in post_data) and (question_tpl in post_data): q = post_data[question_tpl][0] a = post_data[answer_tpl][0] answers = common.escape(a).split('##') answers = [j for j in answers if j] tasks.append( tuple( [common.escape(q)] + answers )) username = db.username_by_id(user_id) creator.create(title, description, username, tuple(tasks)) headers.append(('Location', '/dashboard')) 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 program(data): query, __, comment = data['text'].strip().partition(' ') if comment: comment = escape(comment) + r'\n' arxiv_id = arxiv_re.search(query) if arxiv_id is None: return _error_msg arxiv_id = arxiv_id.group() entry = fetch_arxiv(id_list=arxiv_id).iterentries().next() if entry is None or entry.entry is None: return _error_msg output = _output_template.format(entry['key'], \ escape(re.sub(r'\s+', u' ', entry['title'], re.U)), \ escape(_format_authors(entry['authors'])), \ comment).encode('utf-8') payload = _payload_template.format(data['channel_id'], data['user_name'], \ output) return output, payload
def changeNick(self, nick, initial=False): nick = nick.decode('utf-8', 'replace').encode('utf-8') if nick == '': nick = self.user if not initial and self.nick == nick: common.debug('trying to set the same nick') return if len(nick) > 129: # to avoid problems with utf-8 return oldNick = self.nick self.nick = nick #self.contactManager.setContactNick(self.user, self.nick) self.emit('self-nick-changed', oldNick, self.nick) self.socket.sendCommand("PRP", "MFN " + urllib.quote(nick)) if not initial and self.affinityCache != '': soap.requests.update_profile(self.proxy, self.affinityCache, \ self.rid, common.escape(nick), \ common.escape(self.personalMessage), self.onNickChanged, oldNick)
def _handle_action_set_message(self, message): '''handle e3.Action.ACTION_SET_MESSAGE ''' self.socket.send_command('UUX', payload='<Data><PSM>' + \ common.escape(message) + '</PSM><CurrentMedia></CurrentMedia>' + \ '<MachineGuid></MachineGuid></Data>') self.session.add_event(e3.Event.EVENT_MESSAGE_CHANGE_SUCCEED, message) self.session.contacts.me.message = message # log the change contact = self.session.contacts.me account = e3.Logger.Account.from_contact(contact) self.session.logger.log('message change', contact.status, message, account) Requester.SetProfile(self.session, contact.nick, message).start()
def renameGroup(self, oldGroup, newGroup): '''rename a group from the group list''' if oldGroup == newGroup: common.debug('oldgroup and new group are the same') return if self.contactManager.getGroupId(newGroup) != None: common.debug('That group name is already in use') return gid = self.contactManager.getGroupId(oldGroup) if gid == None: common.debug('The specified group does not exist') return else: self.contactManager.renameGroup(gid, newGroup) group = self.contactManager.getGroup(gid) objOldGroup = ContactData.Group(oldGroup) self.emit('group-attr-changed', objOldGroup, group) soap.manager.do_request(self.proxy,\ 'http://www.msn.com/webservices/AddressBook/ABGroupUpdate', \ 'contacts.msn.com', 443, '/abservice/abservice.asmx', \ soap.templates.renameGroup % (gid, common.escape(newGroup)), \ self.onGroupRenamed, (oldGroup, newGroup))
def __init__(self, msn, config): self.user = msn.user self.password = common.escape(msn.password) self.MSPAuth = msn.MSPAuth self.dg = msn.demographics self.config = config
def __init__( self, msn, config ): self.user = msn.user self.password = common.escape(msn.password) self.MSPAuth = msn.MSPAuth self.dg = msn.demographics self.config = config