Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add iCal export for workouts
Roland Geider1e2d345e01f7
diff --git a/requirements.txt b/requirements.txtindex 879c5379e..9d11acf09 100644--- a/requirements.txt+++ b/requirements.txt@@ -11,4 +11,5 @@ django-tastypie==0.9.16python-mimeparsepilloweasy-thumbnails-django_compressor\ No newline at end of file+django_compressor+icalendar\ No newline at end of filediff --git a/setup.py b/setup.pyindex 581dd34e0..c224a8781 100644--- a/setup.py+++ b/setup.py@@ -57,6 +57,7 @@ setup('pillow','easy-thumbnails','django_compressor',+ 'icalendar'],entry_points={'console_scripts': [diff --git a/wger/manager/templates/mobile/workout/view.html b/wger/manager/templates/mobile/workout/view.htmlindex 00f766ee2..332cb948e 100644--- a/wger/manager/templates/mobile/workout/view.html+++ b/wger/manager/templates/mobile/workout/view.html@@ -166,6 +166,18 @@ $( document ).off("pageinit").on("pageinit", function() {{% trans "Make a copy of this workout" %}</a>+<a href="#export-ical-link"+ data-rel="popup"+ data-role="button"+ data-position-to="window">+ <img src="{% static 'images/icons/calendar.svg' %}"+ width="32"+ height="32"+ alt="{% trans 'Export calendar file' %}"+ title="{% trans 'Export calendar file' %}">+ {% trans "Export calendar file" %}+</a>+<a href="{% url 'workout-delete' workout.id %}"data-role="button"><img src="{% static 'images/icons/trash.svg' %}"@@ -174,4 +186,30 @@ $( document ).off("pageinit").on("pageinit", function() {alt="{% trans 'Delete this workout' %}">{% trans "Delete this workout" %}</a>+++<div data-role="popup"+ id="export-ical-link"+ data-overlay-theme="a"+ class="ui-content">+ <div>+ <h3>{% trans "Export calendar file" %}</h3>+ <p>{% blocktrans %}Export this workout as a calendar file. You can+then import it into your calendar application for example google calendar,+outlook or iCal. This will create an appointment for each training day with+the appropriate exercises.{% endblocktrans %}</p>+ <p>+ <a href="{% url 'workout-ical' workout.id %}"+ data-role="button"+ target="_blank">+ <img src="{% static 'images/icons/calendar.svg' %}"+ width="32"+ height="32"+ alt="{% trans 'Export calendar file' %}"+ title="{% trans 'Export calendar file' %}">+ {% trans "Export calendar file" %}+ </a>+ </p>+ </div>+</div>{% endblock %}diff --git a/wger/manager/templates/navigation.html b/wger/manager/templates/navigation.htmlindex 3a0472f00..a5f0d2e06 100644--- a/wger/manager/templates/navigation.html+++ b/wger/manager/templates/navigation.html@@ -27,7 +27,7 @@data-toggle="dropdown">{% trans "Workouts" %} <b class="caret"></b></a><ul class="dropdown-menu"><li><a href="{% url 'wger.manager.views.workout.overview' %}" rel="nofollow">{% trans "Workouts" %}</a></li>- <li><a href="{% url 'workout-calendar' %}" rel="nofollow">{% trans "Calendar" %}</a></li>+ <li><a href="{% url 'workout-calendar' %}" rel="nofollow">{% trans "Weight log calendar" %}</a></li><li><a href="{% url 'schedule-overview' %}" rel="nofollow">{% trans "Workouts schedules" %}</a></li></ul></li>diff --git a/wger/manager/templates/workout/view.html b/wger/manager/templates/workout/view.htmlindex ef4ba9e57..135c3c5f7 100644--- a/wger/manager/templates/workout/view.html+++ b/wger/manager/templates/workout/view.html@@ -28,6 +28,14 @@ $(document).ready(function() {$(".exercise-comments").hide();{% endif %}toggle_comments();++ // Popup for adding logs+ $('#export-ical-link').click(function(e){+ e.preventDefault();+ $('#export-ical-popup').dialog({+ modal: true+ });+ });});</script>{% endblock %}@@ -152,6 +160,17 @@ $(document).ready(function() {</a></p>+<p>+<a href="#export-ical-popup" id="export-ical-link">+ <img src="{% static 'images/icons/calendar.svg' %}"+ width="32"+ height="32"+ alt="{% trans 'Export calendar file' %}"+ title="{% trans 'Export calendar file' %}">+ {% trans "Export calendar file" %}+</a>+</p>+<p><a href="{% url 'workout-copy' workout.id %}"class="modal-dialog">@@ -164,7 +183,6 @@ $(document).ready(function() {</a></p>-<p><a href="{% url 'workout-delete' workout.id %}"class="modal-dialog">@@ -175,4 +193,24 @@ $(document).ready(function() {{% trans "Delete this workout" %}</a></p>++<div id="export-ical-popup" style="display:none;">+ <div>+ <h3>{% trans "Export calendar file" %}</h3>+ <p>{% blocktrans %}Export this workout as a calendar file. You can+then import it into your calendar application for example google calendar,+outlook or iCal. This will create an appointment for each training day with+the appropriate exercises.{% endblocktrans %}</p>+ <p>+ <a href="{% url 'workout-ical' workout.id %}" class="btn btn-block">+ <img src="{% static 'images/icons/calendar.svg' %}"+ width="32"+ height="32"+ alt="{% trans 'Export calendar file' %}"+ title="{% trans 'Export calendar file' %}">+ {% trans "Export calendar file" %}+ </a>+ </p>+ </div>+</div>{% endblock %}diff --git a/wger/manager/tests/test_ical.py b/wger/manager/tests/test_ical.pynew file mode 100644index 000000000..63074077a--- /dev/null+++ b/wger/manager/tests/test_ical.py@@ -0,0 +1,39 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager 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 Affero General Public License++import datetime++from wger.manager.tests.testcase import WorkoutManagerTestCase+from wger.utils.helpers import next_weekday+++class IcalToolsTestCase(WorkoutManagerTestCase):+ '''+ Tests some tools used for iCal generation+ '''++ def test_next_weekday(self):+ '''+ Test the next weekday function+ '''+ start_date = datetime.date(2013, 12, 5)++ # Find next monday+ self.assertEqual(next_weekday(start_date, 0), datetime.date(2013, 12, 9))++ # Find next wednesday+ self.assertEqual(next_weekday(start_date, 2), datetime.date(2013, 12, 11))++ # Find next saturday+ self.assertEqual(next_weekday(start_date, 5), datetime.date(2013, 12, 7))diff --git a/wger/manager/urls.py b/wger/manager/urls.pyindex 86e177fde..d10dc5a02 100644--- a/wger/manager/urls.py+++ b/wger/manager/urls.py@@ -81,6 +81,9 @@ urlpatterns = patterns('wger.manager.views',url(r'^workout/calendar/(?P<year>\d{4})-(?P<month>\d{1,2})$','log.calendar',name='workout-calendar'),+ url(r'^workout/(?P<pk>\d+)/ical$',+ 'ical.export',+ name='workout-ical'),# Schedulesurl(r'^workout/schedule/overview$',diff --git a/wger/manager/views/ical.py b/wger/manager/views/ical.pynew file mode 100644index 000000000..59422fa00--- /dev/null+++ b/wger/manager/views/ical.py@@ -0,0 +1,101 @@+# -*- coding: utf-8 -*-++# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager 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 Affero General Public License++import logging+import uuid+import pytz+import datetime++from icalendar import Calendar+from icalendar import Alarm+from icalendar import Event+from icalendar.tools import UIDGenerator++from django.http import HttpResponse+from django.contrib.auth.decorators import login_required+from django.conf import settings+from django.contrib.sites.models import Site++from wger import get_version+from wger.manager.models import Workout+from wger.utils.helpers import next_weekday++logger = logging.getLogger('wger.custom')+++'''+Exports workouts and schedules as an iCal file that can be imported to a+calendaring application.++The icalendar module has atrocious documentation, to get the slightest chance+to make this work, looking at the module test files or the official RF is+*really* the only way....++* https://tools.ietf.org/html/rfc5545+* https://github.com/collective/icalendar/tree/master/src/icalendar/tests+'''+++@login_required+def export(request, pk):+ '''+ Export the current workout as iCal file+ '''++ # Load objects+ workout = Workout.objects.get(pk=pk)+ site = Site.objects.get(pk=settings.SITE_ID)+ generator = UIDGenerator()++ # Create the calendar+ calendar = Calendar()+ calendar.add('prodid', '-//wger Workout Manager//wger.de//')+ calendar.add('version', get_version())++ # Create the events and set the occurrence for each as weekly+ start_date = workout.creation_date+ end_date = start_date + datetime.timedelta(weeks=request.user.userprofile.workout_duration)+ for day in workout.day_set.all():++ # Make the description of the event with the day's exercises+ description_list = []+ for set in day.set_set.select_related():+ for exercise in set.exercises.select_related():+ description_list.append(unicode(exercise))+ description = ', '.join(description_list) if description_list else day.description++ # Make an event for each weekday+ for weekday in day.day.all():+ event = Event()+ event.add('summary', day.description)+ event.add('description', description)+ event.add('dtstart', next_weekday(start_date, weekday.id - 1))+ event.add('dtend', next_weekday(start_date, weekday.id - 1))+ event.add('rrule', {'freq': 'weekly', 'until': end_date})+ event['uid'] = generator.uid(host_name=site.domain)+ event.add('priority', 5)+ calendar.add_component(event)++ # Create an alarm for the end of the workout+ #alarm = Alarm()+ #alarm.+ #calendar.add_component(alarm)++ # Send the file to the user+ response = HttpResponse(mimetype='text/calendar')+ response['Content-Disposition'] = 'attachment; filename=calendar-{0}.ics'.format(workout.pk)+ response.write(calendar.to_ical())+ return responsediff --git a/wger/software/templates/changelog.html b/wger/software/templates/changelog.htmlindex 77d2ac92f..ccb2d6fcf 100644--- a/wger/software/templates/changelog.html+++ b/wger/software/templates/changelog.html@@ -13,6 +13,7 @@<ul><li>Calendar view to more easily check workout logs</li><li>Add automatic email remainders for new workouts</li>+ <li>New iCal export to add workouts and schedules e.g. to google calendar</li></ul>diff --git a/wger/utils/helpers.py b/wger/utils/helpers.pyindex d33544b5a..1f968babf 100644--- a/wger/utils/helpers.py+++ b/wger/utils/helpers.py@@ -17,6 +17,7 @@import loggingimport decimalimport json+import datetimefrom functools import wraps@@ -50,3 +51,23 @@ def disable_for_loaddata(signal_handler):returnsignal_handler(*args, **kwargs)return wrapper+++def next_weekday(date, weekday):+ '''+ Helper function to find the next weekday after a given date,+ e.g. the first Monday after the 2013-12-05++ See link for more details:+ * http://stackoverflow.com/questions/6558535/python-find-the-date-for-the-first-monday-after-a++ :param date: the start date+ :param weekday: weekday (0, Monday, 1 Tuesday, 2 Wednesday)+ :type date: datetime.date+ :type weekday int+ :return: datetime.date+ '''+ days_ahead = weekday - date.weekday()+ if days_ahead <= 0:+ days_ahead += 7+ return date + datetime.timedelta(days_ahead)