コード例 #1
0
    def comment(self, uid, activity_id, message):
        has_access, activity = self.has_access(uid, activity_id)

        if activity is None:
            return self.close_and_return({
                'error':
                ('access-denied' if has_access is False else 'does-not-exist')
            })

        commentid = str(uuid.uuid1())

        self.db.execute('comment_activity', commentid, activity_id, uid,
                        message)

        activity['comments'] = self.get_comments(activity_id)
        activity['flagged'] = self.has_flagged(uid, activity_id)

        likes = self.db.get_all('get_activity_likes', activity_id)

        activity['likes'] = likes

        activity['liked'] = self.has_liked(uid, activity_id)

        users = self.db.get_all('get_commenters', activity_id, uid)

        uids = [user['uid'] for user in users]

        other_user = User(uid, self.host, self.username, self.password,
                          self.database)

        owner = User(activity['uid'], self.host, self.username, self.password,
                     self.database)

        def send_notifications(num_users, notifications, other_user, message,
                               uids, activity_id, uid, owner):
            print('Sending Notifications in the Background')
            if num_users > 0:
                notifications.send_notification_to_users(
                    "{} {} commented in your discussion".format(
                        other_user.firstname, other_user.lastname),
                    bleach.clean(message),
                    uids,
                    4,
                    data={'activity_id': activity_id})

            if uid != owner.uid and owner.uid not in uids and owner.notify_new_comment:
                notifications.send_notification_to_user(
                    "{} {} commented on your activity".format(
                        other_user.firstname, other_user.lastname),
                    bleach.clean(message),
                    owner.uid,
                    data={'activity_id': activity_id})

        thread = threading.Thread(target=send_notifications,
                                  args=(len(users), self.notifications,
                                        other_user, message, uids, activity_id,
                                        uid, owner))
        thread.start()

        return self.close_and_return(activity)
コード例 #2
0
    def like(self, uid, activity_id):

        # Check if the user has access to the activity
        has_access, activity = self.has_access(uid, activity_id)

        # If we don't have an activity, send an error
        if activity is None:
            return self.close_and_return({
                'error':
                ('access-denied' if has_access is False else 'does-not-exist')
            })

        # Otherwise, like the activity
        self.db.execute(
            'unlike_activity', activity_id, uid
        )  #Clear out any of their previous likes of this activity just in case
        self.db.execute('like_activity', activity_id, uid)

        # Return the activity after updating its content
        activity['flagged'] = self.has_flagged(uid, activity_id)

        comments = self.db.get_all('get_activity_comments',
                                   activity['activity_id'])
        for comment in comments:
            comment['timestamp'] = comment['timestamp'].isoformat()
        activity['comments'] = comments

        likes = self.db.get_all('get_activity_likes', activity_id)

        activity['likes'] = likes

        activity['liked'] = self.has_liked(uid, activity_id)

        viewer = User(uid, self.host, self.username, self.password,
                      self.database)
        owner = User(activity['uid'], self.host, self.username, self.password,
                     self.database)

        name = viewer.firstname + ' ' + viewer.lastname

        def send_notification(host, username, password, database, name, uid,
                              data):
            notifs = Notifications(self.host, self.username, self.password,
                                   self.database)
            notifs.send_notification_to_user(
                name + " loved your post!",
                "You have received a like on one of your activities!",
                owner.uid,
                data=data)

        if owner.notify_new_like:
            thread = threading.Thread(target=send_notification,
                                      args=(self.host, self.username,
                                            self.password, self.database, name,
                                            owner.uid, {}))
            thread.start()

        return self.close_and_return(activity)
コード例 #3
0
 def put(self):
     # get the post data
     post_data = request.get_json()
     # check if user already exists
     user = User.query.filter_by(email=post_data.get('email')).first()
     if not user:
         try:
             user = User(
                 first_name=post_data.get('first_name'),
                 last_name=post_data.get('last_name'),
                 email=post_data.get('email'),
                 password=post_data.get('password')
             )
             # insert the user
             db.session.add(user)
             db.session.commit()
             # generate the auth token
             auth_token = encode_auth_token(user)
             responseObject = {
                 'status': 'success',
                 'message': 'Successfully registered.',
                 'auth_token': auth_token.decode()
             }
             return jsonify(responseObject)
         except Exception as e:
             responseObject = {
                 'status': 'fail',
                 'message': 'Some error occurred. Please try again.'
             }
             return make_response(jsonify(responseObject), 502)
     else:
         responseObject = {
             'status': 'fail',
             'message': 'User already exists. Please Log in.',
         }
         return make_response(jsonify(responseObject), 409)
コード例 #4
0
def upload_default_profile_picture(uid):
    #Copy the default profile image
    user = User(uid, host, username, password, database)

    user.set_default_profile_image()
コード例 #5
0
    def set_sharing_policy(self, uid, activity_id, category, uids=[]):
        is_subscriber = self.subscriptions.isPayingUser(uid)

        record = self.db.get_one('get_activity', activity_id)

        if record is None:
            return self.close_and_return({'error': 'does-not-exist'})

        activity = self.activity_from_record(record)

        if activity['uid'] != uid:
            return self.close_and_return({'error': 'access-denied'})

        if category in ('all', 'friends', 'none', 'supportGroup'):
            self.db.execute('clear_sharing_policy', activity_id)
            self.db.execute('set_sharing_policy', activity_id, category)

            if category != 'none' and category != 'supportGroup':
                friends = self.db.get_all('get_friends', uid)

                user = User(uid, self.host, self.username, self.password,
                            self.database)

                types = {
                    'diary': 'diary entry',
                    'highlow': 'High/Low',
                    'audio': 'audio entry',
                    'meditation': 'meditation session'
                }

                activity_type = types[activity['type']]

                uids = [friend['uid'] for friend in friends]

                def send_notifications(notifications, user, activity_type,
                                       uids, activity_id):
                    notifications.send_notification_to_users(
                        "New Feed Item!",
                        "{} shared a new {}!".format(
                            user.firstname + " " + user.lastname,
                            activity_type),
                        uids,
                        2,
                        data={'activity_id': activity_id})

                thread = threading.Thread(target=send_notifications,
                                          args=(self.notifications, user,
                                                activity_type, uids,
                                                activity_id))
                thread.start()

        elif category == 'uids':
            if not is_subscriber:
                return self.close_and_return(
                    {'error': 'requires-subscription'})
            if uids is None:
                return self.close_and_return({'error': 'no-uids-provided'})
            self.db.execute('clear_sharing_policy', activity_id)
            for uid in uids:
                self.db.execute('add_uid_to_sharing_policy', activity_id, uid)

            user = User(uid, self.host, self.username, self.password,
                        self.database)

            types = {
                'diary': 'diary entry',
                'highlow': 'High/Low',
                'audio': 'audio entry',
                'meditation': 'meditation session'
            }

            activity_type = types[activity['type']]

            def send_notifications(notifications, user, activity_type, uids,
                                   activity_id):
                notifications.send_notification_to_users(
                    "New Feed Item!",
                    "{} shared a new {}!".format(
                        user.firstname + " " + user.lastname, activity_type),
                    uids,
                    2,
                    data={'activity_id': activity_id})

            thread = threading.Thread(target=send_notifications,
                                      args=(self.notifications, user,
                                            activity_type, uids, activity_id))
            thread.start()
        else:
            return self.close_and_return({'error': 'invalid-category'})

        activity['flagged'] = self.has_flagged(uid, activity_id)

        comments = self.db.get_all('get_activity_comments',
                                   activity['activity_id'])
        for comment in comments:
            comment['timestamp'] = comment['timestamp'].isoformat()

        activity['comments'] = comments

        likes = self.db.get_all('get_activity_likes', activity_id)

        activity['likes'] = likes

        activity['liked'] = self.has_liked(uid, activity_id)

        return self.close_and_return(activity)
コード例 #6
0
    def add(self, uid, _type, data, date):
        #Create activity ID
        activity_id = str(uuid.uuid1())

        #Check data is valid
        if self.verify_activity_data(_type, data):
            if not self.data_allowed_for_subscription(uid, _type, data):
                return self.close_and_return(
                    {'error': 'requires-subscription'})
            self.db.execute('add_activity', activity_id, uid,
                            json.loads(data)['title'], _type, data, date)

            if _type != 'meditation':
                self.db.execute('set_sharing_policy', activity_id, 'none')
            else:
                self.db.execute('set_sharing_policy', activity_id, 'all')

                friends = self.db.get_all('get_friends', uid)

                user = User(uid, self.host, self.username, self.password,
                            self.database)

                types = {
                    'diary': 'diary entry',
                    'highlow': 'High/Low',
                    'audio': 'audio entry',
                    'meditation': 'meditation session'
                }

                activity_type = types[_type]

                uids = [friend['uid'] for friend in friends]

                self.notifications.send_notification_to_users(
                    "New Feed Item!",
                    "{} shared a new {}!".format(
                        user.firstname + " " + user.lastname, activity_type),
                    uids,
                    2,
                    data={'activity_id': activity_id})

            record = self.db.get_one('get_user_activity', uid, activity_id)
            activity = self.activity_from_record(record)

            comments = self.db.get_all('get_activity_comments',
                                       activity['activity_id'])
            for comment in comments:
                comment['timestamp'] = comment['timestamp'].isoformat()

            activity['comments'] = comments

            activity['flagged'] = self.has_flagged(uid, activity_id)

            likes = self.db.get_all('get_activity_likes', activity_id)

            activity['likes'] = likes

            activity['liked'] = self.has_liked(uid, activity_id)

            return self.close_and_return(activity)
        return self.close_and_return({'error': 'invalid-data'})
コード例 #7
0
ファイル: HighLow.py プロジェクト: highlowapp/highlowbackend
    def create(self,
               uid,
               _date,
               high=None,
               low=None,
               high_image=None,
               low_image=None,
               isPrivate=False,
               request_id=None,
               supports_html=False):
        ## Create a new High/Low entry in the database ##

        #Connect to MySQL
        conn = pymysql.connect(self.host,
                               self.username,
                               self.password,
                               self.database,
                               cursorclass=pymysql.cursors.DictCursor,
                               charset='utf8mb4')
        cursor = conn.cursor()

        #Check to see if this is a duplicate request. If it is, return the original response
        if request_id is not None:
            request_id = pymysql.escape_string(bleach.clean(request_id))
            cursor.execute(
                "SELECT * FROM onetime_requests WHERE request_id='{}';".format(
                    request_id))

            duplicate = cursor.fetchone()

            if duplicate is not None:
                return duplicate['response']

        _date = pymysql.escape_string(bleach.clean(_date))

        cursor.execute(
            "SELECT * FROM highlows WHERE uid='{}' AND _date='{}';".format(
                uid, _date))

        possible_duplicate = cursor.fetchone()

        if possible_duplicate is not None:
            self.high_low_id = possible_duplicate["highlowid"]
            self.date = _date
            self.high_image = possible_duplicate["high_image"]
            self.low_image = possible_duplicate["low_image"]
            self.high = possible_duplicate["high"]
            self.low = possible_duplicate["low"]
            self.uid = possible_duplicate["uid"]
            self.total_likes = possible_duplicate["total_likes"]
            self.timestamp = possible_duplicate["_timestamp"]
            self.isPrivate = possible_duplicate["private"] == 1
            conn.commit()
            conn.close()
            return self.update(uid, high, low, high_image, low_image,
                               isPrivate)

        #Create a High/Low ID
        self.high_low_id = str(uuid.uuid1())

        if high != None:
            self.high = pymysql.escape_string(self.sanitize_html(high))

            self.high = "{}".format(self.high)

        if low != None:
            self.low = pymysql.escape_string(self.sanitize_html(low))
            self.low = "{}".format(self.low)

        if high_image != None:
            fileStorage = FileStorage()

            upload_result = json.loads(
                fileStorage.upload_to_high_images(high_image))

            if 'error' in upload_result:
                conn.commit()
                conn.close()
                return json.dumps(upload_result)

            self.high_image = "{}".format(upload_result["file"])

        if low_image != None:
            fileStorage = FileStorage()

            upload_result = json.loads(
                fileStorage.upload_to_low_images(low_image))

            if 'error' in upload_result:
                conn.commit()
                conn.close()
                return json.dumps(upload_result)

            self.low_image = "{}".format(upload_result["file"])

        self.isPrivate = isPrivate

        _date = pymysql.escape_string(bleach.clean(_date))

        self.date = _date

        self.uid = uid

        #Now, insert the data
        cursor.execute(
            "INSERT INTO highlows(highlowid, uid, high, low, high_image, low_image, total_likes, _date, private) VALUES('{}', '{}', {}, {}, {}, {}, 0, '{}', {});"
            .format(
                self.high_low_id, uid,
                "'{}'".format(self.high) if self.high else "NULL",
                "'{}'".format(self.low) if self.low else "NULL",
                "'{}'".format(self.high_image) if self.high_image else "NULL",
                "'{}'".format(self.low_image) if self.low_image else "NULL",
                self.date, "TRUE" if self.isPrivate else "FALSE"))

        #...and update the streak
        cursor.execute(
            "UPDATE users SET streak = streak + 1 WHERE uid='{}';".format(uid))

        cursor.execute(
            "SELECT _timestamp FROM highlows WHERE highlowid='{}';".format(
                self.high_low_id))

        self.timestamp = cursor.fetchone()["_timestamp"]

        #Commit and close the connection
        conn.commit()
        conn.close()

        if not self.isPrivate:
            try:
                user = User(uid, self.host, self.username, self.password,
                            self.database)

                uids = user.get_friend_uids()

                notifs = Notifications(self.host, self.username, self.password,
                                       self.database)

                try:
                    notifs.send_notification_to_users(
                        "New Feed Item",
                        user.firstname + " " + user.lastname +
                        " created a new High/Low!",
                        uids,
                        2,
                        data={"highlowid": self.high_low_id})
                except:
                    pass
                """
                for other_uid in uids:
                    try:
                        friend = User(other_uid, self.host, self.username, self.password, self.database)
                        if friend.notify_new_feed_item:
                            notifs.send_notification_to_user("New Feed Item", user.firstname + " " + user.lastname + " created a new High/Low!", other_uid, data={"highlowid": self.high_low_id})
                    except: 
                        continue
                """
            except:
                pass

        #Return the HighLow ID
        response = json.dumps(
            self.get_json(uid=self.uid, supports_html=supports_html))

        #If a request ID was given, store it in the onetime requests table
        if request_id is not None:
            request_id = pymysql.escape_string(bleach.clean(request_id))
            #Connect to MySQL
            conn = pymysql.connect(self.host,
                                   self.username,
                                   self.password,
                                   self.database,
                                   cursorclass=pymysql.cursors.DictCursor,
                                   charset='utf8mb4')
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO onetime_requests(request_id, response) VALUES('{}', '{}');"
                .format(request_id, response))
            conn.commit()
            conn.close()

        return response
コード例 #8
0
ファイル: HighLow.py プロジェクト: highlowapp/highlowbackend
    def comment(self, uid, message, request_id=None):
        #Collect the specified data and add to the database
        conn = pymysql.connect(self.host,
                               self.username,
                               self.password,
                               self.database,
                               cursorclass=pymysql.cursors.DictCursor,
                               charset='utf8mb4')
        cursor = conn.cursor()

        #Check to see if this is a duplicate request. If it is, return the original response
        if request_id is not None:
            request_id = pymysql.escape_string(bleach.clean(request_id))
            cursor.execute(
                "SELECT * FROM onetime_requests WHERE request_id='{}';".format(
                    request_id))

            duplicate = cursor.fetchone()

            if duplicate is not None:
                return json.loads(duplicate['response'])

        commentid = str(uuid.uuid1())

        #Clean the message
        cleaned_message = pymysql.escape_string(bleach.clean(message))

        if len(cleaned_message) == 0:
            return {"error": "no-comment"}

        cursor.execute(
            "INSERT INTO comments(commentid, highlowid, uid, message) VALUES('{}', '{}', '{}', '{}');"
            .format(commentid, self.high_low_id, uid, cleaned_message))

        cursor.execute("""
        SELECT DISTINCT
    comments.uid AS uid
FROM
    comments
JOIN users ON users.uid = comments.uid
WHERE comments.highlowid = '{}' AND users.notify_new_comment = TRUE AND comments.uid != '{}';
        """.format(self.high_low_id, uid))
        users = cursor.fetchall()

        other_user = User(uid, self.host, self.username, self.password,
                          self.database)
        notifs = Notifications(self.host, self.username, self.password,
                               self.database)

        if len(users) > 0:
            notifs.send_notification_to_users(
                other_user.firstname + " " + other_user.lastname +
                " commented on your discussion",
                bleach.clean(message), [user["uid"] for user in users],
                4,
                data={"highlowid": self.high_low_id})

        notifs.send_notification_to_user(other_user.firstname + " " +
                                         other_user.lastname +
                                         " commented on your High/Low",
                                         bleach.clean(message),
                                         self.uid,
                                         data={"highlowid": self.high_low_id})

        conn.commit()
        conn.close()

        response = self.get_comments()

        #If a request ID was given, store it in the onetime requests table
        if request_id is not None:
            request_id = pymysql.escape_string(bleach.clean(request_id))

            #Connect to MySQL
            conn = pymysql.connect(self.host,
                                   self.username,
                                   self.password,
                                   self.database,
                                   cursorclass=pymysql.cursors.DictCursor,
                                   charset='utf8mb4')
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO onetime_requests(request_id, response) VALUES('{}', '{}');"
                .format(request_id, json.dumps(response)))
            conn.commit()
            conn.close()

        return response
コード例 #9
0
ファイル: HighLow.py プロジェクト: highlowapp/highlowbackend
    def like(self, uid):
        ## Add a new entry to the "Likes" table
        #Connect to MySQL
        conn = pymysql.connect(self.host,
                               self.username,
                               self.password,
                               self.database,
                               cursorclass=pymysql.cursors.DictCursor,
                               charset='utf8mb4')
        cursor = conn.cursor()

        #Make sure this user hasn't "liked" before
        cursor.execute(
            "SELECT * FROM likes WHERE highlowid='{}' AND uid='{}';".format(
                self.high_low_id, uid))

        if cursor.fetchone() != None:
            conn.commit()
            conn.close()
            return {'error': 'already-liked'}

        #Make sure the highlow does not belong to the user
        cursor.execute(
            "SELECT uid FROM highlows WHERE highlowid='{}' AND uid='{}';".
            format(self.high_low_id, uid))

        if cursor.fetchone() != None:
            conn.commit()
            conn.close()
            return {'error': 'not-allowed'}

        #Create the entry
        cursor.execute(
            "INSERT INTO likes(highlowid, uid) VALUES('{}', '{}');".format(
                self.high_low_id, uid))

        #Update the HighLow's total_likes
        cursor.execute(
            "UPDATE highlows SET total_likes = total_likes + 1 WHERE highlowid='{}';"
            .format(self.high_low_id))

        cursor.execute(
            "SELECT total_likes FROM highlows WHERE highlowid='{}';".format(
                self.high_low_id))

        highlow = cursor.fetchone()

        cursor.execute(
            "SELECT firstname, lastname FROM users WHERE uid='{}';".format(
                uid))

        liker = cursor.fetchone()

        name = liker["firstname"] + " " + liker["lastname"]

        #Commit and close the connection
        conn.commit()
        conn.close()

        user = User(self.uid, self.host, self.username, self.password,
                    self.database)

        if user.notify_new_like:
            notifs = Notifications(self.host, self.username, self.password,
                                   self.database)
            notifs.send_notification_to_user(
                name + " likes your post!",
                "You have received a like on one of your High/Lows!",
                self.uid,
                data={"highlowid": self.high_low_id})
        return {'status': 'success', 'total_likes': highlow["total_likes"]}