コード例 #1
0
ファイル: profile.py プロジェクト: colinbdclark/OER-Commons
def avatar_update(request):
    response = dict(status="error", message=u"")

    form = AvatarForm(request.POST, request.FILES)

    if form.is_valid():
        user = request.user
        profile = Profile.objects.get_or_create(user=user)[0]
        if profile.avatar:
            delete(profile.avatar)
        avatar = form.cleaned_data["file"]
        if avatar.content_type == "image/jpeg":
            extension = ".jpg"
        elif avatar.content_type == "image/png":
            extension = ".png"
        elif avatar.content_type == "image/gif":
            extension = ".gif"
        else:
            extension = ""
        filename = "%i%s" % (user.id, extension)
        profile.avatar.save(filename, avatar, save=False)
        profile.hide_avatar = False
        profile.save()

        response["status"] = "success"
        response["message"] = u"Your picture is saved."
        response["url"] = profile.get_avatar_url() + "?" + str(int(time.time()))

    else:
        response["message"] = form.errors["file"][0]

    # We don't use application/json content type here because IE misinterprets it.
    return HttpResponse(json.dumps(response))
コード例 #2
0
ファイル: tasks.py プロジェクト: colinbdclark/OER-Commons
def update_screenshot(item, force=False):

    api_key = getattr(settings, "URL2PNG_KEY", None)
    api_secret = getattr(settings, "URL2PNG_SECRET", None)
    if not api_key or not api_secret:
        screenshot_logger.warning(u"Either URL2PNG_KEY or URL2PNG_SECRET is missing. Can't fetch screenshot.")
        return

    url = item.url

    url = url.strip()
    url = urllib.quote(url, safe="%/:=&?~#+!$,;'@()*[]")
    if not url:
        return

    if item.http_status != 200:
        screenshot_logger.warning(u"Skipping '%s'. HTTP status is not 200." % item.url)
        return

    if item.screenshot and not force:
        screenshot_logger.warning(u"Skipping '%s'. Screenshot exists already." % item.url)
        return

    url_hash = md5_constructor(smart_str(url)).hexdigest()
    filename = "%s-%i-%s.png" % (item._meta.object_name.lower(), item.id, url_hash)
    filename = os.path.join(item.screenshot.field.get_directory_name(), filename)

    # Remove existing screenshot
    if item.screenshot:
        try:
            delete(item.screenshot)
        except OSError:
            pass
        update_item(item, screenshot=None)

    full_path = os.path.join(settings.MEDIA_ROOT, filename)
    dirname = os.path.dirname(full_path)
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    bounds = "1000x1000"
    token = md5_constructor("%s+%s" % (api_secret, url)).hexdigest()
    screenshot_url = "http://api.url2png.com/v3/%s/%s/%s/%s" % (api_key, token, bounds, url)

    try:
        response = urllib2.urlopen(screenshot_url, timeout=120)
    except:
        screenshot_logger.error(u"Failed to fetch screenshot for '%s': %s %s" % (url, sys.exc_info()[0], sys.exc_info()[1]))
        return

    f = open(full_path, "w+")
    f.write(response.read())
    f.close()
    update_item(item, screenshot=filename)
    screenshot_logger.info(u"Fetched screenshot for '%s'" % url)
コード例 #3
0
ファイル: profile.py プロジェクト: colinbdclark/OER-Commons
def avatar_delete(request):
    response = dict(status="error", message=u"")

    user = request.user
    profile = Profile.objects.get_or_create(user=user)[0]
    if profile.avatar:
        delete(profile.avatar)
    profile.hide_avatar = True
    profile.save()

    response["status"] = "success"
    response["message"] = u"Your picture is deleted."
    response["url"] = profile.get_avatar_url()
    return response
コード例 #4
0
ファイル: tasks.py プロジェクト: pombredanne/OER-Commons
def update_screenshot(item):
    url = item.url

    url = url.strip()
    url = urllib.quote(url, safe="%/:=&?~#+!$,;'@()*[]")
    if not url:
        return

    if item.http_status != 200:
        if item.screenshot:
            delete(item.screenshot)
            update_item(item, screenshot=None)
        return

    url_hash = md5_constructor(smart_str(url)).hexdigest()
    filename = "%s-%i-%s.png" % (item._meta.object_name.lower(), item.id, url_hash)
    filename = os.path.join(item.screenshot.field.get_directory_name(), filename)

    # Remove existing screenshot
    if item.screenshot:
        try:
            delete(item.screenshot)
        except OSError:
            pass
        update_item(item, screenshot=None)

    full_path = os.path.join(settings.MEDIA_ROOT, filename)
    dirname = os.path.dirname(full_path)
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    width = 1024
    height = 768

    executable = settings.WEBKIT2PNG_EXECUTABLE % dict(
        filename=full_path, url='"%s"' % url.replace('"', '\\"'), width=width, height=height
    )
    if isinstance(executable, unicode):
        executable = executable.encode(sys.getfilesystemencoding())
    args = shlex.split(executable)

    @timeout(timeout_duration=60 * 2)
    def fetch_screenshot(args):
        p = subprocess.Popen(args)
        try:
            p.wait()
            return 1
        except TimeoutError:
            p.kill()
            raise
        finally:
            try:
                p.terminate()
            except OSError:
                pass
        return None

    result = fetch_screenshot(args)
    if result:
        if os.path.exists(full_path):
            update_item(item, screenshot=filename)
    else:
        update_item(item, screenshot=None)