def __init__(self): # Variable declarations max_login_attempts = 3 # specifies the max amount of login attempts the user can take before getting blocked login_attempts = 1 usr = Users() usr._init_()
def crea_usuarios(self): """Da de alta en ldap los usuarios que están en el listado""" lista=[] if self.esAlumnos: tipo="student" else: tipo="teacher" for usuario in self.usuarios: if not self.existsUsername(usuario['login']): if self.esAlumnos: if usuario['foto'] == 'false': foto=None else: foto=self.encode(usuario['foto']) else: foto=None surname=usuario['primer-apellido'] + ' ' + usuario['segundo-apellido'] nuevo=Users(self.ldap_con ,tipo,usuario['nombre'],surname.strip(), usuario['dni'],usuario['login'],usuario['passwd'],usuario['passwd'],'','',foto) nuevo.add() lista.append((usuario['login'],True,usuario['passwd'])) else: lista.append((usuario['login'],False,'')) return lista
def __init__( self, database, settings, suppress_exceptions = False ): """ Create a new Root object with the given settings. @type database: controller.Database @param database: database to use for all controllers @type settings: dict @param settings: CherryPy-style settings @rtype: Root @return: newly constructed Root """ self.__database = database self.__settings = settings self.__users = Users( database, settings[u"luminotes.http_url"], settings[u"luminotes.https_url"], settings[u"luminotes.support_email"], settings[u"luminotes.payment_email"], settings[u"luminotes.rate_plans"], settings[u"luminotes.download_products"], ) self.__groups = Groups( database, self.__users ) self.__files = Files( database, self.__users, settings[u"luminotes.download_products"], settings[u"luminotes.web_server"], ) self.__notebooks = Notebooks( database, self.__users, self.__files, settings[ u"luminotes.https_url"] ) self.__forums = Forums( database, self.__notebooks, self.__users ) self.__blog = Forum( database, self.__notebooks, self.__users, u"blog" ) self.__suppress_exceptions = suppress_exceptions # used for unit tests
def crea_usuarios(self): """Da de alta en ldap los usuarios que están en el listado""" lista = [] if self.esAlumnos: tipo = "student" else: tipo = "teacher" for usuario in self.usuarios: if not self.existsUsername(usuario['login']): if self.esAlumnos: if usuario['foto'] == 'false': foto = None else: foto = self.encode(usuario['foto']) else: foto = None surname = usuario['primer-apellido'] + ' ' + usuario[ 'segundo-apellido'] nuevo = Users(self.ldap_con, tipo, usuario['nombre'], surname.strip(), usuario['dni'], usuario['login'], usuario['passwd'], usuario['passwd'], '', '', foto) nuevo.add() lista.append((usuario['login'], True, usuario['passwd'])) else: lista.append((usuario['login'], False, '')) return lista
class clientProtocolFactory(ClientFactory): protocol = clientProtocol def __init__(self, alias, rsakey, GUIobject): self.GUI = GUIobject self.log = GUIobject.log self.status_log = GUIobject.status_log self.messages = GUIobject.messages self.received = 0 self.sent = 0 self.alias = alias self.pid = 1 self.RSAkey = rsakey self.publickey = rsakey.publickey().__getstate__() self.challenge = "my_encryption_challenge" self.challenge_answer = rsakey.encrypt(self.challenge, "") self.Users = Users(GUIobject.userPanel); self.Users.addUser("1", alias); self.Channels = Channels(GUIobject.chanPanel) def clientConnectionFailed(self, reason, bla): self.GUI.update_status_log("Couldn't connect...\n", LOG_ERR)
def register_user(): """ @api {post} /user/create Add a new user @apiVersion 1.0.0 @apiName add_user @apiGroup User @apiParam {String} name User's name. @apiParam {String} surname User's surname. @apiParam {String} email User's email. @apiParam {String} pseudo User's pseudo. @apiParam {Number} type User's type. @apiParam {String} password User's password. @apiSuccess {String} Token Must be used in every request to the API. """ if not request.json: abort(400) user_input = request.json user = Users() for field in user.field_for_register: value = user_input.get(field) if value == '' or value == None: abort(400) token = user.register(user_input) return jsonify({'token': token})
async def money(self, context, *args): try: # using money on a target. if len(args) > 0: # retrieve the target ID from the whoever the user mentioned target_id = context.message.mentions[0].id target = Users(target_id) if target.find_user() == 0: await context.send("Target does not have account.") return # fetch_user returns a User object that matches an id provided discord_member_target = await self.client.fetch_user(target_id) # embed the money retrieved from get_user_money(), set thumbnail to 64x64 version of target's id em = discord.Embed(title="", colour=0x607D4A) em.add_field( name=discord_member_target.display_name, value=f"**:moneybag: ** {target.get_user_money()}", inline=True, ) thumb_url = ( f"https://cdn.discordapp.com/avatars/{discord_member_target.id}" f"/{discord_member_target.avatar}.webp?size=64") em.set_thumbnail(url=thumb_url) await context.send(context.author.mention, embed=em) # if they passed no parameter, get their own money else: # create user instance with their discord ID, check database for their money field user = Users(context.author.id) # embed the money retrieved from get_user_money(), set thumbnail to 64x64 version of user's id em = discord.Embed(title="", colour=0x607D4A) em.add_field( name=context.author.display_name, value=f"**:moneybag: ** {user.get_user_money()}", inline=True, ) thumb_url = ( f"https://cdn.discordapp.com/avatars/{context.author.id}" f"/{context.author.avatar}.webp?size=64") em.set_thumbnail(url=thumb_url) await context.send(context.author.mention, embed=em) # Added this exception for debugging purposes. except Exception as e: msg = f"Not ok! {e.__class__} occurred" log.debug(msg) await context.send( f"{context.author.mention}```ml\nuse =money like so: **=money** or **=money @user**" ) finally: # delete original message to reduce spam await context.message.delete()
def send_start(_, message): start_text = "Привет! Этот бот отправляет тебе расписание перед парами!\n" \ "Так же можешь почитать `/help`" message.reply_text(start_text) u = Users() if u.check_user(message.chat.id) is False: u.reg_user(message.chat.username, message.chat.id, "user")
def start_message(message): user = users.get(message.chat.id) if not user: user = Users(message.chat.id) users[message.chat.id] = user bot.send_message(message.chat.id, 'Выбери сайт(ы), на который(ые) ты хочешь подписаться', reply_markup=key_board1) user.state = 1
def remove(): data = request.get_json() username = data.get("username") favorite = data.get("favorite") try: Users.remove_from_favorites(username, favorite) return jsonify({"status": "success"}) except: return jsonify({"status": "failed"})
def get_subscribers(): try: if session['loggedin'] == True: a=u.user_subscribers(mongo,request.form['user']) a.update({"status":"success"}) return json.dumps(a) except KeyError: a=u.user_subscribers(mongo,request.form['user']) a.update({"status":"error"}) return json.dumps(a)
def get_subscribers(): try: if session['loggedin'] == True: a = u.user_subscribers(mongo, request.form['user']) a.update({"status": "success"}) return json.dumps(a) except KeyError: a = u.user_subscribers(mongo, request.form['user']) a.update({"status": "error"}) return json.dumps(a)
def send_every_day(): today = date.today() lessons = wrapper.date_wrapper(today.day) u = Users() users = u.get_users() for id, _, _ in users: try: app.send_message(id, lessons) except PeerIdInvalid: pass
async def register(self, context): # create new user instance with their discord ID to store in database new_user = Users(context.message.author.id) if new_user.find_user() == 1: await self.client.say('<:worrymag1:531214786646507540> You **already** have an account registered!') return em = discord.Embed(title="", colour=0x607d4a) em.add_field(name=context.message.author.display_name, value=new_user.add_user(), inline=True) em.set_thumbnail(url=context.message.author.avatar_url) await self.client.say(embed=em)
def send_announce(_, message): u = Users() users = u.get_users() admins = u.get_admins() if message.chat.id in admins: for id, username, _ in users: app.send_message(id, message.command[1]) else: try: app.send_message(message.chat.id, "У вас нет прав") except PeerIdInvalid: pass
def create_account(): data = request.get_json() username = data.get("username") password = data.get("password") password_hash = hash_password(password) new_user = Users(username=username, password_hash=password_hash) try: new_user.add_user() return jsonify({"created": "success"}) except IntegrityError: print("Account already exists!") return jsonify({"created": "failed"})
class clientProtocolFactory(ClientFactory): protocol = clientProtocol def __init__(self, log, alias, msgObject): self.log = log self.messages = msgObject self.alias = alias self.pid = 1 self.Users = Users(); self.Users.addUser("1", alias); def clientConnectionFailed(self, reason, bla): self.log.log("Couldn't connect...\n", LOG_ERR)
def login_user(): if not request.json: abort(400) user = Users() if request.json['email'] == None or request.json['email'] == '': abort(400) if request.json['password'] == None or request.json['password'] == '': abort(400) user_info = user.login(request.json) return jsonify(user_info) return
async def enter_daily_tournament(self, context): # the bulk work of this feature is when the results are calculated from daily_maintenance.py # create instance of user who wants to enter the daily, server-specific colosseum tournament fighter = Users(context.message.author.id) # update their tourney_server_id entry to be the server they executed the command on msg = fighter.update_user_tourney_server_id( context.message.server.name, context.message.server.id) # embed the tourney registration confirmation message, set thumbnail to 40x40 of the respective server's icon em = discord.Embed(description=msg, colour=0x607d4a) thumb_url = "https://cdn.discordapp.com/icons/{0.id}/{0.icon}.webp?size=40".format( context.message.server) em.set_thumbnail(url=thumb_url) await self.client.say(embed=em)
async def adopt_pet(self, context): # create instance of the user who wishes to feed their pet pet_owner = Users(context.author.id) if pet_owner.find_pet() == 1: msg = await context.send("Failed! You already have a pet!") await asyncio.sleep(5) await msg.delete() return intro_msg = "Welcome to the **Pet Shelter**!\n\nPlease enter your desired pet name now:" # embed intro message, then overwrite the variable with the actual message object em = discord.Embed(description=intro_msg, colour=0x607D4A) em.set_thumbnail( url= "https://cdn.discordapp.com/emojis/746904102650249296.gif?size=128" ) await context.send(embed=em) # wait for user's pet name entry # helper to check if it's the author that it's responding. def is_author(m): return m.author == context.author and m.channel == context.channel pet_name = await self.client.wait_for("message", check=is_author, timeout=60) # remove everything except alphanumerics from the user's pet name entry pet_name = re.sub(r"\W+", "", pet_name.clean_content) # create an object to scan profanity pf = ProfanityFilter() # while the pet name entry has profanity, prompt user to re-enter a name while not pf.is_clean(pet_name): await context.send( "Pet name has profanity! Please enter a new one now:") # wait for user's new pet name entry pet_name = await self.client.wait_for("message", check=is_author, timeout=60) # remove everything except alphanumerics from the user's pet name entry pet_name = re.sub(r"\W+", "", pet_name.clean_content) adoption_msg = pet_owner.add_pet(pet_name[:15]) # embed confirmation message em = discord.Embed(description=adoption_msg, colour=0x607D4A) em.set_thumbnail( url="https://cdn.discordapp.com/emojis/563872560308289536.png?v=1") await context.send(embed=em)
def main(): ''' ユーザの顔写真を追加する ./ProjectOneFacePhoto/AddFace 以下にディレクトリ名をユーザ名として準備しておく ''' photo_dirs = glob.glob('./ProjectOneFacePhoto/AddFace/*') names = [os.path.basename(r) for r in photo_dirs] project_one = FaceApi(SUBSCRIPTION_KEY, 'project-one') users = Users('users.json') for name, photo_dir in zip(names, photo_dirs): person_id = users.get_person_id(name) add_face_photo(project_one, person_id, photo_dir) project_one.train_group() time.sleep(5) project_one.check_train_progress()
async def daily2(self, context): # create instance of user who earned their vote bonus user = Users(context.message.author.id) # get the user's current level user_level = user.get_user_level(0) # get int version of level, SEE USERS.PY dailyreward = user_level * 50 msg = '<a:worryswipe:525755450218643496> Daily **$' + str(dailyreward) \ + '** received! <a:worryswipe:525755450218643496>\n' + user.update_user_money(dailyreward) # embed the confirmation message, set thumbnail to user's id em = discord.Embed(title="", colour=0x607d4a) em.add_field(name="Thanks for voting, {}!".format(context.message.author.display_name), value=msg, inline=True) em.set_thumbnail(url=context.message.author.avatar_url) await self.client.say(embed=em)
class testUsers(unittest.TestCase): def setUp(self): self.sut = Users() def test_add_creates_new_user(self): self.sut.add("Marcel", "Gigi") self.assertEquals(1, len(self.sut.dict)) self.assertEquals("Marcel", list(self.sut.dict.keys())[0]) def test_add_appends_new_user_to_list_of_followed_users(self): self.sut.add("Marcel", "Gigi") followed = self.sut.dict["Marcel"] self.assertEquals(1, len(followed)) self.assertEquals("Gigi", followed[0]) def test_add_appends_multiple_followed_users(self): self.sut.dict["Marcel"] = ["Gigi"] self.sut.add("Marcel", "Bogdan") followed = self.sut.dict["Marcel"] self.assertEquals(2, len(followed)) self.assertEquals("Gigi", followed[0]) self.assertEquals("Bogdan", followed[1]) def test_add_does_not_append_same_followed_user_multiple_times(self): self.sut.dict["Marcel"] = ["Gigi"] self.sut.add("Marcel", "Gigi") followed = self.sut.dict["Marcel"] self.assertEquals(1, len(followed)) def test_get_returns_empty_list(self): result = self.sut.get("Marcel") self.assertEquals(0, len(result)) def test_get_returns_list_of_followed_users(self): list = ["Gigi", "Gogu"] self.sut.dict["Marcel"] = list result = self.sut.get("Marcel") self.assertEquals(list, result)
def __init__(self, User=Users()): root = Tk() root.title("Dash board") style = ttk.Style() style.theme_use("alt") image = PhotoImage(file="userimage.png") imageframe = ttk.Frame(root, width=10, height=10).grid(row=0, column=0) ttk.Label(imageframe, image=image).grid(row=0, column=0) container = ttk.Frame(root, width=800, height=600) container.grid(row=0, column=1) def DeleteaccountButtonfunction(): root.destroy() root.quit() from Deleteaccount import Deleteaccount next = Deleteaccount(User) DeleteaccountButton = ttk.Button( container, text=" Delete account ", command=DeleteaccountButtonfunction).pack() def ChangepasswordButtonfunction(): root.destroy() root.quit() after = Changepassword(User) ChangepasswordButton = ttk.Button( container, text="Change password", command=ChangepasswordButtonfunction).pack() root.mainloop()
def __init__(self, User=Users()): root = Tk() root.title("Delete account") ttk.Label(root, text="Enter your password").pack() Passwordfield = Text(root, width=35, height=2) Passwordfield.pack() def Deletebuttonfunction(): if Passwordfield.get("1.0", tkinter.END) == User.Password: User.Deleteaccount() else: tkinter.messagebox.showinfo("Error", "Failed Try later") root.destroy() root.quit() Deletebutton = ttk.Button(root, text="Delete!", command=Deletebuttonfunction).pack() def Cancelbuttonfunction(): root.destroy() root.quit() next = Dashboard(User) Cancelbutton = ttk.Button(root, text="Cancel", command=Cancelbuttonfunction).pack() root.mainloop()
def __init__(self, log, alias, msgObject): self.log = log self.messages = msgObject self.alias = alias self.pid = 1 self.Users = Users(); self.Users.addUser("1", alias);
def update_user(): if not request.json: abort(400) isEmpty = True user = Users() for field in user.field_for_register: value = request.json.get(field) if value != '' and value != None: isEmpty = False if isEmpty is False: updateUser = user.update(request.json) return jsonify(updateUser) else: abort(400)
def new_user(): name=request.form['name'] email=request.form['email'] password=request.form['password'] username=request.form['username'] a=u.new(mongo,name,email,password,username) return a
def new_user(): name = request.form['name'] email = request.form['email'] password = request.form['password'] username = request.form['username'] a = u.new(mongo, name, email, password, username) return a
def check_following_exists(): try: return json.dumps( u.check_following(mongo, session['username'], request.form['referer'])) except KeyError: json.dumps({"status": False})
def more_jokes(): a = u.user_followers(mongo, session['username']) d = [] for i in a['following']: d.append(i['user']) return json.dumps( j.load_more_jokes(mongo, d, ObjectId(request.form['oid'])))
def processUser(name, todayMonth): usersList = [] print(todayMonth) print(name) user_file = open('file/usersNew.txt', 'r') for ulist in user_file: list = ulist.split(',') savedate = list[5] savedateStr = savedate.split('-') dd = int(savedateStr[0]) mm = int(savedateStr[1]) yy = int(savedateStr[2]) print(mm) if list[0] == name and mm == todayMonth: goal = float(list[4]) #current month #saveCurrent = float(list[3]) saveTotal = searchHistoryforTotalSaving(list[0], list[6]) howmuchMore = goal - saveTotal howmuchMore = '%.2f' % howmuchMore monthly = 0.05 / 12 convert = monthly / 100 interest = saveTotal * convert i = '%.2f' % interest s = Users(list[0], list[1], list[2], list[3], list[4], list[5], list[6], list[7], howmuchMore, i, list[8]) usersList.append(s) return usersList
def pub_subscriptions(username): try: a=u.view(mongo,username) a.update({'email_hash': md5.new(a['email']).hexdigest()}) return render_template("user_subscriptions.html", title="Crackpot | "+a['name'], info=a) except KeyError: return "Error, not found!"
def LoginButtonfunction(): User = Person() User.Username = UsernameField.get("1.0", END) User.Password = passwordField.get("1.0", END) if len(User.Username) - 1 != 0 and len(User.Password) - 1 != 0: Data = User.Login(User.Username, User.Password) if Data[0] and Data[1].Authorize: if not Data[1].Admin: User = Users() else: User = Admin() User.Username = Data[1].Username User.Password = Data[1].Password User.Folderpath = Data[1].Folderpath User.Authorize = Data[1].Authorize User.Admin = Data[1].Admin if not User.Admin: root.destroy() root.quit() from Dashboard import Dashboard next = Dashboard(User) else: pass # الى هيعمل ال admin else: tkinter.messagebox.showinfo(" Invalid Credintial", "User Doesnot exist thank you :)") root.destroy() root.quit() else: tkinter.messagebox.showinfo("Empty fields", "Do net leave any field empty ")
def get_profile_data(): data = request.get_json() username = data.get("username") favorites = Users.get_favorites(username) if favorites: return jsonify({"favorites": favorites}) return jsonify({"favorites": "none"})
def loadSkarphedChildren(self): self.loadPublicKey() self.getMaintenanceMode() self.loadRendermode() if 'skarphed.users.view' in self.serverRights: self.users = Users(self) self.addChild(self.users) if 'skarphed.modules.install' in self.serverRights or 'skarphed.modules.uninstall' in self.serverRights: self.modules = Modules(self) self.addChild(self.modules) if 'skarphed.roles.view' in self.serverRights: self.roles = Roles(self) self.addChild(self.roles) if True: #'skarphed.sites.view' in self.serverRights self.sites = Sites(self) self.addChild(self.sites) if True: self.views = Views(self) self.addChild(self.views) if True: #'skarphed.template.modify' in self.serverRights self.template = Template(self) self.addChild(self.template) if True: #'skarphed.operation.modify' in self.serverRights self.operationManager = OperationManager(self) #TODO: restliche implementieren self.pokethread = PokeThread(self) self.pokethread.start()
def __init__(self): self.__version__ = '3.1.3' logger_format = '%(asctime)s %(message)s' logging.basicConfig(format=logger_format, level=logging.INFO, datefmt="%H:%M:%S", filename='./logfile.log', filemode='w') logging.getLogger().addHandler(SysLogHandler(facility=SysLogHandler.LOG_DAEMON, address='/dev/log')) self._SIGKILL = False self.logging = logging self.config = DB('./config.json') self.network = Network(self) self.display = DisplayContent() self.detector = Detector() self.ultrasound = Ultrasound(self) self.temp = Temp() self.server = SimpleWebSocketServer('', 8069, WebSocketServer, self) self.cook = Cook(self) self.energy = Energy(self) self.history = History(self) self.audio = Audio(self) self.users = Users(self) self.automations = Automations(self) signal.signal(signal.SIGTERM, self.sig_handler) signal.signal(signal.SIGINT, self.sig_handler) self.log("Boot: v" + self.__version__)
def get_userinfo(param): a=u.get_userinfo(mongo,session['username']) if param in a: return a[param] elif param=="email_hash": return md5.new(a['email']).hexdigest() else: return ""
def unsubscribe(): try: if u.unsubscribe_user(mongo, session['username'], request.form['referer']): return json.dumps({"status": True}) else: return json.dumps({"status": False}) except KeyError: return json.dumps({"status": False})
def get_userinfo(param): a = u.get_userinfo(mongo, session['username']) if param in a: return a[param] elif param == "email_hash": return md5.new(a['email']).hexdigest() else: return ""
def update_profile(): name=request.form['name'] email=request.form['email'] bio=request.form['bio'] url=request.form['url'] location=request.form['location'] color=request.form['color'] return u.update(mongo,session['username'],name,email,bio,url,location,color)
def init(): """ NOTE : initialize database """ My_db_class() # initialize Users Users()
async def update_pet_name(self, context): # create instance of the user who wishes to change their pet name pet_owner = Users(context.author.id) # retrieve pet name pet_name = pet_owner.get_user_pet_name() intro_msg = f"Welcome to the **Pet Shelter**!\n\nPlease enter your new name for **{pet_name}** now:" # embed intro message, then overwrite the variable with the actual message object em = discord.Embed(description=intro_msg, colour=0x607D4A) em.set_thumbnail( url= "https://cdn.discordapp.com/emojis/560065150489722880.png?size=128" ) await context.send(embed=em) # wait for user's pet name entry # helper to check if it's the author that it's responding. def is_author(m): return m.author == context.author and m.channel == context.channel pet_name = await self.client.wait_for("message", check=is_author, timeout=60) # remove everything except alphanumerics from the user's pet name entry pet_name = re.sub(r"\W+", "", pet_name.clean_content) # create an object to scan profanity pf = ProfanityFilter() # while the pet name entry has profanity, prompt user to re-enter a name while not pf.is_clean(pet_name): await context.send( "Pet name has profanity! Please enter a new one now:") # wait for user's new pet name entry pet_name = await self.client.wait_for("message", check=is_author, timeout=60) # remove everything except alphanumerics from the user's pet name entry pet_name = re.sub(r"\W+", "", pet_name.clean_content) confirmation_msg = pet_owner.update_user_pet_name(pet_name[:15]) # embed confirmation message em = discord.Embed(description=confirmation_msg, colour=0x607D4A) em.set_thumbnail( url="https://cdn.discordapp.com/emojis/746904102650249296.gif?v=1") await context.send(embed=em)
def subscribed_jokes(): try: a=u.user_followers(mongo,session['username']) d=[] for i in a['following']: d.append(i['user']) return json.dumps(j.my_wall(mongo,d)) except KeyError: return json.dumps({"status": "error"})
def __init__(self, list_of_names): """ NOTE : - go through all triggered reminders and fetch a line of text from each; append to report """ self.report = [] for name in list_of_names: for rem in Users.get_by_name(name).check_reminders(): self.report.append(rem.get_report_line()) return None
def public_profile(username): a=u.view(mongo,username) if a.has_key('username'): a.update({'email_hash': md5.new(a['email']).hexdigest()}) try: ref={} ref.update({'ref_name': get_userinfo('name'), 'ref_bio': get_userinfo('bio'), 'ref_avatar': get_userinfo('email_hash')}) return render_template("public_view.html", title="Crackpot | "+a['name'], info=a, ref=ref, username=session['username'], avatar_hash=get_userinfo('email_hash')) except KeyError: return render_template("public_view.html", title="Crackpot | "+a['name'], info=a) else: return "Error! Not found..."
def subscribe(): try: if session['loggedin'] == True: name=request.form['subscribe'] user_name=request.form['name'] user_bio=request.form['bio'] user_avatar=request.form['avatar'] ref_name=request.form['ref_name'] ref_bio=request.form['ref_bio'] ref_avatar=request.form['ref_avatar'] return u.subscribe(mongo,session['username'],name,user_name,user_bio,user_avatar, ref_name, ref_bio, ref_avatar) else: return json.dumps({"status": "loggedin_error", "url": "/login"}) except KeyError: return json.dumps({"status": "loggedin_error", "url": "/login"})
def __init__(self, config_path): if not os.path.exists(config_path): raise ValueError("Can't find config file \"" + config_path + "\"") #if sys.stdout = Unbuffered(sys.stdout) sys.stderr = Unbuffered(sys.stderr) self.__config = ConfigParser() self.__config.read(config_path) self.__active_mails_count = 0 self.__send_lock = Lock() self.__users_db = Users(self.get_param_str('Main', 'ACCESS_FILE_PATH')) self.__whitelist = FilterList(self.get_param_str('Main', 'WHITELIST_SENDERS')) self.__blacklist = FilterList(self.get_param_str('Main', 'BLACKLIST_SENDERS'))
def __init__(self, alias, rsakey, GUIobject): self.GUI = GUIobject self.log = GUIobject.log self.status_log = GUIobject.status_log self.messages = GUIobject.messages self.received = 0 self.sent = 0 self.alias = alias self.pid = 1 self.RSAkey = rsakey self.publickey = rsakey.publickey().__getstate__() self.challenge = "my_encryption_challenge" self.challenge_answer = rsakey.encrypt(self.challenge, "") self.Users = Users(GUIobject.userPanel); self.Users.addUser("1", alias); self.Channels = Channels(GUIobject.chanPanel)
class msh: def __init__(self, config_path): if not os.path.exists(config_path): raise ValueError("Can't find config file \"" + config_path + "\"") #if sys.stdout = Unbuffered(sys.stdout) sys.stderr = Unbuffered(sys.stderr) self.__config = ConfigParser() self.__config.read(config_path) self.__active_mails_count = 0 self.__send_lock = Lock() self.__users_db = Users(self.get_param_str('Main', 'ACCESS_FILE_PATH')) self.__whitelist = FilterList(self.get_param_str('Main', 'WHITELIST_SENDERS')) self.__blacklist = FilterList(self.get_param_str('Main', 'BLACKLIST_SENDERS')) #def def _send_response(self, email_from, msg): self.__send_lock.acquire() if not msg is None: print "[%s] Sending response to '%s'" % (datetime.today().strftime('%d/%m/%y %H:%M'), email_from) recipients = [email_from, self.get_param_str('Mail', 'SEND_COPY_TO')] message = "%s%s%s\n%s" % ('From: %s \n' % (self.get_param_str('Main', 'BOT_NAME')), 'To: %s \n' % (email_from), 'Subject: Report %s \n' % (datetime.today().strftime('%d/%m/%y %H:%M')), msg) if is_enabled(self.get_param_str("Mail", "USE_SSL")): session = smtplib.SMTP_SSL(self.get_param_str("Mail", "SMTP_SERVER"), self.get_param_int("Mail", "SMTP_SSL_PORT")) else: session = smtplib.SMTP(self.get_param_str("Mail", "SMTP_SERVER"), self.get_param_int("Mail", "SMTP_PORT")) #if if is_enabled(self.get_param_str("Debug", "NETWORK_COMM_LOGGING")): session.set_debuglevel(100) #if session.login(self.get_param_str("Mail", "EMAIL_USER"), self.get_param_str("Mail", "EMAIL_PASS")) session.sendmail(self.get_param_str("Mail", "EMAIL_USER"), recipients, message) session.quit() #if self.__send_lock.release() #def def _check_pop(self): print "[%s] Going to get messages by POP" % (datetime.today().strftime('%d/%m/%y %H:%M')) if is_enabled(self.get_param_str("Mail", "USE_SSL")): session = poplib.POP3_SSL(self.get_param_str("Mail", "POP_SERVER"), self.get_param_int("Mail", "POP_SSL_PORT")) else: session = poplib.POP3(self.get_param_str("Mail", "POP_SERVER"), self.get_param_int("Mail", "POP_PORT")) #if if is_enabled(self.get_param_str("Debug", "NETWORK_COMM_LOGGING")): session.set_debuglevel(100) #if try: session.user(self.get_param_str("Mail", "EMAIL_USER")) session.pass_(self.get_param_str("Mail", "EMAIL_PASS")) except poplib.error_proto as e: sys.stderr.write("Got an error while conencting to POP server: '%s'\n" % (e)) return False #try numMessages = len(session.list()[1]) for i in range(numMessages): m_parsed = Parser().parsestr("\n".join(session.top(i+1, 0)[1])) if self.get_param_str('Main', 'SUBJECT_CODE_PHRASE') == m_parsed['subject']: #Looks like valid cmd for bot, continue if self._process_msg("\n".join(session.retr(i+1)[1])): session.dele(i+1) #if #if #for session.quit() #def def _check_imap(self): print "[%s] Going to get messages by IMAP" % (datetime.today().strftime('%d/%m/%y %H:%M')) if is_enabled(self.get_param_str("Mail", "USE_SSL")): session = imaplib.IMAP4_SSL(self.get_param_str("Mail", "IMAP_SERVER"), self.get_param_int("Mail", "IMAP_SSL_PORT")) else: session = imaplib.IMAP4(self.get_param_str("Mail", "IMAP_SERVER"), self.get_param_int("Mail", "IMAP_PORT")) #if if is_enabled(self.get_param_str("Debug", "NETWORK_COMM_LOGGING")): session.debug = 100 #if try: session.login(self.get_param_str("Mail", "EMAIL_USER"), self.get_param_str("Mail", "EMAIL_PASS")) except imaplib.IMAP4.error as e: sys.stderr.write("Got an error while connecting to IMAP server: '%s'\n" % (e)) return False #try session.select(self.get_param_str('Mail', 'IMAP_MAILBOX_NAME')) typ, data = session.search(None, 'SUBJECT', self.get_param_str("Main", "SUBJECT_CODE_PHRASE")) # 'UNSEEN') if not data[0] is None: for num in data[0].split(): typ, data = session.fetch(num, '(RFC822)') if self._process_msg(data[0][1]): session.store(num, '+FLAGS', '\\Deleted') # session.store(num, '+FLAGS', '\\Seen') #if #for #if session.expunge() session.close() session.logout() #def def _process_msg(self, raw_email): if not type(raw_email) is types.StringType: return True #if m_parsed = Parser().parsestr(raw_email) m_from = m_parsed['from'] if self.__active_mails_count > self.get_param_int('Main', 'NUMBER_OF_PROCESSING_THREADS'): print "[%s] All processing threads are busy. Will try in next iteratio" % (datetime.today().strftime('%d/%m/%y %H:%M')) return False #if print "[%s] Processing message from user '%s'" % (datetime.today().strftime('%d/%m/%y %H:%M'), m_from) #check it in white/black lists if not self.__whitelist.has_elem(m_from, is_enabled(self.get_param_str('Main', 'USE_REGEXP_IN_FILTERING'))): print "Got command from unknown email (%s)" % (m_from) return True #if if self.__blacklist.has_elem(m_from, is_enabled(self.get_param_str('Main', 'USE_REGEXP_IN_FILTERING'))): print "Got command from blacklisted email (%s)" % (m_from) return True #if self.__active_mails_count += 1 for m_body in self._get_payload_from_msg(m_parsed): if self._check_user(m_body[0]): for i in xrange(1, len(m_body)): #self._thread_routine(ddm_from, m_body[i].strip()) Process(target=self._thread_routine, args=(m_from, m_body[i].strip())).start() #for else: print "Received an incorrect pair of user+password!" #if #for return True #def def _get_payload_from_msg(self, parsed_email): """ Generator for extracting all message boundles from email """ if parsed_email.is_multipart(): for msg_from_multipart in parsed_email.get_payload(): # proccesing recursively all multipart messages for sub_msg in self._get_payload_from_msg(msg_from_multipart): yield sub_msg #for #for else: yield parsed_email.get_payload().split("\n") #if #def def _thread_routine(self, m_from, command): self._send_response(m_from, self._perform_user_cmd(command)) self.__active_mails_count -= 1 #def def _check_user(self, credentials_str): try: user, passwd = credentials_str.strip().split(":") return self.__users_db.check(user, passwd) except ValueError: return False; #try #def def _perform_user_cmd(self, command): if 0 >= len(command): return None #if print "[%s] Going to process command '%s'" % (datetime.today().strftime('%d/%m/%y %H:%M'), command) buff = "[%s] %s \r\n" % (datetime.today().strftime('%d/%m/%y %H:%M'), command) if ":list" == command: pass elif command.startswith(":stop"): id = 0 try: id = int(command[5:]) pass except ValueError as e: buf += "Error! Got incorrect parameter for 'stop' command '%s'\n" % (command[5:]) sys.stderr.write("Error! Got incorrect parameter for 'stop' command '%s'\n" % (command[5:])) #try else: time = None if command.startswith(":time="): try: ind = command.index(" ") try: time = int(command[6:ind]) command = command[ind+1:] except ValueError as e: buff += "Error! Got incorrect parameter for 'time' command '%s'\n" % (command[6:ind]) sys.stderr.write("Error! Got incorrect parameter for 'time' command '%s'\n" % (command[6:ind])) return buff #try except ValueError as e: buff += "Error! Wrong format of 'time' command '%s'\n" % (command[6:]) sys.stderr.write("Error! Wrong format of 'time' command '%s'\n" % (command[6:])) return buff #try #if out_buf = [] t = threading.Thread(target=self._run_popen, args=(command, out_buf)) t.start() t.join(time) buff += "\n".join(out_buf) if t.isAlive(): try: t._Thread__stop() buff += "Thread has timeouted after timeout = %i!" % (time) except: sys.stream.write("Thread with command '%s' could not be terminated" % (command)) #try #if #if return buff #def def _run_popen(self, cmd, out_buf_list): get_rev = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) get_rev.wait() for str in get_rev.stdout.readlines(): out_buf_list.append(str) #for out_buf_list.append("retcode = %d\r\n" % get_rev.returncode) #def def check_for_new_commands(self): print "[%s] Checking for new commands\n" % (datetime.today().strftime('%d/%m/%y %H:%M')) if is_enabled(self.get_param_str('Mail', 'USE_IMAP')): return self._check_imap() else: return self._check_pop() #if #def def add_new_user(self, user, passwd): return self.__users_db.add(user, passwd) #def def _get_param(self, sect, param): res = None try: res = self.__config.get(sect, param) except NoOptionError as e: sys.stderr.write("%s\n" % (str(e))) #try return res #def def get_param_int(self, sect, param): res = 0 try: res = int(self._get_param(sect, param)) except ValueError as e: sys.stderr.write("%s\n" % (str(e))) except TypeError as e: sys.stderr.write("%s\n" % (str(e))) #try return res #def def get_param_str(self, sect, param): return self._get_param(sect, param)
def setUp(self): self.sut = Users()
def db_test(config): test_user = { "username" : "test" , "password" : "29148931" , "salt" : "1234" , "admin" : "1" } users = Users() users.create() users.save(test_user) test_room = { "room_id" : "seka" , "password" : "29148931" } test_room2 = { "room_id" : "test" , "password" : "29148931" } rooms = Rooms() rooms.create() rooms.save(test_room) rooms.save(test_room2) test_entry = { "room_id" : "seka" , "entry" : u"この内容はテストです" , "type" : "keep" , "good" : 4 } test_entry2 = { "room_id" : "seka" , "entry" : u"この内容はテストです" , "type" : "try" , "good" : 5 } entries = Entry() entries.create() entries.save(test_entry) entries.save(test_entry) entries.save(test_entry) entries.save(test_entry2) entries.save(test_entry2) goods = Goods() goods.create() test_comment = { "kpt_id" : 1 , "text" : u"テストのコメントです" } test_comment2 = { "kpt_id" : 1 , "text" : u"テストのコメントです2" } test_comment3 = { "kpt_id" : 2 , "text" : u"テスト2のコメントです" } comments = Comments() comments.create() comments.save(test_comment) comments.save(test_comment2) comments.save(test_comment3)
def initWorld(self, playerId, chosenCharId, x, y, h): self.keyMap = {"hello":0, "left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0, "chat":0, "fast":0, "chat0": 0, "chat1": 0, "users": 0} base.win.setClearColor(Vec4(0,0,0,1)) # chat box self.chatbox = Chat(self.cManager, self) self.activeUsers = Users(self.cManager, self) taskMgr.add(self.message, 'message') # Post the instructions self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[A]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[D]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[W]: Run Ralph Forward") self.inst4 = addInstructions(0.75, "[S]: Run Ralph Backward") self.inst6 = addInstructions(0.70, "[Left Arrow]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[Right Arrow]: Rotate Camera Right") self.inst8 = addInstructions(0.60, "[0]: Toggle Chat Broadcast") self.inst9 = addInstructions(0.55, "[1]: Toggle Private Chat - username/") self.inst10 = addInstructions(0.50, "[L]: List Connected Users") # Set up the environment # self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0,0,0) self.environ.setScale(100,100,1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) #Collision Code # Initialize the collision traverser. base.cTrav = CollisionTraverser() # Initialize the Pusher collision handler. self.pusher = CollisionHandlerPusher() self.bTrav = base.cTrav # Create the main character, Ralph self.mainCharRef = Character(self, chosenCharId, True) self.mainCharRef.setPlayerId(playerId) self.characters.append(self.mainCharRef) self.mainChar = self.mainCharRef.getActor() #Create second bike self.mainCharRef2 = Character(self, 3, True) self.mainCharRef2.setPlayerId(2) self.characters.append(self.mainCharRef2) self.mainChar2 = self.mainCharRef2.getActor() resetPos = True if (x == 0 and y == 0): resetPos = False if resetPos: self.mainChar.setPos(x, y, 0) self.mainChar.setH(h) self.cManager.sendRequest(Constants.CMSG_CREATE_CHARACTER, [playerId, chosenCharId, self.mainChar.getX(), self.mainChar.getY(), self.mainChar.getZ()]) self.previousPos = self.mainChar.getPos() taskMgr.doMethodLater(.1, self.updateMove, 'updateMove') # Creating Stationary spheres self.spheres = [] self.sphereCount = 3 for x in range(self.sphereCount): self.spheres.append(StationarySphere(self)) for sphere in self.spheres: taskMgr.add(sphere.rotateForAll, "rotateSphere") self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) floorNode = render.attachNewNode("Floor NodePath") # Create a collision plane solid. collPlane = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0))) # Call our function that creates a nodepath with a collision node. floorCollisionNP = self.makeCollisionNodePath(floorNode, collPlane) # Accept the control keys for movement and rotation self.accept("escape", self.quitGame) self.accept("a", self.setKey, ["left",1]) self.accept("d", self.setKey, ["right",1]) self.accept("w", self.setKey, ["forward",1]) self.accept("s", self.setKey, ["backward",1]) self.accept("lshift", self.setKey, ["fast", 1]) self.accept("arrow_left", self.setKey, ["cam-left",1]) self.accept("arrow_right", self.setKey, ["cam-right",1]) self.accept("a-up", self.setKey, ["left",0]) self.accept("d-up", self.setKey, ["right",0]) self.accept("w-up", self.setKey, ["forward",0]) self.accept("s-up", self.setKey, ["backward",0]) self.accept("lshift-up", self.setKey, ["fast", 0]) self.accept("arrow_left-up", self.setKey, ["cam-left",0]) self.accept("arrow_right-up", self.setKey, ["cam-right",0]) self.accept("h", self.setKey, ["hello",1]) self.accept("h-up", self.setKey, ["hello",0]) self.accept("0", self.setKey, ["chat0", 1]) self.accept("0-up", self.setKey, ["chat0", 0]) self.accept("1", self.setKey, ["chat1", 1]) self.accept("1-up", self.setKey, ["chat1", 0]) self.accept("l", self.setKey, ["users", 1]) self.accept("l-up", self.setKey, ["users", 0]) taskMgr.add(self.move,"moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.mainChar.getX(),self.mainChar.getY()+10,2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
class World(DirectObject): currentTime = 0 idleTime = 0 mySequence = None pandaPace = None jumpState = False isWalk = False previousPos = None #used to store the mainChar pos from one frame to another host = "" port = 0 characters = [] #Stores the list of all the others players characters def __init__(self): # Network Setup print "Object Created" self.characters = [] def setConnectionManager(self, connectionManager): self.cManager = connectionManager def initWorld(self, playerId, chosenCharId, x, y, h): self.keyMap = {"hello":0, "left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0, "chat":0, "fast":0, "chat0": 0, "chat1": 0, "users": 0} base.win.setClearColor(Vec4(0,0,0,1)) # chat box self.chatbox = Chat(self.cManager, self) self.activeUsers = Users(self.cManager, self) taskMgr.add(self.message, 'message') # Post the instructions self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[A]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[D]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[W]: Run Ralph Forward") self.inst4 = addInstructions(0.75, "[S]: Run Ralph Backward") self.inst6 = addInstructions(0.70, "[Left Arrow]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[Right Arrow]: Rotate Camera Right") self.inst8 = addInstructions(0.60, "[0]: Toggle Chat Broadcast") self.inst9 = addInstructions(0.55, "[1]: Toggle Private Chat - username/") self.inst10 = addInstructions(0.50, "[L]: List Connected Users") # Set up the environment # self.environ = loader.loadModel("models/square") self.environ.reparentTo(render) self.environ.setPos(0,0,0) self.environ.setScale(100,100,1) self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg") self.environ.setTexture(self.moon_tex, 1) #Collision Code # Initialize the collision traverser. base.cTrav = CollisionTraverser() # Initialize the Pusher collision handler. self.pusher = CollisionHandlerPusher() self.bTrav = base.cTrav # Create the main character, Ralph self.mainCharRef = Character(self, chosenCharId, True) self.mainCharRef.setPlayerId(playerId) self.characters.append(self.mainCharRef) self.mainChar = self.mainCharRef.getActor() #Create second bike self.mainCharRef2 = Character(self, 3, True) self.mainCharRef2.setPlayerId(2) self.characters.append(self.mainCharRef2) self.mainChar2 = self.mainCharRef2.getActor() resetPos = True if (x == 0 and y == 0): resetPos = False if resetPos: self.mainChar.setPos(x, y, 0) self.mainChar.setH(h) self.cManager.sendRequest(Constants.CMSG_CREATE_CHARACTER, [playerId, chosenCharId, self.mainChar.getX(), self.mainChar.getY(), self.mainChar.getZ()]) self.previousPos = self.mainChar.getPos() taskMgr.doMethodLater(.1, self.updateMove, 'updateMove') # Creating Stationary spheres self.spheres = [] self.sphereCount = 3 for x in range(self.sphereCount): self.spheres.append(StationarySphere(self)) for sphere in self.spheres: taskMgr.add(sphere.rotateForAll, "rotateSphere") self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) floorNode = render.attachNewNode("Floor NodePath") # Create a collision plane solid. collPlane = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0))) # Call our function that creates a nodepath with a collision node. floorCollisionNP = self.makeCollisionNodePath(floorNode, collPlane) # Accept the control keys for movement and rotation self.accept("escape", self.quitGame) self.accept("a", self.setKey, ["left",1]) self.accept("d", self.setKey, ["right",1]) self.accept("w", self.setKey, ["forward",1]) self.accept("s", self.setKey, ["backward",1]) self.accept("lshift", self.setKey, ["fast", 1]) self.accept("arrow_left", self.setKey, ["cam-left",1]) self.accept("arrow_right", self.setKey, ["cam-right",1]) self.accept("a-up", self.setKey, ["left",0]) self.accept("d-up", self.setKey, ["right",0]) self.accept("w-up", self.setKey, ["forward",0]) self.accept("s-up", self.setKey, ["backward",0]) self.accept("lshift-up", self.setKey, ["fast", 0]) self.accept("arrow_left-up", self.setKey, ["cam-left",0]) self.accept("arrow_right-up", self.setKey, ["cam-right",0]) self.accept("h", self.setKey, ["hello",1]) self.accept("h-up", self.setKey, ["hello",0]) self.accept("0", self.setKey, ["chat0", 1]) self.accept("0-up", self.setKey, ["chat0", 0]) self.accept("1", self.setKey, ["chat1", 1]) self.accept("1-up", self.setKey, ["chat1", 0]) self.accept("l", self.setKey, ["users", 1]) self.accept("l-up", self.setKey, ["users", 0]) taskMgr.add(self.move,"moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.mainChar.getX(),self.mainChar.getY()+10,2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) def makeCollisionNodePath(self, nodepath, solid): ''' Creates a collision node and attaches the collision solid to the supplied NodePath. Returns the nodepath of the collision node. ''' # Creates a collision node named after the name of the NodePath. collNode = CollisionNode("%s c_node" % nodepath.getName()) collNode.addSolid(solid) collisionNodepath = nodepath.attachNewNode(collNode) return collisionNodepath #Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value #print "In setKey", key, value self.cManager.sendRequest(Constants.CMSG_KEY, [key, value]) # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def getDist(self): mainCharX = self.mainChar.getPos().x mainCharY = self.mainChar.getPos().y pandaX = self.pandaActor2.getPos().x pandaY = self.pandaActor2.getPos().y dist = math.sqrt(abs(mainCharX-pandaX)**2 + abs(mainCharY-pandaY)**2) return dist def move(self, task): # If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. base.camera.lookAt(self.mainChar) if (self.keyMap["cam-left"]!=0): base.camera.setX(base.camera, -20 * globalClock.getDt()) if (self.keyMap["cam-right"]!=0): base.camera.setX(base.camera, +20 * globalClock.getDt()) # save mainChar's initial position so that we can restore it, # in case he falls off the map or runs into something. startpos = self.mainChar.getPos() starthpr = self.mainChar.getHpr() # If left-shift is pressed, speed-up ralph ralphSpeed = 1 if(self.keyMap["fast"]==1): ralphSpeed = 3 # If a move-key is pressed, move ralph in the specified direction. if (self.keyMap["left"]!=0): self.mainChar.setH(self.mainChar.getH() + 300 * globalClock.getDt() * ralphSpeed) if (self.keyMap["right"]!=0): self.mainChar.setH(self.mainChar.getH() - 300 * globalClock.getDt() * ralphSpeed) if (self.keyMap["forward"] != 0 and self.mainCharRef.type == 2): self.mainChar.setY(self.mainChar, -500 * globalClock.getDt() * ralphSpeed) elif (self.keyMap["forward"] != 0 and self.mainCharRef.type == 3): self.mainChar.setZ(self.mainChar, 25 * globalClock.getDt() * ralphSpeed) elif (self.keyMap["forward"] != 0): self.mainChar.setY(self.mainChar, -25 * globalClock.getDt() * ralphSpeed) if (self.keyMap["backward"] != 0 and self.mainCharRef.type == 2): self.mainChar.setY(self.mainChar, 500 * globalClock.getDt() * ralphSpeed) elif (self.keyMap["backward"] != 0 and self.mainCharRef.type == 3): self.mainChar.setZ(self.mainChar, -25 * globalClock.getDt() * ralphSpeed) elif (self.keyMap["backward"] != 0): self.mainChar.setY(self.mainChar, 25 * globalClock.getDt() * ralphSpeed) # If ralph is moving, loop the run animation. # If he is standing still, stop the animation. if (self.keyMap["forward"] != 0) or (self.keyMap["backward"] != 0) or (self.keyMap["left"] != 0) or ( self.keyMap["right"] != 0): if self.isMoving is False : self.isMoving = True if self.mainCharRef.type != 3: self.mainChar.loop("run") else: if self.isMoving: self.isMoving = False if self.mainCharRef.type != 3: self.mainChar.stop() self.mainChar.pose("walk",5) # Detecting collisions only when ralph is moving if self.isMoving: # Collision With Spheres isCollidingWithSphere = False for sphere in self.spheres: if self.mainCharRef.isColliding(sphere.actor.getPos(), sphere.boundingRadius): isCollidingWithSphere = True if isCollidingWithSphere: self.mainChar.setPos(startpos) self.mainChar.setHpr(starthpr) # Collision With Other Ralphs isCollidingWithOtherRalphs = False for chacracter in self.characters: if not chacracter.isMainChar and self.mainCharRef.isColliding(chacracter.actor.getPos(), chacracter.boundingRadius): isCollidingWithOtherRalphs = True if isCollidingWithOtherRalphs: self.mainChar.setH(self.mainChar.getH() - 180) # If the camera is too far from ralph, move it closer. # If the camera is too close to ralph, move it farther. camvec = self.mainChar.getPos() - base.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if (camdist > 10.0): base.camera.setPos(base.camera.getPos() + camvec*(camdist-10)) camdist = 10.0 if (camdist < 5.0): base.camera.setPos(base.camera.getPos() - camvec*(5-camdist)) camdist = 5.0 # The camera should look in ralph's direction, # but it should also try to stay horizontal, so look at # a floater which hovers above ralph's head. self.floater.setPos(self.mainChar.getPos()) self.floater.setZ(self.mainChar.getZ() + 2.0) base.camera.lookAt(self.floater) return task.cont def startConnection(self): """Create a connection to the remote host. If a connection cannot be created, it will ask the user to perform additional retries. """ if self.cManager.connection == None: if not self.cManager.startConnection(): return False return True def message(self, task): # hide all chatboxes if self.keyMap["chat0"] != 0: if self.chatbox.getVisible() is False: self.chatbox.setVisible(True) self.chatbox.show(0) else: self.chatbox.setVisible(False) self.chatbox.hide() self.keyMap["chat0"] = 0 if self.keyMap["chat1"] != 0: if self.chatbox.getVisible() is False: self.chatbox.setVisible(True) self.chatbox.show(1) else: self.chatbox.setVisible(False) self.chatbox.hide() self.keyMap["chat1"] = 0 if self.keyMap["users"] != 0: self.activeUsers.toggle() self.keyMap["users"] = 0 return task.cont def updateMove(self, task): if self.isMoving == True : # moving = self.mainChar.getPos() - self.previousPos moving = self.mainChar.getPos(); self.cManager.sendRequest(Constants.CMSG_MOVE, [moving.getX() ,moving.getY(),moving.getZ(), self.mainChar.getH()]) #self.cManager.sendRequest(Constants.RAND_FLOAT, 1.0) self.previousPos = self.mainChar.getPos() return task.again def quitGame(self): self.cManager.closeConnection() sys.exit()
from Users import Users usr = Users() usr.__init__() usr.show_login_window()
class Root( object ): """ The root of the controller hierarchy, corresponding to the "/" URL. """ def __init__( self, database, settings, suppress_exceptions = False ): """ Create a new Root object with the given settings. @type database: controller.Database @param database: database to use for all controllers @type settings: dict @param settings: CherryPy-style settings @rtype: Root @return: newly constructed Root """ self.__database = database self.__settings = settings self.__users = Users( database, settings[u"luminotes.http_url"], settings[u"luminotes.https_url"], settings[u"luminotes.support_email"], settings[u"luminotes.payment_email"], settings[u"luminotes.rate_plans"], settings[u"luminotes.download_products"], ) self.__groups = Groups( database, self.__users ) self.__files = Files( database, self.__users, settings[u"luminotes.download_products"], settings[u"luminotes.web_server"], ) self.__notebooks = Notebooks( database, self.__users, self.__files, settings[ u"luminotes.https_url"] ) self.__forums = Forums( database, self.__notebooks, self.__users ) self.__blog = Forum( database, self.__notebooks, self.__users, u"blog" ) self.__suppress_exceptions = suppress_exceptions # used for unit tests @expose( Main_page ) @end_transaction @grab_user_id @validate( note_title = unicode, invite_id = Valid_id( none_okay = True ), after_login = Valid_string( min = 0, max = 1000 ), plan = Valid_int( none_okay = True ), yearly = Valid_bool( none_okay = True ), user_id = Valid_id( none_okay = True ), ) def default( self, note_title, invite_id = None, after_login = None, plan = None, yearly = False, user_id = None ): """ Convenience method for accessing a note in the main notebook by name rather than by note id. @type note_title: unicode @param note_title: title of the note to return @type invite_id: unicode @param invite_id: id of the invite used to get to this note (optional) @type after_login: unicode @param after_login: URL to redirect to after login (optional, must start with "/") @type plan: int @param plan: rate plan index (optional, defaults to None) @type yearly: bool @param yearly: True for yearly plan, False for monthly (optional, defaults to False) @rtype: unicode @return: rendered HTML page """ # if the user is logged in and not using https, and they request the sign up or login note, then # redirect to the https version of the page (if available) https_url = self.__settings[u"luminotes.https_url"] https_proxy_ip = self.__settings[u"luminotes.https_proxy_ip"] if note_title in ( u"sign_up", u"login" ) and https_url and cherrypy.request.remote_addr != https_proxy_ip: if invite_id: return dict( redirect = u"%s/%s?invite_id=%s" % ( https_url, note_title, invite_id ) ) if after_login: return dict( redirect = u"%s/%s?after_login=%s" % ( https_url, note_title, after_login ) ) if plan: return dict( redirect = u"%s/%s?plan=%s&yearly=%s" % ( https_url, note_title, plan, yearly ) ) else: return dict( redirect = u"%s/%s" % ( https_url, note_title ) ) anonymous = self.__database.select_one( User, User.sql_load_by_username( u"anonymous" ) ) if anonymous: main_notebook = self.__database.select_one( Notebook, anonymous.sql_load_notebooks( undeleted_only = True ) ) result = self.__users.current( user_id = user_id ) note_title = note_title.replace( u"_", " " ) note = self.__database.select_one( Note, main_notebook.sql_load_note_by_title( note_title ) ) if not note: raise cherrypy.NotFound result.update( self.__notebooks.contents( main_notebook.object_id, user_id = user_id, note_id = note.object_id ) ) if invite_id: result[ "invite_id" ] = invite_id if after_login and after_login.startswith( u"/" ): result[ "after_login" ] = after_login if plan: result[ "signup_plan" ] = plan result[ "signup_yearly" ] = yearly return result @expose() def r( self, password_reset_id ): """ Redirect to the password reset URL, based on the given password_reset id. The sole purpose of this method is to shorten password reset URLs sent by email so email clients don't wrap them. """ # if the value looks like an id, it's a password reset id, so redirect try: validator = Valid_id() password_reset_id = validator( password_reset_id ) except ValueError: raise cherrypy.NotFound return dict( redirect = u"/users/redeem_reset/%s" % password_reset_id, ) @expose() def i( self, invite_id ): """ Redirect to the invite redemption URL, based on the given invite id. The sole purpose of this method is to shorten invite redemption URLs sent by email so email clients don't wrap them. """ # if the value looks like an id, it's an invite id, so redirect try: validator = Valid_id() invite_id = validator( invite_id ) except ValueError: raise cherrypy.NotFound return dict( redirect = u"/users/redeem_invite/%s" % invite_id, ) @expose() def d( self, download_access_id ): """ Redirect to the product download thanks URL, based on the given download access id. The sole purpose of this method is to shorten product download URLs sent by email so email clients don't wrap them. """ # if the value looks like an id, it's a download access id, so redirect try: validator = Valid_id() download_access_id = validator( download_access_id ) except ValueError: raise cherrypy.NotFound return dict( redirect = u"/users/thanks_download?access_id=%s" % download_access_id, ) @expose( view = Front_page ) @strongly_expire @end_transaction @grab_user_id @update_auth @validate( user_id = Valid_id( none_okay = True ), ) def index( self, user_id ): """ Provide the information necessary to display the web site's front page, potentially performing a redirect to the https version of the page or the user's first notebook. """ https_url = self.__settings[u"luminotes.https_url"] https_proxy_ip = self.__settings[u"luminotes.https_proxy_ip"] # if the server is configured to auto-login a particular user, log that user in and redirect to # their first notebook auto_login_username = self.__settings[u"luminotes.auto_login_username"] if auto_login_username: user = self.__database.select_one( User, User.sql_load_by_username( auto_login_username ), use_cache = True ) if user and user.username: first_notebook = self.__database.select_one( Notebook, user.sql_load_notebooks( parents_only = True, undeleted_only = True ) ) if first_notebook: return dict( redirect = u"/notebooks/%s" % first_notebook.object_id, authenticated = user, ) # if the user is logged in and the HTTP request has no referrer, then redirect to the user's # first notebook if user_id: referer = cherrypy.request.headerMap.get( u"Referer" ) if not referer: user = self.__database.load( User, user_id ) if user and user.username: first_notebook = self.__database.select_one( Notebook, user.sql_load_notebooks( parents_only = True, undeleted_only = True ) ) if first_notebook: return dict( redirect = u"%s/notebooks/%s" % ( https_url, first_notebook.object_id ) ) # if the user is logged in and not using https, then redirect to the https version of the page (if available) if https_url and cherrypy.request.remote_addr != https_proxy_ip: return dict( redirect = u"%s/" % https_url ) result = self.__users.current( user_id ) parents = [ notebook for notebook in result[ u"notebooks" ] if notebook.trash_id and not notebook.deleted ] if len( parents ) > 0: result[ "first_notebook" ] = parents[ 0 ] else: result[ "first_notebook" ] = None return result @expose( view = Tour_page ) @end_transaction @grab_user_id @validate( user_id = Valid_id( none_okay = True ), ) def tour( self, user_id ): result = self.__users.current( user_id ) parents = [ notebook for notebook in result[ u"notebooks" ] if notebook.trash_id and not notebook.deleted ] if len( parents ) > 0: result[ "first_notebook" ] = parents[ 0 ] else: result[ "first_notebook" ] = None return result @expose() def take_a_tour( self ): return dict( redirect = u"/tour" ) @expose( view = Main_page ) @end_transaction @grab_user_id @validate( note_id = Valid_id( none_okay = True ), user_id = Valid_id( none_okay = True ), ) def guide( self, note_id = None, user_id = None ): """ Provide the information necessary to display the Luminotes user guide. @type note_id: unicode or NoneType @param note_id: id of single note to load (optional) @rtype: unicode @return: rendered HTML page @raise Validation_error: one of the arguments is invalid """ result = self.__users.current( user_id ) anon_result = self.__users.current( None ) guide_notebooks = [ nb for nb in anon_result[ "notebooks" ] if nb.name == u"Luminotes user guide" ] result.update( self.__notebooks.contents( guide_notebooks[ 0 ].object_id, user_id = user_id ) ) # if a single note was requested, just return that one note if note_id: result[ "startup_notes" ] = [ note for note in result[ "startup_notes" ] if note.object_id == note_id ] return result @expose( view = Main_page ) @end_transaction @grab_user_id @validate( user_id = Valid_id( none_okay = True ), ) def privacy( self, user_id = None ): """ Provide the information necessary to display the Luminotes privacy policy. @rtype: unicode @return: rendered HTML page @raise Validation_error: one of the arguments is invalid """ result = self.__users.current( user_id ) anon_result = self.__users.current( None ) privacy_notebooks = [ nb for nb in anon_result[ "notebooks" ] if nb.name == u"Luminotes privacy policy" ] result.update( self.__notebooks.contents( privacy_notebooks[ 0 ].object_id, user_id = user_id ) ) return result @expose( view = Upgrade_page ) @strongly_expire @end_transaction @grab_user_id @validate( user_id = Valid_id( none_okay = True ), ) def pricing( self, user_id = None ): """ Provide the information necessary to display the Luminotes pricing page. """ result = self.__users.current( user_id ) parents = [ notebook for notebook in result[ u"notebooks" ] if notebook.trash_id and not notebook.deleted ] if len( parents ) > 0: result[ "first_notebook" ] = parents[ 0 ] else: result[ "first_notebook" ] = None result[ "rate_plans" ] = self.__settings[u"luminotes.rate_plans"] result[ "unsubscribe_button" ] = self.__settings[u"luminotes.unsubscribe_button"] return result @expose() def upgrade( self ): return dict( redirect = u"/pricing", ) @expose() def support( self ): return dict( redirect = u"/community", ) @expose( view = Download_page ) @strongly_expire @end_transaction @grab_user_id @validate( upgrade = Valid_bool( none_okay = True ), user_id = Valid_id( none_okay = True ), ) def download( self, upgrade = False, user_id = None ): """ Provide the information necessary to display the Luminotes download page. """ result = self.__users.current( user_id ) parents = [ notebook for notebook in result[ u"notebooks" ] if notebook.trash_id and not notebook.deleted ] if len( parents ) > 0: result[ "first_notebook" ] = parents[ 0 ] else: result[ "first_notebook" ] = None result[ "download_products" ] = self.__settings[u"luminotes.download_products" ] referer = cherrypy.request.headerMap.get( u"Referer" ) result[ "upgrade" ] = upgrade or ( referer and u"localhost:" in referer ) return result # TODO: move this method to controller.Notebooks, and maybe give it a more sensible name @expose( view = Json ) @end_transaction def next_id( self ): """ Return the next available database object id for a new note. This id is guaranteed to be unique among all existing notes. @rtype: json dict @return: { 'next_id': nextid } """ next_id = self.__database.next_id( Note ) return dict( next_id = next_id, ) @expose( view = Json ) def ping( self ): return dict( response = u"pong", ) @expose( view = Json ) def shutdown( self ): # this is typically only allowed in the desktop configuration if self.__settings[u"luminotes.allow_shutdown_command" ] is not True: return dict() cherrypy.server.stop() return dict() @expose( view = Close_page ) def close( self ): # this is typically only allowed in the desktop configuration if self.__settings[u"luminotes.allow_shutdown_command"] is not True: return dict() cherrypy.server.stop() return dict() def _cp_on_http_error( self, status, message ): """ CherryPy HTTP error handler, used to display page not found and generic error pages. """ support_email = self.__settings[u"luminotes.support_email"] if status == 404: cherrypy.response.headerMap[ u"Status" ] = u"404 Not Found" cherrypy.response.status = status cherrypy.response.body = [ unicode( Not_found_page( support_email ) ) ] return import traceback if not self.__suppress_exceptions: cherrypy.log( traceback.format_exc() ) self.report_traceback() import sys error = sys.exc_info()[ 1 ] if hasattr( error, "to_dict" ): error_message = error.to_dict().get( u"error" ) else: error_message = None cherrypy.response.body = [ unicode( Error_page( support_email, message = error_message ) ) ] def report_traceback( self ): """ If a support email address is configured, send it an email with the current traceback. """ support_email = self.__settings[u"luminotes.support_email"] if not support_email: return False import smtplib import traceback from email import Message message = Message.Message() message[ u"From" ] = support_email message[ u"To" ] = support_email message[ u"Subject" ] = u"Luminotes traceback" message.set_payload( u"requested URL: %s\n" % cherrypy.request.browser_url + u"user id: %s\n" % cherrypy.session.get( "user_id" ) + u"username: %s\n\n" % cherrypy.session.get( "username" ) + traceback.format_exc() ) # send the message out through localhost's smtp server server = smtplib.SMTP() server.connect() server.sendmail( message[ u"From" ], [ support_email ], message.as_string() ) server.quit() return True database = property( lambda self: self.__database ) notebooks = property( lambda self: self.__notebooks ) users = property( lambda self: self.__users ) groups = property( lambda self: self.__groups ) files = property( lambda self: self.__files ) forums = property( lambda self: self.__forums ) blog = property( lambda self: self.__blog )
def sayHello(self): user = Users() return self.message + " - " + hello() + " - " + user.sayHello()