Ejemplo n.º 1
0
	def _update_mark(self, marked):
		"""
		Handles the AJAX calls from the app mark actions
		"""
		post_args = parse_qs(self._env["wsgi.input"].read())
		if "id" not in post_args:
			Logger.warning("not in post args: %s" % str(post_args))
			return self.construct_response(json.dumps({
				"success": False,
				"error": "missing args",
				"id": None
			}), self._route_types.JSON_CONTENT_TYPE)

		post_ids = post_args["id"]
		_, id = post_ids[0].split("_")
		p = Photo.get_by_id(id)
		if p == None:
			Logger.warning("no photo retrieved")
			return self.construct_response(json.dumps({
				"success": False,
				"error": "invalid_id",
				"id": id
			}), self._route_types.JSON_CONTENT_TYPE)

		p.marked = marked
		p.store()
		a = self.construct_response(json.dumps({
				"success": True,
				"details": {
					"marked": p.marked,
					"id": id
				}
			}), self._route_types.JSON_CONTENT_TYPE)
		return a
Ejemplo n.º 2
0
	def _get_image(self, size, action):
		"""
		Fetches the large image for lightboxing for the given photo id. Returns
		the image raw data.
		"""
		id = self._get_id_from_path(action)
		try:
			id = int(id)
			p = Photo.get_by_id(id)
		except Exception as e:
			p = None

		if p == None:
			fc = util.FileContainer(os.path.join(S.IMPORT_DIR, id), S.IMPORT_DIR)
			fc.time = util.get_time(fc)["time"]
			p = Photo.from_file_container(fc)

		if p == None:
			Logger.warning("could not find photo for %s" % id)
			image_path = S.BROKEN_IMG_PATH
		else:
			rel_thumb_path = p.get_or_create_thumb(size)
			image_path = os.path.join(S.THUMBNAIL_DIR, rel_thumb_path)

		f = open(image_path)
		raw_image = f.read()
		f.close()
		return self.construct_response(raw_image, self._route_types.JPEG_CONTENT_TYPE)
Ejemplo n.º 3
0
	def get_one(self):
		"""
		Fetches and returns raw data for a single photo
		"""
		self._get_id_from_path("single")
		a = Photo.get_by_id(id)
		return self.construct_response()
Ejemplo n.º 4
0
    def get_one(self):
        """
		Fetches and returns raw data for a single photo
		"""
        self._get_id_from_path("single")
        a = Photo.get_by_id(id)
        return self.construct_response()
Ejemplo n.º 5
0
    def _get_image(self, size, action):
        """
		Fetches the large image for lightboxing for the given photo id. Returns
		the image raw data.
		"""
        id = self._get_id_from_path(action)
        try:
            id = int(id)
            p = Photo.get_by_id(id)
        except Exception as e:
            p = None

        if p == None:
            fc = util.FileContainer(os.path.join(S.IMPORT_DIR, id),
                                    S.IMPORT_DIR)
            fc.time = util.get_time(fc)["time"]
            p = Photo.from_file_container(fc)

        if p == None:
            Logger.warning("could not find photo for %s" % id)
            image_path = S.BROKEN_IMG_PATH
        else:
            rel_thumb_path = p.get_or_create_thumb(size)
            image_path = os.path.join(S.THUMBNAIL_DIR, rel_thumb_path)

        f = open(image_path)
        raw_image = f.read()
        f.close()
        return self.construct_response(raw_image,
                                       self._route_types.JPEG_CONTENT_TYPE)
Ejemplo n.º 6
0
    def post(self, comp_id=0):
        """A user is submitting scores."""
        user_id, user = self.get_user()
        comp_id = int(comp_id)
        comp = Competition.get_by_id(comp_id)

        if not user or not comp:
            # stop some unauthorised post submissions.
            self.redirect("/competitions")
            return

        results = self.parse_scores(self.request.POST)

        for photo_id, score in results.iteritems():
            photo = Photo.get_by_id(photo_id)
            # photo = self.get_photo(photo_id)
            new_score = Scores(photo=photo.key, user_from=user.key, score=score)
            new_score.put()

        # record that user has submitted scores for this comp
        usercomp = self.get_usercomp(user, comp)
        usercomp.submitted_scores = True
        usercomp.put()

        self.redirect("/competition/%d" % (comp_id))
Ejemplo n.º 7
0
    def _check(self, photo_id):
        '''Helper method which checks the proper permissions for deleting the
        photograph.

        Return
        ------
        data : dict
            Data to be passed to the template.
        error : boolean
            True if user has permission to delete the photo
        '''
        user_id, user = self.get_user()
        if not user:
            self.redirect('/')

        referrer = self.request.referrer
        data = {
            'page_title': 'Delete Photograph',
            'userid': user_id,
            'user': user,
            'referrer': referrer if referrer else '/',
        }

        photo = Photo.get_by_id(photo_id)
        if not photo:
            data['error_msg'] = "Photograph doesn't exist."
            return data, True

        my_photo = user_id == photo.user.id()
        extra_photo = photo.competition is None

        if not extra_photo:
            comp = photo.competition.get()
            if comp.status != OPEN:
                error_msg = "Can only delete a photograph from an open competition."
                data['error_msg'] = error_msg
                return data, True
        else:
            comp = None

        #photo_user = photo.user.id()
        #if not user.admin and user_id != photo_user:
        if not self._user_permission(user, extra_photo, my_photo):
            error_msg = "You don't have permission to delete this photograph."
            data['error_msg'] = error_msg
            return data, True

        # no errors
        data['photo'] = photo
        data['url'] = photo.url(400)
        data['title'] = photo.title
        data['comp'] = comp
        return data, False
Ejemplo n.º 8
0
    def get(self, photo_id=0):
        '''View a photograph'''
        user_id, user = self.get_user()

        photo_id = int(photo_id)
        photo = Photo.get_by_id(photo_id)

        if not photo:
            data = {
                'page_title': 'Error',
                'user': user,
                'error_msg': 'Could not find photograph.'
            }
            self.render('error.html', **data)
            return

        can_view = self._can_view_photo(photo, user)
        if not can_view:
            msg = (
                'You cannot view pictures in competitions which are not '
                'finished.'
            )
            data = {
                'page_title': 'Cannot view picture',
                'user': user,
                'error_msg': msg
            }
            self.render('error.html', **data)
            return

        data = {
            'page_title': 'Photo',
            'page_subtitle': photo.title,
            'user': user,
            'userid': user_id,
            'photoid': photo_id,
            'can_comment': self._can_comment(user, photo),
            'delete_my_photo': self._can_delete(user, photo),
            'url': photo.url(),
            'title': photo.title,
            'comments': list(Comment.photo_comments(photo))
        }
        data.update(photo.exif())
        self.render('photo.html', **data)
Ejemplo n.º 9
0
    def get(self, photo_id=0):
        user_id, user = self.get_user()

        if not user or not user.admin:
            self.redirect('/')
            return

        photo_id = int(photo_id)
        if photo_id == 0:
            photos = list(Photo.query().fetch())
        else:
            photo = Photo.get_by_id(photo_id)
            if not photo:
                data = {
                    'user': user,
                    'page_title': 'Exif data - no such photo',
                    'message': 'no photo exists with this id',
                }
                self.render('error.html', **data)
            photos = [photo]

        results = []
        for photo in photos:
            exif = blob_exif(photo.blob)
            results.append((
                photo,
                exif,
            ))
            photo.populate(**exif)
            photo.put()

        data = {
            'user': user,
            'page_title': 'Exif data extractor',
            'photos': results,
        }

        self.render('help/exif.html', **data)
Ejemplo n.º 10
0
    def _update_mark(self, marked):
        """
		Handles the AJAX calls from the app mark actions
		"""
        post_args = parse_qs(self._env["wsgi.input"].read())
        if "id" not in post_args:
            Logger.warning("not in post args: %s" % str(post_args))
            return self.construct_response(
                json.dumps({
                    "success": False,
                    "error": "missing args",
                    "id": None
                }), self._route_types.JSON_CONTENT_TYPE)

        post_ids = post_args["id"]
        _, id = post_ids[0].split("_")
        p = Photo.get_by_id(id)
        if p == None:
            Logger.warning("no photo retrieved")
            return self.construct_response(
                json.dumps({
                    "success": False,
                    "error": "invalid_id",
                    "id": id
                }), self._route_types.JSON_CONTENT_TYPE)

        p.marked = marked
        p.store()
        a = self.construct_response(
            json.dumps({
                "success": True,
                "details": {
                    "marked": p.marked,
                    "id": id
                }
            }), self._route_types.JSON_CONTENT_TYPE)
        return a
Ejemplo n.º 11
0
    def post(self, photo_id=0):
        '''Adding a new comment to a photo.'''
        user_id, user = self.get_user()
        if not user:
            self.redirect('/')
            return

        photo_id = int(photo_id)
        comment = self.request.get('comment-text')
        #comment = escape(comment)

        logging.info(photo_id)

        photo = Photo.get_by_id(photo_id)
        new_comment = Comment(
            photo=photo.key,
            user=user.key,
            text=comment
        )
        new_comment.put()

        # keep track of the total number of comments
        photo.comment_count += 1
        photo.put()

        # send an email to the photographer and commentators, letting them
        # know of the new comment
        to = self._email_addresses(photo, user)

        if not to:
            # the commentator is also the photographer and there are
            # no comments from other users - no email to send.
            logging.info('Comment made, but no need to send email.')
            self.redirect(self.request.path)
            return

        body = (
            'Someone has made a comment on a photograph.'
            '\n\n'
            'From: {}\n\n'
            '{}'  # comment
            '\n\n'
            "The following link will take you to the photograph's page.\n"
            'http://prelude-hmpc.appspot.com/photo/{}'
        )
        body = body.format(user.username, comment, photo_id)

        try:
            email = mail.EmailMessage(
                sender='HMPC Bot <*****@*****.**>',
                subject='HMPC: New photograph comment',
                bcc=to,
                body=body
            )
            email.send()
        except OverQuotaError, msg:
            logging.error(msg)
            # send a message to admin (me) then I can forward to users
            new_body = body + '\n\nSend to:\n' + ', '.join(to)
            mail.send_mail_to_admins(
                sender='HMPC Bot <*****@*****.**>',
                subject='HMPC: New photograph comment (over quota)',
                body=new_body
            )