Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Also export schedules as calendar files

Roland Geiderf1b6fd3d5786
diff --git a/wger/manager/templates/mobile/schedule/view.html b/wger/manager/templates/mobile/schedule/view.html
index e503b041d..e3d252e56 100644
--- a/wger/manager/templates/mobile/schedule/view.html
+++ b/wger/manager/templates/mobile/schedule/view.html
@@ -81,6 +81,19 @@ edit the order per drag-and-drop. It's also possible to add one workout more
than once.{% endblocktrans %}</p>
<h3>{% trans "Options" %}</h3>
+<p>
+<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>
+</p>
+
<p>
<a href="{% url 'schedule-edit' schedule.id %}"
data-role="button">
@@ -102,4 +115,29 @@ than once.{% endblocktrans %}</p>
title="{% trans 'Delete schedule' %}">
{% trans "Delete schedule" %}</a>
</p>
+
+<div data-role="popup"
+ id="export-ical-link"
+ data-overlay-theme="a"
+ class="ui-content">
+ <div>
+ <h3>{% trans "Export calendar file" %}</h3>
+ <p>{% trans "Export this schedule as a calendar file." %}</p>
+ <p>{% blocktrans %}You can then import the file 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 'schedule-ical' schedule.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/mobile/workout/view.html b/wger/manager/templates/mobile/workout/view.html
index 332cb948e..dae75e2d7 100644
--- a/wger/manager/templates/mobile/workout/view.html
+++ b/wger/manager/templates/mobile/workout/view.html
@@ -194,10 +194,10 @@ $( document ).off("pageinit").on("pageinit", function() {
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>{% trans "Export this workout as a calendar file." %}</p>
+ <p>{% blocktrans %}You can then import the file 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"
diff --git a/wger/manager/templates/navigation.html b/wger/manager/templates/navigation.html
index a5f0d2e06..3a0472f00 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 "Weight log calendar" %}</a></li>
+ <li><a href="{% url 'workout-calendar' %}" rel="nofollow">{% trans "Calendar" %}</a></li>
<li><a href="{% url 'schedule-overview' %}" rel="nofollow">{% trans "Workouts schedules" %}</a></li>
</ul>
</li>
diff --git a/wger/manager/templates/schedule/view.html b/wger/manager/templates/schedule/view.html
index 08bd54703..d00229f98 100644
--- a/wger/manager/templates/schedule/view.html
+++ b/wger/manager/templates/schedule/view.html
@@ -44,6 +44,16 @@ $(function() {
init_sortable();
init_schedule_datepicker();
});
+
+$(document).ready(function() {
+ // Popup for exporting ical file
+ $('#export-ical-link').click(function(e){
+ e.preventDefault();
+ $('#export-ical-popup').dialog({
+ modal: true
+ });
+ });
+ });
</script>
{% endblock %}
@@ -145,6 +155,16 @@ edit the order per drag-and-drop. It's also possible to add one workout more
than once.{% endblocktrans %}</p>
<h3>{% trans "Options" %}</h3>
+<p>
+<a href="#" 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 'schedule-edit' schedule.id %}"
class="modal-dialog">
@@ -167,4 +187,24 @@ than once.{% endblocktrans %}</p>
{% trans "Delete schedule" %}</a>
</p>
+
+<div id="export-ical-popup" style="display:none;">
+ <div>
+ <h3>{% trans "Export calendar file" %}</h3>
+ <p>{% trans "Export this schedule as a calendar file." %}</p>
+ <p>{% blocktrans %}You can then import the file 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 'schedule-ical' schedule.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/templates/workout/view.html b/wger/manager/templates/workout/view.html
index 135c3c5f7..77273c479 100644
--- a/wger/manager/templates/workout/view.html
+++ b/wger/manager/templates/workout/view.html
@@ -29,7 +29,7 @@ $(document).ready(function() {
{% endif %}
toggle_comments();
- // Popup for adding logs
+ // Popup for exporting ical file
$('#export-ical-link').click(function(e){
e.preventDefault();
$('#export-ical-popup').dialog({
@@ -197,10 +197,10 @@ $(document).ready(function() {
<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>{% trans "Export this workout as a calendar file." %}</p>
+ <p>{% blocktrans %}You can then import the file 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' %}"
diff --git a/wger/manager/tests/test_ical.py b/wger/manager/tests/test_ical.py
index a8e56242f..16d7579e3 100644
--- a/wger/manager/tests/test_ical.py
+++ b/wger/manager/tests/test_ical.py
@@ -20,6 +20,9 @@ from wger.manager.tests.testcase import WorkoutManagerTestCase
from wger.utils.helpers import next_weekday
+# TODO: parse the generated calendar files with the icalendar library
+
+
class IcalToolsTestCase(WorkoutManagerTestCase):
'''
Tests some tools used for iCal generation
@@ -58,7 +61,8 @@ class WorkoutICalExportTestCase(WorkoutManagerTestCase):
else:
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'text/calendar')
- self.assertEqual(response['Content-Disposition'], 'attachment; filename=calendar-3.ics')
+ self.assertEqual(response['Content-Disposition'],
+ 'attachment; filename=Calendar-workout-3.ics')
# Approximate size
self.assertGreater(len(response.content), 550)
@@ -86,3 +90,51 @@ class WorkoutICalExportTestCase(WorkoutManagerTestCase):
self.user_login('admin')
self.export_ical(fail=True)
+
+
+class ScheduleICalExportTestCase(WorkoutManagerTestCase):
+ '''
+ Tests exporting the ical file for a scheduel
+ '''
+
+ def export_ical(self, fail=False):
+ '''
+ Helper function
+ '''
+
+ response = self.client.get(reverse('schedule-ical', kwargs={'pk': 2}))
+
+ if fail:
+ self.assertIn(response.status_code, (404, 302))
+ else:
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response['Content-Type'], 'text/calendar')
+ self.assertEqual(response['Content-Disposition'],
+ 'attachment; filename=Calendar-schedule-2.ics')
+
+ # Approximate size
+ self.assertGreater(len(response.content), 1650)
+ self.assertLess(len(response.content), 1660)
+
+ def test_export_ical_anonymous(self):
+ '''
+ Tests exporting a schedule as an ical file as an anonymous user
+ '''
+
+ self.export_ical(fail=True)
+
+ def test_export_ical_owner(self):
+ '''
+ Tests exporting a schedule as an ical file as the owner user
+ '''
+
+ self.user_login('admin')
+ self.export_ical(fail=False)
+
+ def test_export_ical_other(self):
+ '''
+ Tests exporting a schedule as an ical file as a logged user not owning the data
+ '''
+
+ self.user_login('test')
+ self.export_ical(fail=True)
diff --git a/wger/manager/urls.py b/wger/manager/urls.py
index d10dc5a02..a2cad8370 100644
--- a/wger/manager/urls.py
+++ b/wger/manager/urls.py
@@ -14,6 +14,7 @@ from wger.manager.views.day import DayEditView
from wger.manager.views.day import DayCreateView
from wger.manager.views import set
from wger.manager.views import misc
+from wger.manager.views import ical
from wger.utils.constants import USER_TAB
@@ -82,7 +83,7 @@ urlpatterns = patterns('wger.manager.views',
'log.calendar',
name='workout-calendar'),
url(r'^workout/(?P<pk>\d+)/ical$',
- 'ical.export',
+ ical.export,
name='workout-ical'),
# Schedules
@@ -101,6 +102,9 @@ urlpatterns = patterns('wger.manager.views',
url(r'^workout/schedule/(?P<pk>\d+)/delete/$',
schedule.ScheduleDeleteView.as_view(),
name='schedule-delete'),
+ url(r'^workout/schedule/(?P<pk>\d+)/ical$',
+ ical.export_schedule,
+ name='schedule-ical'),
url(r'^workout/schedule/api/(?P<pk>\d+)/edit$',
'schedule.edit_step_api',
name='schedule-edit-api'),
diff --git a/wger/manager/views/ical.py b/wger/manager/views/ical.py
index 59422fa00..4d7f65e91 100644
--- a/wger/manager/views/ical.py
+++ b/wger/manager/views/ical.py
@@ -15,24 +15,23 @@
# 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.shortcuts import get_object_or_404
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.manager.models import Workout, Schedule
from wger.utils.helpers import next_weekday
+
logger = logging.getLogger('wger.custom')
@@ -49,25 +48,37 @@ to make this work, looking at the module test files or the official RF is
'''
-@login_required
-def export(request, pk):
+# Helper functions
+def get_calendar():
'''
- 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()
+ Creates and returns a calendar object
- # Create the calendar
+ :return: Calendar
+ '''
calendar = Calendar()
calendar.add('prodid', '-//wger Workout Manager//wger.de//')
calendar.add('version', get_version())
+ return calendar
+
+
+def get_events_workout(calendar, workout, duration, start_date=None):
+ '''
+ Creates all necessary events from the given workout and adds them to
+ the calendar. Each event's occurrence ist set to weekly (one event for
+ each training day).
+
+ :param calendar: calendar to add events to
+ :param workout: Workout
+ :param duration: duration in weeks
+ :param start_date: start date, default: profile default
+ :return: None
+ '''
+
+ start_date = start_date if start_date else workout.creation_date
+ end_date = start_date + datetime.timedelta(weeks=duration)
+ generator = UIDGenerator()
+ site = Site.objects.get(pk=settings.SITE_ID)
- # 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
@@ -89,13 +100,52 @@ def export(request, pk):
event.add('priority', 5)
calendar.add_component(event)
- # Create an alarm for the end of the workout
- #alarm = Alarm()
- #alarm.
- #calendar.add_component(alarm)
+
+# Views
+@login_required
+def export(request, pk):
+ '''
+ Export the current workout as an iCal file
+ '''
+
+ # Load workout
+ workout = get_object_or_404(Workout, pk=pk, user=request.user)
+
+ # Create the calendar
+ calendar = get_calendar()
+
+ # Create the events and add them to the calendar
+ get_events_workout(calendar, workout, request.user.userprofile.workout_duration)
+
+ # Send the file to the user
+ response = HttpResponse(mimetype='text/calendar')
+ response['Content-Disposition'] = \
+ 'attachment; filename=Calendar-workout-{0}.ics'.format(workout.pk)
+ response.write(calendar.to_ical())
+ return response
+
+
+@login_required
+def export_schedule(request, pk):
+ '''
+ Export the current schedule as an iCal file
+ '''
+
+ # Load schedule
+ schedule = get_object_or_404(Schedule, pk=pk, user=request.user)
+
+ # Create the calendar
+ calendar = get_calendar()
+
+ # Create the events and add them to the calendar
+ start_date = datetime.date.today()
+ for step in schedule.schedulestep_set.all():
+ get_events_workout(calendar, step.workout, step.duration, start_date)
+ start_date = start_date + datetime.timedelta(weeks=step.duration)
# Send the file to the user
response = HttpResponse(mimetype='text/calendar')
- response['Content-Disposition'] = 'attachment; filename=calendar-{0}.ics'.format(workout.pk)
+ response['Content-Disposition'] = \
+ 'attachment; filename=Calendar-schedule-{0}.ics'.format(schedule.pk)
response.write(calendar.to_ical())
return response