~ubuntu-branches/ubuntu/natty/pytrainer/natty-proposed

« back to all changes in this revision

Viewing changes to import/file_garmintools.py

  • Committer: Bazaar Package Importer
  • Author(s): Alessio Treglia
  • Date: 2010-02-04 06:07:11 UTC
  • mfrom: (4.1.3 sid)
  • Revision ID: james.westby@ubuntu.com-20100204060711-25n5aw66w5egeiph
Tags: 1.7.1-1ubuntu1
* Merge from debian testing, remaining changes:
  - debian/control:
    + Replace Depends on iceweasel with firefox | abrowser.
    + Bump python-dev,debhelper build-dependencies.
    - Drop dependency on python-glade2 (libglade -> gtkbuilder transition).
  - debian/rules:
    + Append --install-laoyut=deb to setup.py install to prevent a build
      failure with Python 2.6.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- coding: iso-8859-1 -*-
 
2
 
 
3
#Copyright (C) Fiz Vazquez vud1@sindominio.net
 
4
# Modified by dgranda
 
5
 
 
6
#This program is free software; you can redistribute it and/or
 
7
#modify it under the terms of the GNU General Public License
 
8
#as published by the Free Software Foundation; either version 2
 
9
#of the License, or (at your option) any later version.
 
10
 
 
11
#This program is distributed in the hope that it will be useful,
 
12
#but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
#GNU General Public License for more details.
 
15
 
 
16
#You should have received a copy of the GNU General Public License
 
17
#along with this program; if not, write to the Free Software
 
18
#Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
19
 
 
20
import logging
 
21
import os
 
22
import StringIO
 
23
from lxml import etree
 
24
from pytrainer.lib.date import Date
 
25
 
 
26
#from pytrainer.lib.xmlUtils import XMLParser
 
27
#from pytrainer.gui.dialogs import fileChooserDialog, guiFlush
 
28
from pytrainer.lib.system import checkConf
 
29
 
 
30
class garmintools():
 
31
        def __init__(self, parent = None, data_path = None):
 
32
                self.parent = parent
 
33
                self.conf = checkConf()
 
34
                self.tmpdir = self.conf.getValue("tmpdir")
 
35
                self.main_data_path = data_path
 
36
                self.data_path = os.path.dirname(__file__)
 
37
                self.xmldoc = None
 
38
                self.activitiesSummary = []
 
39
 
 
40
        def getXmldoc(self):
 
41
                ''' Function to return parsed xmlfile '''
 
42
                return self.xmldoc
 
43
 
 
44
        def getFileType(self):
 
45
                return _("Garmin tools dump file")
 
46
 
 
47
        def getActivitiesSummary(self):
 
48
                return self.activitiesSummary
 
49
 
 
50
        def testFile(self, filename):
 
51
                logging.debug('>>')
 
52
                logging.debug("Testing " + filename)
 
53
                #Check if file is a garmintools dump
 
54
                try:
 
55
                        with open(filename, 'r') as f:
 
56
                                xmlString = f.read()
 
57
                        #add a root element to make correct xml
 
58
                        fileString = StringIO.StringIO("<root>"+xmlString+"</root>")
 
59
                        #parse string as xml
 
60
                        xmldoc = etree.parse(fileString)
 
61
                        #Parse XML schema
 
62
                        xmlschema_doc = etree.parse(self.main_data_path+"schemas/garmintools.xsd")
 
63
                        xmlschema = etree.XMLSchema(xmlschema_doc)
 
64
                        if (xmlschema.validate(xmldoc)):
 
65
                                #Valid garmintools file
 
66
                                self.xmldoc = xmldoc
 
67
                                startTime = self.getDateTime(self.startTimeFromFile(xmldoc))
 
68
                                indatabase = self.inDatabase(xmldoc, startTime)
 
69
                                sport = self.getSport(xmldoc)
 
70
                                distance, duration  = self.getDetails(xmldoc, startTime)
 
71
                                distance = distance / 1000.0
 
72
                                self.activitiesSummary.append( (0,
 
73
                                                                                                indatabase, 
 
74
                                                                                                startTime[1].strftime("%Y-%m-%dT%H:%M:%S"), 
 
75
                                                                                                "%0.2f" % distance , 
 
76
                                                                                                str(duration), 
 
77
                                                                                                sport,
 
78
                                                                                                ) )
 
79
                                return True
 
80
                except:
 
81
                        #Not garmintools dump file
 
82
                        return False
 
83
                return False
 
84
        
 
85
        def getDateTime(self, time_):
 
86
                return Date().getDateTime(time_)
 
87
 
 
88
        def inDatabase(self, tree, startTime):
 
89
                #comparing date and start time (sport may have been changed in DB after import)
 
90
                time = startTime
 
91
                if time is None:
 
92
                        return False
 
93
                time = time[0].strftime("%Y-%m-%dT%H:%M:%SZ")
 
94
                if self.parent.parent.ddbb.select("records","*","date_time_utc=\"%s\"" % (time)):
 
95
                        return True
 
96
                else:
 
97
                        return False
 
98
 
 
99
        def getDetails(self, tree, startTime):
 
100
                root = tree.getroot()
 
101
                points = root.findall(".//point")
 
102
                while True:
 
103
                        lastPoint = points[-1]
 
104
                        try:
 
105
                                distance = lastPoint.get("distance")
 
106
                                if distance is None:
 
107
                                        points = points[:-1]
 
108
                                        continue
 
109
                                time = lastPoint.get("time")
 
110
                                break
 
111
                        except:
 
112
                                points = points[:-1]
 
113
                                continue
 
114
                return float(distance), self.getDateTime(time)[0]-startTime[0]
 
115
 
 
116
        def getSport(self, tree):
 
117
                #return sport from file
 
118
                root = tree.getroot()
 
119
                sportElement = root.find(".//run")
 
120
                try:
 
121
                        sport = sportElement.get("sport")
 
122
                        sport = sport.capitalize()
 
123
                except:
 
124
                        sport = "import"
 
125
                return sport
 
126
 
 
127
        def startTimeFromFile(self, tree):
 
128
                root = tree.getroot()
 
129
                #Find first point
 
130
                pointElement = root.find(".//point")
 
131
                if pointElement is not None:
 
132
                        #Try to get time from point
 
133
                        time = pointElement.get("time")
 
134
                        print "#TODO first time is different from time used by gpsbabel and has locale embedded: " + time
 
135
                        return time
 
136
                return None
 
137
 
 
138
        def getGPXFile(self, ID):
 
139
                """
 
140
                        Generate GPX file based on activity ID
 
141
 
 
142
                        Returns (sport, GPX filename)
 
143
                """
 
144
                sport = None
 
145
                gpxFile = None
 
146
                if ID == "0": #Only one activity in file
 
147
                        gpxFile = "%s/garmintools-%s.gpx" % (self.tmpdir, ID)
 
148
                        sport = self.getSport(self.xmldoc)
 
149
                        self.createGPXfile(gpxFile, self.xmldoc)
 
150
                return sport, gpxFile
 
151
 
 
152
        def createGPXfile(self, gpxfile, tree):
 
153
                """ Function to transform a Garmintools dump file to a valid GPX+ file
 
154
                """
 
155
                xslt_doc = etree.parse(self.data_path+"/translate_garmintools.xsl")
 
156
                transform = etree.XSLT(xslt_doc)
 
157
                result_tree = transform(tree)
 
158
                result_tree.write(gpxfile, xml_declaration=True)
 
159