Permalink
Browse files

web uploaders

This should close #4 and close #9
  • Loading branch information...
1 parent e8ab6bb commit 28b8aac124e27ae8dec6dd4e0490fd603e966e11 @mlt committed Jul 25, 2012
View
@@ -1,42 +0,0 @@
-#!/usr/bin/env python
-# Use https://github.com/chmouel/python-garmin-upload
-# Don't forget patch https://github.com/chmouel/python-garmin-upload/issues/1
-# Create ~/.schwinn810.yaml with the following 3 lines
-# garmin:
-# username: your_garmin_connect_user_name
-# password: your_password
-
-import argparse
-#from UploadGarmin import UploadGarmin
-from antd import connect # requires python-poster
-from yaml import load, dump
-import os, logging
-
-logging.basicConfig()
-
-parser = argparse.ArgumentParser(description='Uploads TCX to Garmin Connect')
-parser.add_argument(nargs='+', dest='tcx', help='TCX files to upload')
-args = parser.parse_args()
-
-stream = file(os.path.expanduser('~/.schwinn810.yaml'), 'r')
-cfg = load(stream)
-cfg = cfg['garmin']
-
-client = connect.GarminConnect()
-client.username = cfg["username"]
-client.password = cfg["password"]
-
-client.data_available(None, "tcx", args.tcx)
-#client.upload("tcx", name)
-
-# g = UploadGarmin()
-
-# print("Using %s and %s to connect" % (cfg["username"], cfg["password"]))
-# g.login(cfg["username"], cfg["password"])
-
-# print("Uploading %s" % args.tcx)
-# wId = g.upload_ctx(args.tcx)
-
-# print("Renaming it to %s" % name[0])
-# g.name_workout(wId, name[0])
-
View
@@ -1,62 +0,0 @@
-#!/usr/bin/perl
-# MapMyRun authorization prototype
-
-use LWP::UserAgent;
-use Net::OAuth;
-#$Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0A;
-use HTTP::Request::Common;
-my $ua = LWP::UserAgent->new;
-
-open FILE, glob("~/.schwinn810mmr");
-$_=<FILE>;
-chomp;
-my $consumer_key = $_;
-$_=<FILE>;
-chomp;
-my $consumer_secret = $_;
-
-my $request = Net::OAuth->request("request token")->new(
- consumer_key => $consumer_key,
- consumer_secret => $consumer_secret,
- request_url => 'http://api.mapmyfitness.com/3.1/oauth/request_token',
- request_method => 'POST',
- signature_method => 'HMAC-SHA1',
- timestamp => time(),
- nonce => time()*rand()
- );
-
-$request->sign;
-
-my $res = $ua->request(POST $request->to_url); # Post message to the Service Provider
-
-if ($res->is_success) {
- my $response = Net::OAuth->response('request token')->from_post_body($res->content);
- print "Got Request Token ", $response->token, "\n";
- print "Got Request Token Secret ", $response->token_secret, "\n";
- print "Go to http://api.mapmyfitness.com/3.1/oauth/authorize?&oauth_token=" . $response->token . " and hit <enter> once authorized\n";
- <STDIN>;
- my $request = Net::OAuth->request("access token")->new(
- consumer_key => $consumer_key,
- consumer_secret => $consumer_secret,
- token => $response->token,
- token_secret => $response->token_secret,
- signature_method => 'HMAC-SHA1',
- request_url => 'http://api.mapmyfitness.com/3.1/oauth/access_token',
- request_method => 'POST',
- timestamp => time(),
- nonce => time()*rand()
- );
-
- $request->sign;
-
- my $res = $ua->request(POST $request->to_url); # Post message to the Service Provider
-
- if ($res->is_success) {
- my $response = Net::OAuth->response('access token')->from_post_body($res->content);
- print "Got Access Token ", $response->token, "\n";
- print "Got Access Token Secret ", $response->token_secret, "\n";
- } else {
- die "Something went wrong 2" . $res->content;
- }
-
-print "Append access token & secret to your .schwinn810mmr\n";
View
@@ -1,129 +0,0 @@
-#!/usr/bin/perl
-# MapMyRun uploader prototype
-
-use LWP::UserAgent;
-use Net::OAuth;
-use JSON;
-use Data::Dumper;
-use HTTP::Request::Common;
-my $ua = LWP::UserAgent->new();
-
-my $name = shift; # track name
-my $fname = shift; # TCX to upload
-
-open FILE, glob("~/.schwinn810mmr");
-$_=<FILE>;
-chomp;
-my $consumer_key = $_;
-$_=<FILE>;
-chomp;
-my $consumer_secret = $_;
-$_=<FILE>;
-chomp;
-my $token = $_;
-$_=<FILE>;
-chomp;
-my $token_secret = $_;
-
-my $request = Net::OAuth->request("protected resource")->new(
- consumer_key => $consumer_key,
- consumer_secret => $consumer_secret,
- token => $token,
- token_secret => $token_secret,
- signature_method => 'HMAC-SHA1',
- request_url => 'http://api.mapmyfitness.com/3.1/users/authenticate_user',
- request_method => 'POST',
- timestamp => time(),
- nonce => time()*rand()
- );
-
-$request->sign;
-
-my $res = $ua->request(POST $request->to_url); # Post message to the Service Provider
-
-if ($res->is_success) {
- my $data = decode_json $res->content;
- my $output = $data->{result}{output};
- print "user_id: " . $output->{user_id} . "\n";
-} else {
- die "[authenticate_user] Something went wrong 1 " . $res->content;
-}
-
-open FILE, $fname;
-$file_contents = do { local $/; <FILE> };
-print "about to send " . length($file_contents) . " bytes\n";
-my $import_tcx = 'http://api.mapmyfitness.com/3.1/workouts/import_tcx';
-
-my $request = Net::OAuth->request("protected resource")->new(
- consumer_key => $consumer_key,
- consumer_secret => $consumer_secret,
- token => $token,
- token_secret => $token_secret,
- signature_method => 'HMAC-SHA1',
- request_url => 'http://api.mapmyfitness.com/3.1/workouts/import_tcx',
- request_method => 'POST',
- timestamp => time(),
- nonce => time()*rand(),
- extra_params => {
- o => 'json',
- tcx => $file_contents,
- baretcx => 1,
- name => $name
- }
- );
-
-$request->sign;
-
-my $res = $ua->post($import_tcx, $request->to_hash);
-
-if ($res->is_success) {
-} else {
- die "[write_tcx] Something went wrong 3 " . $res->message . " code=" . $res->code;
-}
-
-exit;
-
-my $data = decode_json $res->content;
-#print Dumper($data);
-$workout_id = $data->{result}{output}{result}{workout_id};
-$workout_key = $data->{result}{output}{result}{workout_key};
-$route_id = $data->{result}{output}{result}{route_id};
-$route_key = $data->{result}{output}{result}{route_key};
-print "workout_id " . $workout_id . "\n";
-
-my $request = Net::OAuth->request("protected resource")->new(
- consumer_key => $consumer_key,
- consumer_secret => $consumer_secret,
- token => $token,
- token_secret => $token_secret,
- signature_method => 'HMAC-SHA1',
- request_url => 'http://api.mapmyfitness.com/3.1/workouts/edit_workout',
- request_method => 'POST',
- timestamp => time(),
- nonce => time()*rand(),
- extra_params => {
- workout_key => $workout_key,
- workout_id => $workout_id,
- calories_burned => 123,
- workout_type_id => 2
-# source => "Schwinn 810 uploader"
- }
- );
-
-$request->sign;
-
-#my $res = $ua->request(PUT $request->to_url); # Post message to the Service Provider
-my $res = $ua->request(POST $request->to_url);#, Contents => $file_contents); # Post message to the Service Provider
-
-if ($res->is_success) {
- print $res->content;
- # my $data = decode_json $res->content;
- # print Dumper($data);
-
-
-} else {
-# my $data = decode_json $res->content;
-# print Dumper($data->{error});
-# print Dumper($res);
- die "[write_tcx] Something went wrong 3" . $res->content . " code=" . $res->code;
-}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
View
@@ -0,0 +1,118 @@
+#!/usr/bin/env python
+# -*- coding: utf-8; mode: python; mode: ropemacs -*-
+
+# Copyright (c) 2012, Mikhail Titov
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import antd.plugin as plugin
+import requests
+import re
+import logging
+import os
+
+_log = logging.getLogger(__name__)
+
+class MMF(plugin.Plugin):
+
+ username = None
+ password = None
+
+ logged_in = False
+ login_invalid = False
+
+ def __init__(self):
+ self.url = 'www.mapmyrun.com'
+
+ def data_available(self, device_sn, format, files):
+ if format not in ("tcx"): return files
+ result = []
+ try:
+ for file in files:
+ self.login()
+ self.upload(format, file)
+ result.append(file)
+ except Exception:
+ _log.warning("Failed to upload to MMF.", exc_info=True)
+ finally:
+ return result
+
+ def login(self):
+ if self.logged_in: return
+ if self.login_invalid: raise InvalidLogin()
+
+ payload = { 'username_login': self.username,
+ 'password_login': self.password,
+ 'action_type': 'login' }
+ url = "http://{:s}/auth/login/".format(self.url)
+ r = requests.get(url)
+ # post login credentials
+ _log.debug("Posting login credentials to MMF. username=%s", self.username)
+ url = "https://{:s}/auth/login/".format(self.url)
+ r = requests.post(url, data=payload, cookies=r.cookies)
+ if 302 != r.status_code:
+ raise InvalidLogin()
+ # verify we're logged in
+ _log.debug("Checking if login was successful.")
+ username = r.cookies['_cache_username']
+ if username == "":
+ self.login_invalid = True
+ raise InvalidLogin()
+ elif username != self.username:
+ _log.warning("Username mismatch, probably OK, if upload fails check user/pass. %s != %s" % (username, self.username))
+ self.logged_in = True
+ self.cookies = r.cookies
+
+ def upload(self, format, file_name):
+ url = "http://{:s}/workout/import/?source=file".format(self.url)
+ r = requests.get(url, cookies=self.cookies)
+ payload = { 'import_uuid': '', 'file_type': 'tcx' }
+ base = os.path.basename(file_name)
+ files = {'file': ( base, open(file_name, 'rb'))}
+ r = requests.post(url, data=payload, files=files, cookies=r.cookies)
+
+ # no need for BeautifulSoup just yet
+ m = re.search('name="data_uuid" value="(.+)"', r.content)
+ if m:
+ payload = { 'activity_type': '16', # run/jog
+ 'route_name': base,
+ 'data_uuid': m.group(1) }
+ _log.info("Uploading %s to MMF.", file_name)
+ r = requests.post(url, data=payload, cookies=r.cookies)
+ else:
+ raise Exception("data_uuid is missing in cookies")
+
+class InvalidLogin(Exception): pass
+
+
+def main():
+ import argparse
+ logging.basicConfig(level=logging.DEBUG)
+
+ parser = argparse.ArgumentParser(description='MMF uploader.')
+ parser.add_argument('--user', nargs=1, required=True,
+ help='Your MMF username')
+ parser.add_argument('--password', nargs=1, required=True,
+ help='Your MMF password')
+ parser.add_argument(dest='tcx', nargs='+',
+ help='TCX files to upload')
+ args = parser.parse_args()
+
+ m = MMF()
+ m.username = args.user[0]
+ m.password = args.password[0]
+ m.data_available(None, 'tcx', args.tcx)
+
+if __name__ == '__main__':
+ main()
Oops, something went wrong.

0 comments on commit 28b8aac

Please sign in to comment.