1 | #!/usr/bin/env python
|
---|
2 | # -*- coding: utf-8 -*-
|
---|
3 | #
|
---|
4 | # Script for importing various stumble files.
|
---|
5 | #
|
---|
6 | # Rick van der Zwet <info@rickvanderzwet.nl>
|
---|
7 | #
|
---|
8 | from django.core.files import File
|
---|
9 | from django.core.management.base import BaseCommand,CommandError
|
---|
10 | from django.db import connection, transaction
|
---|
11 | from django.db.utils import IntegrityError
|
---|
12 | from gheat.models import *
|
---|
13 | from optparse import OptionParser, make_option
|
---|
14 | import datetime
|
---|
15 | import gzip
|
---|
16 | import os
|
---|
17 | import sys
|
---|
18 | import logging
|
---|
19 |
|
---|
20 | from collections import defaultdict
|
---|
21 |
|
---|
22 | from gheat.dataimport import import_file
|
---|
23 |
|
---|
24 | logging.basicConfig(level=logging.INFO, format='# %(levelname)s: %(message)s')
|
---|
25 | logger = logging.getLogger()
|
---|
26 |
|
---|
27 |
|
---|
28 | valid_prefixes = ['DroidStumbler-', 'Kismet-EeePC-', 'Kismet-', 'ScanResult-']
|
---|
29 | def strip_prefix(filename):
|
---|
30 | """ Prefix removal """
|
---|
31 | for prefix in valid_prefixes:
|
---|
32 | if filename.startswith(prefix):
|
---|
33 | filename = filename[len(prefix):]
|
---|
34 | return filename
|
---|
35 |
|
---|
36 |
|
---|
37 | valid_suffixes = ['.gz', '.gpsxml', '.netxml', '.csv', '.ns1']
|
---|
38 | def strip_suffix(filename):
|
---|
39 | """ Suffix removal """
|
---|
40 | for suffix in valid_suffixes:
|
---|
41 | if filename.endswith(suffix):
|
---|
42 | filename = filename[:-len(suffix)]
|
---|
43 | return filename
|
---|
44 |
|
---|
45 |
|
---|
46 | def strip_file(filename):
|
---|
47 | """ Prefix and suffix removal """
|
---|
48 | return strip_suffix(strip_prefix(filename))
|
---|
49 |
|
---|
50 |
|
---|
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:
|
---|
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()
|
---|
62 |
|
---|
63 |
|
---|
64 | class Command(BaseCommand):
|
---|
65 | args = '<netstumber.ns1>[.gz] [netstumber2.ns1[.gz] netstumber3.ns1[.gz] ...]'
|
---|
66 | option_list = BaseCommand.option_list + (
|
---|
67 | make_option('-k', '--kaart', dest='kaart', default='onbekend',
|
---|
68 | help="Kaart gebruikt"),
|
---|
69 | make_option('-f', '--force', dest='force', default=False, action="store_true",
|
---|
70 | help="Import anyways, even if the meetrondje is already imported"),
|
---|
71 | make_option('-m', '--meetrondje', dest='meetrondje', default=None),
|
---|
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"),
|
---|
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"),
|
---|
81 | )
|
---|
82 |
|
---|
83 | def handle(self, *args, **options):
|
---|
84 | if options['verbosity'] == 2:
|
---|
85 | logger.setLevel(logging.DEBUG)
|
---|
86 | if len(args) == 0:
|
---|
87 | self.print_help(sys.argv[0],sys.argv[1])
|
---|
88 | raise CommandError("Not all arguments are provided")
|
---|
89 |
|
---|
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]
|
---|
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 |
|
---|
98 | # Make sure the all exists at first
|
---|
99 | for filename in args:
|
---|
100 | if not os.path.isfile(filename):
|
---|
101 | raise CommandError("file '%s' does not exists" % filename)
|
---|
102 |
|
---|
103 |
|
---|
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
|
---|
123 | gebruiker, created = Gebruiker.objects.get_or_create(naam=options['gebruiker'],
|
---|
124 | email=options['email'])
|
---|
125 | apparatuur, created = Apparatuur.objects.get_or_create(kaart=options['kaart'])
|
---|
126 |
|
---|
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 |
|
---|
136 | # Check if all files are valid
|
---|
137 | for filename in args:
|
---|
138 | logger.info("Meetrondje: %s", meetrondje)
|
---|
139 | logger.info("Bestand: %s", filename)
|
---|
140 | meetbestand = MeetBestand(meetrondje=meetrondje,is_imported=True)
|
---|
141 | meetbestand.bestand.save(os.path.basename(filename),File(open(filename)))
|
---|
142 | meetbestand.save()
|
---|
143 |
|
---|
144 | counters = import_file(filename,meetrondje)
|
---|
145 | logger.info("summary accesspoints: total:%(ap_total)-6s added:%(ap_added)-6s failed:%(ap_failed)-6s ignored:%(ap_ignored)-6s" % counters)
|
---|
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)
|
---|
148 |
|
---|
149 |
|
---|
150 |
|
---|
151 |
|
---|