[9078] | 1 | #!/usr/bin/env python
|
---|
[9560] | 2 | # -*- coding: utf-8 -*-
|
---|
[9084] | 3 | #
|
---|
[9640] | 4 | # Script for importing various stumble files.
|
---|
[9084] | 5 | #
|
---|
[9560] | 6 | # Rick van der Zwet <info@rickvanderzwet.nl>
|
---|
| 7 | #
|
---|
[9637] | 8 | from django.core.files import File
|
---|
[9158] | 9 | from django.core.management.base import BaseCommand,CommandError
|
---|
[9628] | 10 | from django.db import connection, transaction
|
---|
[9548] | 11 | from django.db.utils import IntegrityError
|
---|
[9628] | 12 | from gheat.models import *
|
---|
[9078] | 13 | from optparse import OptionParser, make_option
|
---|
| 14 | import datetime
|
---|
[9173] | 15 | import gzip
|
---|
[9158] | 16 | import os
|
---|
| 17 | import sys
|
---|
[9552] | 18 | import logging
|
---|
[9078] | 19 |
|
---|
[9560] | 20 | from collections import defaultdict
|
---|
[9552] | 21 |
|
---|
[9640] | 22 | from gheat.dataimport import import_file
|
---|
[9560] | 23 |
|
---|
[10925] | 24 | logging.basicConfig(level=logging.INFO, format='# %(levelname)s: %(message)s')
|
---|
[10814] | 25 | logger = logging.getLogger()
|
---|
[9560] | 26 |
|
---|
| 27 |
|
---|
[9669] | 28 | valid_prefixes = ['DroidStumbler-', 'Kismet-EeePC-', 'Kismet-', 'ScanResult-']
|
---|
[9623] | 29 | def strip_prefix(filename):
|
---|
[9627] | 30 | """ Prefix removal """
|
---|
[9626] | 31 | for prefix in valid_prefixes:
|
---|
| 32 | if filename.startswith(prefix):
|
---|
| 33 | filename = filename[len(prefix):]
|
---|
[9623] | 34 | return filename
|
---|
[9627] | 35 |
|
---|
| 36 |
|
---|
[9623] | 37 | valid_suffixes = ['.gz', '.gpsxml', '.netxml', '.csv', '.ns1']
|
---|
| 38 | def strip_suffix(filename):
|
---|
[9627] | 39 | """ Suffix removal """
|
---|
[9623] | 40 | for suffix in valid_suffixes:
|
---|
[9626] | 41 | if filename.endswith(suffix):
|
---|
| 42 | filename = filename[:-len(suffix)]
|
---|
[9623] | 43 | return filename
|
---|
[9627] | 44 |
|
---|
| 45 |
|
---|
[9623] | 46 | def strip_file(filename):
|
---|
[9627] | 47 | """ Prefix and suffix removal """
|
---|
[9623] | 48 | return strip_suffix(strip_prefix(filename))
|
---|
[9561] | 49 |
|
---|
| 50 |
|
---|
[9627] | 51 | #Kismet-20110805-15-37-30-1
|
---|
| 52 | #ScanResult-2011-05-09-201117
|
---|
| 53 | strptime_choices = ['%Y%m%d-%H-%M-%S-1', '%Y-%m-%d-%H%M%S']
|
---|
| 54 | def process_date(datestr):
|
---|
| 55 | for strptime in strptime_choices:
|
---|
[9632] | 56 | try:
|
---|
| 57 | return datetime.datetime.strptime(datestr,strptime)
|
---|
| 58 | except ValueError:
|
---|
| 59 | pass
|
---|
| 60 | logger.error("Invalid date '%s', options: %s, using: now()", datestr, strptime_choices)
|
---|
| 61 | return datetime.datetime.now()
|
---|
[9627] | 62 |
|
---|
[9628] | 63 |
|
---|
[9078] | 64 | class Command(BaseCommand):
|
---|
[9619] | 65 | args = '<netstumber.ns1>[.gz] [netstumber2.ns1[.gz] netstumber3.ns1[.gz] ...]'
|
---|
[9080] | 66 | option_list = BaseCommand.option_list + (
|
---|
[9619] | 67 | make_option('-k', '--kaart', dest='kaart', default='onbekend',
|
---|
| 68 | help="Kaart gebruikt"),
|
---|
[9669] | 69 | make_option('-f', '--force', dest='force', default=False, action="store_true",
|
---|
| 70 | help="Import anyways, even if the meetrondje is already imported"),
|
---|
[9560] | 71 | make_option('-m', '--meetrondje', dest='meetrondje', default=None),
|
---|
[9619] | 72 | make_option('-g', '--gebruiker', dest='gebruiker', default='username',
|
---|
| 73 | help='Naam van de persoon die de meting uitgevoerd heeft'),
|
---|
| 74 | make_option('-e', '--email', dest='email', default='foo@bar.org',
|
---|
| 75 | help='Email van de persoon die de meting uitgevoerd heeft'),
|
---|
| 76 | make_option('-d', '--datum', dest='datum', default=None,
|
---|
| 77 | help="Provide date in following format: '%Y%m%d-%H-%M-%S-1', by \
|
---|
| 78 | default it will be generated from the filename"),
|
---|
[10814] | 79 | make_option('-b', '--batch', dest='batch', default=False, action="store_true",
|
---|
| 80 | help="Batch import modes, gives no errors if items is already imported"),
|
---|
[9560] | 81 | )
|
---|
[9078] | 82 |
|
---|
[9080] | 83 | def handle(self, *args, **options):
|
---|
[9629] | 84 | if options['verbosity'] == 2:
|
---|
[9619] | 85 | logger.setLevel(logging.DEBUG)
|
---|
[9560] | 86 | if len(args) == 0:
|
---|
[9158] | 87 | self.print_help(sys.argv[0],sys.argv[1])
|
---|
| 88 | raise CommandError("Not all arguments are provided")
|
---|
| 89 |
|
---|
[9623] | 90 | # Please first the netxml and the gpsxml files and the rest
|
---|
| 91 | sorted_args = [x for x in args if "netxml" in x] +\
|
---|
| 92 | [x for x in args if "gpsxml" in x] +\
|
---|
| 93 | [x for x in args if "ns1" in x]
|
---|
[9563] | 94 | remainder = list(set(args) - set(sorted_args))
|
---|
| 95 | args = sorted_args + remainder
|
---|
| 96 | logger.debug("Parsing files in the following order: %s", args)
|
---|
| 97 |
|
---|
[9623] | 98 | # Make sure the all exists at first
|
---|
[9619] | 99 | for filename in args:
|
---|
| 100 | if not os.path.isfile(filename):
|
---|
| 101 | raise CommandError("file '%s' does not exists" % filename)
|
---|
[9560] | 102 |
|
---|
[9619] | 103 |
|
---|
[9623] | 104 | def get_date(filename):
|
---|
| 105 | if options['datum'] == None:
|
---|
| 106 | datestr = strip_file(os.path.basename(filename))
|
---|
| 107 | datum = process_date(datestr)
|
---|
| 108 | elif options['datum'] == 'now':
|
---|
| 109 | datum = datetime.datetime.now()
|
---|
| 110 | else:
|
---|
| 111 | datum = process_date(options['datum'])
|
---|
| 112 | return datum
|
---|
| 113 |
|
---|
| 114 | def get_meetrondje(meetrondje):
|
---|
| 115 | # Meetrondje from filename if needed
|
---|
| 116 | if options['meetrondje'] == None:
|
---|
| 117 | meetrondje = strip_suffix(os.path.basename(filename))
|
---|
| 118 | else:
|
---|
| 119 | meetrondje = options['meetrondje']
|
---|
| 120 | return meetrondje
|
---|
| 121 |
|
---|
| 122 | # Get Gheat Objects, pre-req
|
---|
[9639] | 123 | gebruiker, created = Gebruiker.objects.get_or_create(naam=options['gebruiker'],
|
---|
[9623] | 124 | email=options['email'])
|
---|
[9639] | 125 | apparatuur, created = Apparatuur.objects.get_or_create(kaart=options['kaart'])
|
---|
[9623] | 126 |
|
---|
[9823] | 127 | # Meetrondje is deducted and checked from first filename
|
---|
| 128 | filename = args[0]
|
---|
| 129 | logger.info("Processing '%s'" % filename)
|
---|
| 130 | meetrondje, created = MeetRondje.objects.get_or_create(
|
---|
| 131 | datum=get_date(filename), naam=get_meetrondje(filename),
|
---|
| 132 | gebruiker=gebruiker, apparatuur=apparatuur)
|
---|
| 133 | if not options['force'] and not created:
|
---|
| 134 | raise CommandError("Meetrondje '%s' already imported", meetrondje)
|
---|
| 135 |
|
---|
[9623] | 136 | # Check if all files are valid
|
---|
[9619] | 137 | for filename in args:
|
---|
[10925] | 138 | logger.info("Meetrondje: %s", meetrondje)
|
---|
| 139 | logger.info("Bestand: %s", filename)
|
---|
[9639] | 140 | meetbestand = MeetBestand(meetrondje=meetrondje,is_imported=True)
|
---|
[9637] | 141 | meetbestand.bestand.save(os.path.basename(filename),File(open(filename)))
|
---|
| 142 | meetbestand.save()
|
---|
| 143 |
|
---|
[9640] | 144 | counters = import_file(filename,meetrondje)
|
---|
[9819] | 145 | logger.info("summary accesspoints: total:%(ap_total)-6s added:%(ap_added)-6s failed:%(ap_failed)-6s ignored:%(ap_ignored)-6s" % counters)
|
---|
[9640] | 146 | logger.info("summary client : total:%(client_total)-6s added:%(client_added)-6s failed:%(client_failed)-6s ignored:%(client_ignored)-6s" % counters)
|
---|
| 147 | logger.info("summary metingen : total:%(meting_total)-6s added:%(meting_added)-6s failed:%(meting_failed)-6s ignored:%(meting_ignored)-6s" % counters)
|
---|
[9560] | 148 |
|
---|
[9640] | 149 |
|
---|
| 150 |
|
---|
| 151 |
|
---|