예제 #1
0
def handle_file(u: Profile, headline: str, category: str, text: str, file):
    m: Media = Media()
    upload_base_path: str = 'uploads/' + str(date.today().year)
    high_res_file_name = upload_base_path + '/HIGHRES_' + ntpath.basename(
        file.name.replace(" ", "_"))
    low_res_file_name = upload_base_path + '/LOWRES_' + ntpath.basename(
        file.name.replace(" ", "_"))
    if not os.path.exists(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path):
        os.makedirs(PATH_TO_UPLOAD_FOLDER_ON_DISK + upload_base_path)
    with open(high_res_file_name, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)
    # TODO crop image
    original = Image.open(high_res_file_name)
    width, height = original.size
    diameter = math.sqrt(math.pow(width, 2) + math.pow(height, 2))
    width /= diameter
    height /= diameter
    width *= IMAGE_SCALE
    height *= IMAGE_SCALE
    cropped = original.resize((int(width), int(height)), PIL.Image.LANCZOS)
    cropped.save(low_res_file_name)
    m.text = escape(text)
    m.cachedText = compile_markdown(escape(text))
    m.category = escape(category)
    m.highResFile = "/" + high_res_file_name
    m.lowResFile = "/" + low_res_file_name
    m.headline = escape(headline)
    m.save()
    mu: MediaUpload = MediaUpload()
    mu.UID = u
    mu.MID = m
    mu.save()
    logging.info("Uploaded file '" + str(file.name) +
                 "' and cropped it. The resulting PK is " + str(m.pk))
예제 #2
0
def add_article_to_group(grpid: int, size: str, arttyp: int, user: Profile):
    grp: ArticleGroup = ArticleGroup.objects.get(id=grpid)
    a: Article = Article()
    a.underConstruction = True
    a.group = grp
    a.description = grp.group_name
    a.visible = False
    a.price = "0000"
    a.largeText = "# This group hasn't been updated yet.\nPlease update matrix of group N° " \
            + str(grpid) + "\n<!-- DEFAULT NOIMP TEXT -->"
    a.cachedText = compile_markdown(a.largeText)
    a.type = arttyp
    a.quantity = 0
    a.size = size
    a.addedByUser = user
    a.chestsize = 0
    a.save()
예제 #3
0
 def test_image_upload(self):
     # since pillow runs unit tests as well we'll simply check for the existance of the images
     p: Profile = Profile.objects.all()[0]
     f = open(self.test_image_path, 'rb')
     img = SimpleUploadedFile(f.name, f.read(), content_type="image/jpg")
     media_actions.handle_file(
         p, "A Test image headline", "Silly Test Images",
         "This is a more detailed description of a CC test image", img)
     assumed_path_hr = "uploads/" + str(
         date.today().year) + "/HIGHRES_cc-test-image.jpg"
     assumed_path_lr = "uploads/" + str(
         date.today().year) + "/LOWRES_cc-test-image.jpg"
     self.assertTrue(os.path.isfile(assumed_path_hr))
     self.assertTrue(os.path.isfile(assumed_path_lr))
     self.assertTrue(
         os.path.getsize(assumed_path_hr) > os.path.getsize(assumed_path_lr)
     )
     med_obj: Media = Media.objects.all()[0]
     self.assertEquals(med_obj.headline, "A Test image headline")
     self.assertEquals(med_obj.category, "Silly Test Images")
     self.assertEquals(
         med_obj.text,
         "This is a more detailed description of a CC test image")
     self.assertEquals(
         med_obj.cachedText,
         compile_markdown(
             "This is a more detailed description of a CC test image"))
     self.assertEquals(med_obj.lowResFile, "/" + assumed_path_lr)
     self.assertEquals(med_obj.highResFile, "/" + assumed_path_hr)
     self.assertEquals(MediaUpload.objects.get(MID=med_obj).UID, p)
     # Clean up FS
     os.remove(assumed_path_lr)
     os.remove(assumed_path_hr)
     if not os.listdir("uploads/" + str(date.today().year)):
         os.rmdir("uploads/" + str(date.today().year))
     if not os.listdir("uploads"):
         os.rmdir("uploads")
     pass
예제 #4
0
def action_save_article(request: HttpRequest):
    """
    This function creates a new or saves an article based on the
    (hopefully) provided POST data elements:
        * price in cents
        * largetext as a markdown text
        * type as a number between 0 and 3 (both inclusive)
        * description a normal text containing the short description
        * visible a bool str if the article should be visible yet
        * quantity the amount of the current aviable pieces
        * size the size of the article (10 char text)
        * [id] (GET) the ID of the article to edit (if non is provided
            it will be assumed that it is a new article)
    The user who added the article will be automatically determined.
    The flashImage will be handled by set action_set_image(request)
    If the article to be saved is a newly generated one the function
    will redirect the user to the flash image selection dialog or
    otherwise will redirect the user to the articles page.
    :param request The current HttpRequest
    :return The crafted response
    """
    try:
        price = request.POST["price"]
        largetext = request.POST["largetext"]
        article_type = request.POST["type"]
        description = request.POST["description"]
        visible = parse_bool(request.POST["visible"])
        quantity = int(request.POST["quantity"])
        size = request.POST["size"]
        chestsize: int = request.POST["chestsize"]
        userp: Profile = get_current_user(request)
        aid = -1  # This means that it's a new article
        a: Article = None
        if request.GET.get("id"):
            aid = int(request.GET["id"])
            a = Article.objects.get(pk=aid)
        else:
            a = Article()
        a.price = str(price)
        a.largeText = str(largetext)
        a.cachedText = compile_markdown(largetext)
        a.type = int(article_type)
        a.description = str(description)
        a.visible = visible
        a.quantity = int(quantity)
        a.size = str(size)
        a.chestsize = chestsize
        a.addedByUser = userp
        a.save()
        if aid < 0:
            logger.info("User '" + userp.displayName +
                        "' created a new article (UID: " + str(userp.pk) + ")")
            return redirect(
                "/admin/media/select?action_url=/admin/actions/add-image-to-article&payload="
                + str(a.id))
        else:
            logger.info("User '" + userp.displayName +
                        "' modified an article (UID: " + str(userp.pk) +
                        " AID: " + str(aid) + ")")
            return redirect("/admin/articles")
    except Exception as e:
        logger.exception(e)
        return redirect('/admin/?error=' + str(e))
예제 #5
0
 def test_markdown_generation(self):
     # Only test this thing not throwing exceptions
     self.assertEquals(compile_markdown("# Test MD"),
                       '<h1 id="test-md">Test MD</h1>')