Beispiel #1
0
    def get(self):
        if self.request.get("id1") and  self.request.get("id2"):
            img1=ImgData.get_by_id(long(self.request.get("id1")))
            img2=ImgData.get_by_id(long(self.request.get("id2")))
            if img1 and img2:
                url1=images.get_serving_url(img1.blob_key)
                url2=images.get_serving_url(img2.blob_key)
                print "##############"
                print url1
                filePointer = urllib2.urlopen(url1)
                data1 = filePointer.read()
                filePointer.close()
                filePointer = urllib2.urlopen(url2)
                data2 = filePointer.read()
                filePointer.close()

                layer1= Image.open(StringIO(data1))
                layer2= Image.open(StringIO(data2))
                images.delete_serving_url(img1.blob_key)
                images.delete_serving_url(img2.blob_key)
                c=Image.new('RGBA',layer1.size,(255,255,255,0))
                c.paste(layer2,(0,0),layer2)
                #newimg=Image.alpha_composite(layer1,c)
                layer1.paste(layer2,(0,0),layer2)
                #newimg.im_feeling_lucky()
                output= StringIO()
                layer1.save(output,format='png')
                imageLayer =output.getvalue()
                output.close()
                self.response.headers['Content-Type']='image/png'
                self.response.out.write(imageLayer)
            else:
                self.error(404)
        else:
            self.error(404)
Beispiel #2
0
    def get(self):

        user = users.get_current_user()

        name = self.request.get('name')

        if not user:
            self.redirect(users.create_login_url())
        else:
            ancestor_key = ndb.Key('PhotoCategory', user.user_id())
            category_key = PhotoCategory.query(ancestor=ancestor_key).filter(
                PhotoCategory.category == name).get().key
            photos = UserPhoto.query(ancestor=category_key)
            for photo in photos:
                if user != photo.author:
                    self.redirect('/')
                    return
                blob_key = photo.blob_key
                images.delete_serving_url(blob_key)
                blob_info = blobstore.BlobInfo.get(blob_key)
                blob_info.delete()
                photo.key.delete()
            category_key.delete()

        self.redirect('/AlbumHome')
Beispiel #3
0
    def post(self):
        deleteStreamList = []
        deleteStreamList = self.request.get_all('deleteCheckbox')
        stream_query = Stream.query()
        keywordObject = Keywords.query()
        for stream in stream_query:
            if str(stream.key.id()) in deleteStreamList:
                print stream.streamName
                try:
                    for q in keywordObject:
                        q.globalKeywordsArray.remove(stream.streamName)
                        q.put()

                    for tag in stream.tags.split(' '):
                        for q in keywordObject:
                            q.globalKeywordsArray.remove(tag)
                            q.put()
                except:
                    pass

                for pic in stream.photos:
                    images.delete_serving_url(pic.blob_key)
                    blobstore.delete(pic.blob_key, rpc=None)
                stream.key.delete()
        self.redirect('/manage')
Beispiel #4
0
    def delete(self):
        """Delete the original file and dynamic serving url if it exists
        """
        filepath = request.args.get('filepath')
        if not filepath:
            return make_response_validation_error('filepath', message='Parameter filepath is required')

        try:
            cloudstorage.delete(filename)
        except cloudstorage.AuthorizationError:
            abort_json(401, "Unauthorized request has been received by GCS.")
        except cloudstorage.ForbiddenError:
            abort_json(403, "Cloud Storage Forbidden Error. GCS replies with a 403 error for many reasons, the most common one is due to bucket permission not correctly setup for your app to access.")
        except cloudstorage.NotFoundError:
            abort_json(404, filepath + " not found on GCS in bucket " + self.bucket)
        except cloudstorage.TimeoutError:
            abort_json(408, 'Remote timed out')

        # TODO get the query string and delete file if asked to
        blobstore_filename = u'/gs/{}/{}'.format(bucket_name, filepath)
        blob_key = blobstore.create_gs_key(blobstore_filename)
        try:
            images.delete_serving_url(blob_key)
        except images.AccessDeniedError:
            abort_json(403, "App Engine Images API Access Denied Error. Files has already been deleted from Cloud Storage")
        except images.ObjectNotFoundError:
            pass

        return '', 204
Beispiel #5
0
    def get(self):
        auth = authenticate(self)

        if auth[0]:
            current_user = User.query(
                User.username == auth[0]._User__email).get()

            form_data = cgi.FieldStorage()
            requests = form_data.getlist("chkDeleteStream")
            index = search.Index(INDEX_NAME)

            for key_str in requests:
                key = ndb.Key(urlsafe=key_str)
                stream = key.get()
                for pic_key in stream.pictures:
                    picture = pic_key.get()
                    picture_name = picture.name
                    filename = '/{}/Pictures'.format(
                        BUCKET_NAME) + "/" + picture_name
                    cloudstorage.delete(filename)
                    blob_key = picture.image
                    images.delete_serving_url(blob_key)
                    blobstore.delete(blob_key)
                    pic_key.delete()
                key.delete()
                index.delete(key_str)
                current_user.streams_owned.remove(key)

            current_user.put()
            time.sleep(.1)

            self.redirect('/ManageStream')
Beispiel #6
0
def RequestJobDelete(jsonRequest):
    ticketToDelete = jsonRequest['ticket']
    query = Delivery.query(ancestor=GetHydroidUnitKey(HYDROID_UNIT_ID)) \
        .filter(Delivery.finished == True) \
        .filter(Delivery.ticket == ticketToDelete)

    deleteTarget = None
    for delivery in query:
        deleteTarget = delivery

    if deleteTarget:
        if deleteTarget.imageBlobURL:
            images.delete_serving_url(deleteTarget.imageBlobKey)
            # images.delete_serving_url_async(deleteTarget.imageBlobKey)
        if deleteTarget.imageBlobKey:
            blobstore.delete(deleteTarget.imageBlobKey)
            # blobstore.delete_async(deleteTarget.imageBlobKey)
        # k = deleteTarget.put() # k.delete()
        key = ndb.Key(Delivery, ticketToDelete, parent=GetHydroidUnitKey(HYDROID_UNIT_ID))
        key.delete()
        # key.delete_async()

        # delete the measure list if any - we can query for runs > 1, but will do it uniform way
        measureQuery = Measure.query(ancestor=GetHydroidUnitKey(HYDROID_UNIT_ID)) \
            .filter(Measure.ticket == ticketToDelete)
        for m in measureQuery:
            if m.imageBlobURL:
                images.delete_serving_url(m.imageBlobKey)
            if m.imageBlobKey:
                blobstore.delete(m.imageBlobKey)
            key = ndb.Key(Measure, m.runid, parent=GetHydroidUnitKey(HYDROID_UNIT_ID))
            key.delete()

        DirtyHistoryList()
Beispiel #7
0
 def delete_file_endpoint(self, name):
     f = CorusFile.get_by_id(name)
     b = blobstore.BlobInfo(f.blob_key)
     if f.serving_url:
         delete_serving_url(b.key())
     b.delete()
     f.key.delete()
     return str('/cor/console/files/?del=' + name)
Beispiel #8
0
def borrarImg_cloud(img):
	if img.blobkeygs:
		filenom='/'+BUCKET +'/'+str(img.key.parent().id())+"/"+img.nombre
		#try:
		gcs.delete(filenom)
		images.delete_serving_url(img.blobkeygs)
		#except:
		#	pass
	img.key.delete()
Beispiel #9
0
def delete_thumbnail(thumbnail_key):
    filename = '/gs/' + THUMBNAIL_BUCKET + '/' + thumbnail_key
    blob_key = blobstore.create_gs_key(filename)
    images.delete_serving_url(blob_key)
    thumbnail_reference = ThumbnailReference.query(
        ThumbnailReference.thumbnail_key == thumbnail_key).get()
    thumbnail_reference.key.delete()
    filename = '/' + THUMBNAIL_BUCKET + '/' + thumbnail_key
    gcs.delete(filename)
Beispiel #10
0
def delete_thumbnail(thumbnail_key):
    filename = '/gs/{}/{}'.format(OUTPUT_BUCKET, thumbnail_key)
    blob_key = blobstore.create_gs_key(filename)
    images.delete_serving_url(blob_key)
    audio_reference = AudioReference.query(
        AudioReference.thumbnail_key == thumbnail_key).get()
    audio_reference.key.delete()

    filename = '/{}/{}'.format(OUTPUT_BUCKET, thumbnail_key)
    cloudstorage.delete(filename)
def delete_thumbnail(thumbnail_key):
    filename = '/gs/{}/{}'.format(THUMBNAIL_BUCKET, thumbnail_key)
    blob_key = blobstore.create_gs_key(filename)
    images.delete_serving_url(blob_key)
    thumbnail_reference = ThumbnailReference.query(
        ThumbnailReference.thumbnail_key == thumbnail_key).get()
    thumbnail_reference.key.delete()

    filename = '/{}/{}'.format(THUMBNAIL_BUCKET, thumbnail_key)
    cloudstorage.delete(filename)
Beispiel #12
0
def delete_thumbnail(thumbnail_key):
    filename = '/gs/{}/{}'.format(THUMBNAIL_BUCKET, thumbnail_key)
    blob_key = blobstore.create_gs_key(filename)
    images.delete_serving_url(blob_key)
    thumbnail_reference = ThumbnailReference.query(
        ThumbnailReference.thumbnail_key == thumbnail_key).get()
    thumbnail_reference.key.delete()

    filename = '/{}/{}'.format(THUMBNAIL_BUCKET, thumbnail_key)
    cloudstorage.delete(filename)
Beispiel #13
0
def upload_image(entity_id, old_key, image_type):
    try:
        # check if the post request has the file part
        if 'photo' not in request.files:
            raise ValueError('No photo part')

        image_file = request.files['photo']

        # if user does not select file, browser also submit a empty part without filename
        if image_file and image_file.filename == '':
            raise ValueError('No file selected')

        ext = allowed_file(image_file.filename)

        # if allowed extension
        if ext:
            # img = Image.open(image_file)
            #
            # # Resize image
            # img.thumbnail((560, 560), Image.ANTIALIAS)
            #
            # # Convert Image to FileStorage type
            # sio = StringIO()
            # sio.name = image_file.filename
            # img.save(sio)
            # sio.seek(0)
            # f = FileStorage(sio)

            timestamp = int(time.mktime(datetime.utcnow().timetuple()))
            if image_type == USER_PROFILE:
                filename = 'user_profile/{}_{}.{}'.format(
                    entity_id, timestamp, ext)
            elif image_type == CIRCLE_PROFILE:
                filename = 'circle_profile/{}_{}.{}'.format(
                    entity_id, timestamp, ext)
            else:
                filename = '{}_{}.{}'.format(entity_id, timestamp, ext)

            res = upload_object(image_file, filename)

            # Delete old Serving URL and old Blob
            if old_key:
                images.delete_serving_url(old_key)
                blobstore.delete(old_key)

            # Create blob_key
            blob_key = blobstore.create_gs_key('/gs/{}/{}'.format(
                BUCKET, filename))

            return blob_key

        raise ValueError('Only .jpg, .jpeg, .png files are allowed')

    except RequestEntityTooLarge:
        raise ValueError('File is too large')
Beispiel #14
0
	def post(self):
		deletePostlist =[]
		deletePostlist=self.request.get_all('deleteCheckbox')
		post_query = Post.query()

		for p in post_query:
			if p.id in deletePostlist:
				for i in range(0,len(p.giftList)):
					images.delete_serving_url(p.giftList[i].image)
					blobstore.delete(p.giftList[i].image,rpc=None)
				p.key.delete()
		self.redirect('/manage')
Beispiel #15
0
 def delete(self, key):
     current_user(required=True)
     key = blobstore.BlobKey(str(urllib.unquote(key)))
     blob_info = blobstore.BlobInfo.get(key)
     if blob_info:
         blob_info.delete()
         if re_image.match(blob_info.content_type):
             delete_serving_url(key)
         return {}
     else:
         self.error(404)
         return {"error": "File not found with key " + key}
Beispiel #16
0
 def delete(self):
     if self.request.get('imgPath'):
         try:
             blobKey = blobstore.create_gs_key(self.request.get('imgPath'))
             print(blobKey)
             images.delete_serving_url(blobKey)
         except images.Error as e:
             self.response.set_status(404, e)
         except image.InvalidBlobKeyError as e:
             self.response.set_status(404, e)
         except blobstore.Error as e:
             self.response.set_status(404, e)
Beispiel #17
0
    def remove_user_image(self):
        """Removes existing user's image completely"""
        self.image_url = ''

        # Find associated UserImage
        user_image = UserImage.query(user_id=self.uid)

        # Remove permenant link for image
        images.delete_serving_url(user_image.blob_key)

        user_image.deleted = True
        user_image.put()
Beispiel #18
0
    def get(self):
        if not self.user:
            return self.redirect('/')

        ## CLEAR DATASTORE

        datastore_keys = []
        datastore_keys.extend(User.query().fetch(keys_only=True))
        datastore_keys.extend(Group.query().fetch(keys_only=True))
        datastore_keys.extend(GroupPost.query().fetch(keys_only=True))
        datastore_keys.extend(PrivateRequest.query().fetch(keys_only=True))

        if len(datastore_keys) > 0:
            ndb.delete_multi(datastore_keys)

        ## CLEAR BLOBSTORE

        blobinfo_objects_query = blobstore.BlobInfo.all()
        blobinfo_objects = blobinfo_objects_query.fetch(400)
        if len(blobinfo_objects) > 0:
            for blobinfo_obj in blobinfo_objects:
                blob_key = blobinfo_obj.key()

                #remove image serving url
                images.delete_serving_url(blob_key)
                #remove blob
                blobstore.delete([blob_key])

        ## CLEAR DOCUMENTS IN SEARCH INDEX(groups)
        ## from delete_all_in_index function at https://cloud.google.com/appengine/docs/python/search/

        group_index = search.Index(name='groups')
        # index.get_range by returns up to 100 documents at a time, so we must
        # loop until we've deleted all items.
        while True:
            # Use ids_only to get the list of document IDs in the index without
            # the overhead of getting the entire document.
            document_ids = [
                document.doc_id
                for document in group_index.get_range(ids_only=True)
            ]

            # If no IDs were returned, we've deleted everything.
            if not document_ids:
                break

            # Delete the documents for the given IDs
            group_index.delete(document_ids)

        ## CLEAR MEMCACHE
        memcache.flush_all()

        return self.render_json("Hard Reset Success")
Beispiel #19
0
    def post(self):
        deletePostlist = []
        deletePostlist = self.request.get_all('deleteCheckbox')
        post_query = Post.query()

        for p in post_query:
            if p.id in deletePostlist:
                for i in range(0, len(p.giftList)):
                    images.delete_serving_url(p.giftList[i].image)
                    blobstore.delete(p.giftList[i].image, rpc=None)
                p.key.delete()
        self.redirect('/manage')
Beispiel #20
0
 def delete(self, key):
     if not users.is_current_user_admin():
         raise AppError("User must be administrator.")
     key = blobstore.BlobKey(str(urllib.unquote(key)))
     blob_info = BlobInfo.get(key)
     if blob_info:
         blob_info.delete()
         if re_image.match(blob_info.content_type):
             delete_serving_url(key)
         return {}
     else:
         self.error(404)
         return {"error": "File not found with key " + key}
Beispiel #21
0
 def delete(self, key):
   if not config.is_current_user_admin():
     raise AppError("User must be administrator.")
   key = blobstore.BlobKey(str(urllib.unquote(key)))
   blob_info = BlobInfo.get(key)
   if blob_info:
     blob_info.delete()
     if HAS_PIL and re_image.match(blob_info.content_type):
       delete_serving_url(key)
     return {}
   else:
     self.error(404)
     return {"error": "File not found with key " + key}
def delete_image(image_type, user_key, group_key):
    user = user_key.get()

    if image_type == 'user':
        blob_key = user.image_blob
        if blob_key:

            # delete the the blob key, serving urls from datastore
            user.image_blob = None
            user.image_url = None

            # stor serving the image and delete the orphan blob
            images.delete_serving_url(blob_key)
            blobstore.delete([blob_key])

            user.put()
            return True
        else:
            # user tried to delete non existing image
            return None

    if image_type == 'group':
        group = group_key.get()

        # check if user is allowed to edit the group
        allowed = check_group_edit_allowed(group, user_key)
        if not allowed:
            # delete the uploaded blob
            blobstore.delete([blob_info.key()])
            return None

        cover_image_blob_key = group.cover_image_blob_key
        if cover_image_blob_key:
            #remove cover image fields if image uploaded
            group.cover_image_blob_key = None
            group.cover_image_url = None

            # stop serving the image and delete the orphan blob
            images.delete_serving_url(cover_image_blob_key)
            blobstore.delete([cover_image_blob_key])

            group.put()

            # update the search index document
            # we don't pass the group image which set to None by default
            add_to_index(group_key.id(), group.name, group.description)
            return True

        else:
            # user tried to delete non existing image
            return None
Beispiel #23
0
def delete_media(gcs_filename):
    images.delete_serving_url(blobstore.create_gs_key(gcs_filename))
    gcs.delete(gcs_filename[3:])
    return True
    
    
    
    
    
    
    
    
    
    
Beispiel #24
0
    def post(self):

        if self.request.get('delete'):
            # this is called directly so we can manually check the CSRF here
            if not self.checkCSRF():
                return self.renderError(412)

            if self.user.pic_gcs:
                path = self.user.pic_gcs
                if path.startswith('/gs/'):
                    path = path[3:]
                gcs.delete(path)
            if self.user.pic_url:
                images.delete_serving_url(self.user.pic_blob)
            if self.user.pic_blob:
                blobstore.delete(self.user.pic_blob)

            self.user.pic_gcs = None
            self.user.pic_blob = None
            self.user.pic_url = None
        else:
            errors = {}
            uploads = self.get_uploads()
            for upload in uploads:
                # enforce file type based on extension
                name, ext = upload.filename.rsplit(".", 1)
                ext = ext.lower()
                if ext not in IMAGE_TYPES:
                    upload.delete()
                    errors = {'type': True}
                    continue

                try:
                    # note that this serving URL supports size and crop query params
                    self.user.pic_url = images.get_serving_url(upload, secure_url=True)
                except images.TransformationError:
                    upload.delete()
                    errors = {'corrupt': True}
                    continue

                self.user.pic_gcs = upload.gs_object_name
                self.user.pic_blob = upload.key()

            if errors:
                return self.redisplay({}, errors)

        self.user.put()
        self.uncache(self.user.slug)
        self.redisplay()
Beispiel #25
0
    def store_picture_from_content(cls, blob_key):
        """ Resize picture and upload to Cloud Storage bucket. Return the GCS key """
        data = blobstore.BlobReader(blob_key).read()
        img = Image(data)
        img.resize(width=800, height=600)
        # img.im_feeling_lucky()
        img = img.execute_transforms(output_encoding=JPEG)

        new_gcs_key = cls.upload_blob_to_gcs(img, content_type='img/jpeg')

        # delete original blob
        delete_serving_url(blob_key)
        blobstore.delete(blob_key)

        return new_gcs_key
Beispiel #26
0
    def store_picture_from_content(cls, blob_key):
        """ Resize picture and upload to Cloud Storage bucket. Return the GCS key """
        data = blobstore.BlobReader(blob_key).read()
        img = Image(data)
        img.resize(width=800, height=600)
        # img.im_feeling_lucky()
        img = img.execute_transforms(output_encoding=JPEG)

        new_gcs_key = cls.upload_blob_to_gcs(img, content_type='img/jpeg')

        # delete original blob
        delete_serving_url(blob_key)
        blobstore.delete(blob_key)

        return new_gcs_key
Beispiel #27
0
def unserveurl():

    config = ConfigParser.RawConfigParser(allow_no_value=True)
    config.read('config.ini')

    expectedKey = config.get("auth", "key")
    receivedKey = request.form['key']

    if expectedKey == receivedKey:
        image = request.form['image']
        bucket = request.form['bucket']

        logging.info('Remove Serving URL for ' + image)

        filename = (bucket + "/" + image)
        logging.info('Filename is ' + filename)

        gskey = blobstore.create_gs_key("/gs/" + filename)
        logging.info('gskey is ' + gskey)

        removal = images.delete_serving_url(gskey)
        logging.info('URL is removed')

        return ("OK")
    else:
        return json.dumps({'error': 'No valid key provided'}), 401, {
            'ContentType': 'application/json'
        }
Beispiel #28
0
 def post(self, album_key):
     user_ = users.get_current_user()
     user_id = user_.user_id()
     query = User.query(User.user == user_id)
     user = query.get()
     for album in user.albums:
         _album = album.get()
         try:
             if (_album.name == album_key):
                 for photo in _album.photos:
                     blob = photo.get().blob_key
                     images.delete_serving_url(blob)
                 break
         except:
             logging.critical("Album link is broken")
     self.redirect('/view_albums')
def upload_image(image_type, blob_info, user_key, group_key):
    user = user_key.get()

    if image_type == 'user':

        # delete the older image if it exists
        if user.image_blob:
            images.delete_serving_url(user.image_blob)
            blobstore.delete([user.image_blob])

        # set new image properties
        user.image_blob = blob_info.key()
        user.image_url = images.get_serving_url(user.image_blob)

        user.put()
        return user.image_url

    if image_type == 'group':
        group = group_key.get()

        # check if user is allowed to edit the group
        allowed = check_group_edit_allowed(group, user_key)
        if not allowed:
            # delete the uploaded blob
            blobstore.delete([blob_info.key()])
            return None

        # delete older image if exists
        if group.cover_image_blob_key:
            # stop serving the blob via image service
            images.delete_serving_url(group.cover_image_blob_key)

            # delete the blob from blobstore
            blobstore.delete([group.cover_image_blob_key])

        # update to newly uploaded image
        group.cover_image_blob_key = blob_info.key()
        group.cover_image_url = images.get_serving_url(
            group.cover_image_blob_key)
        group.put()

        # update the search index document to contain latest image url or description
        add_to_index(group_key.id(), group.name, group.description,
                     group.cover_image_url)
        return group.cover_image_url
Beispiel #30
0
def delete_image_url():
    blob_key = request.args.get('blob_key')

    try:
        images.delete_serving_url(blob_key)
    except images.BlobKeyRequiredError:
        error = json.dumps({'error': 'Blob key not found.'})
        return json_response(error, 400)
    except images.InvalidBlobKeyError:
        error = json.dumps({'error': 'Blob key invalid.'})
        return json_response(error, 400)
    except images.Error:
        error = json.dumps(
            {'error': 'Some error occured when deleting serving url.'})
        return json_response(error, 400)

    return json_response(json.dumps({'message':
                                     'success delete serving url!'}))
Beispiel #31
0
    def get(self):
        # QUERY user
        user_id = users.get_current_user().user_id()
        query = User.query(User.user == user_id)
        user = query.get()
        for album in user.albums:
            _album = album.get()
            try:
                for photo in _album.photos:
                    # Get first image in each album
                    blob = photo.get().blob_key
                    images.delete_serving_url(blob)
                    break
            except:
                logging.critical("Album link is broken")

        #view_hide_form should reset I think
        logging.critical('HidePhotoHandler')
        self.redirect('/create.html')
Beispiel #32
0
    def post(self):
        ticketNo = int(self.request.headers['ticket'])
        runs = int(self.request.headers['runs'])
        blobInfo = self.get_uploads()[0]

        if ticketNo == 0:       # transient status image
            measure = GetSingletonMeasure()
            if measure.imageBlobURL:
                images.delete_serving_url(measure.imageBlobKey)
            if measure.imageBlobKey:
                blobstore.delete(measure.imageBlobKey)
            measure.imageBlobKey = blobInfo.key()
            measure.imageBlobURL = images.get_serving_url(measure.imageBlobKey)
            measure.put()
            return

        # store the blob key
        if runs == 1:       # single instance data is stored in the delivery data itself
            delivered = GetDeliveryItemForTicket(ticketNo, HYDROID_UNIT_ID)
            if delivered:
                delivered.imageBlobKey = blobInfo.key()
                delivered.imageBlobURL = images.get_serving_url(delivered.imageBlobKey)
                delivered.put()
                DirtyHistoryList()
            else:
                blobInfo.delete()
        else:               # multi data instance
            runid = int(self.request.headers['runid'])
            measureQuery = Measure.query(ancestor=GetHydroidUnitKey(HYDROID_UNIT_ID))\
                .filter(Measure.ticket == ticketNo).filter(Measure.runid == runid)

            # todo: a better way of getting the single result?
            # todo: like this: measure = measureQuery.fetch(1)[0]? but did not work?!!
            measure = None
            for m in measureQuery:
                measure = m

            if measure:
                measure.imageBlobKey = blobInfo.key()
                measure.imageBlobURL = images.get_serving_url(measure.imageBlobKey)
                measure.put()
            else:
                blobInfo.delete()
Beispiel #33
0
    def delete(cls, key):
        activity = key.get() if type(key) is ndb.Key else cls.get_by_id(key)
        if activity:
            # Delete the related images
            for m in activity.media:
                try:
                    # recreate the filename
                    filename = "/%s/%s/%s%s" % (get_application_id(), activity.service_code, m.id, '.jpg')

                    # delete blob serving url
                    delete_serving_url(blobstore.create_gs_key('/gs' + filename))

                    # delete the binary
                    gcs.delete(filename)
                except gcs.NotFoundError:
                    pass

            # Now delete the real activity
            activity.key.delete()
Beispiel #34
0
 def post(self):
     original_url=self.request.headers['Referer']
     stream_name=re.findall('=(.*)%3D%3D',original_url)[0]
     stream=Stream.query(Stream.name==stream_name, Stream.author==users.get_current_user()).fetch()[0]
     dellsts=self.request.get_all("status")
     print dellsts
     pictures=db.GqlQuery("SELECT * FROM Picture " +"WHERE ANCESTOR IS :1 AND imgkey IN :2",db.Key.from_path('Stream',stream_name),dellsts)
     for picture in pictures:
         blobstore.delete(picture.imgkey)
         images.delete_serving_url(picture.imgkey)
     db.delete(pictures)
     pic_count= Count_pic.query(ancestor=ndb.Key('Stream',stream_name)).fetch()[0]
     #  print(pic_counts)
     # for pic_count in pic_counts:
     pic_count.numbers=pic_count.numbers - len(dellsts)
     pic_count.put()
     stream.numberofpictures=pic_count.numbers
     stream.put()
     self.redirect(original_url)
Beispiel #35
0
 def post(self):
     te_id = self.request.get("te_id")
     teacher = ndb.Key(teachme_db.teacher, int(te_id),
                       parent=self.user.key).get()
     profile_pic = self.get_uploads("profile_pic")
     if profile_pic:
         blob_info = profile_pic[0]
         if teacher.profile_pic:
             if teacher.profile_pic_r:
                 images.delete_serving_url(teacher.profile_pic)
             blobstore.delete(teacher.profile_pic)
         teacher.profile_pic = blob_info.key()
         teacher.profile_pic_r = images.get_serving_url(teacher.profile_pic,
                                                        size=200,
                                                        secure_url=True)
         self.user.profile_pic = blob_info.key()
         self.user.profile_pic_r = teacher.profile_pic_r
         teacher.put()
         self.user.put()
     self.redirect("/profile/teacher/%s" % str(teacher.key.id()))
 def _delete_blob(self):
     """Delete blob images and resources."""
     blob_info = blobstore.BlobInfo.get(self.blobkey)
     if blob_info:
         delete_serving_url(blob_info.key())
         blobstore.delete(blob_info.key())
         blob_info.delete()
     if self.resource:
         try:
             gcs.delete(self.resource)
         except gcs.NotFoundError:
             pass
     if self.original:
         try:
             gcs.delete(self.original)
         except gcs.NotFoundError:
             pass
     self.blobkey = None
     self.url = None
     self.width = None
     self.height = None
Beispiel #37
0
def userprofilephotoconfirm():
    member = MemberInfo()

    #this will cause an ugly key error if we don't handle it properly
    try:
      inputUploadedPictureFile = request.files['inputProfilepicture']
      if inputUploadedPictureFile:
        header = inputUploadedPictureFile.headers['Content-Type']
        parsed_header = parse_options_header(header)
        blob_key = parsed_header[1]['blob-key']
    except:
      #no need to log this error output
      dummyvariable = ""

      #a user is uploading a picture, either new if they did not have one prior, or uploaded a new one which would delete the old one
      if inputUploadedPictureFile:
        if member.pictureblobstorekey:
          blobstore.delete(member.pictureblobstorekey)
          images.delete_serving_url(member.pictureblobstorekey)
        member.pictureservingurl = images.get_serving_url(blob_key)
        member.pictureblobstorekey = blob_key
        member.put()

      return render_template('userprofilephotosaved.html', member=member)
    except:
      try:
        #If you couldn't complete the user save, be sure to delete the photo from the blobstore or re-use it later (to avoid a lost child hanging around)
        inputUploadedPictureFile = request.files['inputProfilepicture']
        if inputUploadedPictureFile:
          header = inputUploadedPictureFile.headers['Content-Type']
          parsed_header = parse_options_header(header)
          blob_key = parsed_header[1]['blob-key']
          blobstore.delete(blob_key)
      except:
        #no need to log this error output
        dummyvariable = ""
      #Create a new form POST URL for the blobstore
      userprofilephoto_form_url = blobstore.create_upload_url('/userprofilephotoconfirm')
      return render_template('userprofilephoto.html', member=member, userprofilephoto_form_url=userprofilephoto_form_url, user_profilepicturesrc=user_profilepicturesrc, alertmessage='Oops!', userprofilephoto_form_url=userprofilephoto_form_url, user_profilepicturesrc=user_profilepicturesrc)
Beispiel #38
0
    def get(self):

        user = users.get_current_user()

        #current_url = urlparse(self.request.url)
        #querys = cgi.parse_qs(current_url.query)
        #pid_num = querys.get('pid')

        photo = ndb.Key(urlsafe=self.request.get('pid')).get()

        if not user:
            self.redirect(users.create_login_url())
        elif user != photo.author:
            self.redirect('/Album')
        else:
            blob_key = photo.blob_key
            images.delete_serving_url(blob_key)
            blob_info = blobstore.BlobInfo.get(blob_key)
            blob_info.delete()
            photo.key.delete()

        self.redirect('/Album')
Beispiel #39
0
    def delete(self):
        key = self.request.get('key') or ''
        key = str(urllib.unquote(key))

        s = json.dumps({key: True}, separators=(',', ':'))
        if 'application/json' in self.request.headers.get('Accept'):
            self.response.headers['Content-Type'] = 'application/json'
        self.response.write(s)

        # delete images in blobstore
        images.delete_serving_url(key)
        blobstore.delete(key, rpc=None)

        # delete keys in ndb
        stream_query = Stream.query()
        for stream in stream_query:
            if str(stream.key.id()) == self.request.get('stream'):
                for pic in stream.photos:
                    if pic.blob_key == key:
                        index = stream.photos.index(pic)
                        del stream.photos[index]
                        stream.put()
Beispiel #40
0
    def get(self):

        user = users.get_current_user()

        #current_url = urlparse(self.request.url)
        #querys = cgi.parse_qs(current_url.query)
        #pid_num = querys.get('pid')

        photo = ndb.Key(urlsafe = self.request.get('pid')).get()


        if not user:
            self.redirect(users.create_login_url())
        elif user != photo.author:
            self.redirect('/Album')
        else:
            blob_key = photo.blob_key
            images.delete_serving_url(blob_key)
            blob_info = blobstore.BlobInfo.get(blob_key)
            blob_info.delete()
            photo.key.delete()

        self.redirect('/Album')
Beispiel #41
0
    def _check_and_create(self, thumb_url, img_path, size, crop, bg, quality):
        """ makes async calls to create this thumbnails """
        sidecar_url = thumb_url.split("=s")[0]
        thumb_url = thumb_url.split(".bsurl")[0]
        thumb_pic = self._get_original_img(img_path) # dont have to transform image, gcs does that for use, so just simply store it
        gs_filepath = self._store_thumb(thumb_url, thumb_pic) # store in GCS

        # gs_serving_url: create once (slow), use forever (fast)
        blob_key = blobstore.create_gs_key("/gs" + gs_filepath)
        # get serving url and removes default size & crop modifiers
        serving_url =  gimages.get_serving_url(blob_key) 
        try:
        # delete old serving_url
            with gcs.open(gs_filepath+".bsurl", 'r') as sidecar:
                sidecar.readline() # throw away, is old serving url
                old_blob_key = sidecar.readline().rstrip("\n")
                gimages.delete_serving_url(old_blob_key)
        except gcs.errors.NotFoundError: #wasnt there
            pass
        # save serving_url in sidecare file /path/thumb.ext.bsurl
        with gcs.open(gs_filepath+".bsurl", 'w') as sidecar:
           sidecar.write(serving_url+"\n")
           sidecar.write(blob_key+"\n")
        return
Beispiel #42
0
 def post(self):
     original_url = self.request.headers['Referer']
     stream_name = re.findall('=(.*)%3D%3D', original_url)[0]
     stream = Stream.query(
         Stream.name == stream_name,
         Stream.author == users.get_current_user()).fetch()[0]
     dellsts = self.request.get_all("status")
     print dellsts
     pictures = db.GqlQuery(
         "SELECT * FROM Picture " + "WHERE ANCESTOR IS :1 AND imgkey IN :2",
         db.Key.from_path('Stream', stream_name), dellsts)
     for picture in pictures:
         blobstore.delete(picture.imgkey)
         images.delete_serving_url(picture.imgkey)
     db.delete(pictures)
     pic_count = Count_pic.query(
         ancestor=ndb.Key('Stream', stream_name)).fetch()[0]
     #  print(pic_counts)
     # for pic_count in pic_counts:
     pic_count.numbers = pic_count.numbers - len(dellsts)
     pic_count.put()
     stream.numberofpictures = pic_count.numbers
     stream.put()
     self.redirect(original_url)
Beispiel #43
0
	def post(self):
		try:
			if 'photo_id' not in self.context['request_args'] or self.context['request_args']['photo_id'] == '':
				raise Exception('No photo_id provided')
			
			photo_id = self.context['request_args']['photo_id']
			
			user_photo = photo_module.Photo.get_by_id(long(photo_id))
			logging.info(user_photo.serving_url)
			

			if user_photo is not None and user_photo.blob is not None:
				blob_key = user_photo.blob.key()

				user_photo.blob = None
				user_photo.active = False
				user_photo.save()

				if blob_key is not None:
					deleted_url = images.delete_serving_url(blob_key)
					logging.info('deleted_url')
					logging.info(deleted_url)
					
					deleted_blob = blobstore.delete(blob_key)
					logging.info('deleted_blob')
					logging.info(deleted_blob)

				#db.delete(user_photo)
			
			url = urls.adminPhotos

			self.redirect(url)
		except images.BlobKeyRequiredError, bkr:
			self.set_response_error(bkr, 500)
			logging.exception(bkr)
			raise bkr
Beispiel #44
0
 def get(self, action):
     email_admin = users.get_current_user().email()
     url_logout = users.create_logout_url("/admin")
     text_exit = {"email": email_admin, "url": url_logout}
     userID = users.get_current_user().user_id()
     apps = get_apps()
     if action == "new":
         nav_actual = "pages"
         template_values = {"exit": text_exit, "nav_actual": nav_actual, "apps": apps}
         template_name = "/manager/view/pages_new.html"
         self.renderTemplate(template_name, template_values)
     if action == "view":
         viewpages = cgi.escape(self.request.get("view"))
         if not viewpages:
             categories_array = []
             category = (
                 PageCategory.query(ancestor=site_key())
                 .filter(PageCategory.category_parent == None)
                 .order(PageCategory.name)
             )
             for c in category:
                 if c.name_short != "empty":
                     categories_array.append(
                         {
                             "name": c.name,
                             "key": c.key.urlsafe(),
                             "idcategory": c.idcategory,
                             "date_publication": c.date_publication,
                         }
                     )
             nav_actual = "pages"
             cat_empty = PageCategory.query(PageCategory.name_short == "empty").get()
             pages_in_catgegory = (
                 PagesinCategory.query(ancestor=site_key())
                 .filter(PagesinCategory.category == cat_empty.key)
                 .order(-PagesinCategory.date_publication)
             )
             pages = []
             for p in pages_in_catgegory:
                 page = p.page.get()
                 pages.append(
                     {
                         "title": page.title,
                         "key": page.key.urlsafe(),
                         "idpage": page.idpage,
                         "date_publication": page.date_publication,
                     }
                 )
             token = urllib.quote(CreateXsrfToken("delete"))
             template_values = {
                 "category": categories_array,
                 "exit": text_exit,
                 "nav_actual": nav_actual,
                 "view": "home",
                 "catactual": "Inicio",
                 "pages": pages,
                 "token": token,
                 "apps": apps,
             }
             template_name = "manager/view/pages_view.html"
             self.renderTemplate(template_name, template_values)
             return
         if viewpages == "category":
             keycategory = cgi.escape(self.request.get("key"))
             key = ndb.Key(urlsafe=keycategory)
             viewcategory = key.get()
             categories_array = []
             category = (
                 PageCategory.query(ancestor=site_key())
                 .filter(PageCategory.category_parent == viewcategory.key)
                 .order(PageCategory.name)
             )
             for c in category:
                 if c.name_short != "empty":
                     categories_array.append(
                         {
                             "name": c.name,
                             "key": c.key.urlsafe(),
                             "idcategory": c.idcategory,
                             "date_publication": c.date_publication,
                         }
                     )
             pages_in_catgegory = (
                 PagesinCategory.query(ancestor=site_key())
                 .filter(PagesinCategory.category == viewcategory.key)
                 .order(-PagesinCategory.date_publication)
             )
             pages = []
             for p in pages_in_catgegory:
                 page = p.page.get()
                 pages.append(
                     {
                         "title": page.title,
                         "key": page.key.urlsafe(),
                         "idpage": page.idpage,
                         "date_publication": page.date_publication,
                     }
                 )
             nav_actual = "pages"
             try:
                 parentcategory = viewcategory.category_parent
                 catactual = (
                     '<a href="/admin/page/view">Inicio</a> > <a href="/admin/page/view?key=%s&view=category">%s</a> > %s '
                     % (parentcategory.key(), parentcategory.name, viewcategory.name)
                 )
             except:
                 catactual = '<a href="/admin/page/view">Inicio</a> > ' + viewcategory.name
             token = urllib.quote(CreateXsrfToken("delete"))
             template_values = {
                 "category": categories_array,
                 "pages": pages,
                 "exit": text_exit,
                 "nav_actual": nav_actual,
                 "view": "category",
                 "catactual": viewcategory.name,
                 "token": token,
                 "apps": apps,
             }
             template_name = "manager/view/pages_view.html"
             self.renderTemplate(template_name, template_values)
             return
     if action == "edit":
         token = self.request.get("token")
         nav_actual = "pages"
         html = ""
         page_key = cgi.escape(self.request.get("key"))
         page = ndb.Key(urlsafe=page_key)
         page = page.get()
         categories = (
             PagesinCategory.query(ancestor=site_key())
             .filter(PagesinCategory.page == page.key)
             .order(-PagesinCategory.date_publication)
         )
         htmlcategories = ""
         responsegroups = {}
         categoiresnames = []
         for c in categories:
             category = c.category.get()
             if category.name_short != "empty":
                 htmlcategories += '<a href="#%s" class="categorybtn">%s</a>' % (category.key.id(), category.name)
                 categoiresnames.append({"catid": category.key.id(), "catname": category.name})
         responsegroups.update({"groups": categoiresnames})
         categoryarray = simplejson.dumps(responsegroups)
         template_values = {
             "categories": htmlcategories,
             "categoriesnames": categoryarray,
             "exit": text_exit,
             "nav_actual": nav_actual,
             "page": page,
             "key": page_key,
             "token": urllib.quote(token),
             "apps": apps,
         }
         template_name = "manager/view/pages_edit.html"
         self.renderTemplate(template_name, template_values)
     if action == "delete":
         page_key = cgi.escape(self.request.get("page"))
         token = self.request.get("token")
         if ValidateXsrfToken(token, "delete"):
             page_key = ndb.Key(urlsafe=page_key)
             page = page_key.get()
             page_in_category = PagesinCategory.query(PagesinCategory.page == page.key).get()
             if page.gs_key and page.gs_filename:
                 # blobstore.delete(page.gs_key)
                 images.delete_serving_url(page.gs_key)
                 gcs.delete(page.gs_filename)
             doc_index = search.Index(name=INDEX_PAGES)
             doc_index.delete(page.idpage)
             page.key.delete()
             page_in_category.key.delete()
             self.redirect("/admin/page/new")
         else:
             self.redirect("/admin/page/view")
Beispiel #45
0
 def remove_screenshot_blob(cls, blob_key):
     """Removes screenshot from blobstore 
     and removes serving url associated with it
     """
     images.delete_serving_url(blob_key)
     blobstore.delete(blob_key)
Beispiel #46
0
 def get(self, action):
     email_admin = users.get_current_user().email()
     url_logout = users.create_logout_url("/admin")
     text_exit = {'email': email_admin, 'url': url_logout}
     userID = users.get_current_user().user_id()
     apps = get_apps()
     if action == 'new':
         nav_actual = 'pages'
         template_values = {
             'exit': text_exit,
             'nav_actual': nav_actual,
             'apps': apps
         }
         template_name = '/manager/view/pages_new.html'
         self.renderTemplate(template_name, template_values)
     if action == 'view':
         viewpages = cgi.escape(self.request.get('view'))
         if not viewpages:
             categories_array = []
             category = PageCategory.query(ancestor=site_key()).filter(
                 PageCategory.category_parent == None).order(
                     PageCategory.name)
             for c in category:
                 if c.name_short != 'empty':
                     categories_array.append({
                         'name':
                         c.name,
                         'key':
                         c.key.urlsafe(),
                         'idcategory':
                         c.idcategory,
                         'date_publication':
                         c.date_publication
                     })
             nav_actual = 'pages'
             cat_empty = PageCategory.query(
                 PageCategory.name_short == 'empty').get()
             pages_in_catgegory = PagesinCategory.query(
                 ancestor=site_key()).filter(
                     PagesinCategory.category == cat_empty.key).order(
                         -PagesinCategory.date_publication)
             pages = []
             for p in pages_in_catgegory:
                 page = p.page.get()
                 pages.append({
                     'title': page.title,
                     'key': page.key.urlsafe(),
                     'idpage': page.idpage,
                     'date_publication': page.date_publication
                 })
             token = urllib.quote(CreateXsrfToken('delete'))
             template_values = {
                 'category': categories_array,
                 'exit': text_exit,
                 'nav_actual': nav_actual,
                 'view': 'home',
                 'catactual': 'Inicio',
                 'pages': pages,
                 'token': token,
                 'apps': apps
             }
             template_name = 'manager/view/pages_view.html'
             self.renderTemplate(template_name, template_values)
             return
         if viewpages == 'category':
             keycategory = cgi.escape(self.request.get('key'))
             key = ndb.Key(urlsafe=keycategory)
             viewcategory = key.get()
             categories_array = []
             category = PageCategory.query(ancestor=site_key()).filter(
                 PageCategory.category_parent == viewcategory.key).order(
                     PageCategory.name)
             for c in category:
                 if c.name_short != 'empty':
                     categories_array.append({
                         'name':
                         c.name,
                         'key':
                         c.key.urlsafe(),
                         'idcategory':
                         c.idcategory,
                         'date_publication':
                         c.date_publication
                     })
             pages_in_catgegory = PagesinCategory.query(
                 ancestor=site_key()).filter(
                     PagesinCategory.category == viewcategory.key).order(
                         -PagesinCategory.date_publication)
             pages = []
             for p in pages_in_catgegory:
                 page = p.page.get()
                 pages.append({
                     'title': page.title,
                     'key': page.key.urlsafe(),
                     'idpage': page.idpage,
                     'date_publication': page.date_publication
                 })
             nav_actual = 'pages'
             try:
                 parentcategory = viewcategory.category_parent
                 catactual = '<a href="/admin/page/view">Inicio</a> > <a href="/admin/page/view?key=%s&view=category">%s</a> > %s ' % (
                     parentcategory.key(), parentcategory.name,
                     viewcategory.name)
             except:
                 catactual = '<a href="/admin/page/view">Inicio</a> > ' + viewcategory.name
             token = urllib.quote(CreateXsrfToken('delete'))
             template_values = {
                 'category': categories_array,
                 'pages': pages,
                 'exit': text_exit,
                 'nav_actual': nav_actual,
                 'view': 'category',
                 'catactual': viewcategory.name,
                 'token': token,
                 'apps': apps
             }
             template_name = 'manager/view/pages_view.html'
             self.renderTemplate(template_name, template_values)
             return
     if action == 'edit':
         token = self.request.get('token')
         nav_actual = 'pages'
         html = ''
         page_key = cgi.escape(self.request.get('key'))
         page = ndb.Key(urlsafe=page_key)
         page = page.get()
         categories = PagesinCategory.query(ancestor=site_key()).filter(
             PagesinCategory.page == page.key).order(
                 -PagesinCategory.date_publication)
         htmlcategories = ''
         responsegroups = {}
         categoiresnames = []
         for c in categories:
             category = c.category.get()
             if category.name_short != 'empty':
                 htmlcategories += '<a href="#%s" class="categorybtn">%s</a>' % (
                     category.key.id(), category.name)
                 categoiresnames.append({
                     'catid': category.key.id(),
                     'catname': category.name
                 })
         responsegroups.update({'groups': categoiresnames})
         categoryarray = simplejson.dumps(responsegroups)
         template_values = {
             'categories': htmlcategories,
             'categoriesnames': categoryarray,
             'exit': text_exit,
             'nav_actual': nav_actual,
             'page': page,
             'key': page_key,
             'token': urllib.quote(token),
             'apps': apps
         }
         template_name = 'manager/view/pages_edit.html'
         self.renderTemplate(template_name, template_values)
     if action == 'delete':
         page_key = cgi.escape(self.request.get('page'))
         token = self.request.get('token')
         if ValidateXsrfToken(token, 'delete'):
             page_key = ndb.Key(urlsafe=page_key)
             page = page_key.get()
             page_in_category = PagesinCategory.query(
                 PagesinCategory.page == page.key).get()
             if page.gs_key and page.gs_filename:
                 # blobstore.delete(page.gs_key)
                 images.delete_serving_url(page.gs_key)
                 gcs.delete(page.gs_filename)
             doc_index = search.Index(name=INDEX_PAGES)
             doc_index.delete(page.idpage)
             page.key.delete()
             page_in_category.key.delete()
             self.redirect('/admin/page/new')
         else:
             self.redirect('/admin/page/view')
Beispiel #47
0
 def remove_screenshot_blob(cls, blob_key):
     """Removes screenshot from blobstore 
     and removes serving url associated with it
     """
     images.delete_serving_url(blob_key)
     blobstore.delete(blob_key)
def remove_from_gcs(blob_key):
    blobstore.delete(blob_key)
    images.delete_serving_url(blob_key)
Beispiel #49
0
    def get(self):
        print("test!!")
        dellsts = self.request.get_all("status")
        if (len(dellsts) > 0):
            streams = Stream.query(
                Stream.name.IN(dellsts),
                Stream.author == users.get_current_user()).fetch()
            counts = CountViews.query(
                CountViews.name.IN(dellsts),
                ancestor=ndb.Key('User',
                                 users.get_current_user().nickname())).fetch()
            for stream in streams:
                pictures = db.GqlQuery(
                    "SELECT * FROM Picture " + "WHERE ANCESTOR IS :1",
                    db.Key.from_path('Stream', stream.name))
                for pic in pictures:
                    images.delete_serving_url(pic.imgkey)
                    blobstore.delete(pic.imgkey)
                db.delete(pictures)
                pic_count = Count_pic.query(
                    ancestor=ndb.Key('Stream', stream.name))
                ndb.delete_multi(ndb.put_multi(pic_count))
                #print pic_count
            ndb.delete_multi(ndb.put_multi(streams))
            ndb.delete_multi(ndb.put_multi(counts))
        dellsts = self.request.get_all("status1")
        #self.response.write(len(dellsts))
        if (len(dellsts) > 0):
            streams = Stream.query(Stream.name.IN(dellsts)).fetch()
            for stream in streams:
                if (users.get_current_user()
                        and users.get_current_user().nickname()
                        in stream.subscribers):
                    stream.subscribers.remove(
                        users.get_current_user().nickname())
                    stream.put()

        picNum_list = []
        streams_1 = Stream.query(Stream.author == users.get_current_user()
                                 ).order(-Stream.creattime).fetch()
        for stream in streams_1:
            pic_count = Count_pic.query(
                ancestor=ndb.Key('Stream', stream.name)).fetch()[0]
            pictures = db.GqlQuery(
                "SELECT * FROM Picture " + "WHERE ANCESTOR IS :1 " +
                "ORDER BY uploaddate DESC",
                db.Key.from_path('Stream', stream.name))
            # print (stream.name, pic_count.numbers)
            # picNum_list.append(pic_count.numbers)
            picNum_list.append(pictures.count())
        streams = Stream.query().fetch()
        streams_2 = []
        count_list = []
        user_name = users.get_current_user().nickname()
        # url =users.create_login_url('/')
        #  if(users.get_current_user()):
        #user_name = users.get_current_user().nickname()
        url = users.create_logout_url('/')
        for stream in streams:
            if (users.get_current_user().email() in stream.subscribers):
                count = CountViews.query(CountViews.name == stream.name,
                                         ancestor=ndb.Key(
                                             'User',
                                             stream.author_name)).fetch()[0]
                pictures = db.GqlQuery(
                    "SELECT * FROM Picture " + "WHERE ANCESTOR IS :1 " +
                    "ORDER BY uploaddate DESC",
                    db.Key.from_path('Stream', stream.name))

                stream.numberofpictures = pictures.count()
                streams_2.append(stream)
                count_list.append(count.numbers)

        #else:
        #   self.redirect(url,permanent=False)

        template_values = {
            'user_name': user_name,
            'streams_1': streams_1,
            'streams_2': streams_2,
            'count_list': count_list,
            'url': url,
            "picNum_list": picNum_list
        }

        template = JINJA_ENVIRONMENT.get_template('management_index.html')
        self.response.write(template.render(template_values))
Beispiel #50
0
def delete_blob(blob_key):
    images.delete_serving_url(blob_key)#delete serving url
    blb = blobstore.BlobInfo.get(blob_key)#delete blob info which deletes blob
    if blb:
        blb.delete()#delete blob info which deletes blob
Beispiel #51
0
 def _remove_portrait(self):
     images.delete_serving_url(self.portrait)
     blobstore.delete(self.portrait)
     self.portrait = None
Beispiel #52
0
 def _remove_portrait(self):
     images.delete_serving_url(self.portrait)
     blobstore.delete(self.portrait)
     self.portrait = None
 def delete(self, stored_image):
   images.delete_serving_url(stored_image.image_blob.key())
   stored_image.image_blob.delete()
   stored_image.delete()
   self._json('OK')
Beispiel #54
0
    def get(self):
        print("test!!")
        dellsts=self.request.get_all("status")
        if (len(dellsts) > 0):
            streams=Stream.query(Stream.name.IN(dellsts), Stream.author==users.get_current_user()).fetch()
            counts=CountViews.query(CountViews.name.IN(dellsts), ancestor=ndb.Key('User', users.get_current_user().nickname())).fetch()
            for stream in streams:
                pictures=db.GqlQuery("SELECT * FROM Picture " +"WHERE ANCESTOR IS :1",db.Key.from_path('Stream',stream.name))
                for pic in pictures:
                    images.delete_serving_url(pic.imgkey)
                    blobstore.delete(pic.imgkey)
                db.delete(pictures)
                pic_count= Count_pic.query(ancestor=ndb.Key('Stream',stream.name))
                ndb.delete_multi(ndb.put_multi(pic_count))
                #print pic_count
            ndb.delete_multi(ndb.put_multi(streams))
            ndb.delete_multi(ndb.put_multi(counts))
        dellsts=self.request.get_all("status1")
        #self.response.write(len(dellsts))
        if (len(dellsts) > 0):
            streams=Stream.query(Stream.name.IN(dellsts)).fetch()
            for stream in streams:
                if(users.get_current_user() and users.get_current_user().nickname() in stream.subscribers):
                    stream.subscribers.remove(users.get_current_user().nickname())
                    stream.put()



        picNum_list = []
        streams_1=Stream.query(Stream.author==users.get_current_user()).order(-Stream.creattime).fetch()
        for stream in streams_1:
           pic_count= Count_pic.query(ancestor=ndb.Key('Stream',stream.name)).fetch()[0]
           pictures=db.GqlQuery("SELECT * FROM Picture " +"WHERE ANCESTOR IS :1 "+"ORDER BY uploaddate DESC",db.Key.from_path('Stream',stream.name))
          # print (stream.name, pic_count.numbers)
          # picNum_list.append(pic_count.numbers)
           picNum_list.append(pictures.count())
        streams = Stream.query().fetch()
        streams_2 = []
        count_list = []
        user_name = users.get_current_user().nickname()
       # url =users.create_login_url('/')
      #  if(users.get_current_user()):
            #user_name = users.get_current_user().nickname()
        url = users.create_logout_url('/')
        for stream in streams:
            if(users.get_current_user().email().lower() in stream.subscribers):
                count=CountViews.query(CountViews.name==stream.name,ancestor=ndb.Key('User',stream.author_name)).fetch()[0]
                pictures=db.GqlQuery("SELECT * FROM Picture " +"WHERE ANCESTOR IS :1 "+"ORDER BY uploaddate DESC",db.Key.from_path('Stream',stream.name))

                stream.numberofpictures = pictures.count()
                streams_2.append(stream)
                count_list.append(count.numbers)

        #else:
         #   self.redirect(url,permanent=False)

        template_values = {
                'user_name':user_name,
                'streams_1': streams_1,
                'streams_2': streams_2,
                'count_list': count_list,
                'url': url,
            "picNum_list":picNum_list
        }

        template = JINJA_ENVIRONMENT.get_template('management_index.html')
        self.response.write(template.render(template_values))
Beispiel #55
0
def delete_image(blob_key):
    if blob_key:
        images.delete_serving_url(blob_key)
        blobstore.delete(blob_key)
Beispiel #56
0
def delete_from_gcs(gcs_filename):
    if gcs_filename:
        images.delete_serving_url(blobstore.create_gs_key(gcs_filename))
        gcs.delete(gcs_filename[3:])
Beispiel #57
0
 def delete(self, stored_image):
     images.delete_serving_url(stored_image.image_blob.key())
     stored_image.image_blob.delete()
     stored_image.delete()
     self._json('OK')
Beispiel #58
0
def delete_from_gcs(gcs_filename):
    if gcs_filename:
        images.delete_serving_url(blobstore.create_gs_key(gcs_filename))
        gcs.delete(gcs_filename[3:])