def getAllCommunities(self): """ get the complete list of properties""" localdb = self.getDb() logger.info(u'getAllCommunities::db={}'.format(localdb)) communitysColl = localdb.communities communitiesList = communitysColl.find().sort("title") logger.info(u'getAllCommunities::communitysList={}'.format(communitiesList)) #Faut-il changer de list ou retourner le bson directement ? result = list() for communitybson in communitiesList: logger.info(u'\tgetAllCommunities::communitybson={}'.format(communitybson)) community = Community() community.convertFromBson(communitybson) userMgr = UserManager() user = userMgr.getUserByUserId(community.admin_user_id) if user is None: community.admin_user_nickName = "Admin inconnu !" else: community.admin_user_nickName = user.nickName logger.info(u"\tgetAllCommunities::community={}".format(community)) tmpdict = community.__dict__ logger.info(u"\tgetAllCommunities::tmpdict={}".format(tmpdict)) result.append(tmpdict) return result
def getAllPosts(self): """ get the complete list of posts""" localdb = self.getDb() logger.info(u'getAllPosts::db={}'.format(localdb)) postsColl = localdb.posts postsList = postsColl.find().sort([("date", -1)]).limit(30) logger.info(u'getAllPosts::postsList={}'.format(postsList)) #Faut-il changer de list ou retourner le bson directement ? result = list() for postbson in postsList: logger.info(u'\tgetAllPosts::postbson={}'.format(postbson)) post = Post() post.convertFromBson(postbson) userMgr = UserManager() user = userMgr.getUserByUserId(post.post_user_id) if user is None: post.nickName = "Anonyme" else: post.nickName = user.nickName logger.info(u'\tgetAllPosts::post={}'.format(post)) tmpdict = post.__dict__ logger.info(u'\tgetAllPosts::tmpdict={}'.format(tmpdict)) result.append(tmpdict) return result
def getAllCommunities(self): """ get the complete list of properties""" localdb = self.getDb() logger.info(u'getAllCommunities::db={}'.format(localdb)) communitysColl = localdb.communities communitiesList = communitysColl.find().sort("title") logger.info( u'getAllCommunities::communitysList={}'.format(communitiesList)) #Faut-il changer de list ou retourner le bson directement ? result = list() for communitybson in communitiesList: logger.info( u'\tgetAllCommunities::communitybson={}'.format(communitybson)) community = Community() community.convertFromBson(communitybson) userMgr = UserManager() user = userMgr.getUserByUserId(community.admin_user_id) if user is None: community.admin_user_nickName = "Admin inconnu !" else: community.admin_user_nickName = user.nickName logger.info(u"\tgetAllCommunities::community={}".format(community)) tmpdict = community.__dict__ logger.info(u"\tgetAllCommunities::tmpdict={}".format(tmpdict)) result.append(tmpdict) return result
def getCommunityByCommunityId(self, com_id): """ get one property by key""" localdb = self.getDb() logger.info( u'getcommunityBycommunityId::community_id={}'.format(com_id)) communitysColl = localdb.communities bsoncommunity = communitysColl.find_one({"com_id": com_id}) logger.info(u'getcommunityBycommunityId::bsoncommunity={}'.format( bsoncommunity)) if bsoncommunity is not None: community = Community() community.convertFromBson(bsoncommunity) userMgr = UserManager() user = userMgr.getUserByUserId(community.admin_user_id) if user is None: community.admin_user_nickName = "Admin inconnu !" else: community.admin_user_nickName = user.nickName logger.info( u"\tgetcommunityBycommunityId::res={}".format(community)) return community else: return None
def updateMatchsResults(): u""" save the result of matchs. only allowed to admin :return the numbers of matchs updated """ logger.info("updateMatchsResults::{}".format(request.json["matchs"])) if "no_save" in request.json: no_save = request.json["no_save"] else: no_save = False logger.info("updateMatchsResults::no_save={}".format(no_save)) if "cookieUserKey" in session: mgr = MatchsManager() matchsjson = request.json["matchs"] cookieUserKey = session['cookieUserKey'] user_mgr = UserManager() user = user_mgr.getUserByUserId(cookieUserKey) logger.info( u"updateMatchsResults::cookieUserKey by ={}".format(cookieUserKey)) logger.info(u"updateMatchsResults::update by ={}".format(user.email)) nbHit = 0 if user.isAdmin: nbHit = mgr.update_all_matchs(matchsjson, no_save) else: logger.info(u"updateMatchsResults::No Admin = 403") return "Ha ha ha ! Mais t'es pas la bonne personne pour faire ça, mon loulou", 403 return jsonify({'nbHit': nbHit}) else: return "Ha ha ha ! Mais t'es qui pour faire ça, mon loulou ?", 403
def updateMatchsResults(): u""" save the result of matchs. only allowed to admin :return the numbers of matchs updated """ logger.info("updateMatchsResults::{}".format(request.json["matchs"])) if "no_save" in request.json: no_save=request.json["no_save"] else: no_save=False logger.info("updateMatchsResults::no_save={}".format(no_save)) if "cookieUserKey" in session: mgr = MatchsManager() matchsjson = request.json["matchs"] cookieUserKey = session['cookieUserKey'] user_mgr = UserManager() user = user_mgr.getUserByUserId(cookieUserKey) logger.info(u"updateMatchsResults::cookieUserKey by ={}".format(cookieUserKey)) logger.info(u"updateMatchsResults::update by ={}".format(user.email)) nbHit=0 if user.isAdmin: nbHit = mgr.update_all_matchs(matchsjson, no_save) else: logger.info(u"updateMatchsResults::No Admin = 403") return "Ha ha ha ! Mais t'es pas la bonne personne pour faire ça, mon loulou", 403 return jsonify({'nbHit': nbHit}) else: return "Ha ha ha ! Mais t'es qui pour faire ça, mon loulou ?", 403
def getAllPosts(self): """ get the complete list of posts""" localdb = self.getDb() logger.info(u'getAllPosts::db={}'.format(localdb)) postsColl = localdb.posts postsList = postsColl.find().sort([("date",-1)]).limit(30) logger.info(u'getAllPosts::postsList={}'.format(postsList)) #Faut-il changer de list ou retourner le bson directement ? result = list() for postbson in postsList: logger.info(u'\tgetAllPosts::postbson={}'.format(postbson)) post = Post() post.convertFromBson(postbson) userMgr = UserManager() user = userMgr.getUserByUserId(post.post_user_id) if user is None: post.nickName = "Anonyme" else: post.nickName = user.nickName logger.info(u'\tgetAllPosts::post={}'.format(post)) tmpdict = post.__dict__ logger.info(u'\tgetAllPosts::tmpdict={}'.format(tmpdict)) result.append(tmpdict) return result
def create_comment_on_blog_post(com_id, blog_id): u""" add a new comment on a blog post. Comment is sent in request.json :return status message :param com_id: id of community (uuid) :param blog_id: id of blog_id(uuid) """ logger.info(u"create_comment_on_blog_post::json param:{} ".format( request.json)) if "cookieUserKey" in session: cookieUserKey = session['cookieUserKey'] logger.info(u"createBlogPost::cookieUserKey={}".format(cookieUserKey)) mgr = BlogsManager() usrManager = UserManager() user = usrManager.getUserByUserId(cookieUserKey) comment = Comment() comment.convertFromJson(request.json["comment"]) comment.author = user.nickName if (comment.body is None) or (comment.body == ""): return jsonify({'msg': "ERROR : body is empty"}), 500 mgr.add_comment_on_blog(com_id, blog_id, comment) return jsonify({'msg': "successfull"}), 200 else: return "hey poussin ! tu dois être authentifié, mon loulou", 403
def test_getallusers(self): os.environ['OPENSHIFT_MONGODB_DB_URL']=u"mongodb://*****:*****@127.0.0.1:27017/euroxxxvi" mgr = UserManager() self.assertIsNotNone(mgr.getDb()) users = mgr.getAllUsers() for u in users: print(u) self.assertIsNotNone(users)
def test_getallusers(self): os.environ[ 'OPENSHIFT_MONGODB_DB_URL'] = u"mongodb://*****:*****@127.0.0.1:27017/euroxxxvi" mgr = UserManager() self.assertIsNotNone(mgr.getDb()) users = mgr.getAllUsers() for u in users: print(u) self.assertIsNotNone(users)
def getBetsOfTheDay(self, com_id): u""" return the result of the bets of the days :param com_id: the com_id :return: the bets of the days """ #STEP 1 : bets of the day for the community nowDate = datetime.utcnow() nowDateMin = nowDate.replace(hour=00, minute=00, second=00).strftime('%Y-%m-%dT%H:%M:%SZ') logger.info('nowDateMin : {}'.format(nowDateMin)) nowDateMax = nowDate.replace(hour=23, minute=59, second= 59).strftime('%Y-%m-%dT%H:%M:%SZ') logger.info('nowDateMax : {}'.format(nowDateMax)) betsList = self.getDb().bets.find({"com_id": com_id, "dateMatch" : {"$gt" : nowDateMin, "$lt":nowDateMax} }).sort([("dateMatch",1), ("key",1) ]) result = dict() #STEP 2 : list of distincts users usermgr = UserManager() userIdTab=[] betsListTwo=list() #to iterate again for bet in betsList: del bet["_id"] betsListTwo.append(bet) if bet["user_id"] not in userIdTab: userIdTab.append(bet["user_id"]) usersList = usermgr.getUsersByUserIdList(userIdTab) usersList.sort(key=lambda user: user["nickName"]) #STEP 3 : list of the matchs of the day keyTab=[] betsListThree=list() #to iterate again for bet in betsListTwo: betsListThree.append(bet) if bet["key"] not in keyTab: keyTab.append(bet["key"]) matchsList = self.getMatchsByMatchKeyList(keyTab) result["matchs"] = matchsList #STEP 4 : for each user, get the list of bets betsOfTheDay = list() for user in usersList: betsTab = [] for bet in betsListThree: if user["user_id"] == bet["user_id"]: betsTab.append(bet) ranking = dict() ranking["user"] = user ranking["bets"] = betsTab betsOfTheDay.append(ranking) result["betsOfTheDay"] = betsOfTheDay return result
def send_email_to_user_id(self, com_id, blog, user_id): u"""" send email to user_id :param com_id the com id :param blog the blog send :param user_id uuid of user to notify - usually the admin od community """ userMgr = UserManager() user = userMgr.getUserByUserId(user_id) recipients = list() recipients.append(user.email) return self.send_email(com_id, blog, recipients)
def test_getsaveuser(self): os.environ['OPENSHIFT_MONGODB_DB_URL']=u"mongodb://*****:*****@127.0.0.1:27017/euroxxxvi" mgr = UserManager() usera = mgr.saveUser("*****@*****.**", "", "", "uuidxxx", False, u"zoo") self.assertIsNotNone(usera) user = mgr.getUserByEmail(u"*****@*****.**") self.assertIsNotNone(user) self.assertIsNotNone(user.email) self.assertIsNotNone(user.user_id)
def test_getsaveuser(self): os.environ[ 'OPENSHIFT_MONGODB_DB_URL'] = u"mongodb://*****:*****@127.0.0.1:27017/euroxxxvi" mgr = UserManager() usera = mgr.saveUser("*****@*****.**", "", "", "uuidxxx", False, u"zoo") self.assertIsNotNone(usera) user = mgr.getUserByEmail(u"*****@*****.**") self.assertIsNotNone(user) self.assertIsNotNone(user.email) self.assertIsNotNone(user.user_id)
def isAdmin(self, com_id, user_id): u""" check if the user is admin of the community :param com_id id of community :param user_id id of user to check """ com = self.getCommunityByCommunityId(com_id) if com.admin_user_id == user_id: return True else: userMgr = UserManager() userFromCookie = userMgr.getUserByUserId(user_id) if (userFromCookie.isAdmin): return True else: return False
def isAdmin(self, com_id, user_id): u""" check if the user is admin of the community :param com_id id of community :param user_id id of user to check """ com = self.getCommunityByCommunityId(com_id) if com.admin_user_id==user_id: return True else: userMgr = UserManager() userFromCookie = userMgr.getUserByUserId(user_id) if (userFromCookie.isAdmin): return True else: return False
def players(self, com_id): u""" list of users of distinct user in a community :param com_id: the community id :return: the number of user who had bet """ userIdList = self.getDb().bets.distinct("user_id", {"com_id":com_id}) usermgr = UserManager() result=list() for uuid in userIdList: user = usermgr.getUserByUserId(uuid) result.append(user.__dict__) logger.info(u'\t\tplayers : {}'.format(result)) result.sort(key=lambda user: user["nickName"]) return result
def players(self, com_id): u""" list of users of distinct user in a community :param com_id: the community id :return: the number of user who had bet """ userIdList = self.getDb().bets.distinct("user_id", {"com_id": com_id}) usermgr = UserManager() result = list() for uuid in userIdList: user = usermgr.getUserByUserId(uuid) result.append(user.__dict__) logger.info(u'\t\tplayers : {}'.format(result)) result.sort(key=lambda user: user["nickName"]) return result
def createhistoryrankings(): u""" :return enregistre l'historique du classement pour toutes les communautés, ainsi que le classement général """ if "cookieUserKey" in session: mgr = StatsManager() cookieUserKey = session['cookieUserKey'] user_mgr = UserManager() user = user_mgr.getUserByUserId(cookieUserKey) nbHit=0 if user.isAdmin: logger.info(u"createhistoryrankings: by ={}".format(user.email)) nbHit = mgr.createHistoryRankings() else: return "Ha ha ha ! Mais t'es pas la bonne personne pour faire ça, mon loulou", 403 return jsonify({'nbHit': nbHit}) else: return "Ha ha ha ! Mais t'es qui pour faire ça, mon loulou ?", 403
def getCommunityByCommunityId(self, com_id): """ get one property by key""" localdb = self.getDb() logger.info(u'getcommunityBycommunityId::community_id={}'.format(com_id)) communitysColl = localdb.communities bsoncommunity = communitysColl.find_one({"com_id": com_id}) logger.info(u'getcommunityBycommunityId::bsoncommunity={}'.format(bsoncommunity)) if bsoncommunity is not None: community = Community() community.convertFromBson(bsoncommunity) userMgr = UserManager() user = userMgr.getUserByUserId(community.admin_user_id) if user is None: community.admin_user_nickName = "Admin inconnu !" else: community.admin_user_nickName = user.nickName logger.info(u"\tgetcommunityBycommunityId::res={}".format(community)) return community else: return None
def create_comment_on_blog_post(com_id, blog_id): u""" add a new comment on a blog post. Comment is sent in request.json :return status message :param com_id: id of community (uuid) :param blog_id: id of blog_id(uuid) """ logger.info(u"create_comment_on_blog_post::json param:{} ".format(request.json)) if "cookieUserKey" in session: cookieUserKey = session['cookieUserKey'] logger.info(u"createBlogPost::cookieUserKey={}".format(cookieUserKey)) mgr = BlogsManager() usrManager = UserManager() user = usrManager.getUserByUserId(cookieUserKey) comment = Comment() comment.convertFromJson(request.json["comment"]) comment.author=user.nickName if (comment.body is None) or(comment.body ==""): return jsonify({'msg': "ERROR : body is empty"}), 500 mgr.add_comment_on_blog(com_id, blog_id, comment) return jsonify({'msg': "successfull"}), 200 else: return "hey poussin ! tu dois être authentifié, mon loulou", 403
def getRanking(self, com_id, category, requester): u""" ranking of the community (if com_id is provided) of ranking of all the bet site :param com_id: the com_id (optionnal) :param category: the category (ALL, GROUPE or FINAL) :param requester: COMMUNITIES_RANKING when the requester is the ranking of the communities :return: the ranking """ #STEP 1 : list of users if com_id is not None: if category == "ALL" or category is None or category == "undefined": userIdList = self.getDb().bets.distinct("user_id", {"com_id":com_id}) else: userIdList = self.getDb().bets.distinct("user_id", {"com_id":com_id, "category":category}) else: userIdList = self.getDb().bets.distinct("user_id") usermgr = UserManager() usermgr.setDb(self.getDb()) userList=list() for uuid in userIdList: user = usermgr.getUserByUserId(uuid) userList.append(user.__dict__) userList.sort(key=lambda user: user["nickName"]) result = list() #STEP 2 : for each user, get the list of bets for user in userList: comList = list() if com_id is not None: com = self.getDb().communities.find_one({"com_id": com_id}) comList.append(com) else: comIdList = self.getCommunitiesIdByUser(user["user_id"]) for comId in comIdList: com = self.getDb().communities.find_one({"com_id": comId}) comList.append(com) communitiesTab = [] nbPointsTot = 0 #STEP 3 : for each com, compute the number of points logger.info(u"\t\tgetRanking : before loading bets:{}".format(user["user_id"])) for com in comList: if category == "ALL" or category is None or category == "undefined": betsList = self.getDb().bets.find({"user_id": user["user_id"], "com_id": com["com_id"]}).sort([("dateMatch",1), ("key",1) ]) else: betsList = self.getDb().bets.find({"user_id": user["user_id"], "com_id": com["com_id"], "category":category}).sort([("dateMatch",1), ("key",1) ]) nbPointsInCom = 0 betsTab = [] #To remove the users who have bet only in the groupe phasis or only in the final phasis (when category = ALL) : hasBetInGroup = False hasBetInFinal = False for bet in betsList: if bet["category"] == "GROUPE": hasBetInGroup = True if bet["category"] == "FINAL": hasBetInFinal = True nbPointsInCom = nbPointsInCom + bet["nbpoints"] del bet["_id"] betsTab.append(bet) com["bets"] = betsTab del com["_id"] if requester == "COMMUNITIES_RANKING": if category == "ALL" or category is None or category == "undefined": if hasBetInGroup is True and hasBetInFinal is True: nbPointsTot = nbPointsTot + nbPointsInCom communitiesTab.append(com) else: nbPointsTot = nbPointsTot + nbPointsInCom communitiesTab.append(com) else: nbPointsTot = nbPointsTot + nbPointsInCom communitiesTab.append(com) if len(communitiesTab) > 0: result.append(self.fillRanking(nbPointsTot, comList, category, user, communitiesTab)) #STEP 4 : return a sorted list result.sort(key=lambda ranking: ranking["nbPoints"], reverse=True) return result
def getRanking(self, com_id, category, requester): u""" ranking of the community (if com_id is provided) of ranking of all the bet site :param com_id: the com_id (optionnal) :param category: the category (ALL, GROUPE or FINAL) :param requester: COMMUNITIES_RANKING when the requester is the ranking of the communities :return: the ranking """ #STEP 1 : list of users if com_id is not None: if category == "ALL" or category is None or category == "undefined": userIdList = self.getDb().bets.distinct( "user_id", {"com_id": com_id}) else: userIdList = self.getDb().bets.distinct( "user_id", { "com_id": com_id, "category": category }) else: userIdList = self.getDb().bets.distinct("user_id") usermgr = UserManager() usermgr.setDb(self.getDb()) userList = list() for uuid in userIdList: user = usermgr.getUserByUserId(uuid) userList.append(user.__dict__) userList.sort(key=lambda user: user["nickName"]) result = list() #STEP 2 : for each user, get the list of bets for user in userList: comList = list() if com_id is not None: com = self.getDb().communities.find_one({"com_id": com_id}) comList.append(com) else: comIdList = self.getCommunitiesIdByUser(user["user_id"]) for comId in comIdList: com = self.getDb().communities.find_one({"com_id": comId}) comList.append(com) communitiesTab = [] nbPointsTot = 0 #STEP 3 : for each com, compute the number of points logger.info(u"\t\tgetRanking : before loading bets:{}".format( user["user_id"])) for com in comList: if category == "ALL" or category is None or category == "undefined": betsList = self.getDb().bets.find({ "user_id": user["user_id"], "com_id": com["com_id"] }).sort([("dateMatch", 1), ("key", 1)]) else: betsList = self.getDb().bets.find({ "user_id": user["user_id"], "com_id": com["com_id"], "category": category }).sort([("dateMatch", 1), ("key", 1)]) nbPointsInCom = 0 betsTab = [] #To remove the users who have bet only in the groupe phasis or only in the final phasis (when category = ALL) : hasBetInGroup = False hasBetInFinal = False for bet in betsList: if bet["category"] == "GROUPE": hasBetInGroup = True if bet["category"] == "FINAL": hasBetInFinal = True nbPointsInCom = nbPointsInCom + bet["nbpoints"] del bet["_id"] betsTab.append(bet) com["bets"] = betsTab del com["_id"] if requester == "COMMUNITIES_RANKING": if category == "ALL" or category is None or category == "undefined": if hasBetInGroup is True and hasBetInFinal is True: nbPointsTot = nbPointsTot + nbPointsInCom communitiesTab.append(com) else: nbPointsTot = nbPointsTot + nbPointsInCom communitiesTab.append(com) else: nbPointsTot = nbPointsTot + nbPointsInCom communitiesTab.append(com) if len(communitiesTab) > 0: result.append( self.fillRanking(nbPointsTot, comList, category, user, communitiesTab)) #STEP 4 : return a sorted list result.sort(key=lambda ranking: ranking["nbPoints"], reverse=True) return result
def getBetsOfTheDay(self, com_id): u""" return the result of the bets of the days :param com_id: the com_id :return: the bets of the days """ #STEP 1 : bets of the day for the community nowDate = datetime.utcnow() nowDateMin = nowDate.replace(hour=00, minute=00, second=00).strftime('%Y-%m-%dT%H:%M:%SZ') logger.info('nowDateMin : {}'.format(nowDateMin)) nowDateMax = nowDate.replace(hour=23, minute=59, second=59).strftime('%Y-%m-%dT%H:%M:%SZ') logger.info('nowDateMax : {}'.format(nowDateMax)) betsList = self.getDb().bets.find({ "com_id": com_id, "dateMatch": { "$gt": nowDateMin, "$lt": nowDateMax } }).sort([("dateMatch", 1), ("key", 1)]) result = dict() #STEP 2 : list of distincts users usermgr = UserManager() userIdTab = [] betsListTwo = list() #to iterate again for bet in betsList: del bet["_id"] betsListTwo.append(bet) if bet["user_id"] not in userIdTab: userIdTab.append(bet["user_id"]) usersList = usermgr.getUsersByUserIdList(userIdTab) usersList.sort(key=lambda user: user["nickName"]) #STEP 3 : list of the matchs of the day keyTab = [] betsListThree = list() #to iterate again for bet in betsListTwo: betsListThree.append(bet) if bet["key"] not in keyTab: keyTab.append(bet["key"]) matchsList = self.getMatchsByMatchKeyList(keyTab) result["matchs"] = matchsList #STEP 4 : for each user, get the list of bets betsOfTheDay = list() for user in usersList: betsTab = [] for bet in betsListThree: if user["user_id"] == bet["user_id"]: betsTab.append(bet) ranking = dict() ranking["user"] = user ranking["bets"] = betsTab betsOfTheDay.append(ranking) result["betsOfTheDay"] = betsOfTheDay return result