def post(self): start = self.get_argument('start', '0') page = self.get_argument('page', '1') start = int(start) if start.isdigit() else 0 page = int(page) if page.isdigit() else 1 total = Photo.get_count() pages = total / MAX_PHOTO_COUNT if total % MAX_PHOTO_COUNT != 0: pages += 1 cur_page_start = (page - 1) * MAX_PHOTO_COUNT if page > pages or (page == pages and cur_page_start + start == total): r = dict(code=400, photos=[]) self.write(json.dumps(r)) self.finish() return photos = Photo.gets(start, 10) # TODO # liked by current user html = [] for photo in photos: i = self.render_string('modules/photo.html', photo=photo) html.append(i) r = dict(code=200, photos=html) self.write(json.dumps(r)) self.finish()
def post(self): user = util.get_user_from_session() bout_id = long(self.request.get('bout_id')) image_blob_key = str(self.get_uploads()[0].key()) bout = Bout.get_by_id(bout_id) photo = Photo.for_bout_user(bout, user.email) if photo: votes = Vote.for_photo(photo) if len(votes) > 0: db.delete(votes) Photo.create(bout, user, image_blob_key) deferred.defer(send_add_photo_notifications, bout, user.email)
def post(self): user = self.current_user text = self.get_argument('text', '') kinds = self.get_arguments('kinds', []) tags = self.get_argument('tags', '') f = self.request.files.get('file') content = f[0].body if f else None if not content: self.render('photo/upload.html') if tags: tags = tags.split(',') Photo.new(text, kinds, tags, user.id, content) self.redirect('/')
def get(self): user_id = self.request.get('user_id') user = User.get_by_key_name(user_id) photos = Photo.all().filter('user', user).fetch(20) current_user_email = util.get_email_from_session() response = [util.make_bout_dict(photo.bout, current_user_email) for photo in photos] self.response.write(json.dumps(response))
def get(self): next = self.request.get('next') owner_email = self.request.get('owner_email') bout_id = long(self.request.get('bout_id')) bout = Bout.get_by_id(bout_id) photo = Photo.for_bout_user(bout, owner_email) response = util.fetch_with_cursor(Comment.all().ancestor(photo).order("-timestamp"), limit=20, cursor=next, mapper=make_comment_dict) self.response.write(json.dumps(response))
def send_add_photo_notifications(bout, from_user_email): if bout and from_user_email: Notification.create('photo_add', bout.owner, from_user_email, bout) photos = Photo.for_(bout) if len(photos)>0: for photo in photos: if photo.owner_email != from_user_email and photo.owner_email != bout.owner.email: Notification.create('photo_add', photo.user, from_user_email, bout)
def findDedicateInPage(pageIndex, buff): print("START: scan page {0}".format(pageIndex)) page = Page(URL, pageIndex, PAGE_SIZE) for photo in page.fetchPhotos(): if Photo.fetchOneById(photo.id) is None: buff.append(photo) print("SCAN: {0} is qulified because cannot find record locally".format(photo.id)) else: print("SKIP: {0} has a local record.".format(photo.id))
def _get_current_bouts(params): user = params['user'] bout = params['result'] if bout.permission == 2: if bout.owner.email != user.email and not Invited.for_(user, bout): return if not Photo.get_by_key_name(user.email, parent=bout): return return util.make_bout_dict(bout, user.email)
def make_users_bout_dict(bout, email): bout_dict = {} bout_dict['id'] = bout.id bout_dict['name'] = bout.name bout_dict['photos'] = [] num_photos = Photo.all().ancestor(bout).count() user_uploaded_photo = Photo.for_bout_user(bout, email) if user_uploaded_photo: bout_dict['photos'].append({'image':user_uploaded_photo.image_url}) num_photos -= 1 for i in range(0, num_photos): bout_dict['photos'].append({}) bout_dict['ended'] = bout.ended if bout_dict['ended']: bout_dict['winners'] = [] if Winner.for_bout_user(bout, email): bout_dict['winners'].append(email) return bout_dict
def post(self): user = util.get_user_from_session() message = self.request.get('message') owner_email = self.request.get('owner_email') bout_id = self.request.get('bout_id') bout = Bout.get_by_id(long(bout_id)) photo = Photo.for_bout_user(bout, owner_email) Comment.create(user, photo, message) Notification.create('comment_add', photo.bout.owner, user.email, bout)
def fetchPhotos(self): params = {'per_page':self.pageSize, 'page':self.pageIndex} r = requests.get(url = self.url, params = params) data = r.json() result = [] for d in data: result.append(Photo(d)) return result
def downloadPhoto(photo, tracker): url = photo.full #url = photo.thumb file_name = '{0}.jpg'.format(get_filename(url)) download_file_name = path.join(DOWNLOAD, file_name) archive_file_name = path.join(ARCHIVE, file_name) delete_file_name = path.join(DELETE, file_name) if Photo.fetchOneById(photo.id) is not None: print("SKIP: {0} has record".format(photo.id)) if path.exists(archive_file_name): print("SKIP: downloading {0} becase exist of {1}, url {2}".format(file_name, archive_file_name, url)) os.rename(archive_file_name, delete_file_name) if tracker is not None: tracker.finishTask(1) tracker.report() return if path.exists(archive_file_name): print("SKIP: downloading {0} becase exist of {1}, url {2}".format(file_name, archive_file_name, url)) photo.insertOrUpdate() os.rename(archive_file_name, delete_file_name) if tracker is not None: tracker.finishTask(1) tracker.report() return if DRY_RUN == False: r_start_time = int(time() * 1000) r = requests.get(url = url) open(download_file_name, 'wb').write(r.content) r_end_time = int(time() * 1000) r_using_time = r_end_time - r_start_time print("FINISH: downloading {0}(use {1} ms)" .format(file_name, r_using_time)) photo.insertOrUpdate() else: print("DRYRUN: downloading {0}".format(file_name)) if tracker is not None: tracker.finishTask(1) tracker.report()
def get_photo_image(id): try: photo = Photo.find_by_id(id) response = make_response() response.data = photo.image response.headers["Content-type"] = photo.mimetype return response except: pass success = '' errors = [] errors.append('画像の取得に失敗しました。') return render_template('result.html', success=success, errors=errors)
def set_winner(bout): bout.change_status(2) participants = sorted(Photo.for_(bout), key=lambda x: Vote.count(x), reverse=True) if len(participants) > 0: max_vote_count = Vote.count(participants[0]) if max_vote_count > 0: for participant in participants: current_vote_count = Vote.count(participant) if current_vote_count == max_vote_count: winner = User.get_by_key_name(participant.owner_email) Winner.create(winner, bout) Notification.create('winner', winner, winner.email, bout) elif current_vote_count < max_vote_count: break
def make_bout_dict(bout, email): bout_dict = {} bout_dict['id'] = bout.id bout_dict['name'] = bout.name bout_dict['description'] = bout.description bout_dict['time_left'] = bout.time_left_string bout_dict['ended'] = bout.ended bout_dict['photos'] = [] user_in_session_photo = Photo.for_bout_user(bout, email) if user_in_session_photo: photo_dict = make_photo_dict(user_in_session_photo, email) bout_dict['photos'].append(photo_dict) for photo in sorted(Photo.for_(bout), key=lambda x: Vote.count(x), reverse=True): if photo.owner_email != email: photo_dict = make_photo_dict(photo, email) bout_dict['photos'].append(photo_dict) if bout.ended: bout_dict['winners'] = [] winners = Winner.for_bout(bout) if len(winners) > 0: for winner in winners: bout_dict['winners'].append(winner.email) return bout_dict
def post(self): self.set_header("Content-Type", "application/json") r = {'code': 500} photo_id = self.get_argument('photo_id') if photo_id: photo = Photo.get(photo_id) if photo: photo.inc_like_count() r = { 'code': 200, 'like_count': photo.like_count, 'photo_id': photo_id } self.write(r) self.finish()
def setup(): user_1 = User.create('email1', 'firstname1', 'lastname1', 'password1') tp_user_1 = ThirdPartyUser(key_name='FB', parent=user_1) tp_user_1.network_id = '359059317608175' tp_user_1.put() user_2 = User.create('email2', 'firstname2', 'lasstname2', 'password2') tp_user_2 = ThirdPartyUser(key_name='FB', parent=user_2) tp_user_2.network_id = '359059317608175' tp_user_2.put() bout_1 = Bout.create(user_1, 'bout1', 'desc1', 1, 1) util.schedule_end(bout_1) photo_1 = Photo.create(bout_1, user_1, 'image_blob_key_1') photo_2 = Photo.create(bout_1, user_2, 'image_blob_key_2') bout_2 = Bout.create(user_2, 'bout2', 'desc2', 1, 2) util.schedule_end(bout_2) Vote.create('email1', photo_1) Vote.create('email2', photo_1) Vote.create('email2', photo_2) #photo_add, photo_vote, comment_add, winner, invited Notification.create('photo_add', bout_1.owner, user_2.email, bout_1) Notification.create('photo_vote', bout_1.owner, user_2.email, bout_1) Notification.create('comment_add', bout_1.owner, user_2.email, bout_1) Notification.create('winner', user_1, user_2.email, bout_1) Notification.create('invited', user_1, user_2.email, bout_1) #Winner.create(user_1, bout_1) Comment(parent=photo_1, user=user_1, message='message1', timestamp=datetime.datetime.now()).put() Comment(parent=photo_1, user=user_2, message='message2', timestamp=datetime.datetime.now()).put() Comment(parent=photo_2, user=user_1, message='message3', timestamp=datetime.datetime.now()).put() Comment(parent=photo_2, user=user_1, message='message4', timestamp=datetime.datetime.now()).put() Comment(parent=photo_2, user=user_2, message='message5', timestamp=datetime.datetime.now()).put() Comment(parent=photo_2, user=user_1, message='message6', timestamp=datetime.datetime.now()).put() Comment(parent=photo_2, user=user_2, message='message7', timestamp=datetime.datetime.now()).put() Comment(parent=photo_2, user=user_2, message='message8', timestamp=datetime.datetime.now()).put() Comment(parent=photo_2, user=user_2, message='message9', timestamp=datetime.datetime.now()).put() Follower.create('email1', user_2) Following.create(user_1, 'email2')
def get(self): response = [] bout_id = long(self.request.get('bout_id')) bout = Bout.get_by_id(bout_id) for rank, photo in enumerate(sorted(Photo.for_(bout), key=lambda x: Vote.count(x), reverse=True), start=1): user_dict = {} owner = User.get_by_key_name(photo.owner_email) user_dict['votes'] = Vote.count(photo) user_dict['rank'] = rank user_dict['email'] = photo.owner_email user_dict['first_name'] = owner.first_name user_dict['last_name'] = owner.last_name user_dict['profile_picture'] = owner.profile_picture response.append(user_dict) self.response.write(json.dumps(response))
def find_match(self): user = self.db_session.query(User).filter(User.id == self.user_id).first() self.vk_user_client = VkApi(token=user.token) candidates = self.search() if len(candidates) == 0: self.write_msg('Никого не найдено') return for candidate in candidates: top_photos = self.get_popular_profile_photos(candidate['id']) candidate['top_photos'] = top_photos result = f"{candidate['first_name']} {candidate['last_name']}\n" result += f"https://vk.com/{candidate['screen_name']}\n" candidate_exists = self.db_session.query(Candidate).filter(Candidate.id == candidate['id']).first() if not candidate_exists: c = Candidate( id=candidate['id'], first_name=candidate['first_name'], last_name=candidate['last_name'], screen_name=candidate['screen_name'], ) self.db_session.add(c) user.candidates.append(c) else: user.candidates.append(candidate_exists) self.write_msg(result) attachments = [] for photo in top_photos: owner_photo_id = f"photo{photo['owner_id']}_{photo['id']}" attachments.append(owner_photo_id) photo_exists = self.db_session.query(Photo).filter(Photo.id == owner_photo_id).first() if not photo_exists: self.db_session.add( Photo( id=owner_photo_id, photo_id=photo['id'], candidate_id=photo['owner_id'], likes_count=photo['likes']['count'], comments_count=photo['comments']['count'], ) ) self.send_attachment(','.join(attachments)) self.db_session.commit()
def _user_has_permission(handler): bout_id = long(handler.request.get('bout_id')) bout = Bout.get_by_id(bout_id) if not bout: logging.info('... invalid bout id') return False if bout.permission == 1: logging.info('... public bout') return True user = session.get_user_from_session() if bout.owner.email == user.email: logging.info('... is owner') return True if Photo.get_by_key_name(user.email, parent=bout): logging.info('... is participant') return True return False
def post(self): start = self.get_argument('start', 0) photos = Photo.gets(0, 20) # TODO # liked by current user html = [] for photo in photos: i = self.render_string('modules/photo.html', photo=photo) html.append(i) # TODO # continue fetching end = False r = dict(code=200, end=end, photos=html) self.write(json.dumps(r))
def post(self): response = {} user = util.get_user_from_session() email = user.key().name() owner_email = self.request.get('owner_email') bout_id = long(self.request.get('bout_id')) bout = Bout.get_by_id(bout_id) photo = Photo.get_by_key_name(owner_email, parent=bout) if Vote.update(email, photo, bout): Notification.create('photo_vote', bout.owner, user.email, bout) message = "%s voted on your photo in the Bout %s."%(user.name, bout.name) util.send_push_notification(photo.user.email, message, bout.id) response = {"success": True, "voted": True} else: response = {"success": True, "voted": False} vote_count = Vote.count(photo) response["vote_count"] = vote_count self.response.write(json.dumps(response))
def test_can_add_a_new_photo(self): user = add_or_get_user("unittest-user1") text = "Hello World!" kinds = ["1000", "1001"] tags = ["Hello", "World"] path = os.path.join(os.path.dirname(__file__), "img/photo.jpg") with open(path, "rb") as f: photo = Photo.new(text, kinds, tags, user.id, f.read()) assert photo assert photo.text == text assert photo.author assert photo.author.id == user.id for kind in kinds: assert kind in photo.kinds for tag in tags: assert tag in photo.tags
def photo(self): return self.photo_id and Photo.get(self.photo_id)
def get(self): next_cursor = self.request.get('next') user_id = self.request.get('user_id') user = User.get_by_key_name(user_id) response = util.fetch_with_cursor(Photo.all().filter('user', user), limit=10, cursor=next_cursor, mapper=user_bout_dict_mapper, mapper_params={'user_email':user.email}) self.response.write(json.dumps(response))
def cover_link(self): p = Photo.get(album_id=self.id) return p.link if p else ''