Ejemplo n.º 1
0
def calc_image_size(width,
                    height,
                    ratio,
                    resize_width=WIDTH,
                    resize_height=HEIGHT):
    """  
    given height, width and ration: resize image 
    width, height and known image ratio, resize 
    width and height to fixed dimensions.
    """
    # image need to be resized?
    if resize_width < width and resize_height < height:

        # image is wider than higher
        if width > height:
            w = resize_width  #WIDTH
            h = int(w / ratio)

        # image is taller than wider
        elif width < height:
            w = resize_height  #HEIGHT
            h = int(w / ratio)

        # image is square
        else:
            w = int(height * ratio)
            h = int(width * ratio)
    else:
        w = int(width)
        h = int(height)

    msg("setting image w<{}> h<{}> r<{}>".format(w, h, ratio))

    return (w, h)
Ejemplo n.º 2
0
def pil_detail(fp, fn):
    fpn = os.path.join(fp, fn)
    try:
        i = Image.open(fpn)
    except IOError:
        print("Unable to load image to find information")
        sys.exit(1)
    msg("<{}>\n\tformat({}) size({}) mode:({})".format(fn, i.format, i.size,
                                                       i.mode))
Ejemplo n.º 3
0
def pil_image_ratio(fp, fn):
    """find image ratio given image"""
    height = 0
    width = 0

    height, width = pil_get_wh(fp, fn)

    ratio = width / height
    msg("ratio <{}>".format(ration))

    return ratio
Ejemplo n.º 4
0
def getMsg(request):
    if not request.user.has_perm('webview.view_notifs'):
        raise PermissionDenied
    # Used by the notification refresh button.  gets a list of pending notifications and writes them of as read if not sticky.
    msgs = UIMsg.objects.filter(
        group__name__in=request.user.groups.all().values_list(
            'name', flat=True)).exclude(user__username=request.user.username)
    for mymsg in msgs:
        msg(request, mymsg.level, mymsg.msg)
        if not mymsg.sticky:
            mymsg.user.add(request.user)
            mymsg.save()
    return render(request, 'widgets/msg.html')
Ejemplo n.º 5
0
def process_video(sfp, dfp, sfn, dfn):
    """process all the videos"""
    # move the file (we still want to use it)
    sfpn = os.path.join(sfp, sfn)
    dfpn = os.path.join(dfp, dfn)
    msg("move <{}> to <{}>".format(sfpn, dfpn))

    try:
        copyfile(sfpn, dfpn)
    except IOError:
        print("Error: unable to move video file")
        print("\tfilename  <{}>".format(sfn))
        print("\tsource fp <{}>".format(sfp))
        print("\tdest   fp <{}>".format(dfp))
        print("\tsfpn <{}>".format(sfpn))
        print("\tdfpn <{}>".format(dfpn))

        sys.exit(1)

    return True
Ejemplo n.º 6
0
def pil_get_wh(fp, fn):
    """extract image height and width using PIL"""
    fpn = os.path.join(fp, fn)
    if os.path.isfile(fpn):
        h = 0
        w = 0
        try:
            i = Image.open(fpn)
            (w, h) = (i.width, i.height)
        except IOError:
            msg("Warning: cannot determine image height and width")
            msg("Warning: problems with file <>".format(fpn))
    else:
        msg("Warning: could not find file <>".format(fpn))
    return [w, h]
Ejemplo n.º 7
0
def index(request, view):
    """
    Display the main page.

    **Context**

    ``Widgets``
        List of widgets for the user's view

    **Template:**

    Loaded from the DB

    :template:`webview/index.html`
    """
    global slalist
    data = []
    view = view[5:]
    # Get the list of hosts so that we can loop through them and create the rows
    if view == '':
        # load hosts from the default view
        hosts = sorted(set(
            UserView.objects.filter(
                group__name__in=request.user.groups.all().values_list(
                    'name', flat=True),
                default=True)[0].widgets.filter(
                    active=True, host__enabled=True).values_list(
                        'host__name', flat=True).order_by('-name')),
                       reverse=True)
    else:
        # load hosts from the view specified in the url
        hosts = sorted(set(
            UserView.objects.get(name=view).widgets.filter(
                active=True,
                host__enabled=True).values_list('host__name',
                                                flat=True).order_by('-name')),
                       reverse=True)
    for host in hosts:
        # For each host, we will get generate the widgets in it's row
        thishost = {}
        wdgts = []
        if view == '':
            # load this host's widgets from the default userview
            uv = UserView.objects.filter(
                group__name__in=request.user.groups.all().values_list(
                    'name', flat=True),
                default=True)[0].widgets.filter(host__name=host, active=True)
        else:
            # load this host's widgets from the view specified in the url
            uv = UserView.objects.get(name=view).widgets.filter(
                host__name=host, active=True)
        for widget in uv:
            thisdata = {
                'name': widget.name,
                'note': widget.note,
                'data': widget.renderWidget(user=request.user)
            }
            wdgts.append(thisdata)
        thishost['widgets'] = wdgts
        thishost['name'] = host
        thishost['note'] = Hosts.objects.get(name=host).note
        data.append(thishost)
        # Preloads the sla widget with any SLAs relating to the user's group.
    sla = None
    slalist = None
    if request.user.has_perm('webview.view_sla'):
        sla = Sla.objects.filter(
            Q(enabled=True,
              warngroups__name__in=request.user.groups.all().values_list(
                  'name', flat=True))
            | Q(enabled=True,
                okgroups__name__in=request.user.groups.all().values_list(
                    'name', flat=True))
            | Q(enabled=True,
                critgroups__name__in=request.user.groups.all().values_list(
                    'name', flat=True))).distinct()
    if request.user.has_perm('webview.view_thresholdlog'
                             ) or request.user.has_perm('webview.view_slalog'):
        slalist = sla.values_list('name', flat=True)
    eventlog = None
    if request.user.has_perm('webview.view_thresholdlog'):
        # Need to figure out if this is useful or not.  Currently, we log all threshold success, making this worthless
        eventlog = EventLog.objects.filter(
            sla__name__in=slalist).order_by('-timestamp')[:10]
    slalog = None
    if request.user.has_perm('webview.view_slalog'):
        # Preloads the slalog widget with any SLAs relating to the user's group.
        slalog = SlaLog.objects.filter(
            sla__name__in=slalist).order_by('-timestamp')[:10]
    trap = None
    if request.user.has_perm('webview.view_traps'):
        now = timezone.now()
        onehour = now - datetime.timedelta(hours=24)
        trap = Trap.objects.filter(timestamp__gt=onehour)
    # Load the list of available userviews for the logged in user
    uvlist = UserView.objects.filter(
        group__name__in=request.user.groups.all().values_list('name',
                                                              flat=True))
    context = {
        'data': data,
        'eventlog': eventlog,
        'slas': sla,
        'slalog': slalog,
        'uvlist': uvlist,
        'taskdelay': getMetadata('taskdelay-1'),
        'trap': trap
    }
    # Load pending message for that user from the database and push them to the UI using the message framework.
    if request.user.has_perm('webview.view_notifs'):
        msgs = UIMsg.objects.filter(group__name__in=request.user.groups.all(
        ).values_list('name', flat=True)).exclude(
            user__username=request.user.username)[:100]
        for mymsg in msgs:
            msg(request, mymsg.level, mymsg.msg)
            if not mymsg.sticky:
                # by adding the user to the m2m field, this msg will get skipped at next collection. see above query
                mymsg.user.add(request.user)
                mymsg.save()
    return render(request, 'index.html', context)
Ejemplo n.º 8
0
def pil_resize(sfp, dfp, sfn, dfn, ext):
    msg("pil_resize")
    msg("source fp <{}>".format(sfp))
    msg("dest   fp <{}>".format(dfp))

    # source filepath and nasrc_fp,me:
    sfpn = os.path.join(sfp, sfn)
    msg("1. sfpn <{}>".format(sfpn))
    msg("    sfp <{}>".format(sfp))
    msg("    sfn <{}>".format(sfn))

    # valid source filepath name?
    if not os.path.isfile(sfpn):
        print("\n")
        print("Error: cannot find specificed file <>".format(sfpn))
        print("")
        sys.exit(1)
    msg("2. src <{}>".format(sfpn))

    # destination filepath and name
    # fail if you cannot find destination
    # directory. Best not spew files all
    # over the place when most likely the
    # error is operator on CLI.
    dfpn = os.path.join(dfp, dfn)
    msg("3. dest <{}>".format(dfpn))
    if not os.path.isdir(dfp):
        print("\n")
        print("Error: destination file directory not found <{}>".format(dfp))
        print("Error: cannot save file <{}>".format(dfpn))
        print("")
        sys.exit(1)

    msg("4. open <{}>".format(sfpn))
    try:
        # original image
        i = Image.open(fp=sfpn)
        msg("height <{}>".format(i.height))
        msg("width  <{}>".format(i.width))

        # find image ratio
        #r = c_image_ratio_hw(i.height, i.width)
        r = image_ratio(i.width, i.height)
        msg("ratio <{}>".format(r))

        # set new image width and height f
        w, h = calc_image_size(i.width, i.height, r)
        msg("w ({}) h ({})".format(w, h))

        msg("5. resize image")
        ir = i.resize((w, h))

        msg("6. save image by TYPE")
        msg("dfpn <{}>".format(dfpn))
        msg("ext <{}>".format(ext))

        ir.save(dfpn)

        i = None
        ir = None

    except IOError:
        # we haven't found a way to process this
        # file, skip but still WARN? -- Na kill
        print("\n")
        print("Warning: unable to resize image")
        print("Warning: unable to move image file at the moment")
        print("\tfilename  <{}>".format(sfn))
        print("\tsource fp <{}>".format(sfp))
        print("\tdest   fp <{}>".format(dfp))
        print("")
        sys.exit(1)

    return True
Ejemplo n.º 9
0
def process(afiles, dfp):
    msg("process")
    if len(afiles) > 0:
        # loop through the list of files
        msg("processing")

        afs = sorted(afiles)
        for sfpn in afs:
            msg("sfpn <{}>".format(sfpn))

            # extract filepath and filename
            sfp, sfn = filepath2title(sfpn)
            msg("source filepath <{}>".format(sfp))
            msg("source filename <{}>".format(sfn))

            if sfn:
                isf = os.path.isfile(sfpn)
                msg("file exist: <{}> is {}".format(sfpn, isf))

                # process file depending on file extension
                # if supported, process otherwise flag and
                # continue.
                if os.path.isfile(sfpn):
                    # process the files one by one
                    if is_file_jpg(sfn):

                        print('>', end='', flush=True)
                        dfn = dt_build_fn_jpg()
                        process_image(sfp, dfp, sfn, dfn, IMG_JPG)
                    elif is_file_png(sfn):

                        print('<', end='', flush=True)
                        dfn = dt_build_fn_png()
                        process_image(sfp, dfp, sfn, dfn, IMG_PNG)
                    elif is_file_video(sfn):

                        print('|', end='', flush=True)
                        dfn = dt_build_fn(ext=VID_M4V)
                        process_video(sfp, dfp, sfn, dfn)
                    else:
                        msg("Warning: file not processed")
                        msg("source filename <{}>".format(sfn))
                        print("?")

                else:
                    print("warning: the source file is not found")
                    print("         <{}>".format(sfn))
                    pass
            else:
                break
        print("")

        return True
    else:
        # load all files found
        return False
Ejemplo n.º 10
0
def is_file_ext(fn, ext):
    fn = fn.lower()
    e = get_file_ext(fn)
    msg("fn=<{}> ext=<{}> ({})".format(fn, e, (e == ext)))
    return (e == ext)
Ejemplo n.º 11
0
def main():
    """cli entry point"""
    usage = "usage: %prog -i -o [-s]"
    parser = OptionParser(usage)

    #------ in/out ------
    parser.add_option("-i",
                      "--input",
                      dest="input",
                      help="input source directory")
    parser.add_option("-o",
                      "--output",
                      dest="output",
                      help="output source directory"),
    parser.add_option("-j",
                      "--jpg",
                      dest="jpg",
                      action="store_true",
                      help="process only jpg files")
    parser.add_option("-p",
                      "--png",
                      dest="png",
                      action="store_true",
                      help="process only png files")

    #------ options ------
    options, args = parser.parse_args()

    #------ process ------
    if options.input:
        # input directory must exist
        if not os.path.isdir(options.input):
            print("Error:   processing input files has failed")
            print("Warning: <{}> is ({})".format(options.input,
                                                 os.path.isdir(options.input)))
            print("")
            sys.exit(1)
        else:
            msg("source: <{}> is dir {}".format(options.input,
                                                os.path.isdir(options.input)))

        # only load 'jpg' images
        if options.jpg:
            afiles = get_fn_jpg(options.input)

        # only load 'png' images
        elif options.png:
            afiles = get_fn_png(options.input)

        # load all the files, skip the ones we can't work with
        else:
            afiles = get_filenames(options.input)
        msg("files {}".format(afiles))

        # where do the processed files go?
        dest_fp = ""
        if options.output:
            if os.path.isdir(options.output):
                dest_fp = options.output
            else:
                print("Warning: Trying to save files to an invalid directory")
                print("         I suggest manually creating the directory")
                print("")
                sys.exit(1)
        else:
            print("Error: Destination path must be supplied")
            print("")
            sys.exit(1)

        # process the files
        if process(afiles, dest_fp):
            msg("destination: ({}) <{}>".format(len(afiles), afiles))
        else:
            print("Error:   processing files has failed")
            print("Warning: <{}> is ({})".format(dest_fp,
                                                 os.path.isdir(dest_fp)))
            print("")
            sys.exit(1)
Ejemplo n.º 12
0
def process_image(sfp, dfp, sfn, dfn, ext):
    msg("sr_fp {}".format(sfp))
    msg("dest_fp {}".format(dfp))
    msg("s_fn {}".format(sfn))
    msg("d_fn {}".format(dfn))

    # resize or fail
    # TODO: Why is this happening
    if not pil_resize(sfp, dfp, sfn, dfn, ext):
        sfpn = os.path.join(sfp, sfn)
        dfpn = os.path.join(dfp, dfn)
        msg("warning: image <{}> cannot be resized".format(sfpn))
        msg("move <{}> to <{}>".format(sfpn, dfpn))
        copyfile(sfpn, dfpn)
        #sys.exit(1)

        return False
    else:
        return True