def get(self):
        self.response.headers['content-type'] = 'text/html'
        userLoggedIn = users.get_current_user() # Here I am getting all details of logged in user.
        UserEmail = ''
        UserProfile = []
        if userLoggedIn: # If any user is logged in, there will be some data in userLoggedIn variable.
            loginLink = users.create_logout_url(self.request.uri)
            loginStatus = 'Logout'
            userDB_Reference = ndb.Key('UsersDB', userLoggedIn.email()).get() # Here I am checking if current user already have record in my DB or not.
            if userDB_Reference == None: # If user record does not exist in DB, variable will be None.
                userDB_Reference = UsersDB(id=userLoggedIn.email())
                userDB_Reference.user_Email = userLoggedIn.email()
                userDB_Reference.put()
            UserEmail = self.request.get('user_Email') # If any value is passed in url for user email id, it will be fetched here.
            if UserEmail == '': # In case no user email is sent in url from previous page, email id taken will be currently logged in user's email id.
                UserEmail = userLoggedIn.email()
            UserProfile = ndb.Key('UsersDB',UserEmail).get()

        else: # If no user is logged in, there will be no data in userLoggedIn variable.
            loginLink = users.create_login_url(self.request.uri)
            loginStatus = 'Login'
            self.redirect('/ProfilePage')

        template_values = {
            'loginLink' : loginLink,
            'loginStatus' : loginStatus,
            'userLoggedIn' : userLoggedIn,
            'UserProfile' : UserProfile
        }
        template = JINJA_ENVIRONMENT.get_template('Following.html')
        self.response.write(template.render(template_values))
 def post(self):
     self.response.headers['content-type'] = 'text/html'
     userLoggedIn = users.get_current_user()
     ButtonOption = self.request.get('submitButton')
     if ButtonOption == "Select":  # This is functionality of selecting user name for first time.
         FirstTimeUserName = self.request.get('FirstTimeUserName')
         FirstTimeUserName = FirstTimeUserName.lower()
         UsersDB_Reference = UsersDB.query(
             UsersDB.user_Name == FirstTimeUserName).get()
         if UsersDB_Reference == None:
             UsersDB_Reference = ndb.Key('UsersDB',
                                         userLoggedIn.email()).get()
             UsersDB_Reference.user_Name = FirstTimeUserName
             UsersDB_Reference.put()
             self.redirect("/ProfilePage?notification=Username Selected")
         else:
             self.redirect(
                 "/ProfilePage?notification=Username Already Exist")
     elif ButtonOption == "Comment":
         userLoggedIn = ndb.Key('UsersDB', userLoggedIn.email()).get()
         image_Key = self.request.get('image_Key')
         CommentBox = self.request.get('CommentBox')
         comments_Data = ndb.Key('CommentsDB', image_Key).get()
         if comments_Data == None:
             comments_Data = CommentsDB(id=str(image_Key))
         comments_Data.commenting_User.append(userLoggedIn.user_Name)
         comments_Data.comment.append(CommentBox)
         comments_Data.put()
         self.redirect('/ProfilePage?notification=CommentAddedSuccessfully')
    def get(self):
        self.response.headers['content-type'] = 'text/html'
        userLoggedIn = users.get_current_user(
        )  # Here I am getting all details of logged in user.
        followers_count = 0
        following_count = 0
        ImageUpload = blobstore.create_upload_url("/createNewPost")
        if userLoggedIn:  # If any user is logged in, there will be some data in userLoggedIn variable.
            loginLink = users.create_logout_url(self.request.uri)
            loginStatus = 'Logout'
            userDB_Reference = ndb.Key('UsersDB', userLoggedIn.email()).get(
            )  # Here I am checking if current user already have record in my DB or not.
            if userDB_Reference == None:  # If user record does not exist in DB, variable will be None.
                userDB_Reference = UsersDB(id=userLoggedIn.email())
                userDB_Reference.user_Email = userLoggedIn.email()
                userDB_Reference.put()
                userLoggedIn = userDB_Reference
            else:  # If user record exist in DB, variable will not be None.
                userLoggedIn = userDB_Reference
            if userLoggedIn.followers_List != None:
                followers_count = len(
                    userLoggedIn.followers_List
                )  # Here count of followers will be fetched.
            if userLoggedIn.following_List != None:
                following_count = len(
                    userLoggedIn.following_List
                )  # Here count of followings will be fetched.
        else:  # If no user is logged in, there will be no data in userLoggedIn variable.
            loginLink = users.create_login_url(self.request.uri)
            loginStatus = 'Login'
            self.redirect('/ProfilePage')

        template_values = {
            'loginLink': loginLink,
            'loginStatus': loginStatus,
            'userLoggedIn': userLoggedIn,
            'followers_count': followers_count,
            'following_count': following_count,
            'ImageUpload': ImageUpload
        }
        template = JINJA_ENVIRONMENT.get_template('CreateNewPost.html')
        self.response.write(template.render(template_values))
Beispiel #4
0
    def __init__(self, *args, **kwargs):
        Server.__init__(self, *args, **kwargs)
        self.id = 0
        self.players = WeakKeyDictionary()
        print "Server Launched"

        self.usersdb = UsersDB()

        self.boards = {}
        self.gamesCount = 0
        # self.usersdb.firstRun()

        self.outstandingContactRequests = []
Beispiel #5
0
    def do_PUT(self):

        if self.path == "/users":
            length = self.headers["Content-length"]
            length = int(length)
            print("content length is:", length)
            body = self.rfile.read(length).decode("utf-8")
            print("body is:", body)
            parsed_body = parse_qs(body)
            print("parsed body is:", parsed_body)

            user_id = parsed_body['user_id'][0]

            #user_id, user_name, user_password, user_wifi, user_wifi_password, user_wifi_coords, reserved_int, reserved_str, user_type
            user_name = parsed_body['user_name'][0]

            user_password = parsed_body['user_password'][0]

            user_wifi = parsed_body['user_wifi'][0]
            user_wifi_password = parsed_body['user_wifi_password'][0]
            user_wifi_coords = parsed_body['user_wifi_coords'][0]
            user_reserved_int = parsed_body['user_reserved_int'][0]
            user_reserved_str = parsed_body['user_reserved_str'][0]
            user_type = parsed_body['user_type'][0]
            #password hashed
            hashed_password = bcrypt.hash(user_password)

            db = UsersDB()

            db.update_by_id(user_id, user_name, hashed_password, user_wifi,
                            user_wifi_password, user_wifi_coords,
                            user_reserved_int, user_reserved_str, user_type)

            self.send_response(200)
            self.end_headers()
        else:
            self.send_error(404, "Not Found")
            return
Beispiel #6
0
    def do_DELETE(self):

        if self.path == "/users":
            length = self.headers["Content-length"]
            length = int(length)
            print("content length is:", length)
            body = self.rfile.read(length).decode("utf-8")
            print("body is:", body)
            parsed_body = parse_qs(body)
            print("parsed body is:", parsed_body)

            user_id = parsed_body['user_id'][0]

            db = UsersDB()
            db.delete_User(user_id)

            self.send_response(200)
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()

        else:
            self.send_error(404, "Not Found")
            return
Beispiel #7
0
    def post(self):
        self.response.headers['content-type'] = 'text/html'
        userLoggedIn = users.get_current_user(
        )  # Here I am getting all details of logged in user.
        if userLoggedIn:  # If any user is logged in, there will be some data in userLoggedIn variable.
            loginLink = users.create_logout_url(self.request.uri)
            loginStatus = 'Logout'
            userDB_Reference = ndb.Key('UsersDB', userLoggedIn.email()).get(
            )  # Here I am checking if current user already have record in my DB or not.
            if userDB_Reference == None:  # If user record does not exist in DB, variable will be None.
                userDB_Reference = UsersDB(id=userLoggedIn.email())
                userDB_Reference.user_Email = userLoggedIn.email()
                userDB_Reference.put()
                userLoggedIn = userDB_Reference
            else:  # If user record exist in DB, variable will not be None.
                userLoggedIn = userDB_Reference
        else:  # If no user is logged in, there will be no data in userLoggedIn variable.
            loginLink = users.create_login_url(self.request.uri)
            loginStatus = 'Login'
            self.redirect('/ProfilePage')

        UserSearchKeyword = self.request.get('UserSearchKeyword')
        UserSearchKeyword = UserSearchKeyword.lower()
        Query = UsersDB.query().fetch()
        QueryResults = []
        for i in range(0, len(Query)):
            if Query[i].user_Email != None:
                if Query[i].user_Email.find(UserSearchKeyword) != -1:
                    QueryResults.append(Query[i].user_Email)
            elif Query[i].user_Name != None:
                if Query[i].user_Name.find(UserSearchKeyword) != -1:
                    QueryResults.append(Query[i].user_Email)

        template_values = {
            'loginLink': loginLink,
            'loginStatus': loginStatus,
            'userLoggedIn': userLoggedIn,
            'Results': QueryResults
        }
        template = JINJA_ENVIRONMENT.get_template('SearchUser.html')
        self.response.write(template.render(template_values))
Beispiel #8
0
 def do_GET(self):
     path = self.path.split("/")
     if path[1] == "users" and len(path) == 2:  ## /users
         # some repsonse code
         self.send_response(200)
         self.end_headers()
         db = UsersDB()
         users = db.get_all_users()
         jsonstring = json.dumps(users)
         self.wfile.write(bytes(jsonstring, "utf-8"))
     elif path[1] == "users" and len(path) == 3:  ## /users/[user_id]
         print(path[2])
         self.send_response(200)
         # self.send_header("Content-type", "application/json")
         # self.send_header("Access-Control-Allow-Origin", self.headers["Origin"])
         self.end_headers()
         db = UsersDB()
         users = db.get_by_id(path[2])
         jsonstring = json.dumps(users)
         self.wfile.write(bytes(jsonstring, "utf-8"))
     else:
         self.send_error(404, "Not Found")
Beispiel #9
0
def main(url):
    url_id = ShortUrlToId(url)
    a = UsersDB()
    final_url = a.fetch('SELECT destination FROM links WHERE id=\'%s\'' %
                        url_id)[0][0]
    return redirect(final_url)
Beispiel #10
0
import time


def createUsers():
    a.query(
        'CREATE TABLE users(uid INTEGER NOT NULL, first_name TEXT, last_name TEXT, sex INTEGER, bday INTEGER, city INTEGER, country INTEGER, home_town INTEGER, university_ids TEXT, schools_ids TEXT, followers INTEGER, relation INTEGER, groups_ids TEXT, date_creation INTEGER);'
    )


def addUser(d):
    if len(a.fetch('Select * from users where uid = %d' % d['uid'])) == 0:
        a.query('INSERT INTO users(uid) values(%d)' % d['uid'])

    uid = d['uid']
    del d['uid']

    for key in d.keys():
        a.query('UPDATE users SET \'%s\'=\'%s\' WHERE uid=\'%s\'' %
                (key, d[key], uid))
    a.query('UPDATE users SET date_creation=\'%s\' WHERE uid=\'%s\'' %
            (time.clock(), uid))
    return


a = UsersDB()
# -----------------------------------------------------------------------------------------------------------------
dictionary = {'uid': 1, 'last_name': 'Beshkurov'}
addUser(dictionary)
# -----------------------------------------------------------------------------------------------------------------
print(a.fetch('select * from users'))
Beispiel #11
0
def show():
    a = UsersDB()
    b = show_all_urls_in_links()
    return b
Beispiel #12
0
def addUrl():
    url = request.query['url']
    a = UsersDB()
    add_url_to_links(url)
    res = IdToShortUrl(a.fetch('SELECT id FROM links WHERE destination=\'%s\'' % url)[0][0])
    return res
Beispiel #13
0
    def do_POST(self):
        #AUTH the user
        #self.load_session()
        if self.path == "/login":
            length = self.headers["Content-length"]
            length = int(length)
            print("content length is:", length)
            body = self.rfile.read(length).decode("utf-8")
            #print("body is:", body)
            parsed_body = parse_qs(body)
            print("parsed body is:", parsed_body)
            user_name = parsed_body['user_name'][0]
            user_password = parsed_body['user_password'][0]

            hashed_password = bcrypt.hash(user_password)
            db = UsersDB()
            #print(hashed_password)
            user = db.get_by_name(user_name)
            # print(user)
            # print("pulled password ", user['user_password'])
            # print("given password ", user_password)
            if (user == None):
                self.send_error(422, "Faliure, user does not exist ")
                return
            if bcrypt.verify(user_password, user['user_password']):
                #sets session to the sote with existing session for user
                user_id = user['user_id']
                print("user_id:", user_id)
                print("Log in successful")
                self.send_response(200)
                self.end_headers()
                return
            else:
                self.send_response(404)
                print("invaild email or password")
                self.end_headers()

        if self.path == "/users":

            length = self.headers["Content-length"]
            length = int(length)
            print("content length is:", length)
            body = self.rfile.read(length).decode("utf-8")
            print("body is:", body)
            parsed_body = parse_qs(body)
            print("parsed body is:", parsed_body)

            user_name = parsed_body['user_name'][0]

            user_password = parsed_body['user_password'][0]

            user_wifi = parsed_body['user_wifi'][0]
            user_wifi_password = parsed_body['user_wifi_password'][0]
            user_wifi_coords = parsed_body['user_wifi_coords'][0]
            user_reserved_int = parsed_body['user_reserved_int'][0]
            user_reserved_str = parsed_body['user_reserved_str'][0]
            user_type = parsed_body['user_type'][0]
            #hash password
            hashed_password = bcrypt.hash(user_password)
            db = UsersDB()

            db.createUser(user_name, hashed_password, user_wifi,
                          user_wifi_password, user_wifi_coords,
                          user_reserved_int, user_reserved_str, user_type)

            self.send_response(201)
            self.send_header("Access-Control-Allow-Origin",
                             self.headers["Origin"])
            self.send_header("Access-Control-Allow-Origin", "true")
            self.end_headers()
            return
        else:
            self.send_error(404, "Not Found")
            return
    def post(self):
        self.response.headers['Content-Type'] = 'application/json'

        WebPageLink = "https://medicare-287205.nw.r.appspot.com/"
        JD = json.loads(self.request.body)
        ResponseData = {}
        FunctionOption = JD["function"]
        userEmail = JD["userEmail"]
        if (userEmail != "" and userEmail != None):
            DBConnect = ndb.Key('UsersDB', userEmail).get()

# Below is code for SignUp.
        if (FunctionOption == "SignUp" and DBConnect == None):
            API_Key = "AIzaSyDvLc7SvzpX6KP6HCfn033xNKaM8UH3e2w"
            params = {"address": JD["Address"], "key": API_Key}
            GoogleAPI = "https://maps.googleapis.com/maps/api/geocode/json"
            url_params = urlencode(params)
            url = GoogleAPI + "?" + url_params
            result = urlfetch.fetch(url=url,
                                    method=urlfetch.POST,
                                    headers=params)
            Latitude = json.loads(
                result.content)['results'][0]['geometry']['location']['lat']
            Longitude = json.loads(
                result.content)['results'][0]['geometry']['location']['lng']
            DBConnect = UsersDB(id=userEmail)
            DBConnect.user_FirstName = JD["FirstName"]
            DBConnect.user_LastName = JD["LastName"]
            DBConnect.user_Email = userEmail
            DBConnect.user_Password = JD["Password"]
            DBConnect.user_Contact = JD["Contact"]
            DBConnect.user_Address = JD["Address"]
            DBConnect.Latitude = Latitude
            DBConnect.Longitude = Longitude
            DBConnect.user_Gender = JD["Gender"]
            DBConnect.user_DOB = JD["DOB"]
            DBConnect.EmailVerified = 0
            DBConnect.ResetPasswordLinkSent = 0
            DBConnect.IsActive = 1
            DBConnect.put()
            SendEmail(
                userEmail,
                "Congratulations! Your MediCare account has been setup", """
Dear """ + DBConnect.user_FirstName + """,

This is an automated email confirmation sent to you in regards of your MediCare account.

Please click on below link to verify your Email Id:
""" + WebPageLink + """VerifyEmail?RegisteredAs=User&userEmail=""" +
                userEmail + """&VerifyStatus=""" +
                hashlib.md5(DBConnect.user_Password.encode()).hexdigest() + """

Thanks & regards,
MediCare Team.
            """)
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserSuccessfullyRegistered"
            self.response.write(json.dumps(ResponseData))
        elif (FunctionOption == "SignUp" and DBConnect != None):
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserAlreadyRegistered"
            self.response.write(json.dumps(ResponseData))

# Below is code for SignIn.
        elif (FunctionOption == "SignIn" and DBConnect != None):
            userPassword = JD["Password"]
            if (DBConnect.IsActive == 1):
                if (DBConnect.user_Password == userPassword):
                    ResponseData['userEmail'] = userEmail
                    ResponseData['notification'] = "SuccessfulSignIn"
                    ResponseData['FirstName'] = DBConnect.user_FirstName
                    ResponseData['LastName'] = DBConnect.user_LastName
                    ResponseData['Contact'] = DBConnect.user_Contact
                    ResponseData['Address'] = DBConnect.user_Address
                    ResponseData['Gender'] = DBConnect.user_Gender
                    ResponseData['DOB'] = DBConnect.user_DOB
                    ResponseData['EmailVerified'] = DBConnect.EmailVerified
                    self.response.write(json.dumps(ResponseData))
                else:
                    ResponseData['userEmail'] = userEmail
                    ResponseData['notification'] = "PasswordMissmatch"
                    self.response.write(json.dumps(ResponseData))
            else:
                ResponseData['userEmail'] = userEmail
                ResponseData['notification'] = "UserInActive"
                self.response.write(json.dumps(ResponseData))
        elif (FunctionOption == "SignIn" and DBConnect == None):
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserNotRegistered"
            self.response.write(json.dumps(ResponseData))

# Below is code for Forgot Password.
        elif (FunctionOption == "ForgotPassword" and DBConnect != None):
            DBConnect.ResetPasswordLinkSent = 1
            DBConnect.put()
            SendEmail(
                userEmail, "Reset password for your MediCare account", """
Dear """ + DBConnect.user_FirstName + """,

This is an automated email sent to reset password of your MediCare account.

Click on below link to reset your password:

""" + WebPageLink + """ResetPassword?RegisteredAs=User&userEmail=""" +
                userEmail + """&FromPage=/UserSignIn&ResetStatus=""" +
                hashlib.md5(DBConnect.user_Password.encode()).hexdigest() + """

In case above link doesn't work, copy and paste the same in url bar of your browser.

Thanks & regards,
MediCare Team.
            """)
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "ResetLinkSent"
            self.response.write(json.dumps(ResponseData))
        elif (FunctionOption == "ForgotPassword" and DBConnect == None):
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserNotRegistered"
            self.response.write(json.dumps(ResponseData))

# Below is code for DeletingUserProfile.
        elif (FunctionOption == "DeleteUser" and DBConnect != None):
            DBConnect.key.delete()
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserSuccessfullyDeleted"
            self.response.write(json.dumps(ResponseData))
        elif (FunctionOption == "DeleteUser" and DBConnect == None):
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserNotRegistered"
            self.response.write(json.dumps(ResponseData))

# Below is code for HomePageAllProductsID.
        elif (FunctionOption == "AllProductID"):
            ProductsData = ProductsDB.query().fetch()
            ResponseProductID = {}
            Product = []
            for i in range(0, len(ProductsData)):
                Product.append(ProductsData[i].ProductID)
            ResponseProductID['ProductID'] = Product
            self.response.write(json.dumps(ResponseProductID))

# Below is code for HomePageAllProductsData.
        elif (FunctionOption == "ProductData"):
            ResponseProduct = {}
            ProductID = JD["ProductID"]
            ProductData = ndb.Key("ProductsDB", ProductID).get()
            ResponseProduct['ProductID'] = ProductData.ProductID
            ResponseProduct['ProductName'] = ProductData.ProductName
            ResponseProduct['Image'] = ProductData.Images[0]
            ResponseProduct['Description'] = ProductData.Description
            ResponseProduct['Dosage'] = ProductData.Dosage
            ResponseProduct['Category'] = ProductData.Category
            ResponseProduct['Ingredients'] = ProductData.Ingredients
            ResponseProduct['Price'] = ProductData.Price
            ResponseProduct['ProductLife'] = ProductData.ProductLife
            ResponseProduct['Quantity'] = ProductData.Quantity
            ResponseProduct[
                'PrescriptionRequired'] = ProductData.PrescriptionRequired
            Stock = []
            for j in range(0, len(ProductData.StockedIn)):
                Stock.append(ProductData.StockedIn[j])
            ResponseProduct['StockedIn'] = Stock
            self.response.write(json.dumps(ResponseProduct))

# Below is code to add products to cart.
        elif (FunctionOption == "AddToCart" and DBConnect != None):
            ProductID = JD["ProductID"]
            ProductDBStatus = ndb.Key("ProductsDB", ProductID).get()
            CartDBStatus = ndb.Key("CartDB", userEmail).get()
            if (CartDBStatus != None):
                if (ProductID not in CartDBStatus.ProductID):
                    CartDBStatus.ProductID.append(ProductID)
                    CartDBStatus.Quantity.append(0)
                    CartDBStatus.PharmacyID.append("None")
                    if (ProductDBStatus.PrescriptionRequired == 1
                            and CartDBStatus.PrescriptionRequired != 1):
                        CartDBStatus.PrescriptionRequired = 1
            else:
                CartDBStatus = CartDB(id=userEmail)
                CartDBStatus.userEmail = userEmail
                CartDBStatus.OrderType = "None"
                CartDBStatus.ProductID.append(ProductID)
                CartDBStatus.Quantity.append(0)
                CartDBStatus.PharmacyID.append("None")
                if (ProductDBStatus.PrescriptionRequired == 1):
                    CartDBStatus.PrescriptionRequired = 1
                else:
                    CartDBStatus.PrescriptionRequired = 0
            CartDBStatus.put()
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "ProductSuccessfullyAdded"
            self.response.write(json.dumps(ResponseData))
        elif (FunctionOption == "AddToCart" and DBConnect == None):
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserNotRegistered"
            self.response.write(json.dumps(ResponseData))

# Below is code to remove products from cart.
        elif (FunctionOption == "RemoveFromCart" and DBConnect != None):
            ProductID = JD["ProductID"]
            ProductData = ndb.Key("ProductsDB", ProductID).get()
            CartData = ndb.Key("CartDB", userEmail).get()
            if (CartData != None):
                if (len(CartData.ProductID) > 1):
                    for i in range(0, len(CartData.ProductID)):
                        if (CartData.ProductID[i] == ProductID):
                            if (ProductData.PrescriptionRequired == 1):
                                CartData.PrescriptionRequired = 0
                                del CartData.PrescriptionImage
                            del CartData.ProductID[i]
                            del CartData.Quantity[i]
                            del CartData.PharmacyID[i]
                            CartData.put()
                            break
                    for i in range(0, len(CartData.ProductID)):
                        PD = ndb.Key("ProductsDB", CartData.ProductID[i]).get()
                        if (PD.PrescriptionRequired == 1):
                            CartData.PrescriptionRequired = 1
                            CartData.put()
                else:
                    CartData.key.delete()
                ResponseData['notification'] = "ProductSuccessfullyRemoved"
            else:
                ResponseData['notification'] = "FailedToRemoveProduct"
            ResponseData['userEmail'] = userEmail
            self.response.write(json.dumps(ResponseData))
        elif (FunctionOption == "RemoveFromCart" and DBConnect == None):
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserNotRegistered"
            self.response.write(json.dumps(ResponseData))

# Below is code for Fetching user profile data.
        elif (FunctionOption == "FetchProfileData" and DBConnect != None):
            ResponseData['userEmail'] = DBConnect.user_Email
            ResponseData['notification'] = "ProfileDataFound"
            ResponseData['FirstName'] = DBConnect.user_FirstName
            ResponseData['LastName'] = DBConnect.user_LastName
            ResponseData['Contact'] = DBConnect.user_Contact
            ResponseData['Address'] = DBConnect.user_Address
            ResponseData['Gender'] = DBConnect.user_Gender
            ResponseData['DOB'] = DBConnect.user_DOB
            ResponseData['EmailVerified'] = DBConnect.EmailVerified
            self.response.write(json.dumps(ResponseData))
        elif (FunctionOption == "FetchProfileData" and DBConnect == None):
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserNotRegistered"
            self.response.write(json.dumps(ResponseData))

# Below is code for updating user profile data.
        elif (FunctionOption == "UpdateProfileData" and DBConnect != None):
            API_Key = "AIzaSyDvLc7SvzpX6KP6HCfn033xNKaM8UH3e2w"
            params = {"address": JD["Address"], "key": API_Key}
            GoogleAPI = "https://maps.googleapis.com/maps/api/geocode/json"
            url_params = urlencode(params)
            url = GoogleAPI + "?" + url_params
            result = urlfetch.fetch(url=url,
                                    method=urlfetch.POST,
                                    headers=params)
            DBConnect.user_FirstName = JD["FirstName"]
            DBConnect.user_LastName = JD["LastName"]
            DBConnect.user_Contact = JD["Contact"]
            DBConnect.user_Address = JD["Address"]
            DBConnect.Latitude = json.loads(
                result.content)['results'][0]['geometry']['location']['lat']
            DBConnect.Longitude = json.loads(
                result.content)['results'][0]['geometry']['location']['lng']
            DBConnect.put()
            SendEmail(
                DBConnect.user_Email,
                "Congratulations! Your MediCare account details are updated successfully",
                """
Dear """ + DBConnect.user_FirstName + """,

This is an automated email confirmation sent to you in regards of successful updation of your MediCare account.

Thanks & regards,
MediCare Team.
            """)
            ResponseData['userEmail'] = DBConnect.user_Email
            ResponseData['notification'] = "ProfileSuccessfullyUpdated"
            ResponseData['FirstName'] = DBConnect.user_FirstName
            ResponseData['LastName'] = DBConnect.user_LastName
            ResponseData['Contact'] = DBConnect.user_Contact
            ResponseData['Address'] = DBConnect.user_Address
            ResponseData['Gender'] = DBConnect.user_Gender
            ResponseData['DOB'] = DBConnect.user_DOB
            ResponseData['EmailVerified'] = DBConnect.EmailVerified
            self.response.write(json.dumps(ResponseData))
        elif (FunctionOption == "UpdateProfileData" and DBConnect == None):
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserNotRegistered"
            self.response.write(json.dumps(ResponseData))

# Below is code for searching product and returning product id if keyword matches.
        elif (FunctionOption == "SearchProduct"):
            ProductIDs = []
            SearchKeyword = JD["SearchKeyword"]
            if (SearchKeyword != ""):
                AllProducts = ProductsDB.query().fetch()
                if (AllProducts != None):
                    for i in range(0, len(AllProducts)):
                        ProdName = AllProducts[i].ProductName.lower()
                        ProdDescription = AllProducts[i].Description.lower()
                        ProdIngredients = AllProducts[i].Ingredients.lower()
                        if (ProdName.find(SearchKeyword.lower()) != -1):
                            ProductIDs.append(AllProducts[i].ProductID)
                        elif (ProdDescription.find(SearchKeyword.lower()) !=
                              -1):
                            ProductIDs.append(AllProducts[i].ProductID)
                        elif (ProdIngredients.find(SearchKeyword.lower()) !=
                              -1):
                            ProductIDs.append(AllProducts[i].ProductID)
            ResponseData['ProductID'] = ProductIDs
            self.response.write(json.dumps(ResponseData))

# Below is code for fetching MyOrdersData for logged in user in android device.
        elif (FunctionOption == "MyOrdersData" and DBConnect != None):
            OrderID = []
            OrderType = []
            OrderStatus = []
            OrderTotal = []
            ActiveOrderDetails = []
            CompletedOrderDetails = []
            OrderDetails = OrdersDB.query(
                OrdersDB.userEmail == userEmail,
                OrdersDB.OrderStatus == "Active").fetch()
            UON1 = []
            UON2 = []
            if (OrderDetails != []):
                for i in range(0, len(OrderDetails)):
                    if (OrderDetails[i].OrderID not in UON1):
                        UON1.append(OrderDetails[i].OrderID)
                for i in range(0, len(UON1)):
                    OrderDetails = OrdersDB.query(
                        OrdersDB.userEmail == userEmail,
                        OrdersDB.OrderStatus == "Active",
                        OrdersDB.OrderID == UON1[i]).fetch()
                    ActiveOrderDetails.append(OrderDetails[0])
                    OrderID.append(ActiveOrderDetails[i].OrderID)
                    OrderType.append(ActiveOrderDetails[i].OrderType)
                    OrderTotal.append(ActiveOrderDetails[i].GrandTotal)
                    if (len(OrderDetails) > 1):
                        for j in range(1, len(OrderDetails)):
                            if (ActiveOrderDetails[i].OrderSubStatus !=
                                    "Reviewing"
                                    and OrderDetails[j].OrderSubStatus
                                    == "Reviewing"):
                                ActiveOrderDetails[
                                    i].OrderSubStatus = OrderDetails[
                                        j].OrderSubStatus
                    OrderStatus.append(ActiveOrderDetails[i].OrderSubStatus)
            OrderDetails = OrdersDB.query(
                OrdersDB.userEmail == userEmail,
                OrdersDB.OrderStatus == "Completed").fetch()
            if (OrderDetails != []):
                for i in range(0, len(OrderDetails)):
                    if (OrderDetails[i].OrderID not in UON1
                            and OrderDetails[i].OrderID not in UON2):
                        UON2.append(OrderDetails[i].OrderID)
                for i in range(0, len(UON2)):
                    OrderDetails = OrdersDB.query(
                        OrdersDB.userEmail == userEmail,
                        OrdersDB.OrderID == UON2[i]).fetch()
                    OrderID.append(OrderDetails[0].OrderID)
                    OrderType.append(OrderDetails[0].OrderType)
                    OrderTotal.append(OrderDetails[0].GrandTotal)
                    if (len(OrderDetails) > 1):
                        OS = OrderDetails[0].OrderStatus
                        OSS = OrderDetails[0].OrderSubStatus
                        for j in range(1, len(OrderDetails)):
                            if (OS != OrderDetails[j].OrderStatus):
                                OS = OrderDetails[j]
                            if (OSS != OrderDetails[j].OrderSubStatus
                                    and OSS != "OrderComplete"):
                                OSS = OrderDetails[j].OrderSubStatus
                            if (OS == "Completed"):
                                CompletedOrderDetails.append(OrderDetails[0])
                                if (OSS != CompletedOrderDetails[
                                        len(CompletedOrderDetails) -
                                        1].OrderSubStatus):
                                    OrderDetails[0].OrderSubStatus = OSS
                    else:
                        if (OrderDetails[0].OrderStatus == "Completed"):
                            CompletedOrderDetails.append(OrderDetails[0])
                    OrderStatus.append(OrderDetails[0].OrderSubStatus)
            ResponseData['OrderID'] = OrderID
            ResponseData['OrderType'] = OrderType
            ResponseData['OrderStatus'] = OrderStatus
            ResponseData['OrderTotal'] = OrderTotal
            self.response.write(json.dumps(ResponseData))
        elif (FunctionOption == "MyOrdersData" and DBConnect == None):
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserNotRegistered"
            self.response.write(json.dumps(ResponseData))

# Below is code for fetching OrdersData for selected OrderID of logged in user in android device.
        elif (FunctionOption == "OrderIDData" and DBConnect != None):
            OrderID = JD["OrderID"]
            ProductID = []
            PharmacyID = []
            ProductStatus = []
            ServiceCharge = 0.0
            DeliveryCharge = 0.0
            ReUploadPrescription = 0
            PaymentRequired = 0
            SubTotalPrice = 0.0

            OrderData = OrdersDB.query(OrdersDB.OrderID == OrderID).fetch()
            if (OrderData != []):
                OrderDetails = OrderData[0]
                DeliveryCharge = DeliveryCharge + OrderData[0].DeliveryCharge
                for i in range(0, len(OrderDetails.ProductID)):
                    PharmacyID.append(
                        OrderData[0].PharmacyID
                    )  # I have got pharmacy id for each product id.
                    ProductStatus.append(
                        OrderData[0].OrderSubStatus
                    )  # I have got individual product status from here.
                    SubTotalPrice = SubTotalPrice + (OrderDetails.Quantity[i] *
                                                     OrderDetails.Price[i])
                    if (OrderData[0].OrderSubStatus == "ReUploadPrescription"):
                        ReUploadPrescription = 1
                        PaymentRequired = 0
                    elif (OrderData[0].OrderSubStatus == "PaymentRequired"):
                        ReUploadPrescription = 0
                        PaymentRequired = 1
                    elif (OrderData[0].OrderSubStatus == "CancelledByVendor"
                          and len(OrderData) > 1):
                        ReUploadPrescription = 0
                        PaymentRequired = 1
                    else:
                        ReUploadPrescription = 0
                        PaymentRequired = 0
                if (len(OrderData) > 1):
                    for i in range(1, len(OrderData)):
                        DeliveryCharge = DeliveryCharge + OrderData[
                            i].DeliveryCharge
                        if (OrderData[i].OrderSubStatus != "CancelledByVendor"
                                and OrderData[i].OrderSubStatus !=
                                "CancelledByCustomer"
                                and OrderDetails.ServiceCharge == 0.0):
                            if (OrderData[i].OrderType != "Collection"):
                                OrderDetails.ServiceCharge = 1.0
                            OrderDetails.OrderTotal = OrderDetails.OrderTotal + OrderData[
                                i].OrderTotal
                        elif (OrderData[i].OrderSubStatus !=
                              "CancelledByVendor"
                              and OrderData[i].OrderSubStatus !=
                              "CancelledByCustomer"
                              and OrderDetails.ServiceCharge != 0.0):
                            OrderDetails.OrderTotal = OrderDetails.OrderTotal + OrderData[
                                i].OrderTotal - OrderData[i].ServiceCharge
                        OrderDetails.DeliveryCharge = OrderDetails.DeliveryCharge + OrderData[
                            i].DeliveryCharge
                        if (OrderDetails.PrescriptionRequired == 0):
                            OrderDetails.PrescriptionRequired = OrderData[
                                i].PrescriptionRequired
                            if (OrderDetails.PrescriptionRequired == 1):
                                OrderDetails.PrescriptionImage = OrderData[
                                    i].PrescriptionImage
                        for j in range(0, len(OrderData[i].ProductID)):
                            PharmacyID.append(OrderData[i].PharmacyID)
                            OrderDetails.ProductID.append(
                                OrderData[i].ProductID[j])
                            OrderDetails.Quantity.append(
                                OrderData[i].Quantity[j])
                            OrderDetails.Price.append(OrderData[i].Price[j])
                            SubTotalPrice = SubTotalPrice + (
                                OrderData[i].Quantity[j] *
                                OrderData[i].Price[j])
                            ProductStatus.append(OrderData[i].OrderSubStatus)
                        if (OrderData[i].OrderSubStatus ==
                                "ReUploadPrescription"):
                            ReUploadPrescription = 1
                            PaymentRequired = 0
                        elif (OrderData[i].OrderSubStatus
                              == "CancelledByVendor" and PaymentRequired == 1):
                            ReUploadPrescription = 0
                            PaymentRequired = 1
                        elif (OrderData[i].OrderSubStatus == "PaymentRequired"
                              and PaymentRequired == 1):
                            ReUploadPrescription = 0
                            PaymentRequired = 1
                        else:
                            PaymentRequired = 0
                ProductID = OrderDetails.ProductID
                ServiceCharge = OrderDetails.ServiceCharge

                ResponseData['OrderID'] = OrderID
                ResponseData['notification'] = "DataFound"
                ResponseData['OrderType'] = OrderDetails.OrderType
                ResponseData['ProductID'] = ProductID
                ResponseData['Quantity'] = OrderDetails.Quantity
                ResponseData['Price'] = OrderDetails.Price
                ResponseData['PharmacyID'] = PharmacyID
                ResponseData['ProductStatus'] = ProductStatus
                ResponseData['ServiceCharge'] = ServiceCharge
                ResponseData['DeliveryCharge'] = DeliveryCharge
                ResponseData[
                    'PrescriptionRequired'] = OrderDetails.PrescriptionRequired
                ResponseData[
                    'PrescriptionImage'] = OrderDetails.PrescriptionImage
                ResponseData['ReUploadPrescription'] = ReUploadPrescription
                ResponseData['PaymentRequired'] = PaymentRequired
                ResponseData['SubTotalPrice'] = SubTotalPrice
            else:
                ResponseData['OrderID'] = OrderID
                ResponseData['notification'] = "NoData"
            self.response.write(json.dumps(ResponseData))
        elif (FunctionOption == "OrderIDData" and DBConnect == None):
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserNotRegistered"
            self.response.write(json.dumps(ResponseData))

# Below is code for fetching data for given pharmacy id.
        elif (FunctionOption == "PharmacyData" and DBConnect != None):
            PharmacyID = JD["PharmacyID"]
            PharmacyData = ndb.Key("PharmacyDB", PharmacyID).get()
            ResponseData['PharmacyID'] = PharmacyData.PharmacyID
            ResponseData['PharmacyName'] = PharmacyData.PharmacyName
            ResponseData['OfficialEmailId'] = PharmacyData.OfficialEmailId
            ResponseData['OfficialContact'] = PharmacyData.OfficialContact
            ResponseData['PhysicalAddress'] = PharmacyData.PhysicalAddress
            ResponseData['Latitude'] = PharmacyData.Latitude
            ResponseData['Longitude'] = PharmacyData.Longitude
            self.response.write(json.dumps(ResponseData))
        elif (FunctionOption == "PharmacyData" and DBConnect == None):
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserNotRegistered"
            self.response.write(json.dumps(ResponseData))

# Below is code for fetching Cart data for logged in user in android device.
        elif (FunctionOption == "FetchCartData" and DBConnect != None):
            CartData = ndb.Key("CartDB", userEmail).get()
            if (CartData != None):
                ResponseData['userEmail'] = userEmail
                ResponseData['notification'] = "ProductsInCart"
                ResponseData['ProductID'] = CartData.ProductID
                ResponseData[
                    'PrescriptionRequired'] = CartData.PrescriptionRequired
                self.response.write(json.dumps(ResponseData))
            else:
                ResponseData['userEmail'] = userEmail
                ResponseData['notification'] = "NoProductsInCart"
                self.response.write(json.dumps(ResponseData))
        elif (FunctionOption == "FetchCartData" and DBConnect == None):
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "UserNotRegistered"
            self.response.write(json.dumps(ResponseData))


# In case no function satisfy conditions, below will be returned.
        else:
            ResponseData['userEmail'] = userEmail
            ResponseData['notification'] = "FunctionNotRecognized"
            self.response.write(json.dumps(ResponseData))
Beispiel #15
0
    def post(self):
        self.response.headers['content-type'] = 'text/html'

        WebPageLink = "https://medicare-287205.nw.r.appspot.com/"
        ButtonName = self.request.get('Button')

        if (ButtonName == "SignInButton"):
            userEmail = self.request.get('userEmail')
            userPassword = self.request.get('userPassword')
            DBConnect = ndb.Key('UsersDB', userEmail).get()
            if (DBConnect != None and DBConnect.IsActive == 1):
                if (DBConnect.user_Password == userPassword):
                    self.redirect('/?userEmail=' + userEmail)
                else:
                    self.redirect('/UserSignIn?notification=PasswordMissmatch')
            else:
                self.redirect(
                    '/UserSignIn?notification=EmailIdNotRegisteredOrInActive')

        elif (ButtonName == "SignUpButton"):
            FirstName = self.request.get('FirstName')
            LastName = self.request.get('LastName')
            Email = self.request.get('userEmail_SU')
            Password = self.request.get('userPassword_SU')
            Contact = self.request.get('Contact')
            Address = self.request.get('Address')
            Gender = self.request.get('Gender')
            DOB = self.request.get('DOB')
            DBConnect = ndb.Key('UsersDB', Email).get()
            if (DBConnect == None):
                API_Key = "AIzaSyDvLc7SvzpX6KP6HCfn033xNKaM8UH3e2w"
                params = {"address": Address, "key": API_Key}
                GoogleAPI = "https://maps.googleapis.com/maps/api/geocode/json"
                url_params = urlencode(params)
                url = GoogleAPI + "?" + url_params
                result = urlfetch.fetch(url=url,
                                        method=urlfetch.POST,
                                        headers=params)
                Latitude = json.loads(
                    result.content
                )['results'][0]['geometry']['location']['lat']
                Longitude = json.loads(
                    result.content
                )['results'][0]['geometry']['location']['lng']
                DBConnect = UsersDB(id=Email)
                DBConnect.user_FirstName = FirstName
                DBConnect.user_LastName = LastName
                DBConnect.user_Email = Email
                DBConnect.user_Password = Password
                DBConnect.user_Contact = Contact
                DBConnect.user_Address = Address
                DBConnect.Latitude = Latitude
                DBConnect.Longitude = Longitude
                DBConnect.user_Gender = Gender
                DBConnect.user_DOB = DOB
                DBConnect.EmailVerified = 0
                DBConnect.ResetPasswordLinkSent = 0
                DBConnect.IsActive = 1
                DBConnect.put()
                SendEmail(
                    Email,
                    "Congratulations! Your MediCare account has been setup",
                    """
Dear """ + DBConnect.user_FirstName + """,

This is an automated email confirmation sent to you in regards of your MediCare account.

Please click on below link to verify your Email Id:
""" + WebPageLink + """VerifyEmail?RegisteredAs=User&userEmail=""" + Email +
                    """&VerifyStatus=""" +
                    hashlib.md5(DBConnect.user_Password.encode()).hexdigest() +
                    """

Thanks & regards,
MediCare Team.
                """)
                self.redirect(
                    '/UserSignIn?notification=UserSuccessfullyRegistered')
            else:
                self.redirect(
                    '/UserSignIn?notification=EmailAlreadyRegistered')

        elif (ButtonName == "ForgotPasswordButton"):
            Email = self.request.get('userEmail_FP')
            DBConnect = ndb.Key('UsersDB', Email).get()
            if (DBConnect != None):
                SendEmail(
                    Email, "Reset password for your MediCare account", """
Dear """ + DBConnect.user_FirstName + """,

This is an automated email sent to reset password of your MediCare account.

Click on below link to reset your password:

""" + WebPageLink + """ResetPassword?RegisteredAs=User&userEmail=""" + Email +
                    """&FromPage=/UserSignIn&ResetStatus=""" +
                    hashlib.md5(DBConnect.user_Password.encode()).hexdigest() +
                    """

In case above link doesn't work, copy and paste the same in url bar of your browser.

Thanks & regards,
MediCare Team.
                """)
                DBConnect.ResetPasswordLinkSent = 1
                DBConnect.put()
                self.redirect('/UserSignIn?notification=PasswordResetLinkSent')
            else:
                self.redirect('/UserSignIn?notification=EmailIdNotRegistered')
    def get(self):
        self.response.headers['content-type'] = 'text/html'
        OtherUserEmail = self.request.get('OtherUserEmail')
        if OtherUserEmail == "":
            OtherUsername = self.request.get('OtherUsername')
            OtherUserEmail = UsersDB.query(
                UsersDB.user_Name == OtherUsername).fetch()
            OtherUserEmail = OtherUserEmail[0].user_Email
        posts_Data = []
        image_Data = []
        followers_count = 0
        following_count = 0
        NumberOfPosts = 0
        OtherUserProfile = []
        userLoggedIn = users.get_current_user()
        current_User_Following_Decision = 0
        image_Key = []
        Comments = []
        Commenting_User = []
        NumberOfComments = []
        if userLoggedIn:  # If any user is logged in, there will be some data in userLoggedIn variable.
            loginLink = users.create_logout_url(self.request.uri)
            loginStatus = 'Logout'
            if userLoggedIn.email() == OtherUserEmail:
                self.redirect('/ProfilePage')
            else:
                OtherUserProfile = ndb.Key('UsersDB', OtherUserEmail).get(
                )  # Here I am fetching record of user data on which currently loggedin user have clicked.
                CurrentUserProfile = ndb.Key(
                    'UsersDB', userLoggedIn.email()).get(
                    )  # Here I am fetching record of user currently loggedin.
                if CurrentUserProfile.following_List != None:
                    for i in range(0, len(CurrentUserProfile.following_List)):
                        if OtherUserEmail == CurrentUserProfile.following_List[
                                i]:
                            current_User_Following_Decision = 1
                            break
                else:
                    current_User_Following_Decision = 0
                posts_Data = PostsDB.query(
                    PostsDB.user_Email == OtherUserProfile.user_Email).get()
                if posts_Data != None:
                    NumberOfPosts = len(posts_Data.post_Caption)
                    for i in range(0, NumberOfPosts):
                        image_Data.append(
                            get_serving_url(posts_Data.post_Image[i]))
                        image_Key.append(posts_Data.post_Image[i])
                for i in range(0, len(image_Key)):
                    comments_Data = ndb.Key('CommentsDB',
                                            str(image_Key[i])).get()
                    if comments_Data != None:
                        Comments.append(comments_Data.comment)
                        Commenting_User.append(comments_Data.commenting_User)
                        NumberOfComments.append(len(comments_Data.comment))
                    else:
                        Comments.append([])
                        Commenting_User.append([])
                        NumberOfComments.append(0)
                if OtherUserProfile.followers_List != None:
                    followers_count = len(
                        OtherUserProfile.followers_List
                    )  # Here count of followers will be fetched.
                if OtherUserProfile.following_List != None:
                    following_count = len(
                        OtherUserProfile.following_List
                    )  # Here count of followings will be fetched.
        else:  # If no user is logged in, there will be no data in userLoggedIn variable.
            loginLink = users.create_login_url(self.request.uri)
            loginStatus = 'Login'
            self.redirect('/ProfilePage')

        template_values = {
            'loginLink': loginLink,
            'loginStatus': loginStatus,
            'userLoggedIn': userLoggedIn,
            'otherUserProfile': OtherUserProfile,
            'posts_Data': posts_Data,
            'followers_count': followers_count,
            'following_count': following_count,
            'NumberOfPosts': NumberOfPosts,
            'image_Data': image_Data,
            'current_User_Following_Decision': current_User_Following_Decision,
            'image_Key': image_Key,
            'Comments': Comments,
            'Commenting_User': Commenting_User,
            'NumberOfComments': NumberOfComments,
        }
        template = JINJA_ENVIRONMENT.get_template('OtherUserProfile.html')
        self.response.write(template.render(template_values))
Beispiel #17
0
from UsersDB import UsersDB


def createVisits():
    a.query(
        'CREATE TABLE visits(id INTEGER NOT NULL PRIMARY KEY autoincrement UNIQUE, vk_id INTEGER, link_id INTEGER, fromWhere TEXT, date INTEGER);'
    )


def addVisit(link_id, vk_id, fromWhere):
    a.query(
        'INSERT INTO visits(vk_id, link_id, fromWhere) values (%d,%d,\'%s\')' % (vk_id, link_id, fromWhere)
    )
    return

a = UsersDB()
    def get(self):
        self.response.headers['content-type'] = 'text/html'
        userLoggedIn = users.get_current_user(
        )  # Here I am getting all details of logged in user.
        posts_Data = []
        image_Data = []
        image_Key = []
        notification = ""
        followers_count = 0
        following_count = 0
        NumberOfPosts = 0
        temp_Comment = []
        Comments = []
        Commenting_User = []
        NumberOfComments = []
        if userLoggedIn:  # If any user is logged in, there will be some data in userLoggedIn variable.
            loginLink = users.create_logout_url(self.request.uri)
            loginStatus = 'Logout'
            userDB_Reference = ndb.Key('UsersDB', userLoggedIn.email()).get(
            )  # Here I am checking if current user already have record in my DB or not.
            if userDB_Reference == None:  # If user record does not exist in DB, variable will be None.
                userDB_Reference = UsersDB(id=userLoggedIn.email())
                userDB_Reference.user_Email = userLoggedIn.email()
                userDB_Reference.put()
                userLoggedIn = userDB_Reference
            else:  # If user record exist in DB, variable will not be None.
                userLoggedIn = userDB_Reference
            posts_Data = PostsDB.query(
                PostsDB.user_Email == userLoggedIn.user_Email).get()
            if posts_Data != None:
                NumberOfPosts = len(posts_Data.post_Caption)
                for i in range(0, NumberOfPosts):
                    image_Data.append(get_serving_url(
                        posts_Data.post_Image[i]))
                    image_Key.append(posts_Data.post_Image[i])
            for i in range(0, len(image_Key)):
                comments_Data = ndb.Key('CommentsDB', str(image_Key[i])).get()
                if comments_Data != None:
                    Comments.append(comments_Data.comment)
                    Commenting_User.append(comments_Data.commenting_User)
                    NumberOfComments.append(len(comments_Data.comment))
                else:
                    Comments.append([])
                    Commenting_User.append([])
                    NumberOfComments.append(0)
            notification = self.request.get('notification')
            if userLoggedIn.followers_List != None:
                followers_count = len(
                    userLoggedIn.followers_List
                )  # Here count of followers will be fetched.
            if userLoggedIn.following_List != None:
                following_count = len(
                    userLoggedIn.following_List
                )  # Here count of followings will be fetched.
        else:  # If no user is logged in, there will be no data in userLoggedIn variable.
            loginLink = users.create_login_url(self.request.uri)
            loginStatus = 'Login'

        template_values = {
            'loginLink': loginLink,
            'loginStatus': loginStatus,
            'userLoggedIn': userLoggedIn,
            'posts_Data': posts_Data,
            'notification': notification,
            'followers_count': followers_count,
            'following_count': following_count,
            'NumberOfPosts': NumberOfPosts,
            'image_Data': image_Data,
            'image_Key': image_Key,
            'Comments': Comments,
            'Commenting_User': Commenting_User,
            'NumberOfComments': NumberOfComments,
        }
        template = JINJA_ENVIRONMENT.get_template('ProfilePage.html')
        self.response.write(template.render(template_values))
Beispiel #19
0
class GameServer(Server):
    channelClass = ServerChannel

    def __init__(self, *args, **kwargs):
        Server.__init__(self, *args, **kwargs)
        self.id = 0
        self.players = WeakKeyDictionary()
        print "Server Launched"

        self.usersdb = UsersDB()

        self.boards = {}
        self.gamesCount = 0
        # self.usersdb.firstRun()

        self.outstandingContactRequests = []

    def NextId(self):
        self.id += 1
        return self.id

    def Connected(self, channel, addr):
        self.addPlayer(channel)
        print "connected"

    def addPlayer(self, player):
        print "New Player" + str(player.addr)
        self.players[player] = True
        self.sendPlayers()

    def delPlayer(self, player):
        print "Deleting Player" + str(player.addr)

        self.updateStatus(player.nickname, False)

        del self.players[player]
        self.sendPlayers()

    def register(self, name, password):
        return self.usersdb.registerUser(name, password)

    def login(self, name, password):
        valid = self.usersdb.authenticate(name, password)

        # fail if already logged in
        if self.getOnlinePlayer(name):
            return False

        self.updateStatus(name, True)

        return valid

    def updateStatus(self, name, online):
        """
        gets online status of player
        :param name:
        :param online:
        :return:
        """
        cNames = self.usersdb.getContacts(name)
        for contact in cNames:
            c = self.getOnlinePlayer(contact)
            if c:
                c.updateContacts(name, online)

    def sendOutstandingContactReqs(self, name):
        """
        when someone signs in, sends contact request that were sent when they were offline
        :param name:
        :return:
        """
        for req in self.outstandingContactRequests:
            if req["to"] == name:
                self.getOnlinePlayer(name).friendRequest(req["from"])
                self.outstandingContactRequests.remove(req)

    def getContacts(self, name):
        """
        returns list of contacts for a playe
        :param name:
        :return:
        """

        contacts = []
        cNames = self.usersdb.getContacts(name)
        for contact in cNames:
            if self.getOnlinePlayer(contact):
                contacts.append({"name": contact, "online": True})
            else:
                contacts.append({"name": contact, "online": False})

        return contacts

    def getOnlinePlayer(self, name):
        """
        If player is online, returns them. Otherwise false
        :param name:
        :return:
        """
        for player in self.players:
            if player.nickname == name:
                return player

        return None

    def searchContact(self, fromname, name):
        """
        Searches for a contact to add
        If they're online, send friend request
        If not online, add them to dictionary for friend request to be sent next time they log in
        :param fromname:
        :param name:
        :return:
        """
        if self.usersdb.hasUser(name):
            # check if player is online now
            player = self.getOnlinePlayer(name)
            if player:
                player.friendRequest(fromname)
            else:
                self.outstandingContactRequests.append({"from": fromname, "to": name})

    def contactAccepted(self, fromname, name):
        """
        When contact accepted, informs player that requested adding and registers contact in database
        :param fromname:
        :param name:
        :return:
        """
        player = self.getOnlinePlayer(name)

        if player:
            player.contactAccepted(fromname)

        self.usersdb.registerContacts(fromname, name)

    def sendChallenge(self, fromname, name):
        """
        passes on challenge to challenged player
        :param fromname:
        :param name:
        :return:
        """
        challengee = self.getOnlinePlayer(name)
        if challengee:
            challengee.sendChallenge(fromname)
        else:
            return False
        return True

    def replyToChallenge(self, accepted, fromname, name):
        """
        If challenge accepted, creates board (serverside) and sets the player's colour
        :param accepted:
        :param fromname:
        :param name:
        :return:
        """
        challenger = self.getOnlinePlayer(name)
        challengee = self.getOnlinePlayer(fromname)  # could pass this in, but w/e

        if accepted:
            board = S_Board(8, challenger, challengee)
            self.boards[self.gamesCount] = board

            challengerColour = randint(0, 1)
            challengeeColour = -1
            if challengerColour == 1:
                challengeeColour = 0
            else:
                challengerColour = 1

            # Testing!
            challengerColour = 0
            challengeeColour = 1

            challenger.gameStart(fromname, board.networkData(), challengerColour, True, self.gamesCount)
            challengee.gameStart(name, board.networkData(), challengeeColour, False, self.gamesCount)

            self.gamesCount += 1

        else:
            challenger.gameRejected(fromname)

    def updateRecords(self, name, won):
        """
        Adds to player's score when they win and saves in database
        :param name:
        :param won: bool
        :return: Dictionary of records
        """
        self.usersdb.updateRecords(name, won)

        return self.usersdb.getRecords(name)

    def getRecords(self, name):
        return self.usersdb.getRecords(name)

    def checkMove(self, tileid, piecetileid, colour, boardNo):
        """
        Checks what kind of move was made and sends to players the appropriate response
        :param tileid: Int - tile that player is trying to move to
        :param piecetileid: Int - tile that player's piece is on
        :param colour: Int - 1 or 0
        :param boardNo:
        :return:
        """
        board = self.boards[boardNo]
        tarSel = board.getTargetSelTiles(tileid, piecetileid)

        result = board.handleMovement(tarSel[0], tarSel[1], colour)

        turnOver = False

        newKing = False
        if result == "move" or result == "take":
            if board.checkKinging(colour, tarSel[0]):
                newKing = True

        if result == "move":
            turnOver = True
        elif result == "musttake":
            turnOver = False
            return result
        elif result == "take":
            turnOver = True
        elif result == "doubletake":
            turnOver = False

        elif result == "invalid":
            return result

        # check if the other player has lost/has no further moves they can make
        if not board.getPossibleMoves(board.swapColour(colour)):
            board.gameOver = True

        self.sendToPlayers(
            {
                "action": "movechecked",
                "verdict": result,
                "board": board.networkData(),
                "newking": newKing,
                "movedx": tarSel[0].x,
                "movedy": tarSel[0].y,
            },
            board.player1,
            board.player2,
            turnOver,
            board.gameOver,
        )

    def sendToPlayers(self, data, player1, player2, turnOver, gameOver):
        """
        Sending move data to relevant players
        :param data:
        :param player1:
        :param player2:
        :param turnOver:
        :param gameOver:
        :return:
        """
        for player in self.players:
            if player == player1 or player == player2:
                player.moveChecked(data, turnOver, gameOver)

    def sendChat(self, fromname, gameNumber, text):
        board = self.boards[gameNumber]

        board.player1.deliverChat(fromname, text)
        board.player2.deliverChat(fromname, text)

    def sendNumPlayers(self, player):
        self.channelClass.Send({"action": "recNumPlayers", "message": len(self.players)})

    def sendPlayers(self):
        self.sendToAll({"action": "players", "players": [p.nickname for p in self.players]})

    def sendToAll(self, data):
        [p.Send(data) for p in self.players]

    def launch(self):
        while True:
            self.Pump()
            sleep(0.0001)