コード例 #1
0
 def change_post(self):
     posts = PostsModel(self.db.get_connection())
     posts.update_title(self.cur_post[0], self.comment_line.text())
     self.comment_line.setText('')
     self.send.show()
     self.save_desc.hide()
     self.show_post(self.r, self.c)
コード例 #2
0
def user_page(username):
    if "userid" not in session:
        return redirect('/login')
    posts = PostsModel(db.get_connection())
    users = UsersModel(db.get_connection())
    subs = SubsModel(db.get_connection())
    userid = users.get_by_name(username)[0]
    all_posts = []
    for i in posts.get_all(userid):
        all_posts.append({
            'pub_date':
            datetime.fromtimestamp(i[5]).strftime('%d.%m.%Y %H:%M'),
            'title':
            i[1],
            'thumb':
            i[3],
            'userid':
            i[4],
            'pid':
            i[0]
        })
    user_data = users.get(userid)
    user_info = {
        'username': user_data[1],
        'main_photo': user_data[4],
        'subscribed': subs.check_subscribed(session['userid'], userid),
        'userid': user_data[0]
    }
    user_data = users.get(session['userid'])
    sess_info = {'username': user_data[1], 'main_photo': user_data[4]}
    return render_template('project_index.html',
                           title='Instagram',
                           posts=all_posts,
                           user_info=user_info,
                           sess_info=sess_info)
コード例 #3
0
def index():
    if "userid" not in session:
        return redirect('/login')
    posts = PostsModel(db.get_connection())
    all_posts = []
    for i in posts.get_all(session['userid']):
        all_posts.append({
            'pub_date':
            datetime.fromtimestamp(i[5]).strftime('%d.%m.%Y %H:%M'),
            'title':
            i[1],
            'thumb':
            i[3],
            'userid':
            i[4],
            'pid':
            i[0]
        })
    users = UsersModel(db.get_connection())
    subs = SubsModel(db.get_connection())
    user_data = users.get(session['userid'])
    user_info = {
        'username': user_data[1],
        'main_photo': user_data[4],
        'followers_count': subs.get_followers(session['userid']),
        'subscriptions_count': subs.get_subscriptions(session['userid']),
        'posts_count': posts.get_count(session['userid']),
        'userid': session['userid']
    }
    return render_template('project_index.html',
                           title='Instagram',
                           posts=all_posts,
                           user_info=user_info,
                           sess_info=user_info)
コード例 #4
0
 def upload(self):
     if self.filename.text() != '':
         save_filename, thmb_filename = save_file(self.filename.text(),
                                                  self.current_user[0])
         posts = PostsModel(self.db.get_connection())
         posts.insert(self.description.toPlainText(), save_filename,
                      thmb_filename, self.current_user[0])
         self.show_page()
     else:
         self.warning.setText('Сначала загрузите фото.')
コード例 #5
0
def del_post(pid):
    if "userid" not in session:
        return redirect('/login')
    posts = PostsModel(db.get_connection())
    post = posts.get(pid)
    if post[4] == session['userid']:
        posts.delete(pid)
    else:
        flash('Доступ запрещен', 'danger')
    return redirect('/')
コード例 #6
0
 def post(self, post_id):
     abort_if_post_not_found(post_id)
     abort_if_not_authorized()
     parser = reqparse.RequestParser()
     parser.add_argument('title')
     args = parser.parse_args()
     # изменияем описание на присланное в запросе post
     PostsModel(db.get_connection()).update_title(post_id, args['title'])
     return jsonify({'success': 'OK'})
コード例 #7
0
def upload_photo():
    if "userid" not in session:
        return redirect('/login')
    form = UploadPhotoForm()
    if form.validate_on_submit():
        f = request.files['file']
        save_filename, thmb_filename = save_file(f)
        posts = PostsModel(db.get_connection())
        posts.insert(form.descrypt.data, save_filename, thmb_filename,
                     session['userid'])
        return redirect('/')
    users = UsersModel(db.get_connection())
    user_data = users.get(session['userid'])
    user_info = {'username': user_data[1], 'main_photo': user_data[4]}
    return render_template('project_add_photos.html',
                           form=form,
                           user_info=user_info,
                           sess_info=user_info)
コード例 #8
0
 def get(self, user_id):
     abort_if_not_authorized()
     if user_id == 0:
         # поиск пользователя
         parser = reqparse.RequestParser()
         parser.add_argument('user_name')
         args = parser.parse_args()
         # получаем данные пользователя по имени
         user = UsersModel(db.get_connection()).get_by_name(
             args['user_name'])
         return jsonify({'user': user})
     else:
         # вывод статистики
         posts = PostsModel(db.get_connection())
         subs = SubsModel(db.get_connection())
         return jsonify({
             'followers_count':
             subs.get_followers(user_id),
             'subscriptions_count':
             subs.get_subscriptions(user_id),
             'posts_count':
             posts.get_count(user_id)
         })
コード例 #9
0
 def show_page(self):
     uic.loadUi('design/main.ui', self)
     self.username.setText(self.current_user[1])
     pixmap = QPixmap('design/little_insta.png')
     if self.del_dialog != '':
         self.del_dialog.close()
         self.del_dialog = ''
     if self.current_page != self.current_user:
         subs = SubsModel(self.db.get_connection())
         self.sub.show()
         self.add_photo.hide()
         self.edit_profile.hide()
         if subs.check_subscribed(self.current_user[0],
                                  self.current_page[0]):
             self.sub.setText('Отписаться')
             self.sub.setStyleSheet('font: 16pt "Yu Gothic UI Semilight";'
                                    'color: rgb(0, 170, 255);'
                                    'border-style: outset;'
                                    'border-width: 2px;'
                                    'border-radius: 10px;'
                                    'border-color: rgb(0, 170, 255);'
                                    'min-width: 3em;'
                                    'padding: 6px;'
                                    'background-color: rgb(255, 255, 255);')
         else:
             self.sub.setText('Подписаться')
             self.sub.setStyleSheet('font: 16pt "Yu Gothic UI Semilight";'
                                    'color: rgb(255, 255, 255);'
                                    'border-style: outset;'
                                    'border-width: 2px;'
                                    'border-radius: 10px;'
                                    'border-color: rgb(0, 170, 255);'
                                    'min-width: 3em;'
                                    'padding: 6px;'
                                    'background-color: rgb(0, 170, 255);')
         self.sub.clicked.connect(self.sub_unsub)
     else:
         self.sub.hide()
         self.add_photo.show()
         self.edit_profile.show()
     self.icon.setPixmap(pixmap)
     self.exit.clicked.connect(self.quit)
     ### данные о пользователе ###
     posts = PostsModel(self.db.get_connection())
     all_posts = []
     for i in posts.get_all(self.current_page[0]):
         all_posts.append({
             'pub_date':
             datetime.fromtimestamp(i[5]).strftime('%d.%m.%Y %H:%M'),
             'title':
             i[1],
             'thumb':
             i[3],
             'userid':
             i[4],
             'pid':
             i[0]
         })
     users = UsersModel(self.db.get_connection())
     subs = SubsModel(self.db.get_connection())
     user_data = users.get(self.current_page[0])
     user_info = {
         'username': user_data[1],
         'main_photo': user_data[4],
         'followers_count': subs.get_followers(self.current_page[0]),
         'subscriptions_count':
         subs.get_subscriptions(self.current_page[0]),
         'posts_count': posts.get_count(self.current_page[0]),
         'userid': self.current_page[0]
     }
     img_name = '/'.join(user_info['main_photo'].split(
         '/')[:-1]) + '/circle_' + user_info['main_photo'].split('/')[-1]
     if not os.path.exists(img_name):
         img = Image.open(user_info['main_photo'])
         img_circle = mask_circle_solid(img, (255, 255, 255), 0, offset=0)
         img_circle.save(img_name)
     pixmap = QPixmap(img_name)
     pixmap_resized = pixmap.scaled(100, 100, QtCore.Qt.KeepAspectRatio)
     self.main_photo.setPixmap(pixmap_resized)
     self.username_2.setText(user_info['username'])
     self.stats.setText(
         'Публикации: {}  Подписчики: {}  Подписки: {}'.format(
             user_info['posts_count'], user_info['followers_count'],
             user_info['subscriptions_count']))
     self.edit_profile.clicked.connect(self.edit)
     self.add_photo.clicked.connect(self.add)
     ### начало таблицы с фотографиями ###
     posts = PostsModel(self.db.get_connection())
     all_posts = []
     for i in posts.get_all(self.current_page[0]):
         all_posts.append({
             'pub_date':
             datetime.fromtimestamp(i[5]).strftime('%d.%m.%Y %H:%M'),
             'title':
             i[1],
             'thumb':
             i[3],
             'userid':
             i[4],
             'pid':
             i[0]
         })
     self.table.setColumnCount(3)
     self.row_count = user_info['posts_count'] // 3 if user_info[
         'posts_count'] % 3 == 0 else user_info['posts_count'] // 3 + 1
     self.table.setRowCount(self.row_count)
     for i in range(0, self.row_count):
         for j in range(0, 3):
             if i * 3 + j < len(all_posts):
                 image = ImageWidget(all_posts[i * 3 + j]['thumb'], self)
                 self.table.setCellWidget(i, j, image)
     self.table.cellClicked[int, int].connect(self.show_post)
     ### поиск пользователя ###
     self.find_user.clicked.connect(self.search_user)
     self.username.clicked.connect(self.return_home)
コード例 #10
0
 def delete_post(self):
     posts = PostsModel(self.db.get_connection())
     posts.delete(self.cur_post[0])
     self.cur_post = ''
     self.show_page()
コード例 #11
0
    def show_post(self, *params):
        if len(params) > 1:
            self.r = params[0]
            self.c = params[1]
        uic.loadUi('design/show_post.ui', self)
        if self.del_dialog != '':
            self.del_dialog.close()
            self.del_dialog = ''
        if self.current_page != self.current_user:
            self.settings_combo.hide()
        self.send.show()
        self.save_desc.hide()
        self.username.setText(self.current_page[1])
        img_name = '/'.join(self.current_page[4].split(
            '/')[:-1]) + '/circle_' + self.current_page[4].split('/')[-1]
        pixmap = QPixmap(img_name)
        pixmap_resized = pixmap.scaled(71, 61, QtCore.Qt.KeepAspectRatio)
        self.main_photo.setPixmap(pixmap_resized)
        self.arrow.clicked.connect(self.show_page)
        posts = PostsModel(self.db.get_connection())
        all_posts = []
        for i in posts.get_all(self.current_page[0]):
            all_posts.append({
                'pub_date':
                datetime.fromtimestamp(i[5]).strftime('%d.%m.%Y %H:%M'),
                'title':
                i[1],
                'thumb':
                i[3],
                'userid':
                i[4],
                'pid':
                i[0]
            })
        if self.r * 3 + self.c > len(all_posts) - 1:
            self.show_page()
            return
        self.cur_post = posts.get(all_posts[self.r * 3 + self.c]['pid'])
        pixmap = QPixmap(self.cur_post[2])
        pixmap_resized = pixmap.scaled(781, 401, QtCore.Qt.KeepAspectRatio)
        r_width = pixmap_resized.width()
        self.photo.move(957 // 2 - r_width // 2, 100)
        self.photo.setPixmap(pixmap_resized)
        likes = LikesModel(self.db.get_connection())
        count = likes.get_count(self.cur_post[0])
        self.likes.setText(str(count))

        if likes.get_your(self.cur_post[0], self.current_user[0]):
            self.like.setIcon(QIcon('design/heart_red.png'))
            self.like.setIconSize(QtCore.QSize(51, 51))
            self.like.clicked.connect(self.del_like)
        else:
            self.like.setIcon(QIcon('design/heart_white.png'))
            self.like.setIconSize(QtCore.QSize(51, 51))
            self.like.clicked.connect(self.add_like)
        comments_ = CommentsModel(self.db.get_connection())
        users = UsersModel(self.db.get_connection())
        comments = comments_.get(self.cur_post[0])
        comment_count = len(comments)
        self.comments.setRowCount(comment_count)
        for i in range(0, comment_count):
            user = users.get(comments[i][2])[1]
            item = QTableWidgetItem(user)
            item.setFont(QFont('Yu Gothic UI Semibold', 16))
            item.setTextAlignment(QtCore.Qt.AlignRight)
            self.comments.setItem(i, 0, item)
            self.comments.setItem(i, 1, QTableWidgetItem(comments[i][4]))
            time = QLabel(time_converter(comments[i][5]))
            time.setStyleSheet(
                'color: rgb(208, 208, 208); font: Yu Gothic UI Semibold; font-size: 16px;'
            )
            self.comments.setCellWidget(i, 2, time)
            if comments[i][2] == self.current_user[0] and comments[i][0] != -1:
                image = QLabel('картинка')
                pixmap = QPixmap('design/can.png')
                pixmap_resized = pixmap.scaled(15, 15,
                                               QtCore.Qt.KeepAspectRatio)
                image.setPixmap(pixmap_resized)
                self.comments.setCellWidget(i, 3, image)
        self.comments.resizeColumnsToContents()
        self.comments.cellClicked[int, int].connect(self.del_comment)
        self.send.clicked.connect(self.add_comment)
        self.settings_combo.setItemIcon(0, QIcon('design/tools.png'))
        self.settings_combo.activated[str].connect(self.settings)
コード例 #12
0
 def delete(self, post_id):
     abort_if_post_not_found(post_id)
     abort_if_not_authorized()
     # удаляем публикацию
     PostsModel(db.get_connection()).delete(post_id)
     return jsonify({'success': 'OK'})
コード例 #13
0
 def get(self, post_id):
     abort_if_post_not_found(post_id)
     abort_if_not_authorized()
     # получаем одну запрошенную публикацию
     post = PostsModel(db.get_connection()).get(post_id)
     return jsonify({'post': post})
コード例 #14
0
def abort_if_post_not_found(post_id):
    if not PostsModel(db.get_connection()).get(post_id):
        abort(404, message="Post {} not found".format(post_id))