Ejemplo n.º 1
0
    def delete(self, *args, **kwargs):
        #first remove directory, then delete from db:
        import shutil, os
        path = self.get_abs_directory_path()
        if os.path.exists(path):
            dest = '%s/deleted/%s' % (settings.STATIC_ROOT, self.uuid)
            if os.path.exists(dest):
                from localground.lib import generic
                dest = dest + '.dup.' + generic.generateID()
            shutil.move(path, dest)

        super(Print, self).delete(*args, **kwargs)
Ejemplo n.º 2
0
 def delete(self, *args, **kwargs):
     #first remove directory, then delete from db:
     import shutil, os
     path = self.get_abs_directory_path()
     if os.path.exists(path):
         dest = '%s/deleted/%s' % (settings.STATIC_ROOT, self.uuid)
         if os.path.exists(dest):
             from localground.lib import generic
             dest = dest + '.dup.' + generic.generateID()
         shutil.move(path, dest)
                 
     super(Scan, self).delete(*args, **kwargs) 
Ejemplo n.º 3
0
 def save_upload(self, file, user, project):
     from localground.lib import generic
     from PIL import Image
     
     #1) first, set user, project, and uuid (required for generating file path):
     self.owner = user
     self.last_updated_by = user
     self.project = project
     self.uuid = generic.generateID()
     
     #2) save original file to disk:
     file_name_new = self.save_file_to_disk(file)
     file_name, ext = os.path.splitext(file_name_new)
     
     #3) thumbnail scan:
     thumbnail_name = '%s_thumb.png' % file_name 
     media_path = self.generate_absolute_path()
     im = Image.open(media_path + '/' + file_name_new)
     im.thumbnail([500, 500], Image.ANTIALIAS)
     im.save('%s/%s' % (media_path, thumbnail_name))
     
     #4) save object to database:
     self.status = StatusCode.objects.get(id=1)
     self.upload_source = UploadSource.objects.get(id=1)
     self.file_name_orig = file.name
     self.file_name_new = file_name_new
     self.file_name_thumb = thumbnail_name
     self.content_type = ext.replace('.', '') #file extension      
     self.host = settings.SERVER_HOST
     self.virtual_path = self.generate_relative_path()
     self.save()
     
     #5) call asynchronous processor routine through celery:
     '''from localground.tasks import process_map
     process_map.delay(self.uuid)'''
     #from localground.tasks import add
     #add.delay(2, 4)
     
     '''        
Ejemplo n.º 4
0
def generate_print(request,
                   identity=None,
                   is_json=False,
                   project=None,
                   embed=False,
                   template_name='forms/print.html',
                   base_template='twitter/base.html'):

    r = request.GET or request.POST
    is_form_requested = r.get('short_form') is not None or \
                        r.get('long_form') is not None

    #initialize variables / data based on query params:
    basemap = WMSOverlay.objects.get(
        id=int(r.get('basemap_id', settings.DEFAULT_BASEMAP_ID)))

    #get / create form (if requested):
    form = None
    if is_form_requested:
        #get existing form:
        if r.get('form_id') != '-1' and r.get('form_id') is not None:
            form = Form.objects.get(id=int(r.get('form_id', 1)))
        #create new form:
        elif r.get('form_id') == '-1':
            form = Form.create_new_form(r, request.user)
            #sql = Form.create_new_form(r, request.user)
            #return HttpResponse(sql)

    forms = Form.objects.filter(owner=identity).order_by('name', )
    layers, layer_ids = [], []
    if r.get('layer_ids') is not None and len(r.get('layer_ids')) > 0:
        layer_ids = [int(n) for n in r.get('layer_ids').split(',')]
        layers = WMSOverlay.objects.filter(id__in=layer_ids)

    scans, scan_ids = [], []
    if r.get('scan_ids') is not None and len(r.get('scan_ids')) > 0:
        scan_ids = [n for n in r.get('scan_ids').split(',')]
        scans = Scan.objects.select_related('source_print').filter(
            id__in=scan_ids)

    layouts = Layout.objects.filter(is_active=True).order_by('id', )
    layout_id = int(r.get('layout', 1))
    layout = Layout.objects.get(id=layout_id)
    zoom = int(r.get('zoom', 17))
    profile = UserProfile.objects.get(user=request.user)

    #set lat / lng (including defaults, if not defined any other way):
    center_lat, center_lng = 55.16, 61.4
    if profile.default_location is not None:
        center_lat = profile.default_location.y
        center_lng = profile.default_location.x
    center_lat = float(r.get('center_lat', center_lat))
    center_lng = float(r.get('center_lng', center_lng))

    map_title = r.get('map_title', None)
    instructions = r.get('instructions', None)
    if instructions is not None:  #preserve line breaks in the pdf report
        instructions = '<br/>'.join(instructions.splitlines())
    center = Point(center_lng, center_lat, srid=4326)

    extras = {}

    #get print layout (comes from database):
    map_width = layout.map_width_pixels
    map_height = layout.map_height_pixels
    qr_size = layout.qr_size_pixels
    border_width = layout.border_width  #6

    if r.get('generate_pdf') is not None:

        #create directory:
        uuID = generic.generateID()
        path = settings.STATIC_ROOT + '/prints/' + uuID
        os.mkdir(path)  #create new directory

        #get basemap (from Google or Cloudmade)
        m = StaticMap()
        info = m.get_basemap_and_extents(basemap, zoom, center, map_width,
                                         map_height)
        map_image = info.get('map_image')
        northeast = info.get('northeast')
        southwest = info.get('southwest')
        bbox = (northeast.coords, southwest.coords)
        bbox = [element for tupl in bbox for element in tupl]
        extents = Polygon.from_bbox(bbox)

        overlay_image = m.get_map(layers,
                                  southwest=southwest,
                                  northeast=northeast,
                                  scans=scans,
                                  height=map_height,
                                  width=map_width,
                                  show_north_arrow=True)

        map_image.paste(overlay_image, (0, 0), overlay_image)

        if layout.is_data_entry:
            map_image = map_image.convert("L")  #convert to black and white

        map_image.save(path + '/map.jpg')

        #add border around map:
        map_image = draw_border(map_image, border_width)
        map_width, map_height = map_image.size
        map_image.save(path + '/map_with_border.jpg')

        #make a thumbnail:
        size = map_width / 3, map_height / 3
        thumbnail = map_image.copy()
        thumbnail.thumbnail(size, Image.ANTIALIAS)
        thumbnail.save(path + '/thumbnail.jpg')

        ##################
        ## GET QR CODES ##
        ##################
        qr_image_1 = generate_qrcode(uuID, 1, path, qr_size, border_width)
        qr_image_2 = generate_qrcode(uuID, 2, path, qr_size, border_width)
        qr_size = qr_image_1.size[0]

        ##################
        ## Generate PDF ##
        ##################
        filename = file_name = 'Print_' + uuID + '.pdf'
        pdf_report = Report(path,
                            file_name=filename,
                            is_landscape=layout.is_landscape,
                            author=request.user.username,
                            title=map_title)

        ##########
        # Page 1 #
        ##########
        # build from the bottom up:
        #   (x & y dependencies are additive from bottom up)

        #add footer:
        if layout.is_data_entry:
            pdf_report.add_footer(qr_image_1, uuID, instructions)

        #add form:
        if layout.is_mini_form and form is not None:
            pdf_report.add_form(4, form, is_mini_form=True)

        #add map:
        pdf_report.add_map(map_image,
                           is_data_entry=layout.is_data_entry,
                           has_mini_form=layout.is_mini_form)

        #add header:
        pdf_report.add_header(is_data_entry=layout.is_data_entry,
                              is_map_page=True)

        ##########
        # Page 2 #
        ##########
        if layout.is_data_entry and r.get('long_form') is not None and \
            form is not None:
            pdf_report.new_page()

            #reorient back to portrait:
            pdf_report.set_orientation(False)

            #add footer:
            pdf_report.add_footer(qr_image_2, uuID, instructions)

            #add form:
            pdf_report.add_form(13, form, is_mini_form=False)

            #add header:
            pdf_report.add_header(is_data_entry=layout.is_data_entry,
                                  is_map_page=False)

        pdf_report.save()

        if layout.is_data_entry:
            p = Print()
            p.uuid = uuID
            p.zoom = zoom
            p.map_width = map_width
            p.map_height = map_height
            p.map_provider = basemap  #provider
            p.host = request.get_host()
            p.map_image_path = 'map.jpg'
            p.pdf_path = filename
            p.preview_image_path = 'thumbnail.jpg'
            p.map_title = map_title
            p.description = instructions
            p.center = center
            p.northeast = northeast
            p.southwest = southwest
            p.owner = request.user
            p.last_updated_by = request.user
            p.extents = extents
            p.layout = layout
            if layout.is_data_entry and form is not None:
                p.form = form
                cols = form.get_fields(print_only=True)
                p.form_column_widths = ','.join(
                    [str(c.display_width) for c in cols])
                p.sorted_field_ids = ','.join([str(c.id) for c in cols])
            p.save()

            for l in layers:
                p.layers.add(l)
            p.projects.add(project)
            p.save()

        extras.update({
            'map': p.thumb(),  #'/static/prints/' + uuID + '/thumbnail.jpg',
            'pdf': p.pdf()  #'/static/prints/' + uuID + '/' + filename
        })

    extras.update({
        'embed': embed,
        'base_template': base_template,
        #'map_image_path': url,
        'width': map_width,
        'height': map_height,
        #'sql': get_sql(),
        'zoom': zoom,
        'center_lat': center_lat,
        'center_lng': center_lng,
        'basemap_id': basemap.id,
        'basemap_provider_id': basemap.name,
        'layer_ids': json.dumps(layer_ids),
        'layer_id_string': r.get('layer_ids'),
        'scan_id_string': r.get('scan_ids'),
        'scans': json.dumps([s.to_dict() for s in scans]),
        'layouts': json.dumps([l.to_dict() for l in layouts]),
        'selectedLayout_id': layout.id,
        'map_title': map_title,
        'instructions': instructions,
        'forms': json.dumps([f.to_dict() for f in forms]),
        'projects': Project.objects.get_objects(request.user),
        'selected_project': project
    })
    if form is not None:
        extras.update({'form': json.dumps(form.to_dict())})
    return render_to_response(template_name,
                              extras,
                              context_instance=RequestContext(request))
Ejemplo n.º 5
0
    def create_new_form(dictionary, user):
        from django.db import connection, transaction
        from localground.lib import generic
        r = dictionary
        ids, alias_dict, type_dict, width_dict = [], {}, {}, {}
        total_width = 0
        table_name = 'table_%s_%s' % (user.username,
                                      generic.generateID(num_digits=10))

        for k, v in r.items():
            #build alias dictionary
            if k.find('alias_') != -1:
                #only add ids once:
                id = int(k.split('_')[1])
                ids.append(id)
                alias_dict.update({id: v})

            #build types dictionary
            if k.find('type_') != -1:
                id = int(k.split('_')[1])
                type_dict.update({id: DataType.objects.get(id=int(v))})

            #build widths dictionary
            if k.find('width_') != -1:
                id = int(k.split('_')[1])
                w = int(float(v))
                total_width = total_width + w
                width_dict.update({id: w})

        if len(ids) == 0:
            return None
        differential = 100 - total_width
        #ensure that total width is 100%:
        width_dict[max(ids)] = width_dict.get(max(ids)) + differential
        ids = sorted(ids)

        form_name = r.get('form_name', 'Untitled Form')

        #create new form entry
        form = Form()
        form.name = form_name
        form.table_name = table_name
        form.owner = user
        form.save()

        #create form field entries:
        for id in ids:
            #alias_dict, type_dict, width_dict
            if id != 0:
                field = Field()
                field.form = form
                field.col_name = 'col_' + str(id)
                field.col_alias = alias_dict.get(id)
                field.data_type = type_dict.get(id)
                field.display_width = width_dict.get(id)  #percentage
                field.ordering = id
                field.is_printable = True
                field.has_snippet_field = True
                field.save()

        form.sync_db()
        return form
Ejemplo n.º 6
0
def generate_print(request, identity=None, is_json=False, project=None, embed=False,
                 template_name='forms/print.html', base_template='twitter/base.html'):
    
    r = request.GET or request.POST
    is_form_requested = r.get('short_form') is not None or \
                        r.get('long_form') is not None
    
    #initialize variables / data based on query params:
    basemap = WMSOverlay.objects.get(
                    id=int(r.get('basemap_id', settings.DEFAULT_BASEMAP_ID)))

    #get / create form (if requested):
    form = None
    if is_form_requested:
        #get existing form:
        if r.get('form_id') != '-1' and r.get('form_id') is not None:
            form = Form.objects.get(id=int(r.get('form_id', 1)))
        #create new form:
        elif r.get('form_id') == '-1':
            form = Form.create_new_form(r, request.user)
            #sql = Form.create_new_form(r, request.user)
            #return HttpResponse(sql)
    
    
    forms = Form.objects.filter(owner=identity).order_by('name',)
    layers, layer_ids = [], []
    if r.get('layer_ids') is not None and len(r.get('layer_ids')) > 0:
        layer_ids = [int(n) for n in r.get('layer_ids').split(',')]
        layers = WMSOverlay.objects.filter(id__in=layer_ids)
    
    scans, scan_ids = [], []
    if r.get('scan_ids') is not None and len(r.get('scan_ids')) > 0:
        scan_ids = [n for n in r.get('scan_ids').split(',')]
        scans = Scan.objects.select_related('source_print').filter(id__in=scan_ids)
                 
    layouts = Layout.objects.filter(is_active=True).order_by('id',)
    layout_id = int(r.get('layout', 1))
    layout = Layout.objects.get(id=layout_id)
    zoom = int(r.get('zoom', 17))
    profile = UserProfile.objects.get(user=request.user)
    
    #set lat / lng (including defaults, if not defined any other way):
    center_lat,center_lng = 55.16, 61.4
    if profile.default_location is not None:
        center_lat = profile.default_location.y
        center_lng = profile.default_location.x
    center_lat = float(r.get('center_lat', center_lat))
    center_lng = float(r.get('center_lng', center_lng))
    
    map_title = r.get('map_title', None)
    instructions = r.get('instructions', None)
    if instructions is not None: #preserve line breaks in the pdf report
        instructions = '<br/>'.join(instructions.splitlines())
    center = Point(center_lng, center_lat, srid=4326)
    
    extras = {}
    
    #get print layout (comes from database):
    map_width = layout.map_width_pixels
    map_height = layout.map_height_pixels
    qr_size = layout.qr_size_pixels
    border_width = layout.border_width #6
        
    if r.get('generate_pdf') is not None:
        
        #create directory:
        uuID        = generic.generateID()
        path        = settings.STATIC_ROOT + '/prints/' + uuID
        os.mkdir(path) #create new directory
    
        #get basemap (from Google or Cloudmade)
        m = StaticMap()
        info = m.get_basemap_and_extents(
                        basemap, zoom, center, map_width, map_height)
        map_image = info.get('map_image')
        northeast = info.get('northeast')
        southwest = info.get('southwest')
        bbox = (northeast.coords, southwest.coords)
        bbox = [element for tupl in bbox for element in tupl]
        extents = Polygon.from_bbox(bbox)
      
        overlay_image = m.get_map(layers, southwest=southwest, northeast=northeast,
                                  scans=scans, height=map_height, width=map_width,
                                  show_north_arrow=True)
        
        map_image.paste(overlay_image, (0, 0), overlay_image)
        

        if layout.is_data_entry:
            map_image = map_image.convert("L") #convert to black and white
        
        map_image.save(path + '/map.jpg')
        
        #add border around map:
        map_image = draw_border(map_image, border_width)
        map_width, map_height = map_image.size
        map_image.save(path + '/map_with_border.jpg')
        
        #make a thumbnail:
        size = map_width/3, map_height/3
        thumbnail = map_image.copy()
        thumbnail.thumbnail(size, Image.ANTIALIAS)
        thumbnail.save(path + '/thumbnail.jpg')
        
        ##################
        ## GET QR CODES ##
        ##################
        qr_image_1 = generate_qrcode(uuID, 1, path, qr_size, border_width)
        qr_image_2 = generate_qrcode(uuID, 2, path, qr_size, border_width)
        qr_size = qr_image_1.size[0]
        
        ##################
        ## Generate PDF ##
        ##################
        filename = file_name='Print_' + uuID + '.pdf'
        pdf_report = Report(
            path, file_name=filename, is_landscape=layout.is_landscape,
            author=request.user.username, title=map_title)
        
        ##########
        # Page 1 #
        ##########
        # build from the bottom up:
        #   (x & y dependencies are additive from bottom up)
        
        #add footer:
        if layout.is_data_entry:
            pdf_report.add_footer(qr_image_1, uuID, instructions)
            
        #add form:
        if layout.is_mini_form and form is not None:
            pdf_report.add_form(4, form, is_mini_form=True) 
            
        #add map:
        pdf_report.add_map(map_image, is_data_entry=layout.is_data_entry,
                           has_mini_form=layout.is_mini_form)
        
        #add header:
        pdf_report.add_header(is_data_entry=layout.is_data_entry, is_map_page=True)
        
        ##########
        # Page 2 #
        ##########
        if layout.is_data_entry and r.get('long_form') is not None and \
            form is not None:
            pdf_report.new_page()
            
            #reorient back to portrait:
            pdf_report.set_orientation(False)
            
            #add footer:
            pdf_report.add_footer(qr_image_2, uuID, instructions)
            
            #add form:
            pdf_report.add_form(13, form, is_mini_form=False) 
            
            #add header:
            pdf_report.add_header(is_data_entry=layout.is_data_entry, is_map_page=False)

        pdf_report.save()
        
        if layout.is_data_entry:
            p = Print()
            p.uuid = uuID
            p.zoom = zoom
            p.map_width = map_width
            p.map_height = map_height
            p.map_provider = basemap #provider
            p.host = request.get_host()
            p.map_image_path = 'map.jpg'
            p.pdf_path = filename
            p.preview_image_path = 'thumbnail.jpg'
            p.map_title = map_title
            p.description = instructions
            p.center = center
            p.northeast = northeast
            p.southwest = southwest
            p.owner = request.user
            p.last_updated_by = request.user
            p.extents = extents
            p.layout = layout
            if layout.is_data_entry and form is not None:
                p.form = form
                cols = form.get_fields(print_only=True)
                p.form_column_widths = ','.join([str(c.display_width) for c in cols])
                p.sorted_field_ids = ','.join([str(c.id) for c in cols])
            p.save()
            
            for l in layers:
                p.layers.add(l)
            p.projects.add(project)
            p.save()

        extras.update({
            'map': p.thumb(), #'/static/prints/' + uuID + '/thumbnail.jpg',
            'pdf': p.pdf() #'/static/prints/' + uuID + '/' + filename
        })
        
    extras.update({
        'embed': embed,
        'base_template': base_template,
        #'map_image_path': url,
        'width': map_width,
        'height': map_height,
        #'sql': get_sql(),
        'zoom': zoom,
        'center_lat': center_lat,
        'center_lng': center_lng,
        'basemap_id': basemap.id,
        'basemap_provider_id': basemap.name,
        'layer_ids': json.dumps(layer_ids),
        'layer_id_string': r.get('layer_ids'),
        'scan_id_string': r.get('scan_ids'),
        'scans': json.dumps([s.to_dict() for s in scans]),
        'layouts': json.dumps([l.to_dict() for l in layouts]),
        'selectedLayout_id': layout.id,
        'map_title': map_title,
        'instructions': instructions,
        'forms': json.dumps([f.to_dict() for f in forms]),
        'projects': Project.objects.get_objects(request.user),
        'selected_project': project
    })
    if form is not None:
        extras.update({'form': json.dumps(form.to_dict())})
    return render_to_response(template_name, extras,
                              context_instance = RequestContext( request))
Ejemplo n.º 7
0
 def create_new_form(dictionary, user):
     from django.db import connection, transaction
     from localground.lib import generic
     r = dictionary
     ids, alias_dict, type_dict, width_dict = [],{},{},{}
     total_width = 0
     table_name = 'table_%s_%s' % (user.username, generic.generateID(num_digits=10))
         
     for k, v in r.items():
         #build alias dictionary
         if k.find('alias_') != -1:
             #only add ids once:
             id = int(k.split('_')[1])
             ids.append(id)
             alias_dict.update({ id: v })
         
         #build types dictionary
         if k.find('type_') != -1:
             id = int(k.split('_')[1])
             type_dict.update({ id: DataType.objects.get(id=int(v)) })
             
         #build widths dictionary
         if k.find('width_') != -1:
             id = int(k.split('_')[1])
             w = int(float(v))
             total_width = total_width + w
             width_dict.update({ id: w })
             
     if len(ids) == 0:
         return None
     differential = 100 - total_width
     #ensure that total width is 100%:
     width_dict[max(ids)] = width_dict.get(max(ids)) + differential
     ids = sorted(ids)
     
     form_name = r.get('form_name', 'Untitled Form')
     
     #create new form entry
     form = Form()
     form.name = form_name
     form.table_name = table_name
     form.owner = user
     form.save()
     
     #create form field entries:
     for id in ids:
         #alias_dict, type_dict, width_dict
         if id != 0:
             field = Field()
             field.form = form
             field.col_name = 'col_' + str(id)
             field.col_alias = alias_dict.get(id)
             field.data_type = type_dict.get(id)
             field.display_width = width_dict.get(id) #percentage
             field.ordering = id
             field.is_printable = True
             field.has_snippet_field = True
             field.save()
      
     form.sync_db()
     return form
Ejemplo n.º 8
0
def upload(request):
    import os
    from datetime import datetime
    
    if request.method == 'POST':
        # 1) Write the file to disk:
        uuID            = generic.generateID()
        f               = request.FILES['Filedata']  #use uploadify when debugging, Filedata otherwise
        file_name       = ''.join(f.name.split(' ')) #removes spaces
        path            = settings.STATIC_ROOT + '/scans/' + uuID
        os.mkdir(path)
        os.chmod(path, 775)
        destination     = open(path + '/' + file_name, 'wb+')
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()
        
        # 2) Insert to the database:
        scan                    = Scan()
        scan.status             = StatusCode.objects.get(id=1)
        scan.upload_source      = UploadSource.objects.get(id=1)
        scan.id                 = uuID
        scan.file_name          = file_name
        scan.name               = request.POST.get('scanName') or request.POST.get('name')
        
        if 'description' in request.POST:
            scan.description    = request.POST.get('description')
        
        #for email input:
        if 'email' in request.POST:
            scan.upload_source  = UploadSource.objects.get(id=2)
            scan.email_sender   = request.POST.get('email')
            if 'body' in request.POST:
                scan.email_body = request.POST.get('body')
            if 'subject' in request.POST:
                scan.email_subject= request.POST.get('subject')
            
        if not request.user.is_anonymous(): 
            scan.user           = request.user
        
        content_type_arr        = file_name.split('.')
        content_type            = content_type_arr[len(content_type_arr)-1]
        scan.content_type       = content_type.lower()
        scan.save()
        
        
        # determine how many scans are in the queue and how long it will take to
        # process everything
        scans_in_queue = Scan.objects.scans_in_queue()
        i = 0
        for q in scans_in_queue:
            i = i+1
            if q.id == scan.id:
                break
        
        responseObj = {
            'scanID': uuID,
            'fileName': file_name,
            'name': request.POST.get('scanName') or request.POST.get('name'),
            'user': request.user.is_anonymous(),
            'content_type': content_type,
            'time_created': datetime.now().strftime('%m/%d/%Y, %I:%M %p'),
            #'url': '/static/scans/' + uuID + '/' + file_name,
            'num_in_queue': i,
            'scans_in_queue': len(Scan.objects.scans_in_queue()),
            'url': '/viewer/?scanID=' + scan.id,
            'description': request.POST.get('description', '')
        }  
        return HttpResponse(json.dumps(responseObj))
    else:
        return HttpResponse(json.dumps(dict(message='Not a post')))