├── .coveragerc ├── .dockerignore ├── .editorconfig ├── .gitattributes ├── .gitignore ├── .pylintrc ├── .travis.yml ├── CONTRIBUTORS.txt ├── LICENSE ├── README.rst ├── compose ├── django │ ├── Dockerfile │ ├── Dockerfile-dev │ ├── entrypoint.sh │ ├── gunicorn.sh │ ├── start-dev.sh │ └── worker.sh ├── mattermost │ ├── Dockerfile │ ├── config.json │ └── docker-entry.sh ├── nginx │ ├── Dockerfile │ └── nginx.conf └── postgres │ ├── Dockerfile │ ├── backup.sh │ ├── list-backups.sh │ └── restore.sh ├── config ├── __init__.py ├── settings │ ├── __init__.py │ ├── common.py │ ├── local.py │ ├── production.py │ └── test.py ├── urls.py └── wsgi.py ├── dev.yml ├── docker-compose.example.yml ├── docs ├── Makefile ├── __init__.py ├── changelog.rst ├── conf.py ├── deploy.rst ├── features.rst ├── index.rst ├── install-locally.rst ├── make.bat ├── tests.rst ├── trax.gif └── user-guide.rst ├── env.example ├── manage.py ├── pytest.ini ├── requirements ├── base.txt ├── local.txt ├── production.txt ├── requirements.apt └── test.txt ├── setup.cfg ├── test.py ├── trax ├── __init__.py ├── contrib │ ├── __init__.py │ └── sites │ │ ├── __init__.py │ │ └── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_alter_domain_unique.py │ │ ├── 0003_set_site_domain_and_name.py │ │ └── __init__.py ├── static │ ├── css │ │ └── project.css │ ├── fonts │ │ └── .gitkeep │ ├── images │ │ └── favicon.ico │ ├── js │ │ └── project.js │ └── sass │ │ └── project.scss ├── taskapp │ ├── __init__.py │ └── celery.py ├── templates │ ├── 403_csrf.html │ ├── 404.html │ ├── 500.html │ ├── account │ │ ├── account_inactive.html │ │ ├── base.html │ │ ├── email.html │ │ ├── email_confirm.html │ │ ├── login.html │ │ ├── logout.html │ │ ├── password_change.html │ │ ├── password_reset.html │ │ ├── password_reset_done.html │ │ ├── password_reset_from_key.html │ │ ├── password_reset_from_key_done.html │ │ ├── password_set.html │ │ ├── signup.html │ │ ├── signup_closed.html │ │ ├── verification_sent.html │ │ └── verified_email_required.html │ ├── base.html │ ├── bootstrap4 │ │ ├── field.html │ │ └── layout │ │ │ └── field_errors_block.html │ ├── pages │ │ ├── about.html │ │ └── home.html │ ├── trax │ │ ├── handlers │ │ │ ├── base_help.md │ │ │ ├── config.md │ │ │ ├── config_help.md │ │ │ ├── cron.md │ │ │ ├── cron_help.md │ │ │ ├── error.md │ │ │ ├── help.md │ │ │ ├── list.md │ │ │ ├── list_help.md │ │ │ ├── remind_add.md │ │ │ ├── remind_delete.md │ │ │ ├── remind_list.md │ │ │ ├── restart.md │ │ │ ├── start.md │ │ │ ├── start_error_missing_arg.md │ │ │ ├── start_help.md │ │ │ ├── stats.md │ │ │ ├── stop.md │ │ │ ├── stop_help.md │ │ │ ├── time.md │ │ │ └── time_help.md │ │ └── reminder.md │ └── users │ │ ├── user_detail.html │ │ ├── user_form.html │ │ └── user_list.html ├── trax │ ├── __init__.py │ ├── admin.py │ ├── dynamic_preferences_registry.py │ ├── exceptions.py │ ├── forms.py │ ├── handlers.py │ ├── management │ │ └── commands │ │ │ ├── __init__.py │ │ │ └── trax_schedule.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20170106_1642.py │ │ └── __init__.py │ ├── models.py │ ├── tasks.py │ ├── templatetags │ │ ├── __init__.py │ │ └── trax_tags.py │ ├── tests │ │ ├── test_forms.py │ │ ├── test_handlers.py │ │ ├── test_reminders.py │ │ ├── test_tasks.py │ │ ├── test_timer.py │ │ └── test_utils.py │ ├── urls.py │ ├── utils.py │ └── views.py └── users │ ├── __init__.py │ ├── adapters.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ ├── 0001_initial.py │ └── __init__.py │ ├── models.py │ ├── tests │ ├── __init__.py │ ├── factories.py │ ├── test_admin.py │ ├── test_models.py │ ├── test_urls.py │ └── test_views.py │ ├── urls.py │ └── views.py └── utility ├── install_os_dependencies.sh ├── install_python_dependencies.sh ├── requirements-jessie.apt ├── requirements-trusty.apt └── requirements-xenial.apt /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | include = trax/* 3 | omit = *migrations*, *tests* 4 | plugins = 5 | django_coverage_plugin 6 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .* 2 | !.coveragerc 3 | !.env 4 | !.pylintrc 5 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.{py,rst,ini}] 12 | indent_style = space 13 | indent_size = 4 14 | 15 | [*.py] 16 | line_length=120 17 | known_first_party=trax 18 | multi_line_output=3 19 | default_section=THIRDPARTY 20 | 21 | [*.{html,css,scss,json,yml}] 22 | indent_style = space 23 | indent_size = 2 24 | 25 | [*.md] 26 | trim_trailing_whitespace = false 27 | 28 | [Makefile] 29 | indent_style = tab 30 | 31 | [nginx.conf] 32 | indent_style = space 33 | indent_size = 2 34 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | docker-compose.yml 2 | volumes 3 | 4 | ### OSX ### 5 | .DS_Store 6 | .AppleDouble 7 | .LSOverride 8 | docs/_build 9 | ### SublimeText ### 10 | # cache files for sublime text 11 | *.tmlanguage.cache 12 | *.tmPreferences.cache 13 | *.stTheme.cache 14 | 15 | # workspace files are user-specific 16 | *.sublime-workspace 17 | 18 | # project files should be checked into the repository, unless a significant 19 | # proportion of contributors will probably not be using SublimeText 20 | # *.sublime-project 21 | 22 | # sftp configuration file 23 | sftp-config.json 24 | 25 | # Basics 26 | *.py[cod] 27 | __pycache__ 28 | 29 | # Logs 30 | logs 31 | *.log 32 | pip-log.txt 33 | npm-debug.log* 34 | 35 | # Unit test / coverage reports 36 | .coverage 37 | .tox 38 | nosetests.xml 39 | htmlcov 40 | 41 | # Translations 42 | *.mo 43 | *.pot 44 | 45 | # Pycharm 46 | .idea/* 47 | 48 | 49 | # Vim 50 | 51 | *~ 52 | *.swp 53 | *.swo 54 | 55 | # npm 56 | node_modules/ 57 | 58 | # Compass 59 | .sass-cache 60 | 61 | # virtual environments 62 | .env 63 | 64 | # User-uploaded media 65 | trax/media/ 66 | 67 | 68 | 69 | staticfiles/ 70 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | load-plugins=pylint_common, pylint_django, pylint_celery 3 | 4 | [FORMAT] 5 | max-line-length=120 6 | 7 | [MESSAGES CONTROL] 8 | disable=missing-docstring,invalid-name 9 | 10 | [DESIGN] 11 | max-parents=13 12 | 13 | [TYPECHECK] 14 | generated-members=REQUEST,acl_users,aq_parent,"[a-zA-Z]+_set{1,2}",save,delete 15 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: true 2 | services: 3 | - docker 4 | before_install: 5 | - docker-compose -f dev.yml build 6 | - cp env.example .env 7 | script: 8 | - docker-compose -f dev.yml run django pytest 9 | 10 | language: python 11 | python: 12 | - "3.5" 13 | -------------------------------------------------------------------------------- /CONTRIBUTORS.txt: -------------------------------------------------------------------------------- 1 | Eliot Berriot 2 | Markus Busche 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | The MIT License (MIT) 3 | Copyright (c) 2016, Eliot Berriot 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | 11 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | trax 2 | ==== 3 | 4 | Simple time tracking server designed to work with Mattermost / Slack. 5 | 6 | .. image:: https://img.shields.io/badge/built%20with-Cookiecutter%20Django-ff69b4.svg 7 | :target: https://github.com/pydanny/cookiecutter-django/ 8 | :alt: Built with Cookiecutter Django 9 | 10 | :License: MIT 11 | 12 | Overview 13 | -------- 14 | 15 | Trax is a time tracking server written in Python/Django, designed to work within a chat server such as Mattermost or Slack. You interact with it directly from your chat server, using slash commands and webhooks:: 16 | 17 | # start to work on something 18 | /trax start making coffee 19 | 20 | # Get a pretty reminder in channel in 5 minutes 21 | /trax remind add "Call mom" "in 5 minutes" 22 | 23 | # start to work on something else 24 | /trax start reading emails 25 | 26 | # Stop working 27 | /trax stop 28 | 29 | # see how you spent your time today 30 | /trax stats 31 | 32 | Documentation 33 | ------------- 34 | 35 | Detailed user guide, installation and deployment instructions are available at https://traxio.readthedocs.io/. 36 | -------------------------------------------------------------------------------- /compose/django/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.5 2 | 3 | ENV PYTHONUNBUFFERED 1 4 | 5 | # Requirements have to be pulled and installed here, otherwise caching won't work 6 | COPY ./requirements /requirements 7 | 8 | RUN pip install -r /requirements/production.txt \ 9 | && groupadd -r django \ 10 | && useradd -r -g django django 11 | 12 | COPY . /app 13 | RUN chown -R django /app 14 | 15 | COPY ./compose/django/gunicorn.sh /gunicorn.sh 16 | COPY ./compose/django/entrypoint.sh /entrypoint.sh 17 | RUN sed -i 's/\r//' /entrypoint.sh \ 18 | && sed -i 's/\r//' /gunicorn.sh \ 19 | && chmod +x /entrypoint.sh \ 20 | && chown django /entrypoint.sh \ 21 | && chmod +x /gunicorn.sh \ 22 | && chown django /gunicorn.sh 23 | 24 | WORKDIR /app 25 | 26 | ENTRYPOINT ["/entrypoint.sh"] 27 | -------------------------------------------------------------------------------- /compose/django/Dockerfile-dev: -------------------------------------------------------------------------------- 1 | FROM python:3.5 2 | 3 | ENV PYTHONUNBUFFERED 1 4 | 5 | RUN apt-get update && apt-get install -y inotify-tools 6 | 7 | # Requirements have to be pulled and installed here, otherwise caching won't work 8 | COPY ./requirements /requirements 9 | RUN pip install -r /requirements/local.txt 10 | RUN pip install -r /requirements/test.txt 11 | 12 | COPY ./compose/django/entrypoint.sh /entrypoint.sh 13 | RUN sed -i 's/\r//' /entrypoint.sh 14 | RUN chmod +x /entrypoint.sh 15 | 16 | COPY ./compose/django/start-dev.sh /start-dev.sh 17 | RUN sed -i 's/\r//' /start-dev.sh 18 | RUN chmod +x /start-dev.sh 19 | 20 | WORKDIR /app 21 | 22 | ENTRYPOINT ["/entrypoint.sh"] 23 | -------------------------------------------------------------------------------- /compose/django/entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | cmd="$@" 4 | 5 | # This entrypoint is used to play nicely with the current cookiecutter configuration. 6 | # Since docker-compose relies heavily on environment variables itself for configuration, we'd have to define multiple 7 | # environment variables just to support cookiecutter out of the box. That makes no sense, so this little entrypoint 8 | # does all this for us. 9 | export REDIS_URL=redis://redis:6379 10 | 11 | # the official postgres image uses 'postgres' as default user if not set explictly. 12 | if [ -z "$POSTGRES_USER" ]; then 13 | export POSTGRES_USER=postgres 14 | fi 15 | 16 | export DATABASE_URL=postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@postgres:5432/$POSTGRES_USER 17 | 18 | export CELERY_BROKER_URL=$REDIS_URL/0 19 | 20 | 21 | function postgres_ready(){ 22 | python << END 23 | import sys 24 | import psycopg2 25 | try: 26 | conn = psycopg2.connect(dbname="$POSTGRES_USER", user="$POSTGRES_USER", password="$POSTGRES_PASSWORD", host="postgres") 27 | except psycopg2.OperationalError: 28 | sys.exit(-1) 29 | sys.exit(0) 30 | END 31 | } 32 | 33 | until postgres_ready; do 34 | >&2 echo "Postgres is unavailable - sleeping" 35 | sleep 1 36 | done 37 | 38 | >&2 echo "Postgres is up - continuing..." 39 | exec $cmd 40 | -------------------------------------------------------------------------------- /compose/django/gunicorn.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | python /app/manage.py collectstatic --noinput 3 | /usr/local/bin/gunicorn config.wsgi -w 4 -b 0.0.0.0:5000 --chdir=/app -------------------------------------------------------------------------------- /compose/django/start-dev.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | python manage.py migrate 3 | python manage.py runserver_plus 0.0.0.0:8000 4 | -------------------------------------------------------------------------------- /compose/django/worker.sh: -------------------------------------------------------------------------------- 1 | sigint_handler() 2 | { 3 | kill $PID 4 | exit 5 | } 6 | 7 | trap sigint_handler SIGINT 8 | CMD="python /app/manage.py trax_schedule" 9 | while true; do 10 | $CMD & 11 | PID=$! 12 | inotifywait -r -e close_write /app/ 13 | kill $PID 14 | done 15 | -------------------------------------------------------------------------------- /compose/mattermost/Dockerfile: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2016 Mattermost, Inc. All Rights Reserved. 2 | # See License.txt for license information. 3 | FROM mysql:5.7 4 | 5 | # Install ca-certificates to support TLS of Mattermost v3.5 6 | RUN apt-get update && apt-get install -y ca-certificates curl 7 | 8 | # 9 | # Configure SQL 10 | # 11 | 12 | ENV MYSQL_ROOT_PASSWORD=mostest 13 | ENV MYSQL_USER=mmuser 14 | ENV MYSQL_PASSWORD=mostest 15 | ENV MYSQL_DATABASE=mattermost_test 16 | 17 | # 18 | # Configure Mattermost 19 | # 20 | 21 | RUN mkdir -p /mattermost/data 22 | VOLUME /mattermost/data 23 | 24 | RUN curl https://releases.mattermost.com/3.6.1/mattermost-team-3.6.1-linux-amd64.tar.gz | tar -xvz 25 | 26 | RUN rm /mattermost/config/config.json 27 | 28 | WORKDIR /mattermost 29 | ADD docker-entry.sh . 30 | RUN chmod +x ./docker-entry.sh 31 | ENTRYPOINT ["./docker-entry.sh"] 32 | 33 | EXPOSE 8065 34 | -------------------------------------------------------------------------------- /compose/mattermost/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "ServiceSettings": { 3 | "SiteURL": "", 4 | "ListenAddress": ":80", 5 | "ConnectionSecurity": "", 6 | "TLSCertFile": "", 7 | "TLSKeyFile": "", 8 | "UseLetsEncrypt": false, 9 | "LetsEncryptCertificateCacheFile": "./config/letsencrypt.cache", 10 | "Forward80To443": false, 11 | "ReadTimeout": 300, 12 | "WriteTimeout": 300, 13 | "MaximumLoginAttempts": 10, 14 | "SegmentDeveloperKey": "", 15 | "GoogleDeveloperKey": "", 16 | "EnableOAuthServiceProvider": true, 17 | "EnableIncomingWebhooks": true, 18 | "EnableOutgoingWebhooks": true, 19 | "EnableCommands": true, 20 | "EnableOnlyAdminIntegrations": true, 21 | "EnablePostUsernameOverride": false, 22 | "EnablePostIconOverride": false, 23 | "EnableTesting": false, 24 | "EnableDeveloper": false, 25 | "EnableSecurityFixAlert": true, 26 | "EnableInsecureOutgoingConnections": false, 27 | "EnableMultifactorAuthentication": false, 28 | "EnforceMultifactorAuthentication": false, 29 | "AllowCorsFrom": "", 30 | "SessionLengthWebInDays": 30, 31 | "SessionLengthMobileInDays": 30, 32 | "SessionLengthSSOInDays": 30, 33 | "SessionCacheInMinutes": 10, 34 | "WebsocketSecurePort": 443, 35 | "WebsocketPort": 80, 36 | "WebserverMode": "gzip", 37 | "EnableCustomEmoji": true, 38 | "RestrictCustomEmojiCreation": "all" 39 | }, 40 | "TeamSettings": { 41 | "SiteName": "Mattermost", 42 | "MaxUsersPerTeam": 50, 43 | "EnableTeamCreation": true, 44 | "EnableUserCreation": true, 45 | "EnableOpenServer": false, 46 | "RestrictCreationToDomains": "", 47 | "EnableCustomBrand": false, 48 | "CustomBrandText": "", 49 | "CustomDescriptionText": "", 50 | "RestrictDirectMessage": "any", 51 | "RestrictTeamInvite": "all", 52 | "RestrictPublicChannelManagement": "all", 53 | "RestrictPrivateChannelManagement": "all", 54 | "RestrictPublicChannelCreation": "all", 55 | "RestrictPrivateChannelCreation": "all", 56 | "RestrictPublicChannelDeletion": "all", 57 | "RestrictPrivateChannelDeletion": "all", 58 | "UserStatusAwayTimeout": 300, 59 | "MaxChannelsPerTeam": 2000, 60 | "MaxNotificationsPerChannel": 1000000 61 | }, 62 | "SqlSettings": { 63 | "DriverName": "mysql", 64 | "DataSource": "mmuser:mostest@tcp(127.0.0.1:3306)/mattermost_test?charset=utf8mb4,utf8", 65 | "DataSourceReplicas": [], 66 | "MaxIdleConns": 10, 67 | "MaxOpenConns": 10, 68 | "Trace": false, 69 | "AtRestEncryptKey": "7rAh6iwQCkV4cA1Gsg3fgGOXJAQ43QVg" 70 | }, 71 | "LogSettings": { 72 | "EnableConsole": true, 73 | "ConsoleLevel": "DEBUG", 74 | "EnableFile": true, 75 | "FileLevel": "INFO", 76 | "FileFormat": "", 77 | "FileLocation": "", 78 | "EnableWebhookDebugging": true, 79 | "EnableDiagnostics": true 80 | }, 81 | "PasswordSettings": { 82 | "MinimumLength": 5, 83 | "Lowercase": false, 84 | "Number": false, 85 | "Uppercase": false, 86 | "Symbol": false 87 | }, 88 | "FileSettings": { 89 | "MaxFileSize": 52428800, 90 | "DriverName": "local", 91 | "Directory": "/mattermost/data/", 92 | "EnablePublicLink": true, 93 | "PublicLinkSalt": "A705AklYF8MFDOfcwh3I488G8vtLlVip", 94 | "ThumbnailWidth": 120, 95 | "ThumbnailHeight": 100, 96 | "PreviewWidth": 1024, 97 | "PreviewHeight": 0, 98 | "ProfileWidth": 128, 99 | "ProfileHeight": 128, 100 | "InitialFont": "luximbi.ttf", 101 | "AmazonS3AccessKeyId": "", 102 | "AmazonS3SecretAccessKey": "", 103 | "AmazonS3Bucket": "", 104 | "AmazonS3Region": "us-east-1", 105 | "AmazonS3Endpoint": "s3.amazonaws.com", 106 | "AmazonS3SSL": true 107 | }, 108 | "EmailSettings": { 109 | "EnableSignUpWithEmail": true, 110 | "EnableSignInWithEmail": true, 111 | "EnableSignInWithUsername": false, 112 | "SendEmailNotifications": false, 113 | "RequireEmailVerification": false, 114 | "FeedbackName": "", 115 | "FeedbackEmail": "", 116 | "FeedbackOrganization": "", 117 | "SMTPUsername": "", 118 | "SMTPPassword": "", 119 | "SMTPServer": "", 120 | "SMTPPort": "", 121 | "ConnectionSecurity": "", 122 | "InviteSalt": "bjlSR4QqkXFBr7TP4oDzlfZmcNuH9YoS", 123 | "PasswordResetSalt": "vZ4DcKyVVRlKHHJpexcuXzojkE5PZ5eL", 124 | "SendPushNotifications": false, 125 | "PushNotificationServer": "", 126 | "PushNotificationContents": "generic", 127 | "EnableEmailBatching": false, 128 | "EmailBatchingBufferSize": 256, 129 | "EmailBatchingInterval": 30 130 | }, 131 | "RateLimitSettings": { 132 | "Enable": false, 133 | "PerSec": 10, 134 | "MaxBurst": 100, 135 | "MemoryStoreSize": 10000, 136 | "VaryByRemoteAddr": true, 137 | "VaryByHeader": "" 138 | }, 139 | "PrivacySettings": { 140 | "ShowEmailAddress": true, 141 | "ShowFullName": true 142 | }, 143 | "SupportSettings": { 144 | "TermsOfServiceLink": "https://about.mattermost.com/default-terms/", 145 | "PrivacyPolicyLink": "", 146 | "AboutLink": "", 147 | "HelpLink": "", 148 | "ReportAProblemLink": "", 149 | "SupportEmail": "feedback@mattermost.com" 150 | }, 151 | "GitLabSettings": { 152 | "Enable": false, 153 | "Secret": "", 154 | "Id": "", 155 | "Scope": "", 156 | "AuthEndpoint": "", 157 | "TokenEndpoint": "", 158 | "UserApiEndpoint": "" 159 | }, 160 | "GoogleSettings": { 161 | "Enable": false, 162 | "Secret": "", 163 | "Id": "", 164 | "Scope": "", 165 | "AuthEndpoint": "", 166 | "TokenEndpoint": "", 167 | "UserApiEndpoint": "" 168 | }, 169 | "Office365Settings": { 170 | "Enable": false, 171 | "Secret": "", 172 | "Id": "", 173 | "Scope": "", 174 | "AuthEndpoint": "", 175 | "TokenEndpoint": "", 176 | "UserApiEndpoint": "" 177 | }, 178 | "LdapSettings": { 179 | "Enable": false, 180 | "LdapServer": "", 181 | "LdapPort": 389, 182 | "ConnectionSecurity": "", 183 | "BaseDN": "", 184 | "BindUsername": "", 185 | "BindPassword": "", 186 | "UserFilter": "", 187 | "FirstNameAttribute": "", 188 | "LastNameAttribute": "", 189 | "EmailAttribute": "", 190 | "UsernameAttribute": "", 191 | "NicknameAttribute": "", 192 | "IdAttribute": "", 193 | "PositionAttribute": "", 194 | "SyncIntervalMinutes": 60, 195 | "SkipCertificateVerification": false, 196 | "QueryTimeout": 60, 197 | "MaxPageSize": 0, 198 | "LoginFieldName": "" 199 | }, 200 | "ComplianceSettings": { 201 | "Enable": false, 202 | "Directory": "./data/", 203 | "EnableDaily": false 204 | }, 205 | "LocalizationSettings": { 206 | "DefaultServerLocale": "en", 207 | "DefaultClientLocale": "en", 208 | "AvailableLocales": "" 209 | }, 210 | "SamlSettings": { 211 | "Enable": false, 212 | "Verify": false, 213 | "Encrypt": false, 214 | "IdpUrl": "", 215 | "IdpDescriptorUrl": "", 216 | "AssertionConsumerServiceURL": "", 217 | "IdpCertificateFile": "", 218 | "PublicCertificateFile": "", 219 | "PrivateKeyFile": "", 220 | "FirstNameAttribute": "", 221 | "LastNameAttribute": "", 222 | "EmailAttribute": "", 223 | "UsernameAttribute": "", 224 | "NicknameAttribute": "", 225 | "LocaleAttribute": "", 226 | "PositionAttribute": "", 227 | "LoginButtonText": "With SAML" 228 | }, 229 | "NativeAppSettings": { 230 | "AppDownloadLink": "https://about.mattermost.com/downloads/", 231 | "AndroidAppDownloadLink": "https://about.mattermost.com/mattermost-android-app/", 232 | "IosAppDownloadLink": "https://about.mattermost.com/mattermost-ios-app/" 233 | }, 234 | "ClusterSettings": { 235 | "Enable": false, 236 | "InterNodeListenAddress": ":8075", 237 | "InterNodeUrls": [] 238 | }, 239 | "MetricsSettings": { 240 | "Enable": false, 241 | "BlockProfileRate": 0, 242 | "ListenAddress": ":8067" 243 | }, 244 | "AnalyticsSettings": { 245 | "MaxUsersForStatistics": 2500 246 | }, 247 | "WebrtcSettings": { 248 | "Enable": false, 249 | "GatewayWebsocketUrl": "", 250 | "GatewayAdminUrl": "", 251 | "GatewayAdminSecret": "", 252 | "StunURI": "", 253 | "TurnURI": "", 254 | "TurnUsername": "", 255 | "TurnSharedKey": "" 256 | } 257 | } 258 | -------------------------------------------------------------------------------- /compose/mattermost/docker-entry.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright (c) 2016 Mattermost, Inc. All Rights Reserved. 3 | # See License.txt for license information. 4 | 5 | echo "Starting MySQL" 6 | /entrypoint.sh mysqld & 7 | 8 | until mysqladmin -hlocalhost -P3306 -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" processlist &> /dev/null; do 9 | echo "MySQL still not ready, sleeping" 10 | sleep 1 11 | done 12 | 13 | sleep 1 14 | 15 | echo "Starting platform" 16 | exec ./bin/platform $@ 17 | -------------------------------------------------------------------------------- /compose/nginx/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM nginx:latest 2 | ADD nginx.conf /etc/nginx/nginx.conf 3 | 4 | 5 | -------------------------------------------------------------------------------- /compose/nginx/nginx.conf: -------------------------------------------------------------------------------- 1 | user nginx; 2 | worker_processes 1; 3 | 4 | error_log /var/log/nginx/error.log warn; 5 | pid /var/run/nginx.pid; 6 | 7 | events { 8 | worker_connections 1024; 9 | } 10 | 11 | http { 12 | include /etc/nginx/mime.types; 13 | default_type application/octet-stream; 14 | 15 | log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 16 | '$status $body_bytes_sent "$http_referer" ' 17 | '"$http_user_agent" "$http_x_forwarded_for"'; 18 | 19 | access_log /var/log/nginx/access.log main; 20 | 21 | sendfile on; 22 | #tcp_nopush on; 23 | 24 | keepalive_timeout 65; 25 | 26 | #gzip on; 27 | 28 | upstream app { 29 | server django:5000; 30 | } 31 | 32 | server { 33 | listen 80; 34 | charset utf-8; 35 | 36 | 37 | 38 | location / { 39 | # checks for static file, if not found proxy to app 40 | try_files $uri @proxy_to_app; 41 | } 42 | 43 | # cookiecutter-django app 44 | location @proxy_to_app { 45 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 46 | proxy_set_header Host $http_host; 47 | proxy_redirect off; 48 | proxy_pass http://app; 49 | 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /compose/postgres/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM postgres:9.6 2 | 3 | # add backup scripts 4 | ADD backup.sh /usr/local/bin/backup 5 | ADD restore.sh /usr/local/bin/restore 6 | ADD list-backups.sh /usr/local/bin/list-backups 7 | 8 | # make them executable 9 | RUN chmod +x /usr/local/bin/restore 10 | RUN chmod +x /usr/local/bin/list-backups 11 | RUN chmod +x /usr/local/bin/backup 12 | -------------------------------------------------------------------------------- /compose/postgres/backup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # stop on errors 3 | set -e 4 | 5 | # we might run into trouble when using the default `postgres` user, e.g. when dropping the postgres 6 | # database in restore.sh. Check that something else is used here 7 | if [ "$POSTGRES_USER" == "postgres" ] 8 | then 9 | echo "creating a backup as the postgres user is not supported, make sure to set the POSTGRES_USER environment variable" 10 | exit 1 11 | fi 12 | 13 | # export the postgres password so that subsequent commands don't ask for it 14 | export PGPASSWORD=$POSTGRES_PASSWORD 15 | 16 | echo "creating backup" 17 | echo "---------------" 18 | 19 | FILENAME=backup_$(date +'%Y_%m_%dT%H_%M_%S').sql.gz 20 | pg_dump -h postgres -U $POSTGRES_USER | gzip > /backups/$FILENAME 21 | 22 | echo "successfully created backup $FILENAME" 23 | -------------------------------------------------------------------------------- /compose/postgres/list-backups.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "listing available backups" 3 | echo "-------------------------" 4 | ls /backups/ 5 | -------------------------------------------------------------------------------- /compose/postgres/restore.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # stop on errors 4 | set -e 5 | 6 | # we might run into trouble when using the default `postgres` user, e.g. when dropping the postgres 7 | # database in restore.sh. Check that something else is used here 8 | if [ "$POSTGRES_USER" == "postgres" ] 9 | then 10 | echo "restoring as the postgres user is not supported, make sure to set the POSTGRES_USER environment variable" 11 | exit 1 12 | fi 13 | 14 | # export the postgres password so that subsequent commands don't ask for it 15 | export PGPASSWORD=$POSTGRES_PASSWORD 16 | 17 | # check that we have an argument for a filename candidate 18 | if [[ $# -eq 0 ]] ; then 19 | echo 'usage:' 20 | echo ' docker-compose run postgres restore ' 21 | echo '' 22 | echo 'to get a list of available backups, run:' 23 | echo ' docker-compose run postgres list-backups' 24 | exit 1 25 | fi 26 | 27 | # set the backupfile variable 28 | BACKUPFILE=/backups/$1 29 | 30 | # check that the file exists 31 | if ! [ -f $BACKUPFILE ]; then 32 | echo "backup file not found" 33 | echo 'to get a list of available backups, run:' 34 | echo ' docker-compose run postgres list-backups' 35 | exit 1 36 | fi 37 | 38 | echo "beginning restore from $1" 39 | echo "-------------------------" 40 | 41 | # delete the db 42 | # deleting the db can fail. Spit out a comment if this happens but continue since the db 43 | # is created in the next step 44 | echo "deleting old database $POSTGRES_USER" 45 | if dropdb -h postgres -U $POSTGRES_USER $POSTGRES_USER 46 | then echo "deleted $POSTGRES_USER database" 47 | else echo "database $POSTGRES_USER does not exist, continue" 48 | fi 49 | 50 | # create a new database 51 | echo "creating new database $POSTGRES_USER" 52 | createdb -h postgres -U $POSTGRES_USER $POSTGRES_USER -O $POSTGRES_USER 53 | 54 | # restore the database 55 | echo "restoring database $POSTGRES_USER" 56 | gunzip -c $BACKUPFILE | psql -h postgres -U $POSTGRES_USER 57 | -------------------------------------------------------------------------------- /config/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agateblue/trax/61a14b2a3cd6366422b27c48b9e3716bbdcd7ae5/config/__init__.py -------------------------------------------------------------------------------- /config/settings/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /config/settings/common.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Django settings for trax project. 4 | 5 | For more information on this file, see 6 | https://docs.djangoproject.com/en/dev/topics/settings/ 7 | 8 | For the full list of settings and their values, see 9 | https://docs.djangoproject.com/en/dev/ref/settings/ 10 | """ 11 | from __future__ import absolute_import, unicode_literals 12 | 13 | import environ 14 | 15 | ROOT_DIR = environ.Path(__file__) - 3 # (trax/config/settings/common.py - 3 = trax/) 16 | APPS_DIR = ROOT_DIR.path('trax') 17 | 18 | env = environ.Env() 19 | env.read_env(str(ROOT_DIR.path('.env'))) 20 | 21 | # APP CONFIGURATION 22 | # ------------------------------------------------------------------------------ 23 | DJANGO_APPS = ( 24 | # Default Django apps: 25 | 'django.contrib.auth', 26 | 'django.contrib.contenttypes', 27 | 'django.contrib.sessions', 28 | 'django.contrib.sites', 29 | 'django.contrib.messages', 30 | 'django.contrib.staticfiles', 31 | 32 | # Useful template tags: 33 | # 'django.contrib.humanize', 34 | 35 | # Admin 36 | 'django.contrib.admin', 37 | ) 38 | THIRD_PARTY_APPS = ( 39 | 'crispy_forms', # Form layouts 40 | 'allauth', # registration 41 | 'allauth.account', # registration 42 | 'allauth.socialaccount', # registration 43 | 'dynamic_preferences', 44 | ) 45 | 46 | # Apps specific for this project go here. 47 | LOCAL_APPS = ( 48 | # custom users app 49 | 'trax.users.apps.UsersConfig', 50 | 'trax.trax', 51 | # Your stuff: custom apps go here 52 | ) 53 | 54 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps 55 | INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS 56 | 57 | # MIDDLEWARE CONFIGURATION 58 | # ------------------------------------------------------------------------------ 59 | MIDDLEWARE = ( 60 | 'django.middleware.security.SecurityMiddleware', 61 | 'django.contrib.sessions.middleware.SessionMiddleware', 62 | 'django.middleware.common.CommonMiddleware', 63 | 'django.middleware.csrf.CsrfViewMiddleware', 64 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 65 | 'django.contrib.messages.middleware.MessageMiddleware', 66 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 67 | ) 68 | 69 | # MIGRATIONS CONFIGURATION 70 | # ------------------------------------------------------------------------------ 71 | MIGRATION_MODULES = { 72 | 'sites': 'trax.contrib.sites.migrations' 73 | } 74 | 75 | # DEBUG 76 | # ------------------------------------------------------------------------------ 77 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug 78 | DEBUG = env.bool('DJANGO_DEBUG', False) 79 | 80 | # FIXTURE CONFIGURATION 81 | # ------------------------------------------------------------------------------ 82 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS 83 | FIXTURE_DIRS = ( 84 | str(APPS_DIR.path('fixtures')), 85 | ) 86 | 87 | # EMAIL CONFIGURATION 88 | # ------------------------------------------------------------------------------ 89 | EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend') 90 | 91 | # MANAGER CONFIGURATION 92 | # ------------------------------------------------------------------------------ 93 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins 94 | ADMINS = ( 95 | ("""Eliot Berriot""", 'contact@eliotberriot.com'), 96 | ) 97 | 98 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#managers 99 | MANAGERS = ADMINS 100 | 101 | # DATABASE CONFIGURATION 102 | # ------------------------------------------------------------------------------ 103 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#databases 104 | DATABASES = { 105 | 'default': env.db('DATABASE_URL', default='postgres:///trax'), 106 | } 107 | DATABASES['default']['ATOMIC_REQUESTS'] = True 108 | 109 | 110 | # GENERAL CONFIGURATION 111 | # ------------------------------------------------------------------------------ 112 | # Local time zone for this installation. Choices can be found here: 113 | # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name 114 | # although not all choices may be available on all operating systems. 115 | # In a Windows environment this must be set to your system time zone. 116 | TIME_ZONE = env('TIME_ZONE', default='UTC') 117 | 118 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code 119 | LANGUAGE_CODE = 'en-us' 120 | 121 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id 122 | SITE_ID = 1 123 | 124 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n 125 | USE_I18N = True 126 | 127 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n 128 | USE_L10N = True 129 | 130 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz 131 | USE_TZ = True 132 | 133 | # TEMPLATE CONFIGURATION 134 | # ------------------------------------------------------------------------------ 135 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#templates 136 | TEMPLATES = [ 137 | { 138 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND 139 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 140 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs 141 | 'DIRS': [ 142 | str(APPS_DIR.path('templates')), 143 | ], 144 | 'OPTIONS': { 145 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug 146 | 'debug': DEBUG, 147 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders 148 | # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types 149 | 'loaders': [ 150 | 'django.template.loaders.filesystem.Loader', 151 | 'django.template.loaders.app_directories.Loader', 152 | ], 153 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors 154 | 'context_processors': [ 155 | 'django.template.context_processors.debug', 156 | 'django.template.context_processors.request', 157 | 'django.contrib.auth.context_processors.auth', 158 | 'django.template.context_processors.i18n', 159 | 'django.template.context_processors.media', 160 | 'django.template.context_processors.static', 161 | 'django.template.context_processors.tz', 162 | 'django.contrib.messages.context_processors.messages', 163 | # Your stuff: custom template context processors go here 164 | ], 165 | }, 166 | }, 167 | ] 168 | 169 | # See: http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs 170 | CRISPY_TEMPLATE_PACK = 'bootstrap4' 171 | 172 | # STATIC FILE CONFIGURATION 173 | # ------------------------------------------------------------------------------ 174 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root 175 | STATIC_ROOT = str(ROOT_DIR('staticfiles')) 176 | 177 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url 178 | STATIC_URL = '/static/' 179 | 180 | # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS 181 | STATICFILES_DIRS = ( 182 | str(APPS_DIR.path('static')), 183 | ) 184 | 185 | # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders 186 | STATICFILES_FINDERS = ( 187 | 'django.contrib.staticfiles.finders.FileSystemFinder', 188 | 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 189 | ) 190 | 191 | # MEDIA CONFIGURATION 192 | # ------------------------------------------------------------------------------ 193 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root 194 | MEDIA_ROOT = str(APPS_DIR('media')) 195 | 196 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url 197 | MEDIA_URL = '/media/' 198 | 199 | # URL Configuration 200 | # ------------------------------------------------------------------------------ 201 | ROOT_URLCONF = 'config.urls' 202 | 203 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application 204 | WSGI_APPLICATION = 'config.wsgi.application' 205 | 206 | 207 | # PASSWORD VALIDATION 208 | # https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators 209 | # ------------------------------------------------------------------------------ 210 | 211 | AUTH_PASSWORD_VALIDATORS = [ 212 | { 213 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 214 | }, 215 | { 216 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 217 | }, 218 | { 219 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 220 | }, 221 | { 222 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 223 | }, 224 | ] 225 | 226 | # AUTHENTICATION CONFIGURATION 227 | # ------------------------------------------------------------------------------ 228 | AUTHENTICATION_BACKENDS = ( 229 | 'django.contrib.auth.backends.ModelBackend', 230 | 'allauth.account.auth_backends.AuthenticationBackend', 231 | ) 232 | 233 | # Some really nice defaults 234 | ACCOUNT_AUTHENTICATION_METHOD = 'username' 235 | ACCOUNT_EMAIL_REQUIRED = True 236 | ACCOUNT_EMAIL_VERIFICATION = 'mandatory' 237 | 238 | ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', True) 239 | ACCOUNT_ADAPTER = 'trax.users.adapters.AccountAdapter' 240 | SOCIALACCOUNT_ADAPTER = 'trax.users.adapters.SocialAccountAdapter' 241 | 242 | # Custom user app defaults 243 | # Select the correct user model 244 | AUTH_USER_MODEL = 'users.User' 245 | LOGIN_REDIRECT_URL = 'users:redirect' 246 | LOGIN_URL = 'account_login' 247 | 248 | # SLUGLIFIER 249 | AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify' 250 | 251 | ########## CELERY 252 | INSTALLED_APPS += ('trax.taskapp.celery.CeleryConfig',) 253 | # if you are not using the django database broker (e.g. rabbitmq, redis, memcached), you can remove the next line. 254 | INSTALLED_APPS += ('kombu.transport.django',) 255 | BROKER_URL = env('CELERY_BROKER_URL', default='django://') 256 | if BROKER_URL == 'django://': 257 | CELERY_RESULT_BACKEND = 'redis://' 258 | else: 259 | CELERY_RESULT_BACKEND = BROKER_URL 260 | ########## END CELERY 261 | 262 | 263 | # Location of root django.contrib.admin URL, use {% url 'admin:index' %} 264 | ADMIN_URL = r'^admin/' 265 | 266 | # Your common stuff: Below this line define 3rd party library settings 267 | # ------------------------------------------------------------------------------ 268 | -------------------------------------------------------------------------------- /config/settings/local.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Local settings 4 | 5 | - Run in Debug mode 6 | 7 | - Use console backend for emails 8 | 9 | - Add Django Debug Toolbar 10 | - Add django-extensions as app 11 | """ 12 | 13 | import socket 14 | import os 15 | from .common import * # noqa 16 | 17 | # DEBUG 18 | # ------------------------------------------------------------------------------ 19 | DEBUG = env.bool('DJANGO_DEBUG', default=True) 20 | TEMPLATES[0]['OPTIONS']['debug'] = DEBUG 21 | 22 | ALLOWED_HOSTS = ['localhost', '.ngrok.io', 'trax'] 23 | 24 | # SECRET CONFIGURATION 25 | # ------------------------------------------------------------------------------ 26 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key 27 | # Note: This key only used for development and testing. 28 | SECRET_KEY = env('DJANGO_SECRET_KEY', default='ti28@iclav37)wqxp*sz66a0ns28wqh@+g97pkvm^dgc1btb2(') 29 | 30 | # Mail settings 31 | # ------------------------------------------------------------------------------ 32 | 33 | EMAIL_PORT = 1025 34 | 35 | EMAIL_HOST = 'localhost' 36 | EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', 37 | default='django.core.mail.backends.console.EmailBackend') 38 | 39 | # CACHING 40 | # ------------------------------------------------------------------------------ 41 | CACHES = { 42 | 'default': { 43 | 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 44 | 'LOCATION': '' 45 | } 46 | } 47 | 48 | # django-debug-toolbar 49 | # ------------------------------------------------------------------------------ 50 | MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',) 51 | # INSTALLED_APPS += ('debug_toolbar', ) 52 | 53 | INTERNAL_IPS = ['127.0.0.1', '10.0.2.2', ] 54 | # tricks to have debug toolbar when developing with docker 55 | if os.environ.get('USE_DOCKER') == 'yes': 56 | ip = socket.gethostbyname(socket.gethostname()) 57 | INTERNAL_IPS += [ip[:-1] + "1"] 58 | 59 | DEBUG_TOOLBAR_CONFIG = { 60 | 'DISABLE_PANELS': [ 61 | 'debug_toolbar.panels.redirects.RedirectsPanel', 62 | ], 63 | 'SHOW_TEMPLATE_CONTEXT': True, 64 | } 65 | 66 | AUTH_PASSWORD_VALIDATORS = [] 67 | 68 | # django-extensions 69 | # ------------------------------------------------------------------------------ 70 | INSTALLED_APPS += ('django_extensions', ) 71 | 72 | # TESTING 73 | # ------------------------------------------------------------------------------ 74 | TEST_RUNNER = 'django.test.runner.DiscoverRunner' 75 | 76 | ########## CELERY 77 | # In development, all tasks will be executed locally by blocking until the task returns 78 | CELERY_ALWAYS_EAGER = True 79 | ########## END CELERY 80 | 81 | # Your local stuff: Below this line define 3rd party library settings 82 | # ------------------------------------------------------------------------------ 83 | -------------------------------------------------------------------------------- /config/settings/production.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Production Configurations 4 | 5 | - Use Amazon's S3 for storing static files and uploaded media 6 | - Use mailgun to send emails 7 | - Use Redis for cache 8 | 9 | 10 | """ 11 | from __future__ import absolute_import, unicode_literals 12 | 13 | from boto.s3.connection import OrdinaryCallingFormat 14 | from django.utils import six 15 | 16 | 17 | from .common import * # noqa 18 | 19 | # SECRET CONFIGURATION 20 | # ------------------------------------------------------------------------------ 21 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key 22 | # Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ 23 | SECRET_KEY = env('DJANGO_SECRET_KEY') 24 | 25 | 26 | # This ensures that Django will be able to detect a secure connection 27 | # properly on Heroku. 28 | SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') 29 | # Use Whitenoise to serve static files 30 | # See: https://whitenoise.readthedocs.io/ 31 | WHITENOISE_MIDDLEWARE = ('whitenoise.middleware.WhiteNoiseMiddleware', ) 32 | MIDDLEWARE = WHITENOISE_MIDDLEWARE + MIDDLEWARE 33 | 34 | 35 | # SECURITY CONFIGURATION 36 | # ------------------------------------------------------------------------------ 37 | # See https://docs.djangoproject.com/en/1.9/ref/middleware/#module-django.middleware.security 38 | # and https://docs.djangoproject.com/ja/1.9/howto/deployment/checklist/#run-manage-py-check-deploy 39 | 40 | # set this to 60 seconds and then to 518400 when you can prove it works 41 | SECURE_HSTS_SECONDS = 60 42 | SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool( 43 | 'DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True) 44 | SECURE_CONTENT_TYPE_NOSNIFF = env.bool( 45 | 'DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True) 46 | SECURE_BROWSER_XSS_FILTER = True 47 | SESSION_COOKIE_SECURE = True 48 | SESSION_COOKIE_HTTPONLY = True 49 | SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True) 50 | CSRF_COOKIE_SECURE = True 51 | CSRF_COOKIE_HTTPONLY = True 52 | X_FRAME_OPTIONS = 'DENY' 53 | 54 | # SITE CONFIGURATION 55 | # ------------------------------------------------------------------------------ 56 | # Hosts/domain names that are valid for this site 57 | # See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts 58 | ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['trax.io']) 59 | # END SITE CONFIGURATION 60 | 61 | INSTALLED_APPS += ('gunicorn', ) 62 | 63 | 64 | # STORAGE CONFIGURATION 65 | # ------------------------------------------------------------------------------ 66 | # Uploaded Media Files 67 | # ------------------------ 68 | # See: http://django-storages.readthedocs.io/en/latest/index.html 69 | INSTALLED_APPS += ( 70 | 'storages', 71 | ) 72 | 73 | AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') 74 | AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') 75 | AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') 76 | AWS_AUTO_CREATE_BUCKET = True 77 | AWS_QUERYSTRING_AUTH = False 78 | AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat() 79 | 80 | # AWS cache settings, don't change unless you know what you're doing: 81 | AWS_EXPIRY = 60 * 60 * 24 * 7 82 | 83 | # TODO See: https://github.com/jschneier/django-storages/issues/47 84 | # Revert the following and use str after the above-mentioned bug is fixed in 85 | # either django-storage-redux or boto 86 | AWS_HEADERS = { 87 | 'Cache-Control': six.b('max-age=%d, s-maxage=%d, must-revalidate' % ( 88 | AWS_EXPIRY, AWS_EXPIRY)) 89 | } 90 | 91 | # URL that handles the media served from MEDIA_ROOT, used for managing 92 | # stored files. 93 | MEDIA_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME 94 | 95 | 96 | # Static Assets 97 | # ------------------------ 98 | STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' 99 | 100 | 101 | # EMAIL 102 | # ------------------------------------------------------------------------------ 103 | DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL', 104 | default='trax ') 105 | EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[trax] ') 106 | SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL) 107 | 108 | # Anymail with Mailgun 109 | INSTALLED_APPS += ("anymail", ) 110 | ANYMAIL = { 111 | "MAILGUN_API_KEY": env('DJANGO_MAILGUN_API_KEY'), 112 | "MAILGUN_SENDER_DOMAIN": env('MAILGUN_SENDER_DOMAIN') 113 | } 114 | EMAIL_BACKEND = "anymail.backends.mailgun.MailgunBackend" 115 | 116 | # TEMPLATE CONFIGURATION 117 | # ------------------------------------------------------------------------------ 118 | # See: 119 | # https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader 120 | TEMPLATES[0]['OPTIONS']['loaders'] = [ 121 | ('django.template.loaders.cached.Loader', [ 122 | 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), 123 | ] 124 | 125 | # DATABASE CONFIGURATION 126 | # ------------------------------------------------------------------------------ 127 | 128 | # Use the Heroku-style specification 129 | # Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ 130 | DATABASES['default'] = env.db('DATABASE_URL') 131 | 132 | # CACHING 133 | # ------------------------------------------------------------------------------ 134 | 135 | REDIS_LOCATION = '{0}/{1}'.format(env('REDIS_URL', default='redis://127.0.0.1:6379'), 0) 136 | # Heroku URL does not pass the DB number, so we parse it in 137 | CACHES = { 138 | 'default': { 139 | 'BACKEND': 'django_redis.cache.RedisCache', 140 | 'LOCATION': REDIS_LOCATION, 141 | 'OPTIONS': { 142 | 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 143 | 'IGNORE_EXCEPTIONS': True, # mimics memcache behavior. 144 | # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior 145 | } 146 | } 147 | } 148 | 149 | 150 | # LOGGING CONFIGURATION 151 | # ------------------------------------------------------------------------------ 152 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#logging 153 | # A sample logging configuration. The only tangible logging 154 | # performed by this configuration is to send an email to 155 | # the site admins on every HTTP 500 error when DEBUG=False. 156 | # See http://docs.djangoproject.com/en/dev/topics/logging for 157 | # more details on how to customize your logging configuration. 158 | LOGGING = { 159 | 'version': 1, 160 | 'disable_existing_loggers': False, 161 | 'filters': { 162 | 'require_debug_false': { 163 | '()': 'django.utils.log.RequireDebugFalse' 164 | } 165 | }, 166 | 'formatters': { 167 | 'verbose': { 168 | 'format': '%(levelname)s %(asctime)s %(module)s ' 169 | '%(process)d %(thread)d %(message)s' 170 | }, 171 | }, 172 | 'handlers': { 173 | 'mail_admins': { 174 | 'level': 'ERROR', 175 | 'filters': ['require_debug_false'], 176 | 'class': 'django.utils.log.AdminEmailHandler' 177 | }, 178 | 'console': { 179 | 'level': 'DEBUG', 180 | 'class': 'logging.StreamHandler', 181 | 'formatter': 'verbose', 182 | }, 183 | }, 184 | 'loggers': { 185 | 'django.request': { 186 | 'handlers': ['mail_admins'], 187 | 'level': 'ERROR', 188 | 'propagate': True 189 | }, 190 | 'django.security.DisallowedHost': { 191 | 'level': 'ERROR', 192 | 'handlers': ['console', 'mail_admins'], 193 | 'propagate': True 194 | } 195 | } 196 | } 197 | 198 | # Custom Admin URL, use {% url 'admin:index' %} 199 | ADMIN_URL = env('DJANGO_ADMIN_URL') 200 | 201 | # Your production stuff: Below this line define 3rd party library settings 202 | # ------------------------------------------------------------------------------ 203 | -------------------------------------------------------------------------------- /config/settings/test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ''' 3 | Test settings 4 | 5 | - Used to run tests fast on the continuous integration server and locally 6 | ''' 7 | 8 | from .common import * # noqa 9 | 10 | 11 | # DEBUG 12 | # ------------------------------------------------------------------------------ 13 | # Turn debug off so tests run faster 14 | DEBUG = False 15 | TEMPLATES[0]['OPTIONS']['debug'] = False 16 | 17 | # SECRET CONFIGURATION 18 | # ------------------------------------------------------------------------------ 19 | # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key 20 | # Note: This key only used for development and testing. 21 | SECRET_KEY = env('DJANGO_SECRET_KEY', default='CHANGEME!!!') 22 | 23 | # Mail settings 24 | # ------------------------------------------------------------------------------ 25 | EMAIL_HOST = 'localhost' 26 | EMAIL_PORT = 1025 27 | 28 | # In-memory email backend stores messages in django.core.mail.outbox 29 | # for unit testing purposes 30 | EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' 31 | 32 | # CACHING 33 | # ------------------------------------------------------------------------------ 34 | # Speed advantages of in-memory caching without having to run Memcached 35 | CACHES = { 36 | 'default': { 37 | 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 38 | 'LOCATION': '' 39 | } 40 | } 41 | 42 | # TESTING 43 | # ------------------------------------------------------------------------------ 44 | TEST_RUNNER = 'django.test.runner.DiscoverRunner' 45 | 46 | 47 | # PASSWORD HASHING 48 | # ------------------------------------------------------------------------------ 49 | # Use fast password hasher so tests run faster 50 | PASSWORD_HASHERS = ( 51 | 'django.contrib.auth.hashers.MD5PasswordHasher', 52 | ) 53 | 54 | # TEMPLATE LOADERS 55 | # ------------------------------------------------------------------------------ 56 | # Keep templates in memory so tests run faster 57 | TEMPLATES[0]['OPTIONS']['loaders'] = [ 58 | ('django.template.loaders.cached.Loader', [ 59 | 'django.template.loaders.filesystem.Loader', 60 | 'django.template.loaders.app_directories.Loader', 61 | ]), 62 | ] 63 | -------------------------------------------------------------------------------- /config/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.conf import settings 5 | from django.conf.urls import include, url 6 | from django.conf.urls.static import static 7 | from django.contrib import admin 8 | from django.views.generic import TemplateView 9 | from django.views import defaults as default_views 10 | 11 | urlpatterns = [ 12 | url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), 13 | url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'), 14 | 15 | # Django Admin, use {% url 'admin:index' %} 16 | url(settings.ADMIN_URL, admin.site.urls), 17 | 18 | # User management 19 | url(r'^users/', include('trax.users.urls', namespace='users')), 20 | url(r'^accounts/', include('allauth.urls')), 21 | url(r'^trax/', include('trax.trax.urls', namespace='trax')), 22 | 23 | # Your stuff: custom urls includes go here 24 | 25 | 26 | ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 27 | 28 | if settings.DEBUG: 29 | # This allows the error pages to be debugged during development, just visit 30 | # these url in browser to see how these error pages look like. 31 | urlpatterns += [ 32 | url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}), 33 | url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}), 34 | url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}), 35 | url(r'^500/$', default_views.server_error), 36 | ] 37 | if 'debug_toolbar' in settings.INSTALLED_APPS: 38 | import debug_toolbar 39 | 40 | urlpatterns += [ 41 | url(r'^__debug__/', include(debug_toolbar.urls)), 42 | ] 43 | -------------------------------------------------------------------------------- /config/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for trax project. 3 | 4 | This module contains the WSGI application used by Django's development server 5 | and any production WSGI deployments. It should expose a module-level variable 6 | named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover 7 | this application via the ``WSGI_APPLICATION`` setting. 8 | 9 | Usually you will have the standard Django WSGI application here, but it also 10 | might make sense to replace the whole Django WSGI application with a custom one 11 | that later delegates to the Django one. For example, you could introduce WSGI 12 | middleware here, or combine a Django application with an application of another 13 | framework. 14 | 15 | """ 16 | import os 17 | 18 | from django.core.wsgi import get_wsgi_application 19 | 20 | 21 | # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks 22 | # if running multiple sites in the same mod_wsgi process. To fix this, use 23 | # mod_wsgi daemon mode with each site in its own daemon process, or use 24 | # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" 25 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") 26 | 27 | # This application object is used by any WSGI server configured to use this 28 | # file. This includes Django's development server, if the WSGI_APPLICATION 29 | # setting points here. 30 | application = get_wsgi_application() 31 | 32 | # Apply WSGI middleware here. 33 | # from helloworld.wsgi import HelloWorldApplication 34 | # application = HelloWorldApplication(application) 35 | -------------------------------------------------------------------------------- /dev.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | 3 | volumes: 4 | postgres_data_dev: {} 5 | postgres_backup_dev: {} 6 | 7 | services: 8 | postgres: 9 | build: ./compose/postgres 10 | volumes: 11 | - postgres_data_dev:/var/lib/postgresql/data 12 | - postgres_backup_dev:/backups 13 | environment: 14 | - POSTGRES_USER=trax 15 | 16 | django: 17 | build: 18 | context: . 19 | dockerfile: ./compose/django/Dockerfile-dev 20 | command: /start-dev.sh 21 | depends_on: 22 | - postgres 23 | environment: 24 | - POSTGRES_USER=trax 25 | - USE_DOCKER=yes 26 | env_file: .env 27 | volumes: 28 | - .:/app 29 | ports: 30 | - "8000:8000" 31 | links: 32 | - postgres 33 | 34 | worker: 35 | build: 36 | context: . 37 | dockerfile: ./compose/django/Dockerfile-dev 38 | command: "./compose/django/worker.sh" 39 | depends_on: 40 | - postgres 41 | environment: 42 | - POSTGRES_USER=trax 43 | - USE_DOCKER=yes 44 | env_file: .env 45 | volumes: 46 | - .:/app 47 | links: 48 | - postgres 49 | 50 | mattermost: 51 | # the webhook url will be http://trax:8000/trax/slash 52 | build: 53 | context: ./compose/mattermost 54 | ports: 55 | - "8065:80" 56 | links: 57 | - "django:trax" 58 | 59 | volumes: 60 | - ./compose/mattermost/config.json:/mattermost/config/config.json:rw 61 | -------------------------------------------------------------------------------- /docker-compose.example.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | 3 | volumes: 4 | postgres_data: {} 5 | postgres_backup: {} 6 | 7 | services: 8 | postgres: 9 | build: ./compose/postgres 10 | volumes: 11 | - postgres_data:/var/lib/postgresql/data 12 | - postgres_backup:/backups 13 | env_file: .env 14 | 15 | django: &django_base 16 | build: 17 | context: . 18 | dockerfile: ./compose/django/Dockerfile 19 | user: django 20 | depends_on: 21 | - postgres 22 | - redis 23 | command: /gunicorn.sh 24 | env_file: .env 25 | 26 | worker: 27 | <<: *django_base 28 | command: python manage.py trax_schedule 29 | 30 | nginx: 31 | build: ./compose/nginx 32 | depends_on: 33 | - django 34 | 35 | ports: 36 | - "0.0.0.0:8079:80" 37 | 38 | 39 | redis: 40 | image: redis:latest 41 | 42 | # celeryworker: 43 | # build: 44 | # context: . 45 | # dockerfile: ./compose/django/Dockerfile 46 | # user: django 47 | # env_file: .env 48 | # depends_on: 49 | # - postgres 50 | # - redis 51 | # command: celery -A trax.taskapp worker -l INFO 52 | # 53 | # celerybeat: 54 | # build: 55 | # context: . 56 | # dockerfile: ./compose/django/Dockerfile 57 | # user: django 58 | # env_file: .env 59 | # depends_on: 60 | # - postgres 61 | # - redis 62 | # command: celery -A trax.taskapp beat -l INFO 63 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | help: 20 | @echo "Please use \`make ' where is one of" 21 | @echo " html to make standalone HTML files" 22 | @echo " dirhtml to make HTML files named index.html in directories" 23 | @echo " singlehtml to make a single large HTML file" 24 | @echo " pickle to make pickle files" 25 | @echo " json to make JSON files" 26 | @echo " htmlhelp to make HTML files and a HTML help project" 27 | @echo " qthelp to make HTML files and a qthelp project" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/trax.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/trax.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/trax" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/trax" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /docs/__init__.py: -------------------------------------------------------------------------------- 1 | # Included so that Django's startproject comment runs against the docs directory 2 | -------------------------------------------------------------------------------- /docs/changelog.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========== 3 | 4 | 0.1.1 (2017-02-07) 5 | ------------------- 6 | 7 | Minor release with better documentation for local setup, see #19. 8 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # trax documentation build configuration file, created by 4 | # sphinx-quickstart. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | from __future__ import unicode_literals 15 | 16 | import os 17 | import sys 18 | 19 | # If extensions (or modules to document with autodoc) are in another directory, 20 | # add these directories to sys.path here. If the directory is relative to the 21 | # documentation root, use os.path.abspath to make it absolute, like shown here. 22 | # sys.path.insert(0, os.path.abspath('.')) 23 | 24 | # -- General configuration ----------------------------------------------------- 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | # needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be extensions 30 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 31 | extensions = [] 32 | 33 | # Add any paths that contain templates here, relative to this directory. 34 | templates_path = ['_templates'] 35 | 36 | # The suffix of source filenames. 37 | source_suffix = '.rst' 38 | 39 | # The encoding of source files. 40 | # source_encoding = 'utf-8-sig' 41 | 42 | # The master toctree document. 43 | master_doc = 'index' 44 | 45 | # General information about the project. 46 | project = 'trax' 47 | copyright = """2016, Eliot Berriot""" 48 | 49 | # The version info for the project you're documenting, acts as replacement for 50 | # |version| and |release|, also used in various other places throughout the 51 | # built documents. 52 | # 53 | # The short X.Y version. 54 | version = '0.1' 55 | # The full version, including alpha/beta/rc tags. 56 | release = '0.1' 57 | 58 | # The language for content autogenerated by Sphinx. Refer to documentation 59 | # for a list of supported languages. 60 | # language = None 61 | 62 | # There are two options for replacing |today|: either, you set today to some 63 | # non-false value, then it is used: 64 | # today = '' 65 | # Else, today_fmt is used as the format for a strftime call. 66 | # today_fmt = '%B %d, %Y' 67 | 68 | # List of patterns, relative to source directory, that match files and 69 | # directories to ignore when looking for source files. 70 | exclude_patterns = ['_build'] 71 | 72 | # The reST default role (used for this markup: `text`) to use for all documents. 73 | # default_role = None 74 | 75 | # If true, '()' will be appended to :func: etc. cross-reference text. 76 | # add_function_parentheses = True 77 | 78 | # If true, the current module name will be prepended to all description 79 | # unit titles (such as .. function::). 80 | # add_module_names = True 81 | 82 | # If true, sectionauthor and moduleauthor directives will be shown in the 83 | # output. They are ignored by default. 84 | # show_authors = False 85 | 86 | # The name of the Pygments (syntax highlighting) style to use. 87 | pygments_style = 'sphinx' 88 | 89 | # A list of ignored prefixes for module index sorting. 90 | # modindex_common_prefix = [] 91 | 92 | 93 | # -- Options for HTML output --------------------------------------------------- 94 | 95 | # The theme to use for HTML and HTML Help pages. See the documentation for 96 | # a list of builtin themes. 97 | html_theme = 'default' 98 | 99 | # Theme options are theme-specific and customize the look and feel of a theme 100 | # further. For a list of options available for each theme, see the 101 | # documentation. 102 | # html_theme_options = {} 103 | 104 | # Add any paths that contain custom themes here, relative to this directory. 105 | # html_theme_path = [] 106 | 107 | # The name for this set of Sphinx documents. If None, it defaults to 108 | # " v documentation". 109 | # html_title = None 110 | 111 | # A shorter title for the navigation bar. Default is the same as html_title. 112 | # html_short_title = None 113 | 114 | # The name of an image file (relative to this directory) to place at the top 115 | # of the sidebar. 116 | # html_logo = None 117 | 118 | # The name of an image file (within the static path) to use as favicon of the 119 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 120 | # pixels large. 121 | # html_favicon = None 122 | 123 | # Add any paths that contain custom static files (such as style sheets) here, 124 | # relative to this directory. They are copied after the builtin static files, 125 | # so a file named "default.css" will overwrite the builtin "default.css". 126 | html_static_path = ['_static'] 127 | 128 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 129 | # using the given strftime format. 130 | # html_last_updated_fmt = '%b %d, %Y' 131 | 132 | # If true, SmartyPants will be used to convert quotes and dashes to 133 | # typographically correct entities. 134 | # html_use_smartypants = True 135 | 136 | # Custom sidebar templates, maps document names to template names. 137 | # html_sidebars = {} 138 | 139 | # Additional templates that should be rendered to pages, maps page names to 140 | # template names. 141 | # html_additional_pages = {} 142 | 143 | # If false, no module index is generated. 144 | # html_domain_indices = True 145 | 146 | # If false, no index is generated. 147 | # html_use_index = True 148 | 149 | # If true, the index is split into individual pages for each letter. 150 | # html_split_index = False 151 | 152 | # If true, links to the reST sources are added to the pages. 153 | # html_show_sourcelink = True 154 | 155 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 156 | # html_show_sphinx = True 157 | 158 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 159 | # html_show_copyright = True 160 | 161 | # If true, an OpenSearch description file will be output, and all pages will 162 | # contain a tag referring to it. The value of this option must be the 163 | # base URL from which the finished HTML is served. 164 | # html_use_opensearch = '' 165 | 166 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 167 | # html_file_suffix = None 168 | 169 | # Output file base name for HTML help builder. 170 | htmlhelp_basename = 'traxdoc' 171 | 172 | 173 | # -- Options for LaTeX output -------------------------------------------------- 174 | 175 | latex_elements = { 176 | # The paper size ('letterpaper' or 'a4paper'). 177 | # 'papersize': 'letterpaper', 178 | 179 | # The font size ('10pt', '11pt' or '12pt'). 180 | # 'pointsize': '10pt', 181 | 182 | # Additional stuff for the LaTeX preamble. 183 | # 'preamble': '', 184 | } 185 | 186 | # Grouping the document tree into LaTeX files. List of tuples 187 | # (source start file, target name, title, author, documentclass [howto/manual]). 188 | latex_documents = [ 189 | ('index', 190 | 'trax.tex', 191 | 'trax Documentation', 192 | """Eliot Berriot""", 'manual'), 193 | ] 194 | 195 | # The name of an image file (relative to this directory) to place at the top of 196 | # the title page. 197 | # latex_logo = None 198 | 199 | # For "manual" documents, if this is true, then toplevel headings are parts, 200 | # not chapters. 201 | # latex_use_parts = False 202 | 203 | # If true, show page references after internal links. 204 | # latex_show_pagerefs = False 205 | 206 | # If true, show URL addresses after external links. 207 | # latex_show_urls = False 208 | 209 | # Documents to append as an appendix to all manuals. 210 | # latex_appendices = [] 211 | 212 | # If false, no module index is generated. 213 | # latex_domain_indices = True 214 | 215 | 216 | # -- Options for manual page output -------------------------------------------- 217 | 218 | # One entry per manual page. List of tuples 219 | # (source start file, name, description, authors, manual section). 220 | man_pages = [ 221 | ('index', 'trax', 'trax Documentation', 222 | ["""Eliot Berriot"""], 1) 223 | ] 224 | 225 | # If true, show URL addresses after external links. 226 | # man_show_urls = False 227 | 228 | 229 | # -- Options for Texinfo output ------------------------------------------------ 230 | 231 | # Grouping the document tree into Texinfo files. List of tuples 232 | # (source start file, target name, title, author, 233 | # dir menu entry, description, category) 234 | texinfo_documents = [ 235 | ('index', 'trax', 'trax Documentation', 236 | """Eliot Berriot""", 'trax', 237 | """Simple time tracking server""", 'Miscellaneous'), 238 | ] 239 | 240 | # Documents to append as an appendix to all manuals. 241 | # texinfo_appendices = [] 242 | 243 | # If false, no module index is generated. 244 | # texinfo_domain_indices = True 245 | 246 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 247 | # texinfo_show_urls = 'footnote' 248 | -------------------------------------------------------------------------------- /docs/deploy.rst: -------------------------------------------------------------------------------- 1 | Deployment guide 2 | ================= 3 | 4 | 5 | Docker setup 6 | ************ 7 | 8 | Docker is the recommended deployment mean as it's both easier to setup and upgrade. 9 | 10 | .. code-block:: shell 11 | 12 | # clone the repository 13 | git clone https://github.com/EliotBerriot/trax.git 14 | cd trax 15 | 16 | # setup the environment variables 17 | # edit the .env file, especially the TIME_ZONE variable 18 | # and the DJANGO_ALLOWED_HOSTS one 19 | cp env.example .env 20 | nano .env 21 | 22 | # set up the docker-compose file 23 | # customize any configuration in the docker compose file 24 | # especially, you can change the listening port and ip 25 | cp docker-compose.example.yml docker-compose.yml 26 | nano docker-compose.yml 27 | 28 | # build and run the containers 29 | docker-compose build 30 | docker-compose up -d 31 | 32 | # create tables in the database 33 | docker-compose run django python manage.py migrate 34 | 35 | # create an admin user (this will be needed to configure your tokens) 36 | docker-compose run django python manage.py createsuperuser 37 | 38 | After that, your trax instance should be available at http://serverip:8079/, unless you customized the port / ip in the docker-compose file. 39 | 40 | You can login to the admin interface at http://serverip:8079/, using the credentials provided in the ``createsuperuser`` command. 41 | 42 | I strongly suggest you deploy a reverse proxy in front of your trax server, for example with nginx. 43 | 44 | Non-docker setup 45 | ********************* 46 | 47 | If you want to setup Trax directly on the system without using Docker, it is still possible but it will require more work. 48 | 49 | In this part, we will assume all Trax files will be stored under ``/srv/trax/``. Update the commands accordingly if you plan to use another path. 50 | 51 | To run Trax, you will some external services for which installation is not covered here: 52 | 53 | - A Redis server 54 | - A PostgreSQL database server 55 | 56 | These services can be installed on the same system as Trax application server or somewhere else (in such a case, they will need to be reachable from the Trax applicaiton server). 57 | 58 | Cloning the project 59 | ------------------- 60 | 61 | .. code-block:: shell 62 | 63 | cd /srv 64 | git clone https://github.com/EliotBerriot/trax.git 65 | cd trax 66 | 67 | Install OS dependencies 68 | ----------------------- 69 | 70 | Trax require few OS-level dependencies that are listed, for debian systems, under requirements/requirements.apt. If you're on another OS, you'll have to find corresponding packages from your package manager. 71 | 72 | Install those packages: 73 | 74 | .. code-block:: shell 75 | 76 | sudo xargs -a requirements/requirements.apt apt-get install 77 | 78 | Install Python dependencies 79 | ---------------------------- 80 | 81 | Trax is tested under Python 3, more specifically Python 3.5 but it should work the same under older version of Python 3. 82 | 83 | .. code-block:: shell 84 | 85 | # create a virtualenv to avoid polluting your system with Trax dependencies 86 | virtualenv -p `which python3` virtualenv 87 | 88 | # activate the virtualenvironment to ensure further commands are executed 89 | # there 90 | source virtualenv/bin/activate 91 | 92 | # install dependencies 93 | pip install -r requiremends/production/txt 94 | 95 | Set project environment variables 96 | ---------------------------------- 97 | 98 | Trax configuration is handled using environment variables. 99 | 100 | .. code-block:: shell 101 | 102 | # copy the example environment file 103 | cp env.example .env 104 | 105 | # Edit the .env file 106 | nano .env 107 | 108 | You'll have to tweak at least the following variables: 109 | 110 | - DJANGO_ALLOWED_HOSTS 111 | - DJANGO_SECRET_KEY 112 | - TIME_ZONE 113 | - DATABASE_URL 114 | - REDIS_URL 115 | 116 | For each one, please refer to the comments in the .env file itself to understand what value you should provide. 117 | 118 | 119 | Setup the database 120 | ------------------ 121 | 122 | Assuming your PostgreSQL server is up and running, and you configured the ``DATABASE_URL`` correctly in the previous step, you can now populate the database with initial tables and data: 123 | 124 | .. code-block:: shell 125 | 126 | python manage.py migrate 127 | 128 | (you will need the database to be created before you can call this command) 129 | 130 | Generate static files 131 | --------------------- 132 | 133 | This is required to collect images, javascript and CSS used by Trax: 134 | 135 | .. code-block:: shell 136 | 137 | python manage.py collectstatic 138 | 139 | Create an administrator 140 | ----------------------- 141 | 142 | This is required if you want to log in to Trax admin interface: 143 | 144 | .. code-block:: shell 145 | 146 | python manage.py createsuperuser 147 | 148 | Check the application server runs properly 149 | ------------------------------------------ 150 | 151 | You should now be able to launch the application server: 152 | 153 | .. code-block:: shell 154 | 155 | gunicorn config.wsgi -b 127.0.0.1:8001 156 | 157 | This would bind the server on 127.0.0.1 and port. Feel free to tweak that. 158 | 159 | Daemonize Trax 160 | --------------- 161 | 162 | Usually, you'll want to daemonize Trax process to avoid launching them by hand. 163 | 164 | This can be done in various way, with tools such as Supervisor or Systemd. This example use two systemd configuration files. 165 | 166 | Application server file: 167 | 168 | .. code-block:: shell 169 | 170 | # /etc/systemd/system/trax-web.service 171 | [Unit] 172 | Description=Trax application server 173 | After=network.target 174 | 175 | [Service] 176 | WorkingDirectory=/srv/trax 177 | ExecStart=/srv/trax/virtualenv/bin/gunicorn config.wsgi -b 127.0.0.1:8001 178 | 179 | [Install] 180 | WantedBy=multi-user.target 181 | 182 | Worker file: 183 | 184 | .. code-block:: shell 185 | 186 | # /etc/systemd/system/trax-worker.service 187 | [Unit] 188 | Description=Trax worker 189 | After=network.target 190 | 191 | [Service] 192 | WorkingDirectory=/srv/trax 193 | ExecStart=/srv/trax/virtualenv/bin/python manage.py trax_schedule 194 | 195 | [Install] 196 | WantedBy=multi-user.target 197 | 198 | After that, you should enable the files and start the processes: 199 | 200 | .. code-block:: shell 201 | 202 | systemctl enable trax-web trax-worker 203 | systemctl start trax-web trax-worker 204 | 205 | And double check everything is working: 206 | 207 | .. code-block:: shell 208 | 209 | systemctl status trax-web trax-worker 210 | 211 | Set up a reverse proxy 212 | ----------------------- 213 | 214 | I strongly recommand proxying incoming requests through Nginx or Apache2 instead of making the application server 215 | directly reachable over the internet. This is also the best way to setup HTTPS on Trax. 216 | 217 | Example nginx configuration: 218 | 219 | .. code-block:: shell 220 | 221 | # /etc/nginx/conf.d/trax.conf 222 | server { 223 | listen 80; 224 | charset utf-8; 225 | server_name yourtraxdomain.com; 226 | 227 | location / { 228 | # checks for static file, if not found proxy to app 229 | try_files $uri @proxy_to_app; 230 | } 231 | 232 | # cookiecutter-django app 233 | location @proxy_to_app { 234 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 235 | proxy_set_header Host $http_host; 236 | proxy_redirect off; 237 | 238 | # update this depending of the adress/port used in your setup 239 | proxy_pass http://127.0.0.1:8001; 240 | } 241 | } 242 | 243 | Remember to restart your nginx instance to load this new configuration: 244 | 245 | .. code-block:: shell 246 | 247 | service nginx restart 248 | 249 | 250 | Initial configuration 251 | ********************* 252 | 253 | In this part, we will assume your mattermost server is available at http://mattermost and your trax server at http://trax. 254 | 255 | Mattermost configuration 256 | ------------------------ 257 | 258 | Head over your mattermost server so you can setup the trax integration. 259 | 260 | In the system console, you will have to enable incoming webhooks and slash commands for the trax integration to work. 261 | 262 | After that, you have to configure two integrations: 263 | 264 | 1. A slash command, pointing to ``http://trax/trax/slash``, so mattermost users can interact with trax using a slash command (I recommand ``trax`` as the trigger word but you can use something else). Copy the validation token, it will be useful 265 | 2. (optionnal) an incoming webhook, so that trax can send reminders in mattermost channels. Also copy the webhook URL. 266 | 267 | Trax configuration 268 | ------------------ 269 | 270 | Log in with your superuser credentials at http://trax/admin/, and visit the `Global preferences `_ section. This is the place where you'll have to input your trax instance settings: 271 | 272 | 1. ``trax__slash_command_token``: input the validation token you got from the mattermost step 273 | 2. ``trax__webhook_url``: input the webhook URL you got from the mattermost step 274 | 275 | Final checks 276 | ------------ 277 | 278 | After that, you should be able to interact with trax within mattermost using the trigger word you choosed:: 279 | 280 | /trax help 281 | 282 | You should see a list of available commands. 283 | 284 | You can now head over :doc:`/user-guide`. 285 | 286 | Upgrading to a newer version 287 | **************************** 288 | 289 | Upgrading to a newer version is done as follows: 290 | 291 | .. code-block:: shell 292 | 293 | git pull 294 | git checkout 295 | docker-compose up -d --build 296 | -------------------------------------------------------------------------------- /docs/features.rst: -------------------------------------------------------------------------------- 1 | Features 2 | =============== 3 | 4 | Philosophy 5 | ---------- 6 | 7 | Trax was designed from the ground-up to be a simple time tracker, integrated within a chat server, such as Mattermost. 8 | 9 | Because of that philosophy, at the moment, the only available interface to trax is the chat server, via the slash command. The only exception is the trax admin interface, which is only here for configuration and management purposes. 10 | 11 | This may evolve in the future. 12 | 13 | 14 | Timers 15 | ------ 16 | 17 | Time tracking is provided using timers, a timer has basically a name, a start date and an end date. 18 | 19 | Users can create, start and stop their own timers to track their time, and can use built-in reporting to 20 | see the time they spend on each timer, per day. 21 | 22 | Reminders 23 | --------- 24 | 25 | Trax also offers in-chat reminders : once you set up a reminder, it will be send directly in-chat when the time comes. 26 | 27 | This is useful to remember a meeting, or to remind your coworker something important needs to be done when you're not here. 28 | 29 | Trax allow recurring reminders too, using the crontab syntax. 30 | 31 | Human dates and time 32 | ------------------------ 33 | 34 | One of the pain with time-related software is how different human and computers handles dates. 35 | 36 | While we want to use shorter, easier to type date or time references, such as "tomorrow" or "in ten minutes", machines need a precise date, such as "2017-09-01 12:37". 37 | 38 | Trax supports human-like date and times when needed as well as more explicit ones, so you can focus on doing things instead of on trax. 39 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. trax documentation master file, created by 2 | sphinx-quickstart. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to trax's documentation! 7 | ==================================================================== 8 | 9 | Trax is an open-source project that provides time-tracking features and aims at being 10 | tightly integrated with modern chat softwares such as Mattermost. 11 | 12 | 13 | Contents: 14 | 15 | .. toctree:: 16 | :maxdepth: 2 17 | 18 | features 19 | user-guide 20 | install-locally 21 | deploy 22 | tests 23 | 24 | 25 | 26 | Indices and tables 27 | ================== 28 | 29 | * :ref:`genindex` 30 | * :ref:`modindex` 31 | * :ref:`search` 32 | -------------------------------------------------------------------------------- /docs/install-locally.rst: -------------------------------------------------------------------------------- 1 | Install locally 2 | =============== 3 | 4 | To get a working local copy of the project, the recommended setup involves Docker 5 | and docker-compose. 6 | 7 | Assuming you have both of these tools installed, you should be able to spin 8 | up a local copy of the project (and a test mattermost server to see how it works within the chat). 9 | 10 | First, create your configuration file and open it in a text editor: 11 | 12 | .. code-block:: shell 13 | 14 | # Especially, you will have to edit the DJANGO_SETTINGS_MODULE line, to: 15 | # DJANGO_SETTINGS_MODULE=config.settings.local 16 | cp env.example .env 17 | 18 | Once you have edited the configuration file, you can run everything: 19 | 20 | .. code-block:: shell 21 | 22 | docker-compose -f dev.yml up 23 | 24 | This will build and launch the required containers, after that, you can access the mattermost server at http://localhost:8065 and the trax server at http://localhost:8000. 25 | 26 | Initial configuration 27 | ********************* 28 | 29 | Mattermost configuration 30 | ------------------------ 31 | 32 | Once your docker containers are up, you can setup easily a test team and user: 33 | 34 | .. code-block:: shell 35 | 36 | # create the team 37 | docker-compose -f dev.yml exec mattermost ./bin/platform team create --name test --display_name "test" 38 | 39 | # create the user 40 | docker-compose -f dev.yml exec mattermost ./bin/platform user create --firstname test --system_admin --email test@test --username test --password testtest 41 | 42 | # add the user to the team 43 | docker-compose -f dev.yml exec mattermost ./bin/platform team add test test 44 | 45 | After that, you have to configure two integrations: 46 | 47 | 1. `A slash command `_ , pointing to ``http://trax:8000/trax/slash``, so mattermost users can interact with trax using a slash command (I recommand ``trax`` as the trigger word but you can use something else). Copy the validation token, it will be useful 48 | 2. (optionnal) an `incoming webhook `_, so that trax can send reminders in mattermost channels. Also copy the webhook URL (but replace the domain part with ``mattermost`` and remove the port) 49 | 50 | Trax configuration 51 | ------------------ 52 | 53 | To finish the trax server configuration, you'll have to create a superuser: 54 | 55 | .. code-block:: shell 56 | 57 | docker-compose -f dev.yml run django python manage.py createsuperuser 58 | 59 | Once done, log with your credentials at http://localhost:8000/admin/, and visit the `Global preferences `_ section. This is the place where you'll have to input your trax instance settings: 60 | 61 | 1. ``trax__slash_command_token``: input the validation token you got from the mattermost step 62 | 2. ``trax__webhook_url``: input the webhook URL you got from the mattermost step (replace the ``localhost`` part with ``mattermost``, so the URL will look like ``http://mattermost:8065/hooks/ked7nmu37id4zyii316be15d5o``) 63 | 64 | Final checks 65 | ------------ 66 | 67 | After that, you should be able to interact with trax within mattermost using the trigger word you choosed:: 68 | 69 | /trax help 70 | 71 | You should see a list of available commands, if everything works fine. 72 | 73 | You can now head over :doc:`/user-guide`. 74 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. linkcheck to check all external links for integrity 37 | echo. doctest to run all doctests embedded in the documentation if enabled 38 | goto end 39 | ) 40 | 41 | if "%1" == "clean" ( 42 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 43 | del /q /s %BUILDDIR%\* 44 | goto end 45 | ) 46 | 47 | if "%1" == "html" ( 48 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 49 | if errorlevel 1 exit /b 1 50 | echo. 51 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 52 | goto end 53 | ) 54 | 55 | if "%1" == "dirhtml" ( 56 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 57 | if errorlevel 1 exit /b 1 58 | echo. 59 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 60 | goto end 61 | ) 62 | 63 | if "%1" == "singlehtml" ( 64 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 68 | goto end 69 | ) 70 | 71 | if "%1" == "pickle" ( 72 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished; now you can process the pickle files. 76 | goto end 77 | ) 78 | 79 | if "%1" == "json" ( 80 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished; now you can process the JSON files. 84 | goto end 85 | ) 86 | 87 | if "%1" == "htmlhelp" ( 88 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can run HTML Help Workshop with the ^ 92 | .hhp project file in %BUILDDIR%/htmlhelp. 93 | goto end 94 | ) 95 | 96 | if "%1" == "qthelp" ( 97 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 98 | if errorlevel 1 exit /b 1 99 | echo. 100 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 101 | .qhcp project file in %BUILDDIR%/qthelp, like this: 102 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\trax.qhcp 103 | echo.To view the help file: 104 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\trax.ghc 105 | goto end 106 | ) 107 | 108 | if "%1" == "devhelp" ( 109 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 110 | if errorlevel 1 exit /b 1 111 | echo. 112 | echo.Build finished. 113 | goto end 114 | ) 115 | 116 | if "%1" == "epub" ( 117 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 118 | if errorlevel 1 exit /b 1 119 | echo. 120 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 121 | goto end 122 | ) 123 | 124 | if "%1" == "latex" ( 125 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 129 | goto end 130 | ) 131 | 132 | if "%1" == "text" ( 133 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The text files are in %BUILDDIR%/text. 137 | goto end 138 | ) 139 | 140 | if "%1" == "man" ( 141 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 145 | goto end 146 | ) 147 | 148 | if "%1" == "texinfo" ( 149 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 150 | if errorlevel 1 exit /b 1 151 | echo. 152 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 153 | goto end 154 | ) 155 | 156 | if "%1" == "gettext" ( 157 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 158 | if errorlevel 1 exit /b 1 159 | echo. 160 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 161 | goto end 162 | ) 163 | 164 | if "%1" == "changes" ( 165 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 166 | if errorlevel 1 exit /b 1 167 | echo. 168 | echo.The overview file is in %BUILDDIR%/changes. 169 | goto end 170 | ) 171 | 172 | if "%1" == "linkcheck" ( 173 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 174 | if errorlevel 1 exit /b 1 175 | echo. 176 | echo.Link check complete; look for any errors in the above output ^ 177 | or in %BUILDDIR%/linkcheck/output.txt. 178 | goto end 179 | ) 180 | 181 | if "%1" == "doctest" ( 182 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 183 | if errorlevel 1 exit /b 1 184 | echo. 185 | echo.Testing of doctests in the sources finished, look at the ^ 186 | results in %BUILDDIR%/doctest/output.txt. 187 | goto end 188 | ) 189 | 190 | :end 191 | -------------------------------------------------------------------------------- /docs/tests.rst: -------------------------------------------------------------------------------- 1 | Running the test suite 2 | ====================== 3 | 4 | To run tests, assuming you have docker and docker-compose installed, you just need to run: 5 | 6 | .. code-block:: shell 7 | 8 | docker-compose -f dev.yml run django pytest 9 | 10 | Internally Pytest is used to run tests, meaning you can pass any regular pytest argument, such as ``--ff`` to rerun failures first, or ``-x`` to stop on first failure: 11 | 12 | .. code-block:: shell 13 | 14 | docker-compose -f dev.yml run django pytest -x --ff 15 | -------------------------------------------------------------------------------- /docs/trax.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agateblue/trax/61a14b2a3cd6366422b27c48b9e3716bbdcd7ae5/docs/trax.gif -------------------------------------------------------------------------------- /docs/user-guide.rst: -------------------------------------------------------------------------------- 1 | User guide 2 | ========== 3 | 4 | Interacting with trax 5 | ---------------------- 6 | 7 | Everytime you want to do something with trax, you'll need to type a slash command in your 8 | chat server. Such commands start with a slash and a trigger word: 9 | 10 | .. code-block:: shell 11 | 12 | /echo "Hello world" 13 | 14 | In the previous example, the trigger world is "echo". 15 | 16 | The trigger word for trax should be "trax", but it is totally possible your administrator has configured 17 | it with another trigger word. For the sake of simplicity, in this guide, we will assume your trigger word is "trax". 18 | 19 | Here is an example of a trax command: 20 | 21 | .. code-block:: shell 22 | 23 | /trax start working 24 | 25 | In this example, "start" is a trax command, and "working" is an argument to this command. For trax, this means ``Start a timer named "working"``. Some trax commands require one or many arguments, while some other don't, or only have optional arguments. For example, you could do: ``/trax help`` to get general help, without providing any argument, or ``/trax help start``, with the ``start`` argument, to get help about the ``start`` command. 26 | 27 | 28 | To sum it up: 29 | 30 | - The slash command a way to tell your chat server "I want to interact with another software" (trax here). It's made of a slash and a trigger word, such as ``/trax`` 31 | - The trax command is the word that follows the trigger word and tell trax what you want to do, such as ``stop`` in ``/trax stop`` 32 | - The arguments come after the trax command. They may be optional, required or even not needed at all 33 | 34 | 35 | Getting help 36 | ------------ 37 | 38 | The most basic thing you should be able to do is to get help. This is done with the following command: 39 | 40 | .. code-block:: shell 41 | 42 | # get general help 43 | /trax help 44 | 45 | # get help about the config command 46 | /trax help config 47 | -------------------------------------------------------------------------------- /env.example: -------------------------------------------------------------------------------- 1 | # ---- Mandatory variables ---- 2 | 3 | # replace me we the real hostname you want to use for you trax instance 4 | DJANGO_ALLOWED_HOSTS=.trax.io 5 | 6 | # @todo you can generate a secret key using [[command]] 7 | DJANGO_SECRET_KEY=replaceme 8 | 9 | # The time zone used for your installation 10 | TIME_ZONE=UTC 11 | 12 | # ---- Deployment specific variables ---- 13 | 14 | # Database configuration (non-docker setup) 15 | # Uncomment if you do not use Docker and replace values with your own 16 | # Example: 17 | # DATABASE_URL=postgres://trax:pa$$word@127.0.0.1:5432/trax 18 | # DATABASE_URL=postgres://user:password@dbhost:port/dbname 19 | 20 | # Redis configuration (non-docker setup) 21 | # Uncomment if you do not use Docker and replace values with your own 22 | # Example: 23 | # REDIS_URL=redis://127.0.0.1:6379/ 24 | # REDIS_URL=redis://redishost:port/ 25 | 26 | # PostgreSQL (Docker setup only, you can comment them if you do not use docker) 27 | POSTGRES_PASSWORD=mysecretpass 28 | POSTGRES_USER=postgresuser 29 | 30 | # ---- Lower-level configuration ---- 31 | # You should not need to touch this 32 | 33 | # General settings 34 | DJANGO_ADMIN_URL=^admin/ 35 | 36 | # we default to production settings, but you have to use 37 | # config.settings.local if you want to work locally, in development 38 | DJANGO_SETTINGS_MODULE=config.settings.production 39 | 40 | 41 | 42 | 43 | # AWS Settings, useless if you're not using AWS (not supported at the moment) 44 | DJANGO_AWS_ACCESS_KEY_ID= 45 | DJANGO_AWS_SECRET_ACCESS_KEY= 46 | DJANGO_AWS_STORAGE_BUCKET_NAME= 47 | 48 | # Used with email, unsupported at the moment 49 | DJANGO_MAILGUN_API_KEY= 50 | DJANGO_SERVER_EMAIL= 51 | MAILGUN_SENDER_DOMAIN= 52 | 53 | # Security! Better to use DNS for this task, but you can use redirect 54 | DJANGO_SECURE_SSL_REDIRECT=False 55 | 56 | # django-allauth, disable if you don't want to allow signup on your instance 57 | DJANGO_ACCOUNT_ALLOW_REGISTRATION=False 58 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == '__main__': 6 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.production') 7 | 8 | try: 9 | from django.core.management import execute_from_command_line 10 | except ImportError: 11 | # The above import may fail for some other reason. Ensure that the 12 | # issue is really that Django is missing to avoid masking other 13 | # exceptions on Python 2. 14 | try: 15 | import django # noqa 16 | except ImportError: 17 | raise ImportError( 18 | "Couldn't import Django. Are you sure it's installed and " 19 | "available on your PYTHONPATH environment variable? Did you " 20 | "forget to activate a virtual environment?" 21 | ) 22 | raise 23 | execute_from_command_line(sys.argv) 24 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | DJANGO_SETTINGS_MODULE=config.settings.test 3 | -------------------------------------------------------------------------------- /requirements/base.txt: -------------------------------------------------------------------------------- 1 | # Wheel 0.25+ needed to install certain packages on CPython 3.5+ 2 | # like Pillow and psycopg2 3 | # See http://bitly.com/wheel-building-fails-CPython-35 4 | # Verified bug on Python 3.5.1 5 | wheel==0.29.0 6 | 7 | # Bleeding edge Django 8 | django==1.10.4 9 | 10 | # Configuration 11 | django-environ==0.4.1 12 | whitenoise==3.2.2 13 | 14 | 15 | # Forms 16 | django-braces==1.10.0 17 | django-crispy-forms==1.6.1 18 | 19 | # Models 20 | django-model-utils==2.6 21 | 22 | # Images 23 | Pillow==3.4.2 24 | 25 | # For user registration, either via email or social 26 | # Well-built with regular release cycles! 27 | django-allauth==0.29.0 28 | 29 | 30 | # Python-PostgreSQL Database Adapter 31 | psycopg2==2.7.3.1 32 | 33 | # Unicode slugification 34 | awesome-slugify==1.6.5 35 | 36 | # Time zones support 37 | pytz==2016.10 38 | 39 | # Redis support 40 | django-redis==4.6.0 41 | redis>=2.10.5 42 | 43 | 44 | celery==3.1.24 45 | 46 | 47 | 48 | 49 | # Your custom requirements go here 50 | dateparser 51 | django-dynamic-preferences>=0.8.3,<0.9 52 | schedule 53 | croniter 54 | requests 55 | docopt 56 | cron-descriptor 57 | -------------------------------------------------------------------------------- /requirements/local.txt: -------------------------------------------------------------------------------- 1 | # Local development dependencies go here 2 | -r base.txt 3 | coverage==4.2 4 | django-coverage-plugin==1.3.1 5 | Sphinx==1.5.1 6 | django-extensions==1.7.5 7 | Werkzeug==0.11.11 8 | django-test-plus==1.0.16 9 | factory-boy==2.8.1 10 | 11 | django-debug-toolbar==1.6 12 | 13 | # improved REPL 14 | ipdb==0.10.1 15 | 16 | pytest-django==3.1.2 17 | pytest-sugar==0.7.1 18 | -------------------------------------------------------------------------------- /requirements/production.txt: -------------------------------------------------------------------------------- 1 | # Pro-tip: Try not to put anything here. Avoid dependencies in 2 | # production that aren't in development. 3 | -r base.txt 4 | 5 | 6 | 7 | # WSGI Handler 8 | # ------------------------------------------------ 9 | gevent==1.2a2 10 | gunicorn==19.6.0 11 | 12 | # Static and Media Storage 13 | # ------------------------------------------------ 14 | boto==2.45.0 15 | django-storages-redux==1.3.2 16 | 17 | 18 | # Email backends for Mailgun, Postmark, SendGrid and more 19 | # ------------------------------------------------------- 20 | django-anymail==0.6.1 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /requirements/requirements.apt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agateblue/trax/61a14b2a3cd6366422b27c48b9e3716bbdcd7ae5/requirements/requirements.apt -------------------------------------------------------------------------------- /requirements/test.txt: -------------------------------------------------------------------------------- 1 | # Test dependencies go here. 2 | -r base.txt 3 | 4 | 5 | 6 | coverage==4.2 7 | flake8==3.2.1 # pyup: != 2.6.0 8 | django-test-plus==1.0.16 9 | factory-boy==2.8.1 10 | 11 | # pytest 12 | pytest-django==3.1.2 13 | pytest-sugar==0.7.1 14 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 120 3 | exclude = .tox,.git,*/migrations/*,*/static/CACHE/*,docs,node_modules 4 | 5 | [pep8] 6 | max-line-length = 120 7 | exclude=.tox,.git,*/migrations/*,*/static/CACHE/*,docs,node_modules 8 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reminder 3 | 4 | Usage: 5 | remind add 6 | 7 | Mandatory arguments: 8 | The message that will be sent when the reminder is triggered 9 | When to set the reminder. It can either be: 10 | 11 | * A relative hint, such as "in two hours" or "tomorrow at noon" 12 | * An absolute date/time, such as "2017-01-10 17:15" 13 | 14 | Note that it you provide multiple words for these arguments, 15 | you have to enclose them using double quotes: 16 | 17 | * GOOD: remind add something tomorrow 18 | * GOOD: remind add "something important" tomorrow 19 | * GOOD: remind add "something important" "tomorrow at noon" 20 | * BAD: remind add something tomorrow at noon 21 | * BAD: remind add something important "tomorrow at noon" 22 | """ 23 | 24 | import docopt 25 | import sys 26 | arguments = docopt.docopt(__doc__, sys.argv[1:]) 27 | print(arguments, sys.argv[1:]) 28 | -------------------------------------------------------------------------------- /trax/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | __version__ = '0.1.1' 3 | __version_info__ = tuple([int(num) if num.isdigit() else num for num in __version__.replace('-', '.', 1).split('.')]) 4 | -------------------------------------------------------------------------------- /trax/contrib/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | To understand why this file is here, please read: 3 | 4 | http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django 5 | """ 6 | # -*- coding: utf-8 -*- 7 | -------------------------------------------------------------------------------- /trax/contrib/sites/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | To understand why this file is here, please read: 3 | 4 | http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django 5 | """ 6 | # -*- coding: utf-8 -*- 7 | -------------------------------------------------------------------------------- /trax/contrib/sites/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | import django.contrib.sites.models 5 | from django.contrib.sites.models import _simple_domain_name_validator 6 | from django.db import migrations, models 7 | 8 | 9 | class Migration(migrations.Migration): 10 | 11 | dependencies = [] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Site', 16 | fields=[ 17 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 18 | ('domain', models.CharField( 19 | max_length=100, verbose_name='domain name', validators=[_simple_domain_name_validator] 20 | )), 21 | ('name', models.CharField(max_length=50, verbose_name='display name')), 22 | ], 23 | options={ 24 | 'ordering': ('domain',), 25 | 'db_table': 'django_site', 26 | 'verbose_name': 'site', 27 | 'verbose_name_plural': 'sites', 28 | }, 29 | bases=(models.Model,), 30 | managers=[ 31 | ('objects', django.contrib.sites.models.SiteManager()), 32 | ], 33 | ), 34 | ] 35 | -------------------------------------------------------------------------------- /trax/contrib/sites/migrations/0002_alter_domain_unique.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | import django.contrib.sites.models 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('sites', '0001_initial'), 12 | ] 13 | 14 | operations = [ 15 | migrations.AlterField( 16 | model_name='site', 17 | name='domain', 18 | field=models.CharField( 19 | max_length=100, unique=True, validators=[django.contrib.sites.models._simple_domain_name_validator], 20 | verbose_name='domain name' 21 | ), 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /trax/contrib/sites/migrations/0003_set_site_domain_and_name.py: -------------------------------------------------------------------------------- 1 | """ 2 | To understand why this file is here, please read: 3 | 4 | http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django 5 | """ 6 | # -*- coding: utf-8 -*- 7 | 8 | from __future__ import unicode_literals 9 | 10 | from django.conf import settings 11 | from django.db import migrations 12 | 13 | 14 | def update_site_forward(apps, schema_editor): 15 | """Set site domain and name.""" 16 | Site = apps.get_model('sites', 'Site') 17 | Site.objects.update_or_create( 18 | id=settings.SITE_ID, 19 | defaults={ 20 | 'domain': 'trax.io', 21 | 'name': 'trax' 22 | } 23 | ) 24 | 25 | 26 | def update_site_backward(apps, schema_editor): 27 | """Revert site domain and name to default.""" 28 | Site = apps.get_model('sites', 'Site') 29 | Site.objects.update_or_create( 30 | id=settings.SITE_ID, 31 | defaults={ 32 | 'domain': 'example.com', 33 | 'name': 'example.com' 34 | } 35 | ) 36 | 37 | 38 | class Migration(migrations.Migration): 39 | 40 | dependencies = [ 41 | ('sites', '0002_alter_domain_unique'), 42 | ] 43 | 44 | operations = [ 45 | migrations.RunPython(update_site_forward, update_site_backward), 46 | ] 47 | -------------------------------------------------------------------------------- /trax/contrib/sites/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | To understand why this file is here, please read: 3 | 4 | http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django 5 | """ 6 | # -*- coding: utf-8 -*- 7 | -------------------------------------------------------------------------------- /trax/static/css/project.css: -------------------------------------------------------------------------------- 1 | /* These styles are generated from project.scss. */ 2 | 3 | .alert-debug { 4 | color: black; 5 | background-color: white; 6 | border-color: #d6e9c6; 7 | } 8 | 9 | .alert-error { 10 | color: #b94a48; 11 | background-color: #f2dede; 12 | border-color: #eed3d7; 13 | } 14 | 15 | /* This is a fix for the bootstrap4 alpha release */ 16 | @media (max-width: 47.9em) { 17 | .navbar-nav .nav-item { 18 | float: none; 19 | width: 100%; 20 | display: inline-block; 21 | } 22 | 23 | .navbar-nav .nav-item + .nav-item { 24 | margin-left: 0; 25 | } 26 | 27 | .nav.navbar-nav.pull-xs-right { 28 | float: none !important; 29 | } 30 | } 31 | 32 | /* Display django-debug-toolbar. 33 | See https://github.com/django-debug-toolbar/django-debug-toolbar/issues/742 34 | and https://github.com/pydanny/cookiecutter-django/issues/317 35 | */ 36 | [hidden][style="display: block;"] { 37 | display: block !important; 38 | } 39 | -------------------------------------------------------------------------------- /trax/static/fonts/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agateblue/trax/61a14b2a3cd6366422b27c48b9e3716bbdcd7ae5/trax/static/fonts/.gitkeep -------------------------------------------------------------------------------- /trax/static/images/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agateblue/trax/61a14b2a3cd6366422b27c48b9e3716bbdcd7ae5/trax/static/images/favicon.ico -------------------------------------------------------------------------------- /trax/static/js/project.js: -------------------------------------------------------------------------------- 1 | /* Project specific Javascript goes here. */ 2 | 3 | /* 4 | Formatting hack to get around crispy-forms unfortunate hardcoding 5 | in helpers.FormHelper: 6 | 7 | if template_pack == 'bootstrap4': 8 | grid_colum_matcher = re.compile('\w*col-(xs|sm|md|lg|xl)-\d+\w*') 9 | using_grid_layout = (grid_colum_matcher.match(self.label_class) or 10 | grid_colum_matcher.match(self.field_class)) 11 | if using_grid_layout: 12 | items['using_grid_layout'] = True 13 | 14 | Issues with the above approach: 15 | 16 | 1. Fragile: Assumes Bootstrap 4's API doesn't change (it does) 17 | 2. Unforgiving: Doesn't allow for any variation in template design 18 | 3. Really Unforgiving: No way to override this behavior 19 | 4. Undocumented: No mention in the documentation, or it's too hard for me to find 20 | */ 21 | $('.form-group').removeClass('row'); 22 | -------------------------------------------------------------------------------- /trax/static/sass/project.scss: -------------------------------------------------------------------------------- 1 | 2 | // project specific CSS goes here 3 | 4 | //////////////////////////////// 5 | //Variables// 6 | //////////////////////////////// 7 | 8 | // Alert colors 9 | 10 | $white: #fff; 11 | $mint-green: #d6e9c6; 12 | $black: #000; 13 | $pink: #f2dede; 14 | $dark-pink: #eed3d7; 15 | $red: #b94a48; 16 | 17 | //////////////////////////////// 18 | //Alerts// 19 | //////////////////////////////// 20 | 21 | // bootstrap alert CSS, translated to the django-standard levels of 22 | // debug, info, success, warning, error 23 | 24 | .alert-debug { 25 | background-color: $white; 26 | border-color: $mint-green; 27 | color: $black; 28 | } 29 | 30 | .alert-error { 31 | background-color: $pink; 32 | border-color: $dark-pink; 33 | color: $red; 34 | } 35 | 36 | //////////////////////////////// 37 | //Navbar// 38 | //////////////////////////////// 39 | 40 | // This is a fix for the bootstrap4 alpha release 41 | 42 | .navbar { 43 | border-radius: 0px; 44 | } 45 | 46 | @media (max-width: 47.9em) { 47 | .navbar-nav .nav-item { 48 | display: inline-block; 49 | float: none; 50 | width: 100%; 51 | } 52 | 53 | .navbar-nav .nav-item + .nav-item { 54 | margin-left: 0; 55 | } 56 | 57 | .nav.navbar-nav.pull-xs-right { 58 | float: none !important; 59 | } 60 | } 61 | 62 | //////////////////////////////// 63 | //Django Toolbar// 64 | //////////////////////////////// 65 | 66 | // Display django-debug-toolbar. 67 | // See https://github.com/django-debug-toolbar/django-debug-toolbar/issues/742 68 | // and https://github.com/pydanny/cookiecutter-django/issues/317 69 | 70 | [hidden][style="display: block;"] { 71 | display: block !important; 72 | } 73 | -------------------------------------------------------------------------------- /trax/taskapp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agateblue/trax/61a14b2a3cd6366422b27c48b9e3716bbdcd7ae5/trax/taskapp/__init__.py -------------------------------------------------------------------------------- /trax/taskapp/celery.py: -------------------------------------------------------------------------------- 1 | 2 | from __future__ import absolute_import 3 | import os 4 | from celery import Celery 5 | from django.apps import apps, AppConfig 6 | from django.conf import settings 7 | 8 | 9 | if not settings.configured: 10 | # set the default Django settings module for the 'celery' program. 11 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') # pragma: no cover 12 | 13 | 14 | app = Celery('trax') 15 | 16 | 17 | class CeleryConfig(AppConfig): 18 | name = 'trax.taskapp' 19 | verbose_name = 'Celery Config' 20 | 21 | def ready(self): 22 | # Using a string here means the worker will not have to 23 | # pickle the object when using Windows. 24 | app.config_from_object('django.conf:settings') 25 | installed_apps = [app_config.name for app_config in apps.get_app_configs()] 26 | app.autodiscover_tasks(lambda: installed_apps, force=True) 27 | 28 | 29 | 30 | 31 | 32 | 33 | @app.task(bind=True) 34 | def debug_task(self): 35 | print('Request: {0!r}'.format(self.request)) # pragma: no cover 36 | -------------------------------------------------------------------------------- /trax/templates/403_csrf.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block title %}Forbidden (403){% endblock %} 4 | 5 | {% block content %} 6 |

Forbidden (403)

7 | 8 |

CSRF verification failed. Request aborted.

9 | {% endblock content %} 10 | -------------------------------------------------------------------------------- /trax/templates/404.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block title %}Page Not found{% endblock %} 4 | 5 | {% block content %} 6 |

Page Not found

7 | 8 |

This is not the page you were looking for.

9 | {% endblock content %} 10 | -------------------------------------------------------------------------------- /trax/templates/500.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block title %}Server Error{% endblock %} 4 | 5 | {% block content %} 6 |

Ooops!!! 500

7 | 8 |

Looks like something went wrong!

9 | 10 |

We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, try refreshing.

11 | {% endblock content %} 12 | 13 | 14 | -------------------------------------------------------------------------------- /trax/templates/account/account_inactive.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | 5 | {% block head_title %}{% trans "Account Inactive" %}{% endblock %} 6 | 7 | {% block inner %} 8 |

{% trans "Account Inactive" %}

9 | 10 |

{% trans "This account is inactive." %}

11 | {% endblock %} 12 | 13 | -------------------------------------------------------------------------------- /trax/templates/account/base.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block title %}{% block head_title %}{% endblock head_title %}{% endblock title %} 3 | 4 | {% block content %} 5 |
6 |
7 | {% block inner %}{% endblock %} 8 |
9 |
10 | {% endblock %} 11 | -------------------------------------------------------------------------------- /trax/templates/account/email.html: -------------------------------------------------------------------------------- 1 | 2 | {% extends "account/base.html" %} 3 | 4 | {% load i18n %} 5 | {% load crispy_forms_tags %} 6 | 7 | {% block head_title %}{% trans "Account" %}{% endblock %} 8 | 9 | {% block inner %} 10 |

{% trans "E-mail Addresses" %}

11 | 12 | {% if user.emailaddress_set.all %} 13 |

{% trans 'The following e-mail addresses are associated with your account:' %}

14 | 15 | 44 | 45 | {% else %} 46 |

{% trans 'Warning:'%} {% trans "You currently do not have any e-mail address set up. You should really add an e-mail address so you can receive notifications, reset your password, etc." %}

47 | 48 | {% endif %} 49 | 50 | 51 |

{% trans "Add E-mail Address" %}

52 | 53 |
54 | {% csrf_token %} 55 | {{ form|crispy }} 56 | 57 |
58 | 59 | {% endblock %} 60 | 61 | 62 | {% block javascript %} 63 | {{ block.super }} 64 | 79 | {% endblock %} 80 | 81 | -------------------------------------------------------------------------------- /trax/templates/account/email_confirm.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | {% load account %} 5 | 6 | {% block head_title %}{% trans "Confirm E-mail Address" %}{% endblock %} 7 | 8 | 9 | {% block inner %} 10 |

{% trans "Confirm E-mail Address" %}

11 | 12 | {% if confirmation %} 13 | 14 | {% user_display confirmation.email_address.user as user_display %} 15 | 16 |

{% blocktrans with confirmation.email_address.email as email %}Please confirm that {{ email }} is an e-mail address for user {{ user_display }}.{% endblocktrans %}

17 | 18 |
19 | {% csrf_token %} 20 | 21 |
22 | 23 | {% else %} 24 | 25 | {% url 'account_email' as email_url %} 26 | 27 |

{% blocktrans %}This e-mail confirmation link expired or is invalid. Please issue a new e-mail confirmation request.{% endblocktrans %}

28 | 29 | {% endif %} 30 | 31 | {% endblock %} 32 | 33 | -------------------------------------------------------------------------------- /trax/templates/account/login.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | {% load account socialaccount %} 5 | {% load crispy_forms_tags %} 6 | 7 | {% block head_title %}{% trans "Sign In" %}{% endblock %} 8 | 9 | {% block inner %} 10 | 11 |

{% trans "Sign In" %}

12 | 13 | {% get_providers as socialaccount_providers %} 14 | 15 | {% if socialaccount_providers %} 16 |

{% blocktrans with site.name as site_name %}Please sign in with one 17 | of your existing third party accounts. Or, sign up 18 | for a {{ site_name }} account and sign in below:{% endblocktrans %}

19 | 20 |
21 | 22 |
    23 | {% include "socialaccount/snippets/provider_list.html" with process="login" %} 24 |
25 | 26 | 27 | 28 |
29 | 30 | {% include "socialaccount/snippets/login_extra.html" %} 31 | 32 | {% else %} 33 |

{% blocktrans %}If you have not created an account yet, then please 34 | sign up first.{% endblocktrans %}

35 | {% endif %} 36 | 37 | 46 | 47 | {% endblock %} 48 | 49 | -------------------------------------------------------------------------------- /trax/templates/account/logout.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | 5 | {% block head_title %}{% trans "Sign Out" %}{% endblock %} 6 | 7 | {% block inner %} 8 |

{% trans "Sign Out" %}

9 | 10 |

{% trans 'Are you sure you want to sign out?' %}

11 | 12 |
13 | {% csrf_token %} 14 | {% if redirect_field_value %} 15 | 16 | {% endif %} 17 | 18 |
19 | 20 | 21 | {% endblock %} 22 | 23 | -------------------------------------------------------------------------------- /trax/templates/account/password_change.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | {% load crispy_forms_tags %} 5 | 6 | {% block head_title %}{% trans "Change Password" %}{% endblock %} 7 | 8 | {% block inner %} 9 |

{% trans "Change Password" %}

10 | 11 |
12 | {% csrf_token %} 13 | {{ form|crispy }} 14 | 15 |
16 | {% endblock %} 17 | 18 | -------------------------------------------------------------------------------- /trax/templates/account/password_reset.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | {% load account %} 5 | {% load crispy_forms_tags %} 6 | 7 | {% block head_title %}{% trans "Password Reset" %}{% endblock %} 8 | 9 | {% block inner %} 10 | 11 |

{% trans "Password Reset" %}

12 | {% if user.is_authenticated %} 13 | {% include "account/snippets/already_logged_in.html" %} 14 | {% endif %} 15 | 16 |

{% trans "Forgotten your password? Enter your e-mail address below, and we'll send you an e-mail allowing you to reset it." %}

17 | 18 |
19 | {% csrf_token %} 20 | {{ form|crispy }} 21 | 22 |
23 | 24 |

{% blocktrans %}Please contact us if you have any trouble resetting your password.{% endblocktrans %}

25 | {% endblock %} 26 | 27 | -------------------------------------------------------------------------------- /trax/templates/account/password_reset_done.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | {% load account %} 5 | 6 | {% block head_title %}{% trans "Password Reset" %}{% endblock %} 7 | 8 | {% block inner %} 9 |

{% trans "Password Reset" %}

10 | 11 | {% if user.is_authenticated %} 12 | {% include "account/snippets/already_logged_in.html" %} 13 | {% endif %} 14 | 15 |

{% blocktrans %}We have sent you an e-mail. Please contact us if you do not receive it within a few minutes.{% endblocktrans %}

16 | {% endblock %} 17 | 18 | -------------------------------------------------------------------------------- /trax/templates/account/password_reset_from_key.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | {% load crispy_forms_tags %} 5 | {% block head_title %}{% trans "Change Password" %}{% endblock %} 6 | 7 | {% block inner %} 8 |

{% if token_fail %}{% trans "Bad Token" %}{% else %}{% trans "Change Password" %}{% endif %}

9 | 10 | {% if token_fail %} 11 | {% url 'account_reset_password' as passwd_reset_url %} 12 |

{% blocktrans %}The password reset link was invalid, possibly because it has already been used. Please request a new password reset.{% endblocktrans %}

13 | {% else %} 14 | {% if form %} 15 |
16 | {% csrf_token %} 17 | {{ form|crispy }} 18 | 19 |
20 | {% else %} 21 |

{% trans 'Your password is now changed.' %}

22 | {% endif %} 23 | {% endif %} 24 | {% endblock %} 25 | 26 | -------------------------------------------------------------------------------- /trax/templates/account/password_reset_from_key_done.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | {% block head_title %}{% trans "Change Password" %}{% endblock %} 5 | 6 | {% block inner %} 7 |

{% trans "Change Password" %}

8 |

{% trans 'Your password is now changed.' %}

9 | {% endblock %} 10 | 11 | -------------------------------------------------------------------------------- /trax/templates/account/password_set.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | {% load crispy_forms_tags %} 5 | 6 | {% block head_title %}{% trans "Set Password" %}{% endblock %} 7 | 8 | {% block inner %} 9 |

{% trans "Set Password" %}

10 | 11 |
12 | {% csrf_token %} 13 | {{ form|crispy }} 14 | 15 |
16 | {% endblock %} 17 | 18 | -------------------------------------------------------------------------------- /trax/templates/account/signup.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | {% load crispy_forms_tags %} 5 | 6 | {% block head_title %}{% trans "Signup" %}{% endblock %} 7 | 8 | {% block inner %} 9 |

{% trans "Sign Up" %}

10 | 11 |

{% blocktrans %}Already have an account? Then please sign in.{% endblocktrans %}

12 | 13 | 21 | 22 | {% endblock %} 23 | 24 | -------------------------------------------------------------------------------- /trax/templates/account/signup_closed.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | 5 | {% block head_title %}{% trans "Sign Up Closed" %}{% endblock %} 6 | 7 | {% block inner %} 8 |

{% trans "Sign Up Closed" %}

9 | 10 |

{% trans "We are sorry, but the sign up is currently closed." %}

11 | {% endblock %} 12 | 13 | -------------------------------------------------------------------------------- /trax/templates/account/verification_sent.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | 5 | {% block head_title %}{% trans "Verify Your E-mail Address" %}{% endblock %} 6 | 7 | {% block inner %} 8 |

{% trans "Verify Your E-mail Address" %}

9 | 10 |

{% blocktrans %}We have sent an e-mail to you for verification. Follow the link provided to finalize the signup process. Please contact us if you do not receive it within a few minutes.{% endblocktrans %}

11 | 12 | {% endblock %} 13 | 14 | -------------------------------------------------------------------------------- /trax/templates/account/verified_email_required.html: -------------------------------------------------------------------------------- 1 | {% extends "account/base.html" %} 2 | 3 | {% load i18n %} 4 | 5 | {% block head_title %}{% trans "Verify Your E-mail Address" %}{% endblock %} 6 | 7 | {% block inner %} 8 |

{% trans "Verify Your E-mail Address" %}

9 | 10 | {% url 'account_email' as email_url %} 11 | 12 |

{% blocktrans %}This part of the site requires us to verify that 13 | you are who you claim to be. For this purpose, we require that you 14 | verify ownership of your e-mail address. {% endblocktrans %}

15 | 16 |

{% blocktrans %}We have sent an e-mail to you for 17 | verification. Please click on the link inside this e-mail. Please 18 | contact us if you do not receive it within a few minutes.{% endblocktrans %}

19 | 20 |

{% blocktrans %}Note: you can still change your e-mail address.{% endblocktrans %}

21 | 22 | 23 | {% endblock %} 24 | 25 | -------------------------------------------------------------------------------- /trax/templates/base.html: -------------------------------------------------------------------------------- 1 | {% load staticfiles i18n %} 2 | 3 | 4 | 5 | 6 | {% block title %}trax{% endblock title %} 7 | 8 | 9 | 10 | 11 | 12 | 15 | 16 | {% block css %} 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | {% endblock %} 26 | 27 | 28 | 29 | 30 | 31 |
32 | 70 |
71 | 72 |
73 | 74 | {% if messages %} 75 | {% for message in messages %} 76 |
{{ message }}
77 | {% endfor %} 78 | {% endif %} 79 | 80 | {% block content %} 81 |

Use this document as a way to quick start any new project.

82 | {% endblock content %} 83 | 84 |
85 | 86 | {% block modal %}{% endblock modal %} 87 | 88 | 90 | 91 | {% block javascript %} 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | {% endblock javascript %} 105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /trax/templates/bootstrap4/field.html: -------------------------------------------------------------------------------- 1 | 2 | {% load crispy_forms_field %} 3 | 4 | {% if field.is_hidden %} 5 | {{ field }} 6 | {% else %} 7 | {% if field|is_checkbox %} 8 |
9 | {% if label_class %} 10 |
11 | {% endif %} 12 | {% endif %} 13 | <{% if tag %}{{ tag }}{% else %}div{% endif %} id="div_{{ field.auto_id }}" {% if not field|is_checkbox %}class="form-group{% if using_grid_layout %} row{% endif %}{% else %}class="checkbox{% endif %}{% if wrapper_class %} {{ wrapper_class }}{% endif %}{% if form_show_errors%}{% if field.errors %} has-danger{% endif %}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}"> 14 | {% if field.label and not field|is_checkbox and form_show_labels %} 15 | 18 | {% endif %} 19 | 20 | {% if field|is_checkboxselectmultiple %} 21 | {% include 'bootstrap4/layout/checkboxselectmultiple.html' %} 22 | {% endif %} 23 | 24 | {% if field|is_radioselect %} 25 | {% include 'bootstrap4/layout/radioselect.html' %} 26 | {% endif %} 27 | 28 | {% if not field|is_checkboxselectmultiple and not field|is_radioselect %} 29 | {% if field|is_checkbox and form_show_labels %} 30 | 35 | {% else %} 36 |
37 | {% crispy_field field %} 38 |
39 | {% include 'bootstrap4/layout/help_text_and_errors.html' %} 40 | {% endif %} 41 | {% endif %} 42 | 43 | {% if field|is_checkbox %} 44 | {% if label_class %} 45 |
46 | {% endif %} 47 |
48 | {% endif %} 49 | {% endif %} 50 | -------------------------------------------------------------------------------- /trax/templates/bootstrap4/layout/field_errors_block.html: -------------------------------------------------------------------------------- 1 | 2 | {% if form_show_errors and field.errors %} 3 | {% for error in field.errors %} 4 |

{{ error }}

5 | {% endfor %} 6 | {% endif %} 7 | 8 | -------------------------------------------------------------------------------- /trax/templates/pages/about.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} -------------------------------------------------------------------------------- /trax/templates/pages/home.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} -------------------------------------------------------------------------------- /trax/templates/trax/handlers/base_help.md: -------------------------------------------------------------------------------- 1 | {% block header %} 2 | | Command | Description | Example | 3 | | -------- | ----------- | ------- | 4 | | {{ handler.entrypoint }} | {{ handler.description|safe }} | {{ handler.get_example|safe }} | 5 | {% endblock %} 6 | {% block content %} 7 | {% endblock %} 8 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/config.md: -------------------------------------------------------------------------------- 1 | {% if setting %}{% if updated %} 2 | Setting "{{ setting }}" was updated from "{{ old_value }}" to "{{ new_value }}". 3 | {% else %} 4 | The current value for setting "{{ setting }}" is "{{ old_value }}". 5 | {% endif %} 6 | {% else %} 7 | Available settings are: 8 | 9 | | Setting | Current value | Description | 10 | | -------- | ----------- | ----------- |{% for conf, value in available_settings %} 11 | | {{ conf.name }} | {{ value }} | {{ conf.description }} | 12 | {% endfor %} 13 | {% endif %} 14 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/config_help.md: -------------------------------------------------------------------------------- 1 | {% extends "trax/handlers/base_help.md" %} 2 | 3 | {% block content %}You can use the `config` command to retrieve and update your personal settings. 4 | 5 | - `/ config`: will list all available settings 6 | - `/ config ` will display the value of a given setting 7 | - `/ config ` will update the value of a given setting 8 | 9 | For example, if you want to know which timezone you are using you can run `/ config timezone`. 10 | 11 | If you want to switch to another timezone, just run `/ config timezone Europe/Istanbul` 12 | {% endblock %} 13 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/cron.md: -------------------------------------------------------------------------------- 1 | `{{ crontab }}` would translate to `{{ description }}` 2 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/cron_help.md: -------------------------------------------------------------------------------- 1 | {% extends "trax/handlers/base_help.md" %} 2 | 3 | {% block content %}Cron is a special syntax to describe recurring things: 4 | 5 | * * * * * -> Cron expression 6 | │ │ │ │ │ 7 | │ │ │ │ └──----- day of week (0 - 6) (Sunday=0) 8 | │ │ │ └──------- month (1 - 12) 9 | │ │ └──--------- day of month (1 - 31) 10 | │ └──----------- hour (0 - 23) 11 | └──------------- min (0 - 59) 12 | 13 | Here are a few examples of cron expressions with their meaning: 14 | 15 | | Cron expression | Meaning | 16 | | ---------------------- | ---------------- | 17 | | `* * * * *` | Every minute | 18 | | `0 * * * *` | Every hour | 19 | | `15 * * * *` | Every hour at minute 15 | 20 | | `15 6 * * *` | Every day at 6:15 | 21 | | `15 6 3 * *` | At 6:15 on day 3 of the month | 22 | | `15 6 3 11 *` | At 6:15 on day 3 of the month, in November | 23 | | `15 6 * 11 5` | At 6:15 on every Friday, in November | 24 | 25 | Advanced examples: 26 | 27 | | Cron expression | Meaning | 28 | | ---------------------- | ---------------- | 29 | | `0,27,53 * * * *` | At minutes 0, 27 and 53 every hour | 30 | | `0 */3 * * *` | Every three hours | 31 | | `0 0 1-10 * *` | At 00:00 AM, between day 1 and 10 of the month | 32 | | `0 0 1-10,20-30 * *` | At 00:00 AM, on day 1 through 10 and 20 through 30 of the month | 33 | 34 | {% endblock %} 35 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/error.md: -------------------------------------------------------------------------------- 1 | An error occured while processing your command: 2 | 3 | {{ exception.messages.0 }} [{{ exception.code}}] 4 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/help.md: -------------------------------------------------------------------------------- 1 | {% if help_content %}{{ help_content }}{% else %}Trax is a small tool to help tracking your time without hassle. 2 | 3 | Available commands: 4 | 5 | | Command | Description | Example | 6 | | -------- | ----------- | ------- |{% for handler in handlers %} 7 | | {{ handler.entrypoint }} | {{ handler.description }} | {{ handler.get_example }} |{% endfor %} 8 | {% endif %} 9 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/list.md: -------------------------------------------------------------------------------- 1 | {% load trax_tags %}{% if timer_groups|length > 0 %}Your timers for {{ date }} are: 2 | {% for group in timer_groups %} 3 | - {{ group.name }}{% if group.is_started %}*{% endif %}: {{ group.today_duration|humanize_timedelta }}{% endfor %} 4 | {% else %}You did not started any timer on {{ date }} :){% endif %} 5 | {% with user.timer_groups.order_by_usage.with_position|slice:':15' as qs %}{% if qs|length > 0 %}Your most used timers are: {% for t in qs %} 6 | {{ t.queryset_position }}. {{ t.name }}{% endfor %}{% endif %}{% endwith %} 7 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/list_help.md: -------------------------------------------------------------------------------- 1 | {% extends "trax/handlers/base_help.md" %} 2 | 3 | {% block content %}You can also provide a date or a hint to query timers from a specific point of time. Example: 4 | 5 | - `/ list yesterday` 6 | - `/ list sunday` 7 | - `/ list 2016-09-07` 8 | - `/ list two weeks ago` 9 | - `/ list last month` 10 | {% endblock %} 11 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/remind_add.md: -------------------------------------------------------------------------------- 1 | Reminder `{{ reminder.message|safe }}` was added and will be sent next time on {{ reminder.next_call }}. 2 | 3 | {% if reminder.is_reccuring %}This is a recurring reminder with the following schedule: `{{ reminder.cron_description}}` (crontab: `{{ reminder.crontab }}`). 4 | 5 | Following calls are: 6 | 7 | {% for date in reminder.all_next|slice:"1:" %}- {{ date }} 8 | {% endfor %} 9 | {% endif %} 10 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/remind_delete.md: -------------------------------------------------------------------------------- 1 | {{ count }} reminders were deleted. 2 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/remind_list.md: -------------------------------------------------------------------------------- 1 | {% if reminders|length == 0 %} 2 | You don't have any reminders. 3 | {% else %} 4 | Your reminders are: 5 | 6 | | ID | Message | Type | Next call | 7 | | ---- | ------- | ---- | --------- |{% for reminder in reminders %} 8 | | {{ reminder.pk }} | {{ reminder.message|safe }} | {% if reminder.is_recurring %}Recurring (`{{ reminder.crontab }}`){% else %}One shot{% endif %} | {{ reminder.next_call }} |{% endfor %} 9 | {% endif %} 10 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/restart.md: -------------------------------------------------------------------------------- 1 | Timer "{{ timer_group.name }}" was restarted. 2 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/start.md: -------------------------------------------------------------------------------- 1 | {% load trax_tags %} 2 | {% with current_timer=timer_group.current_timer %} 3 | {% if current_timer.duration > 1 %} 4 | Timer "{{ timer_group.name }}" is already timing and so far you have tracked {{ timer_group.today_duration|humanize_timedelta }}. 5 | {% else %} 6 | Timer "{{ timer_group.name }}" was started. 7 | {% endif %} 8 | {% endwith %} 9 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/start_error_missing_arg.md: -------------------------------------------------------------------------------- 1 | {% if user.timer_groups.count > 0 %} 2 | You did not provide a valid timer name, here is a list of your most used timers: 3 | 4 | {% for t in user.timer_groups.order_by_usage.with_position|slice:':15' %}{{ t.queryset_position }}. {{ t.name }} 5 | {% endfor %} 6 | {% else %} 7 | Please provide a valid timer name. Examples: 8 | 9 | - `/ start making coffee` 10 | - `/ start important meeting` 11 | 12 | {% endif %} 13 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/start_help.md: -------------------------------------------------------------------------------- 1 | {% extends "trax/handlers/base_help.md" %} 2 | 3 | {% block content %}You can also use shortcuts to start a timer. Consider the following output from / start: 4 | 5 | You did not provide a valid timer name, here is a list of your most used timers: 6 | 7 | 1. make coffee 8 | 2. have a meeting 9 | 3. take a nap 10 | 11 | Then you can call `/ start 3` to start the `take a nap` timer. 12 | {% endblock %} 13 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/stats.md: -------------------------------------------------------------------------------- 1 | {% load trax_tags %} 2 | Your time tracking statistics for the period from {{ start_date }} to {{ end_date }}: 3 | 4 | | | {% for header in headers %}{{ header.date }} | {% endfor %} **Total** | 5 | | -------- | ----------- | ------- |{% for row in rows %} 6 | | {{ row.label }} | {% for value in row.values %}{% if value %}{{ value }}{% else %}-{% endif %} |{% endfor %} **{% if row.total %}{{ row.total }}{% else %}-{% endif %}** |{% endfor %} 7 | | **Total** | {% for v in interval_totals %}**{% if v %}{{ v }}{% else %}-{% endif %}** | {% endfor %} **{% if total %}{{ total }}{% else %}-{% endif %}** | 8 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/stop.md: -------------------------------------------------------------------------------- 1 | {% if timer_groups|length > 0 %} 2 | Timers were successfully stopped on {{ end_date }}: 3 | {% for t in timer_groups %} 4 | - {{ t.name }} 5 | {% endfor %} 6 | {% else %} 7 | No timer was running 8 | {% endif %} 9 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/stop_help.md: -------------------------------------------------------------------------------- 1 | {% extends "trax/handlers/base_help.md" %} 2 | 3 | {% block content %}When stopping your timer, you can also provide an optional time at which the timer should be stopped. This is especially useful if you forget to stop a timer: 4 | 5 | # we start a timer 6 | / start some task 7 | 8 | # we work one hour and forgot to stop the timer 9 | # two hours after that, we retroactively stop the timer 10 | / stop one hour ago 11 | 12 | You can provide relative times or absolute ones. Examples: 13 | 14 | - `/ stop 10 minutes ago` 15 | - `/ stop 17:35` 16 | {% endblock %} 17 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/time.md: -------------------------------------------------------------------------------- 1 | {% load tz %} 2 | {% timezone timezone %} 3 | The current date/time in timezone {{ timezone }} is **{{ current }}** 4 | {% endtimezone %} 5 | -------------------------------------------------------------------------------- /trax/templates/trax/handlers/time_help.md: -------------------------------------------------------------------------------- 1 | {% extends "trax/handlers/base_help.md" %} 2 | 3 | {% block content %} 4 | You can also provide a specific timezone if you want to know the time under another timezone. Examples: 5 | 6 | - `/ time` 7 | - `/ time Europe/Istanbul` 8 | - `/ time Europe/London` 9 | 10 | {% endblock %} 11 | -------------------------------------------------------------------------------- /trax/templates/trax/reminder.md: -------------------------------------------------------------------------------- 1 | {{ reminder.message|safe }} 2 | {% if reminder.is_recurring %}This recurring reminder was scheduled by {{ reminder.user.username }}. Next ones are: 3 | 4 | {% for date in reminder.all_next %}- {{ date }} 5 | {% endfor %} 6 | {% else %} 7 | This reminder was scheduled by {{ reminder.user.username }}. 8 | {% endif %} 9 | -------------------------------------------------------------------------------- /trax/templates/users/user_detail.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load static %} 3 | 4 | {% block title %}User: {{ object.username }}{% endblock %} 5 | 6 | {% block content %} 7 |
8 | 9 |
10 |
11 | 12 |

{{ object.username }}

13 | {% if object.name %} 14 |

{{ object.name }}

15 | {% endif %} 16 |
17 |
18 | 19 | {% if object == request.user %} 20 | 21 |
22 | 23 |
24 | My Info 25 | E-Mail 26 | 27 |
28 | 29 |
30 | 31 | {% endif %} 32 | 33 | 34 |
35 | {% endblock content %} 36 | 37 | -------------------------------------------------------------------------------- /trax/templates/users/user_form.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load crispy_forms_tags %} 3 | 4 | {% block title %}{{ user.username }}{% endblock %} 5 | 6 | {% block content %} 7 |

{{ user.username }}

8 |
9 | {% csrf_token %} 10 | {{ form|crispy }} 11 |
12 |
13 | 14 |
15 |
16 |
17 | {% endblock %} 18 | -------------------------------------------------------------------------------- /trax/templates/users/user_list.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% load static i18n %} 3 | {% block title %}Members{% endblock %} 4 | 5 | {% block content %} 6 |
7 |

Users

8 | 9 |
10 | {% for user in user_list %} 11 | 12 |

{{ user.username }}

13 |
14 | {% endfor %} 15 |
16 |
17 | {% endblock content %} 18 | -------------------------------------------------------------------------------- /trax/trax/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agateblue/trax/61a14b2a3cd6366422b27c48b9e3716bbdcd7ae5/trax/trax/__init__.py -------------------------------------------------------------------------------- /trax/trax/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from . import models 4 | 5 | 6 | @admin.register(models.Timer) 7 | class TimerAdmin(admin.ModelAdmin): 8 | list_display = [ 9 | 'group', 10 | 'start_date', 11 | 'end_date', 12 | 'duration', 13 | ] 14 | list_filter = [ 15 | 'group__user', 16 | 'group__slug', 17 | ] 18 | search_fields = [ 19 | 'group__user__username', 20 | 'group__name', 21 | 'group__slug', 22 | ] 23 | 24 | 25 | @admin.register(models.TimerGroup) 26 | class TimerGroupAdmin(admin.ModelAdmin): 27 | list_display = [ 28 | 'name', 29 | 'user', 30 | 'creation_date', 31 | 'is_started', 32 | ] 33 | list_filter = [ 34 | 'user', 35 | 'slug', 36 | ] 37 | search_fields = [ 38 | 'user__username', 39 | 'name', 40 | 'slug', 41 | ] 42 | 43 | 44 | @admin.register(models.Reminder) 45 | class ReminderAdmin(admin.ModelAdmin): 46 | list_display = [ 47 | 'message', 48 | 'user', 49 | 'creation_date', 50 | 'is_recurring', 51 | 'next_call', 52 | 'crontab', 53 | ] 54 | search_fields = [ 55 | 'user__username', 56 | 'message', 57 | ] 58 | -------------------------------------------------------------------------------- /trax/trax/dynamic_preferences_registry.py: -------------------------------------------------------------------------------- 1 | import pytz 2 | from django.conf import settings 3 | from dynamic_preferences.types import ( 4 | ChoicePreference, Section, StringPreference) 5 | from dynamic_preferences.registries import user_preferences_registry 6 | from dynamic_preferences.registries import global_preferences_registry 7 | 8 | glob = Section('global') 9 | trax = Section('trax') 10 | 11 | 12 | @global_preferences_registry.register 13 | class SlashCommandToken(StringPreference): 14 | section = trax 15 | name = 'slash_command_token' 16 | description = "The token used to validate slash command payload" 17 | default = 'CHANGEME' 18 | 19 | 20 | @global_preferences_registry.register 21 | class WebHookUrl(StringPreference): 22 | section = trax 23 | name = 'webhook_url' 24 | description = "The webhook URL where trax can send messages" 25 | default = 'http://changeme' 26 | 27 | 28 | @user_preferences_registry.register 29 | class TimeZone(ChoicePreference): 30 | section = glob 31 | name = 'timezone' 32 | description = "The timezone used for date handling" 33 | choices = [(t, t) for t in pytz.all_timezones] 34 | 35 | def get_default(self): 36 | return settings.TIME_ZONE 37 | -------------------------------------------------------------------------------- /trax/trax/exceptions.py: -------------------------------------------------------------------------------- 1 | from django.forms import ValidationError 2 | 3 | 4 | class HandleError(ValidationError): 5 | pass 6 | -------------------------------------------------------------------------------- /trax/trax/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | from django.conf import settings 3 | from dynamic_preferences.registries import global_preferences_registry 4 | 5 | from trax.users.models import User 6 | from . import handlers 7 | 8 | 9 | class SlashCommandForm(forms.Form): 10 | token = forms.CharField() 11 | channel_id = forms.CharField() 12 | channel_name = forms.CharField() 13 | command = forms.CharField() 14 | team_domain = forms.CharField() 15 | team_id = forms.CharField() 16 | user_id = forms.CharField() 17 | user_name = forms.CharField() 18 | text = forms.CharField() 19 | 20 | # will be deduced from command 21 | handler = forms.CharField(required=False) 22 | action = forms.CharField(required=False) 23 | arguments = forms.CharField(required=False) 24 | 25 | # will be deduced from user id 26 | user = forms.ModelChoiceField(required=False, queryset=User.objects.all()) 27 | 28 | def clean_token(self): 29 | global_preferences = global_preferences_registry.manager() 30 | expected_token = global_preferences['trax__slash_command_token'] 31 | if expected_token != self.cleaned_data['token']: 32 | raise forms.ValidationError('Invalid token') 33 | return self.cleaned_data['token'] 34 | 35 | def clean_user(self): 36 | # First, we try to bind to an existing user without external ID 37 | try: 38 | user = User.objects.get( 39 | username=self.cleaned_data['user_name'], 40 | external_id__isnull=True) 41 | user.external_id = self.cleaned_data['user_id'] 42 | user.save() 43 | return user 44 | except User.DoesNotExist: 45 | pass 46 | 47 | # otherwise, we fallback to simply creating a user from scratch 48 | return User.objects.get_or_create( 49 | external_id=self.cleaned_data['user_id'], 50 | username=self.cleaned_data['user_name'], 51 | defaults={ 52 | 'is_active': False, 53 | } 54 | )[0] 55 | 56 | def clean_action(self): 57 | try: 58 | return self.cleaned_data['text'].split(' ')[0].strip() 59 | except KeyError: 60 | # No arguments were sent, we fallback on help 61 | return 'help' 62 | 63 | def clean_arguments(self): 64 | try: 65 | return ' '.join(self.cleaned_data['text'].split(' ')[1:]).strip() 66 | except KeyError: 67 | return '' 68 | 69 | 70 | def clean_handler(self): 71 | action = self.clean_action() 72 | try: 73 | return [h for h in handlers.handlers if h.valid_for_action(action)][0] 74 | except IndexError: 75 | raise forms.ValidationError('No handler found for action {0}'.format(action)) 76 | -------------------------------------------------------------------------------- /trax/trax/management/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agateblue/trax/61a14b2a3cd6366422b27c48b9e3716bbdcd7ae5/trax/trax/management/commands/__init__.py -------------------------------------------------------------------------------- /trax/trax/management/commands/trax_schedule.py: -------------------------------------------------------------------------------- 1 | import traceback 2 | import schedule 3 | import time 4 | 5 | from django.core.management.base import BaseCommand, CommandError 6 | from django.utils import timezone 7 | 8 | from trax.trax import tasks 9 | 10 | 11 | class Command(BaseCommand): 12 | help = 'Run the cron-like task to do recurring tasks' 13 | 14 | def handle(self, *args, **options): 15 | schedule.every(1).hours.do(tasks.kill_obsolete_timers) 16 | schedule.every(5).seconds.do(tasks.send_reminders) 17 | 18 | self.stdout.write(self.style.SUCCESS('Starting job runner...')) 19 | while True: 20 | time.sleep(1) 21 | try: 22 | schedule.run_pending() 23 | except: 24 | traceback.print_exc() 25 | -------------------------------------------------------------------------------- /trax/trax/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.10.4 on 2016-12-27 10:13 3 | from __future__ import unicode_literals 4 | 5 | from django.conf import settings 6 | from django.db import migrations, models 7 | import django.db.models.deletion 8 | import django.utils.timezone 9 | 10 | 11 | class Migration(migrations.Migration): 12 | 13 | initial = True 14 | 15 | dependencies = [ 16 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 17 | ] 18 | 19 | operations = [ 20 | migrations.CreateModel( 21 | name='Timer', 22 | fields=[ 23 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 24 | ('start_date', models.DateTimeField(default=django.utils.timezone.now)), 25 | ('end_date', models.DateTimeField(blank=True, null=True)), 26 | ], 27 | ), 28 | migrations.CreateModel( 29 | name='TimerGroup', 30 | fields=[ 31 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 32 | ('name', models.CharField(max_length=150)), 33 | ('slug', models.CharField(max_length=150)), 34 | ('creation_date', models.DateTimeField(default=django.utils.timezone.now)), 35 | ('description', models.TextField()), 36 | ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='timer_groups', to=settings.AUTH_USER_MODEL)), 37 | ], 38 | ), 39 | migrations.AddField( 40 | model_name='timer', 41 | name='group', 42 | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='timers', to='trax.TimerGroup'), 43 | ), 44 | ] 45 | -------------------------------------------------------------------------------- /trax/trax/migrations/0002_auto_20170106_1642.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.10.4 on 2017-01-06 15:42 3 | from __future__ import unicode_literals 4 | 5 | from django.conf import settings 6 | from django.db import migrations, models 7 | import django.db.models.deletion 8 | import trax.trax.models 9 | 10 | 11 | class Migration(migrations.Migration): 12 | 13 | dependencies = [ 14 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 15 | ('trax', '0001_initial'), 16 | ] 17 | 18 | operations = [ 19 | migrations.CreateModel( 20 | name='Reminder', 21 | fields=[ 22 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 23 | ('creation_date', models.DateTimeField(default=trax.trax.models.get_now)), 24 | ('next_call', models.DateTimeField(blank=True, null=True)), 25 | ('completed_on', models.DateTimeField(blank=True, null=True)), 26 | ('crontab', models.CharField(blank=True, max_length=100, null=True)), 27 | ('message', models.TextField()), 28 | ('channel_id', models.CharField(blank=True, max_length=100, null=True)), 29 | ('channel_name', models.CharField(blank=True, max_length=100, null=True)), 30 | ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reminders', to=settings.AUTH_USER_MODEL)), 31 | ], 32 | ), 33 | migrations.AlterModelOptions( 34 | name='timer', 35 | options={'ordering': ('-start_date',)}, 36 | ), 37 | migrations.AlterModelOptions( 38 | name='timergroup', 39 | options={'ordering': ('-creation_date',)}, 40 | ), 41 | migrations.AlterField( 42 | model_name='timer', 43 | name='start_date', 44 | field=models.DateTimeField(default=trax.trax.models.get_now), 45 | ), 46 | migrations.AlterField( 47 | model_name='timergroup', 48 | name='creation_date', 49 | field=models.DateTimeField(default=trax.trax.models.get_now), 50 | ), 51 | migrations.AlterUniqueTogether( 52 | name='timergroup', 53 | unique_together=set([('slug', 'user')]), 54 | ), 55 | ] 56 | -------------------------------------------------------------------------------- /trax/trax/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agateblue/trax/61a14b2a3cd6366422b27c48b9e3716bbdcd7ae5/trax/trax/migrations/__init__.py -------------------------------------------------------------------------------- /trax/trax/models.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import requests 3 | import pytz 4 | import json 5 | import croniter 6 | 7 | from django.db import models, transaction 8 | from django.utils import timezone 9 | from django.forms import ValidationError 10 | from django.utils.text import slugify 11 | from django.core.exceptions import ValidationError 12 | from django.template import loader, Context 13 | from django.utils import safestring 14 | 15 | from dynamic_preferences.registries import global_preferences_registry 16 | 17 | from trax.users.models import User 18 | 19 | 20 | def get_now(): 21 | return timezone.now() 22 | 23 | 24 | class TimerGroupQuerySet(models.QuerySet): 25 | def running(self): 26 | return self.filter(timers__end_date__isnull=True) 27 | 28 | def since(self, start_date, end_date=None): 29 | qs = self.filter(timers__start_date__gte=start_date) 30 | if end_date: 31 | q = models.Q(timers__end_date__lt=end_date) | models.Q(timers__end_date__isnull=True) 32 | qs = qs.filter(q).filter(timers__start_date__lt=end_date) 33 | return qs.distinct() 34 | 35 | def order_by_usage(self): 36 | return self.annotate(c=models.Count('timers')).order_by('-c') 37 | 38 | def with_position(self): 39 | qs = list(self.all()) 40 | for i, e in enumerate(qs): 41 | setattr(e, 'queryset_position', i + 1) 42 | return qs 43 | 44 | def stop(self): 45 | qs = list(self.all().running()) 46 | for group in qs: 47 | group.stop() 48 | 49 | return qs 50 | 51 | 52 | class TimerGroupManager(models.Manager): 53 | 54 | def start(self, name, user, **kwargs): 55 | slug = slugify(name) 56 | # first, we check if a timer for this group is already started 57 | qs = user.timer_groups.filter(slug=slug).running() 58 | existing = qs.first() 59 | if existing: 60 | return existing 61 | 62 | # we stop any previously running group for the same user 63 | user.timer_groups.stop() 64 | 65 | # then we get_or_create a new group based on the given name 66 | group, created = self.get_or_create( 67 | user=user, slug=slugify(name), 68 | defaults={'name': name}, 69 | ) 70 | 71 | # and finally, we start the whole thing 72 | group.start() 73 | return group 74 | 75 | 76 | class TimerGroup(models.Model): 77 | name = models.CharField(max_length=150) 78 | slug = models.CharField(max_length=150) 79 | creation_date = models.DateTimeField(default=get_now) 80 | description = models.TextField() 81 | user = models.ForeignKey(User, related_name='timer_groups') 82 | 83 | objects = TimerGroupManager.from_queryset(TimerGroupQuerySet)() 84 | 85 | def __str__(self): 86 | return '{0} / {1}'.format(self.user, self.name) 87 | 88 | class Meta: 89 | unique_together = ('slug', 'user') 90 | ordering = ('-creation_date',) 91 | 92 | @property 93 | def today_duration(self): 94 | today = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) 95 | return self.get_duration(today) 96 | 97 | def get_duration(self, start, end=None): 98 | return self.timers.all().since(start, end).duration() 99 | 100 | @property 101 | def current_timer(self): 102 | return self.timers.running().order_by('-start_date').first() 103 | 104 | @property 105 | def is_started(self): 106 | return TimerGroup.objects.filter(pk=self.pk).running().exists() 107 | 108 | def start(self): 109 | self.user.timer_groups.stop() 110 | return self.timers.create( 111 | group=self, 112 | ) 113 | 114 | def stop(self, end=None): 115 | for timer in self.timers.all().running(): 116 | timer.stop(end=end) 117 | 118 | 119 | class TimerQuerySet(models.QuerySet): 120 | def running(self): 121 | return self.filter(end_date__isnull=True) 122 | 123 | def since(self, start_date, end_date=None): 124 | qs = self.filter(start_date__gte=start_date) 125 | if end_date: 126 | q = models.Q(end_date__lt=end_date) | models.Q(end_date__isnull=True) 127 | qs = qs.filter(q).filter(start_date__lt=end_date) 128 | return qs.distinct() 129 | 130 | def duration(self): 131 | duration = 0 132 | for timer in self.all(): 133 | duration += timer.duration 134 | 135 | return datetime.timedelta(seconds=duration) 136 | 137 | 138 | class Timer(models.Model): 139 | start_date = models.DateTimeField(default=get_now) 140 | end_date = models.DateTimeField(null=True, blank=True) 141 | group = models.ForeignKey(TimerGroup, related_name='timers') 142 | 143 | objects = TimerQuerySet.as_manager() 144 | 145 | class Meta: 146 | ordering = ('-start_date',) 147 | 148 | def __str__(self): 149 | return '{0}: {1} -> {2}'.format( 150 | self.group.name, self.start_date, self.end_date 151 | ) 152 | 153 | @property 154 | def duration(self): 155 | end = self.end_date or timezone.now() 156 | return (end - self.start_date).seconds 157 | 158 | def save(self, **kwargs): 159 | if self.end_date and self.end_date < self.start_date: 160 | raise ValidationError('End date must be greater than start date') 161 | 162 | # we try to find any overlapping timer 163 | qs = Timer.objects.filter(group__user=self.group.user) 164 | query = models.Q(start_date__lte=self.start_date, end_date__gte=self.start_date) 165 | 166 | if self.end_date: 167 | query |= models.Q(start_date__lte=self.end_date, end_date__gte=self.end_date) 168 | 169 | duplicates = qs.running() | qs.filter(query) 170 | if self.pk: 171 | duplicates = duplicates.exclude(pk=self.pk) 172 | 173 | if duplicates.exists(): 174 | raise ValidationError('Timer is overlapping another timer from the same group') 175 | return super().save(**kwargs) 176 | 177 | @property 178 | def is_started(self): 179 | return self.end_date is None 180 | 181 | def stop(self, end=None): 182 | self.end_date = end or timezone.now() 183 | self.save() 184 | 185 | 186 | class ReminderQuerySet(models.QuerySet): 187 | def sendable(self): 188 | now = timezone.now() 189 | return self.filter(next_call__lte=now) 190 | 191 | 192 | class Reminder(models.Model): 193 | creation_date = models.DateTimeField(default=get_now) 194 | next_call = models.DateTimeField(null=True, blank=True) 195 | completed_on = models.DateTimeField(null=True, blank=True) 196 | crontab = models.CharField(null=True, blank=True, max_length=100) 197 | user = models.ForeignKey(User, related_name='reminders') 198 | message = models.TextField() 199 | channel_id = models.CharField(max_length=100, null=True, blank=True) 200 | channel_name = models.CharField(max_length=100, null=True, blank=True) 201 | 202 | objects = ReminderQuerySet.as_manager() 203 | 204 | @property 205 | def is_recurring(self): 206 | return bool(self.crontab) 207 | 208 | def save(self, **kwargs): 209 | if not self.pk and self.is_recurring: 210 | self.schedule_next_call() 211 | 212 | return super().save(**kwargs) 213 | 214 | def schedule_next_call(self): 215 | """ 216 | When using a recurring reminder via crontab 217 | """ 218 | if not self.is_recurring: 219 | raise ValueError('Cannot schedule next call without crontab') 220 | 221 | if self.next_call: 222 | raise ValueError('Next call is already scheduled') 223 | 224 | self.next_call = self.get_next() 225 | 226 | def get_next(self): 227 | if not self.is_recurring: 228 | raise ValueError('Not a recurring reminder') 229 | return self.crontab_schedule.get_next(datetime.datetime) 230 | 231 | def all_next(self, length=3): 232 | if not self.is_recurring: 233 | raise ValueError('Not a recurring reminder') 234 | schedule = self.crontab_schedule 235 | nexts = [] 236 | for i in range(length): 237 | nexts.append(schedule.get_next(datetime.datetime)) 238 | return nexts 239 | 240 | @property 241 | def crontab_schedule(self): 242 | if not self.crontab: 243 | raise ValueError('Crontab is not set') 244 | 245 | tz = pytz.timezone(self.user.preferences['global__timezone']) 246 | now = timezone.now() 247 | now = now.astimezone(tz) 248 | return croniter.croniter(self.crontab, now) 249 | 250 | @transaction.atomic 251 | def send(self, strict=True): 252 | if strict and timezone.now() < self.next_call: 253 | raise ValueError('This reminder cannot be send, it\'s too early') 254 | 255 | request = self.prepare_request() 256 | session = requests.Session() 257 | response = session.send(request) 258 | response.raise_for_status() 259 | 260 | self.completed_on = timezone.now() 261 | self.next_call = None 262 | if self.is_recurring: 263 | self.schedule_next_call() 264 | self.save() 265 | 266 | return response 267 | 268 | def render(self): 269 | t = loader.get_template('trax/reminder.md') 270 | 271 | context = {} 272 | context['reminder'] = self 273 | return safestring.mark_safe(t.render(Context(context)).strip()) 274 | 275 | def prepare_request(self): 276 | preferences = global_preferences_registry.manager() 277 | url = preferences['trax__webhook_url'] 278 | data = { 279 | 'text': self.render(), 280 | 'channel': self.channel_name, 281 | } 282 | return requests.Request( 283 | 'POST', 284 | url=url, 285 | data={'payload': json.dumps(data)}, 286 | ).prepare() 287 | -------------------------------------------------------------------------------- /trax/trax/tasks.py: -------------------------------------------------------------------------------- 1 | from django.utils import timezone 2 | 3 | from . import models 4 | 5 | 6 | def kill_obsolete_timers(): 7 | now = timezone.now() 8 | today = now.date() 9 | 10 | candidates = models.Timer.objects.running() 11 | candidates = candidates.filter(start_date__date__lt=today) 12 | 13 | for candidate in candidates: 14 | candidate.stop() 15 | 16 | print('Closed %s timers' % len(candidates)) 17 | 18 | 19 | def send_reminders(): 20 | candidates = models.Reminder.objects.sendable() 21 | 22 | for reminder in candidates: 23 | reminder.send() 24 | 25 | print('Sended %s reminders' % len(candidates)) 26 | -------------------------------------------------------------------------------- /trax/trax/templatetags/__init__.py: -------------------------------------------------------------------------------- 1 | from django import template 2 | 3 | from trax.trax import utils 4 | register = template.Library() 5 | 6 | @register.filter(name='humanize_timedelta') 7 | def d(value): 8 | return utils.humanize_timedelta(value) 9 | -------------------------------------------------------------------------------- /trax/trax/templatetags/trax_tags.py: -------------------------------------------------------------------------------- 1 | from django import template 2 | 3 | from trax.trax import utils 4 | register = template.Library() 5 | 6 | 7 | @register.filter(name='humanize_timedelta') 8 | def d(value): 9 | return utils.humanize_timedelta(value) 10 | -------------------------------------------------------------------------------- /trax/trax/tests/test_forms.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from test_plus.test import TestCase 3 | 4 | from trax.trax import models, forms, handlers 5 | from trax.users.models import User 6 | from django.conf import settings 7 | 8 | from dynamic_preferences.registries import global_preferences_registry 9 | 10 | 11 | class TestForms(TestCase): 12 | 13 | def setUp(self): 14 | self.preferences = global_preferences_registry.manager() 15 | self.preferences['trax__slash_command_token'] = 'good_token' 16 | 17 | def test_slash_command_form_requires_valid_token(self): 18 | data = { 19 | 'channel_id': 'cniah6qa73bjjjan6mzn11f4ie', 20 | 'channel_name': 'town-square', 21 | 'command': '/trax', 22 | 'text': 'start test', 23 | 'team_domain': 'testteam', 24 | 'team_id': 'rdc9bgriktyx9p4kowh3dmgqyc', 25 | 'token': 'wrong_token', 26 | 'user_id': 'testuser', 27 | 'user_name': 'testid', 28 | } 29 | 30 | form = forms.SlashCommandForm(data) 31 | form.is_valid() 32 | 33 | self.assertIn('token', form.errors) 34 | 35 | def test_can_validate_form(self): 36 | payload = { 37 | 'channel_id': 'cniah6qa73bjjjan6mzn11f4ie', 38 | 'channel_name': 'town-square', 39 | 'command': '/trax', 40 | 'text': 'start test timer', 41 | 'team_domain': 'testteam', 42 | 'team_id': 'rdc9bgriktyx9p4kowh3dmgqyc', 43 | 'token': 'good_token', 44 | 'user_id': 'testid', 45 | 'user_name': 'testuser', 46 | } 47 | 48 | form = forms.SlashCommandForm(payload) 49 | is_valid = form.is_valid() 50 | 51 | data = form.cleaned_data 52 | 53 | self.assertTrue(is_valid) 54 | 55 | user = User.objects.get( 56 | is_active=False, 57 | username=data['user_name'], 58 | external_id=data['user_id']) 59 | 60 | self.assertEqual(data['user'], user) 61 | self.assertEqual(data['action'], 'start') 62 | self.assertEqual(data['arguments'], 'test timer') 63 | self.assertEqual(data['handler'], handlers.handlers_by_key['start']) 64 | -------------------------------------------------------------------------------- /trax/trax/tests/test_handlers.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import datetime 3 | 4 | from test_plus.test import TestCase 5 | from django.conf import settings 6 | from django.utils import timezone 7 | 8 | from trax.trax import models, forms, handlers 9 | from trax.users.models import User 10 | 11 | 12 | class TestForms(TestCase): 13 | def setUp(self): 14 | self.user = self.make_user() 15 | 16 | def test_start_timer_handler(self): 17 | handler = handlers.handlers_by_key['start'] 18 | arguments = 'this is my timer' 19 | 20 | now = timezone.now() 21 | with unittest.mock.patch('django.utils.timezone.now', return_value=now): 22 | result = handler.handle(arguments, user=self.user) 23 | 24 | group = result['timer_group'] 25 | 26 | self.assertEqual(group.name, 'this is my timer') 27 | self.assertEqual(group.slug, 'this-is-my-timer') 28 | self.assertEqual(group.user, self.user) 29 | 30 | timer = group.timers.first() 31 | 32 | self.assertGreaterEqual(timer.start_date, now) 33 | self.assertEqual(timer.end_date, None) 34 | 35 | def test_can_start_using_an_integer_shortcut(self): 36 | handler = handlers.handlers_by_key['start'] 37 | group1 = models.TimerGroup.objects.start('Test 1', user=self.user) 38 | group1 = models.TimerGroup.objects.start('Test 1', user=self.user) 39 | group2 = models.TimerGroup.objects.start('Test 2', user=self.user) 40 | 41 | arguments = '1' 42 | result = handler.handle(arguments, user=self.user) 43 | 44 | self.assertEqual(result['timer_group'], group1) 45 | self.assertTrue(group1.is_started) 46 | 47 | def test_stop_timer(self): 48 | handler = handlers.handlers_by_key['stop'] 49 | group = models.TimerGroup.objects.start('Test 2', user=self.user) 50 | 51 | self.assertTrue(group.is_started) 52 | 53 | result = handler.handle('', user=self.user) 54 | timer = group.timers.first() 55 | 56 | self.assertFalse(group.is_started) 57 | self.assertFalse(timer.is_started) 58 | 59 | def test_can_stop_timer_in_the_past(self): 60 | handler = handlers.handlers_by_key['stop'] 61 | now = timezone.now().replace(microsecond=0) 62 | start = now - datetime.timedelta(hours=2) 63 | with unittest.mock.patch('django.utils.timezone.now', return_value=start): 64 | group = models.TimerGroup.objects.start('Test 2', user=self.user) 65 | 66 | timer = group.current_timer 67 | 68 | self.assertEqual(timer.start_date, start) 69 | 70 | now = start + datetime.timedelta(hours=2) 71 | with unittest.mock.patch('django.utils.timezone.now', return_value=now): 72 | result = handler.handle('one hour ago', user=self.user) 73 | 74 | timer.refresh_from_db() 75 | difference = timer.end_date - (timer.start_date + datetime.timedelta(hours=1)) 76 | self.assertEqual(difference.seconds, 0) 77 | 78 | def test_list_timers(self): 79 | handler = handlers.handlers_by_key['list'] 80 | group = models.TimerGroup.objects.start('Test 2', user=self.user) 81 | 82 | result = handler.handle('', user=self.user) 83 | self.assertEqual(len(result['timer_groups']), 1) 84 | self.assertEqual(result['timer_groups'].first(), group) 85 | 86 | def test_stats_handler(self): 87 | handler = handlers.handlers_by_key['stats'] 88 | group1 = models.TimerGroup.objects.start('Test 1', user=self.user) 89 | group2 = models.TimerGroup.objects.start('Test 2', user=self.user) 90 | empty_group = models.TimerGroup.objects.create( 91 | name='Empty', slug='empty', user=self.user) 92 | 93 | result = handler.handle('', user=self.user) 94 | self.assertEqual(len(result['rows']), 2) 95 | self.assertEqual(result['rows'][0]['label'], 'Test 1') 96 | self.assertEqual(result['rows'][1]['label'], 'Test 2') 97 | 98 | def test_restart_handler(self): 99 | group1 = models.TimerGroup.objects.start('Test 1', user=self.user) 100 | group2 = models.TimerGroup.objects.start('Test 2', user=self.user) 101 | group2.stop() 102 | 103 | handler = handlers.handlers_by_key['restart'] 104 | result = handler.handle('', user=self.user) 105 | 106 | group2.refresh_from_db() 107 | self.assertTrue(group2.is_started) 108 | 109 | def test_config_handler(self): 110 | self.user.delete() 111 | with self.settings(TIME_ZONE='Europe/Berlin'): 112 | user = self.make_user() 113 | tz = user.preferences['global__timezone'] 114 | self.assertEqual(tz, 'Europe/Berlin') 115 | 116 | handler = handlers.handlers_by_key['config'] 117 | result = handler.handle('timezone Europe/Paris', user=user) 118 | 119 | self.assertEqual(user.preferences['global__timezone'], 'Europe/Paris') 120 | 121 | def test_remind_handler(self): 122 | handler = handlers.handlers_by_key['remind'] 123 | now = timezone.now() 124 | with unittest.mock.patch('django.utils.timezone.now', return_value=now): 125 | result = handler.handle( 126 | 'add "drink water" "in two hours"', 127 | channel_id='test_id', 128 | channel_name='test_name', 129 | user=self.user) 130 | 131 | reminder = self.user.reminders.first() 132 | self.assertEqual( 133 | reminder.next_call.replace(microsecond=0), 134 | (now + datetime.timedelta(hours=2)).replace(microsecond=0)) 135 | self.assertEqual(reminder.message, 'drink water') 136 | self.assertEqual(reminder.channel_id, 'test_id') 137 | self.assertEqual(reminder.channel_name, 'test_name') 138 | 139 | def test_remind_delete_handler(self): 140 | reminder = models.Reminder.objects.create( 141 | user=self.user, 142 | crontab='30 12 * * *', 143 | message='Hello, how are you ?', 144 | channel_id='channel_id', 145 | channel_name='channel_name', 146 | ) 147 | handler = handlers.handlers_by_key['remind'] 148 | now = timezone.now() 149 | with unittest.mock.patch('django.utils.timezone.now', return_value=now): 150 | result = handler.handle( 151 | 'delete {0}'.format(reminder.pk), user=self.user) 152 | 153 | self.assertEqual(self.user.reminders.count(), 0) 154 | 155 | def test_remind_handler_can_provide_crontab(self): 156 | handler = handlers.handlers_by_key['remind'] 157 | now = timezone.now() 158 | with unittest.mock.patch('django.utils.timezone.now', return_value=now): 159 | result = handler.handle( 160 | 'add "drink water" "1 1 * * *"', 161 | channel_id='test_id', 162 | channel_name='test_name', 163 | user=self.user) 164 | 165 | reminder = self.user.reminders.first() 166 | self.assertEqual(reminder.crontab, '1 1 * * *') 167 | self.assertEqual(reminder.message, 'drink water') 168 | self.assertEqual(reminder.channel_id, 'test_id') 169 | self.assertEqual(reminder.channel_name, 'test_name') 170 | -------------------------------------------------------------------------------- /trax/trax/tests/test_reminders.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import datetime 3 | import requests 4 | import pytz 5 | 6 | from test_plus.test import TestCase 7 | from dynamic_preferences.registries import global_preferences_registry 8 | 9 | from trax.trax import models 10 | from django.utils import timezone 11 | from django.forms import ValidationError 12 | from trax.users.models import User 13 | 14 | 15 | class TestTimer(TestCase): 16 | 17 | def setUp(self): 18 | self.user = self.make_user() 19 | # self.preferences = global_preferences_registry.manager() 20 | # self.preferences['trax__slash_command_token'] = 'good_token' 21 | 22 | def test_can_create_reminder(self): 23 | 24 | now = timezone.now() 25 | one_minute = now + datetime.timedelta(minutes=1) 26 | 27 | with unittest.mock.patch('django.utils.timezone.now', return_value=now): 28 | reminder = models.Reminder.objects.create( 29 | user=self.user, 30 | next_call=one_minute, 31 | message='Hello, how are you ?', 32 | channel_id='channel_id', 33 | channel_name='channel_name', 34 | ) 35 | self.assertEqual(reminder.creation_date, now) 36 | self.assertEqual(reminder.completed_on, None) 37 | 38 | @unittest.mock.patch('requests.Session.send') 39 | def test_can_send_reminder(self, r): 40 | r.return_value = unittest.mock.Mock(status=200) 41 | now = timezone.now() 42 | one_minute = now + datetime.timedelta(minutes=1) 43 | 44 | reminder = models.Reminder.objects.create( 45 | user=self.user, 46 | next_call=one_minute, 47 | message='Hello, how are you ?', 48 | channel_id='channel_id', 49 | channel_name='channel_name', 50 | ) 51 | with self.assertRaises(ValueError): 52 | reminder.send() 53 | 54 | with unittest.mock.patch('django.utils.timezone.now', return_value=one_minute): 55 | reminder.send() 56 | 57 | self.assertEqual(reminder.completed_on, one_minute) 58 | self.assertEqual(reminder.next_call, None) 59 | 60 | def test_reminder_can_use_contrab_to_set_next_call(self): 61 | self.user.preferences['global__timezone'] = 'UTC' 62 | now = timezone.now().replace(hour=12, minute=0, second=0, microsecond=0) 63 | expected = (now + datetime.timedelta(minutes=30)) 64 | 65 | with unittest.mock.patch('django.utils.timezone.now', return_value=now): 66 | 67 | reminder = models.Reminder.objects.create( 68 | user=self.user, 69 | crontab='30 12 * * *', 70 | message='Hello, how are you ?', 71 | channel_id='channel_id', 72 | channel_name='channel_name', 73 | ) 74 | 75 | print(reminder.next_call, expected) 76 | self.assertEqual(reminder.next_call, expected) 77 | 78 | @unittest.mock.patch('requests.Session.send') 79 | def test_sending_recurring_reminder_also_set_next_call(self, r): 80 | self.user.preferences['global__timezone'] = 'UTC' 81 | r.return_value = unittest.mock.Mock(status=200) 82 | 83 | now = timezone.now().replace(hour=12, minute=0, second=0, microsecond=0) 84 | expected = now + datetime.timedelta(minutes=30) 85 | 86 | with unittest.mock.patch('django.utils.timezone.now', return_value=now): 87 | 88 | reminder = models.Reminder.objects.create( 89 | user=self.user, 90 | crontab='30 12 * * *', 91 | message='Hello, how are you ?', 92 | channel_id='channel_id', 93 | channel_name='channel_name', 94 | ) 95 | 96 | self.assertEqual(reminder.next_call, expected) 97 | 98 | with unittest.mock.patch('django.utils.timezone.now', return_value=expected): 99 | reminder.send() 100 | 101 | self.assertEqual(reminder.completed_on, expected) 102 | self.assertEqual(reminder.next_call, expected + datetime.timedelta(days=1)) 103 | -------------------------------------------------------------------------------- /trax/trax/tests/test_tasks.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import datetime 3 | 4 | from test_plus.test import TestCase 5 | from django.conf import settings 6 | from django.utils import timezone 7 | 8 | from trax.trax import models, tasks 9 | 10 | 11 | class TestTasks(TestCase): 12 | def setUp(self): 13 | self.user = self.make_user() 14 | 15 | def test_can_kill_obsolete_timers(self): 16 | now = timezone.now() 17 | yesterday = now - datetime.timedelta(days=2) 18 | with unittest.mock.patch('django.utils.timezone.now', return_value=yesterday): 19 | group1 = models.TimerGroup.objects.start('Test 1', user=self.user) 20 | 21 | with unittest.mock.patch('django.utils.timezone.now', return_value=now): 22 | tasks.kill_obsolete_timers() 23 | 24 | group1.refresh_from_db() 25 | 26 | self.assertFalse(group1.is_started) 27 | self.assertEqual(group1.timers.first().end_date, now) 28 | 29 | @unittest.mock.patch('requests.Session.send') 30 | def test_can_send_reminder(self, r): 31 | r.return_value = unittest.mock.Mock(status=200) 32 | now = timezone.now() 33 | one_minute = now + datetime.timedelta(minutes=1) 34 | two_minute = now + datetime.timedelta(minutes=2) 35 | 36 | reminder1 = models.Reminder.objects.create( 37 | user=self.user, 38 | next_call=one_minute, 39 | message='Hello, how are you ?', 40 | channel_id='channel_id', 41 | channel_name='channel_name', 42 | ) 43 | reminder2 = models.Reminder.objects.create( 44 | user=self.user, 45 | next_call=two_minute, 46 | message='not send', 47 | channel_id='channel_id', 48 | channel_name='channel_name', 49 | ) 50 | 51 | with unittest.mock.patch('django.utils.timezone.now', return_value=one_minute): 52 | tasks.send_reminders() 53 | 54 | reminder1.refresh_from_db() 55 | reminder2.refresh_from_db() 56 | 57 | self.assertEqual(reminder1.completed_on, one_minute) 58 | self.assertEqual(reminder1.next_call, None) 59 | self.assertEqual(reminder2.completed_on, None) 60 | self.assertEqual(reminder2.next_call, two_minute) 61 | -------------------------------------------------------------------------------- /trax/trax/tests/test_timer.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import json 3 | import datetime 4 | from test_plus.test import TestCase 5 | from dynamic_preferences.registries import global_preferences_registry 6 | 7 | from trax.trax import models 8 | from django.utils import timezone 9 | from django.forms import ValidationError 10 | from trax.users.models import User 11 | 12 | 13 | class TestTimer(TestCase): 14 | 15 | def setUp(self): 16 | self.user = self.make_user() 17 | self.preferences = global_preferences_registry.manager() 18 | self.preferences['trax__slash_command_token'] = 'good_token' 19 | 20 | def test_can_start_timer_group(self): 21 | now = timezone.now() 22 | with unittest.mock.patch('django.utils.timezone.now', return_value=now): 23 | group = models.TimerGroup.objects.start('Test 2', user=self.user) 24 | 25 | self.assertEqual(group.name, 'Test 2') 26 | self.assertEqual(group.slug, 'test-2') 27 | self.assertEqual(group.user, self.user) 28 | 29 | timer = group.timers.first() 30 | 31 | self.assertGreaterEqual(timer.start_date, now) 32 | self.assertEqual(timer.end_date, None) 33 | 34 | def test_can_stop_timer_group(self): 35 | group = models.TimerGroup.objects.start('Test 2', user=self.user) 36 | group.stop() 37 | timer = group.timers.first() 38 | 39 | self.assertGreater(timer.end_date, timer.start_date) 40 | 41 | def test_starting_another_timer_for_same_user_stop_previous_one(self): 42 | group1 = models.TimerGroup.objects.start('test1', user=self.user) 43 | group2 = models.TimerGroup.objects.start('test2', user=self.user) 44 | 45 | timer1 = group1.timers.first() 46 | timer2 = group2.timers.first() 47 | 48 | self.assertGreater(timer1.end_date, timer1.start_date) 49 | self.assertGreater(timer2.start_date, timer1.end_date) 50 | 51 | def test_can_get_group_today_duration(self): 52 | now = timezone.now() 53 | delta = datetime.timedelta(hours=1) 54 | with unittest.mock.patch('django.utils.timezone.now', return_value=now - delta): 55 | group = models.TimerGroup.objects.start('Test 2', user=self.user) 56 | 57 | self.assertEqual(group.creation_date, now - delta) 58 | with unittest.mock.patch('django.utils.timezone.now', return_value=now): 59 | self.assertEqual(group.today_duration, delta) 60 | 61 | def test_can_start_timer_via_api_endpoint(self): 62 | payload = { 63 | 'channel_id': 'cniah6qa73bjjjan6mzn11f4ie', 64 | 'channel_name': 'town-square', 65 | 'command': '/trax', 66 | 'text': 'start This is my timer', 67 | 'team_domain': 'testteam', 68 | 'team_id': 'rdc9bgriktyx9p4kowh3dmgqyc', 69 | 'token': 'good_token', 70 | 'user_id': 'testid', 71 | 'user_name': 'thisisme', 72 | } 73 | 74 | expected = { 75 | "response_type": "ephemeral", 76 | "text": """Timer "This is my timer" was started.""" 77 | } 78 | 79 | url = self.reverse('trax:slash-command') 80 | now = timezone.now() 81 | response = self.client.post(url, payload) 82 | json_data = json.loads(response.content.decode('utf-8')) 83 | 84 | self.assertEqual(response.status_code, 200) 85 | self.assertEqual(json_data, expected) 86 | 87 | user = User.objects.get(username='thisisme', external_id='testid') 88 | 89 | self.assertFalse(user.is_active) 90 | 91 | group = models.TimerGroup.objects.latest('id') 92 | 93 | self.assertEqual(group.name, 'This is my timer') 94 | self.assertEqual(group.slug, 'this-is-my-timer') 95 | self.assertEqual(group.user, user) 96 | 97 | timer = group.timers.first() 98 | 99 | self.assertGreater(timer.start_date, now) 100 | self.assertEqual(timer.end_date, None) 101 | 102 | def test_cannot_stop_timer_with_end_date_smaller_than_start_date(self): 103 | now = timezone.now().replace(microsecond=0) 104 | start = now - datetime.timedelta(hours=2) 105 | invalid = start - datetime.timedelta(hours=3) 106 | 107 | with unittest.mock.patch('django.utils.timezone.now', return_value=start): 108 | group = models.TimerGroup.objects.start('Test 1', user=self.user) 109 | 110 | with self.assertRaises(ValidationError): 111 | group.stop(invalid) 112 | 113 | def test_timers_cannot_overlap(self): 114 | now = timezone.now().replace(microsecond=0) 115 | start = now - datetime.timedelta(hours=2) 116 | 117 | group1 = models.TimerGroup.objects.start('Test 1', user=self.user) 118 | group2 = models.TimerGroup.objects.create(name='Test 2', slug='test', user=self.user) 119 | 120 | with self.assertRaises(ValidationError): 121 | group2.timers.create() 122 | -------------------------------------------------------------------------------- /trax/trax/tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import datetime 3 | from test_plus.test import TestCase 4 | 5 | from trax.trax import models, forms, handlers 6 | from trax.users.models import User 7 | from django.conf import settings 8 | 9 | from trax.trax import utils 10 | 11 | 12 | class TestForms(TestCase): 13 | 14 | def test_humanize_timedelta(self): 15 | tests = [ 16 | (datetime.timedelta(hours=1, minutes=10), '1 hours, 10 minutes'), 17 | (datetime.timedelta(hours=5, minutes=10), '5 hours, 10 minutes'), 18 | (datetime.timedelta(minutes=1, seconds=30), '1 minutes, 30 seconds'), 19 | ] 20 | 21 | for d, expected in tests: 22 | self.assertEqual(utils.humanize_timedelta(d), expected) 23 | -------------------------------------------------------------------------------- /trax/trax/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, unicode_literals 3 | 4 | from django.conf.urls import url 5 | 6 | from . import views 7 | 8 | urlpatterns = [ 9 | url( 10 | regex=r'^slash$', 11 | view=views.slash_command, 12 | name='slash-command' 13 | ), 14 | ] 15 | -------------------------------------------------------------------------------- /trax/trax/utils.py: -------------------------------------------------------------------------------- 1 | import dateparser 2 | from django.utils import timezone 3 | 4 | 5 | def humanize_timedelta(delta): 6 | days, rem = divmod(delta.seconds, 86400) 7 | hours, rem = divmod(rem, 3600) 8 | minutes, seconds = divmod(rem, 60) 9 | if seconds < 1:seconds = 1 10 | magnitudes = ["days", "hours", "minutes"] 11 | if seconds / delta.seconds > 0.05: 12 | magnitudes.append('seconds') 13 | locals_ = locals() 14 | magnitudes_str = ("{n} {magnitude}".format(n=int(locals_[magnitude]), magnitude=magnitude) 15 | for magnitude in magnitudes if locals_[magnitude]) 16 | return ", ".join(magnitudes_str) 17 | 18 | 19 | def parse_future(s, tz): 20 | now = timezone.now() 21 | result = dateparser.parse(s, settings={'PREFER_DATES_FROM': 'future'}) 22 | if result: 23 | result = tz.localize(result) 24 | return result 25 | -------------------------------------------------------------------------------- /trax/trax/views.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from django.http import JsonResponse 4 | from django.views.decorators.http import require_http_methods 5 | from django.views.decorators.csrf import csrf_exempt 6 | from django.conf import settings 7 | from django.db import transaction 8 | from django.utils import timezone 9 | 10 | from dynamic_preferences.registries import global_preferences_registry 11 | from . import forms 12 | from . import exceptions 13 | from . import handlers 14 | 15 | # from . import handlers 16 | 17 | 18 | @csrf_exempt 19 | @require_http_methods(["POST"]) 20 | @transaction.atomic 21 | def slash_command(request): 22 | global_preferences = global_preferences_registry.manager() 23 | expected_token = global_preferences['trax__slash_command_token'] 24 | if expected_token != request.POST['token']: 25 | return JsonResponse({'text': 'Invalid token'}, status=403) 26 | 27 | form = forms.SlashCommandForm(request.POST) 28 | data = { 29 | 'response_type': 'ephemeral' 30 | } 31 | if not form.is_valid(): 32 | data['text'] = handlers.HelpHandler().get_response_content( 33 | request=request, 34 | action='help', 35 | arguments='', 36 | context={}) 37 | return JsonResponse(data) 38 | 39 | cd = form.cleaned_data 40 | handler, arguments = cd['handler'], cd['arguments'] 41 | 42 | with timezone.override(cd['user'].preferences['global__timezone']): 43 | try: 44 | result = handler.handle(**cd) 45 | except (exceptions.HandleError, exceptions.ValidationError) as e: 46 | data['text'] = handler.get_exception_response_content( 47 | exception=e, 48 | user=cd['user'], 49 | request=request, 50 | action=cd['action'], 51 | arguments=arguments 52 | ) 53 | return JsonResponse(data) 54 | data = { 55 | 'response_type': handler.response_type 56 | } 57 | data['text'] = handler.get_response_content( 58 | request=request, 59 | user=cd['user'], 60 | action=cd['action'], 61 | arguments=arguments, 62 | context=result,) 63 | 64 | if data['response_type'] == 'in_channel': 65 | data['text'] = '*{0} invoked command "{1} {2}"*\n\n'.format( 66 | cd['user'].username, cd['command'], cd['text'] 67 | ) + data['text'] 68 | return JsonResponse(data) 69 | -------------------------------------------------------------------------------- /trax/users/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | -------------------------------------------------------------------------------- /trax/users/adapters.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.conf import settings 3 | from allauth.account.adapter import DefaultAccountAdapter 4 | from allauth.socialaccount.adapter import DefaultSocialAccountAdapter 5 | 6 | 7 | class AccountAdapter(DefaultAccountAdapter): 8 | def is_open_for_signup(self, request): 9 | return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True) 10 | 11 | 12 | class SocialAccountAdapter(DefaultSocialAccountAdapter): 13 | def is_open_for_signup(self, request, sociallogin): 14 | return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True) 15 | -------------------------------------------------------------------------------- /trax/users/admin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, unicode_literals 3 | 4 | from django import forms 5 | from django.contrib import admin 6 | from django.contrib.auth.admin import UserAdmin as AuthUserAdmin 7 | from django.contrib.auth.forms import UserChangeForm, UserCreationForm 8 | from .models import User 9 | 10 | 11 | class MyUserChangeForm(UserChangeForm): 12 | class Meta(UserChangeForm.Meta): 13 | model = User 14 | 15 | 16 | class MyUserCreationForm(UserCreationForm): 17 | 18 | error_message = UserCreationForm.error_messages.update({ 19 | 'duplicate_username': 'This username has already been taken.' 20 | }) 21 | 22 | class Meta(UserCreationForm.Meta): 23 | model = User 24 | 25 | def clean_username(self): 26 | username = self.cleaned_data["username"] 27 | try: 28 | User.objects.get(username=username) 29 | except User.DoesNotExist: 30 | return username 31 | raise forms.ValidationError(self.error_messages['duplicate_username']) 32 | 33 | 34 | @admin.register(User) 35 | class MyUserAdmin(AuthUserAdmin): 36 | form = MyUserChangeForm 37 | add_form = MyUserCreationForm 38 | fieldsets = ( 39 | ('User Profile', {'fields': ('name',)}), 40 | ('Trax', {'fields': ('external_id',)}), 41 | ) + AuthUserAdmin.fieldsets 42 | list_display = ('username', 'name', 'is_superuser') 43 | search_fields = ['name'] 44 | -------------------------------------------------------------------------------- /trax/users/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class UsersConfig(AppConfig): 5 | name = 'trax.users' 6 | verbose_name = "Users" 7 | 8 | def ready(self): 9 | """Override this to put in: 10 | Users system checks 11 | Users signal registration 12 | """ 13 | pass 14 | -------------------------------------------------------------------------------- /trax/users/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.10.4 on 2016-12-27 10:49 3 | from __future__ import unicode_literals 4 | 5 | import django.contrib.auth.models 6 | import django.contrib.auth.validators 7 | from django.db import migrations, models 8 | import django.utils.timezone 9 | 10 | 11 | class Migration(migrations.Migration): 12 | 13 | initial = True 14 | 15 | dependencies = [ 16 | ('auth', '0008_alter_user_username_max_length'), 17 | ] 18 | 19 | operations = [ 20 | migrations.CreateModel( 21 | name='User', 22 | fields=[ 23 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 24 | ('password', models.CharField(max_length=128, verbose_name='password')), 25 | ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), 26 | ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), 27 | ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), 28 | ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), 29 | ('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')), 30 | ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), 31 | ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), 32 | ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), 33 | ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), 34 | ('name', models.CharField(blank=True, max_length=255, verbose_name='Name of User')), 35 | ('external_id', models.CharField(blank=True, null=True, max_length=255, unique=True)), 36 | ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), 37 | ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), 38 | ], 39 | options={ 40 | 'verbose_name': 'user', 41 | 'abstract': False, 42 | 'verbose_name_plural': 'users', 43 | }, 44 | managers=[ 45 | ('objects', django.contrib.auth.models.UserManager()), 46 | ], 47 | ), 48 | ] 49 | -------------------------------------------------------------------------------- /trax/users/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agateblue/trax/61a14b2a3cd6366422b27c48b9e3716bbdcd7ae5/trax/users/migrations/__init__.py -------------------------------------------------------------------------------- /trax/users/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals, absolute_import 3 | 4 | from django.contrib.auth.models import AbstractUser 5 | from django.core.urlresolvers import reverse 6 | from django.db import models 7 | from django.utils.encoding import python_2_unicode_compatible 8 | from django.utils.translation import ugettext_lazy as _ 9 | 10 | 11 | @python_2_unicode_compatible 12 | class User(AbstractUser): 13 | 14 | # First Name and Last Name do not cover name patterns 15 | # around the globe. 16 | name = models.CharField(_('Name of User'), blank=True, max_length=255) 17 | external_id = models.CharField( 18 | null=True, blank=True, max_length=255, unique=True) 19 | 20 | def __str__(self): 21 | return self.username 22 | 23 | def get_absolute_url(self): 24 | return reverse('users:detail', kwargs={'username': self.username}) 25 | -------------------------------------------------------------------------------- /trax/users/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agateblue/trax/61a14b2a3cd6366422b27c48b9e3716bbdcd7ae5/trax/users/tests/__init__.py -------------------------------------------------------------------------------- /trax/users/tests/factories.py: -------------------------------------------------------------------------------- 1 | import factory 2 | 3 | 4 | class UserFactory(factory.django.DjangoModelFactory): 5 | username = factory.Sequence(lambda n: 'user-{0}'.format(n)) 6 | email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) 7 | password = factory.PostGenerationMethodCall('set_password', 'password') 8 | 9 | class Meta: 10 | model = 'users.User' 11 | django_get_or_create = ('username', ) 12 | -------------------------------------------------------------------------------- /trax/users/tests/test_admin.py: -------------------------------------------------------------------------------- 1 | from test_plus.test import TestCase 2 | 3 | from ..admin import MyUserCreationForm 4 | 5 | 6 | class TestMyUserCreationForm(TestCase): 7 | 8 | def setUp(self): 9 | self.user = self.make_user('notalamode', 'notalamodespassword') 10 | 11 | def test_clean_username_success(self): 12 | # Instantiate the form with a new username 13 | form = MyUserCreationForm({ 14 | 'username': 'alamode', 15 | 'password1': '7jefB#f@Cc7YJB]2v', 16 | 'password2': '7jefB#f@Cc7YJB]2v', 17 | }) 18 | # Run is_valid() to trigger the validation 19 | valid = form.is_valid() 20 | self.assertTrue(valid) 21 | 22 | # Run the actual clean_username method 23 | username = form.clean_username() 24 | self.assertEqual('alamode', username) 25 | 26 | def test_clean_username_false(self): 27 | # Instantiate the form with the same username as self.user 28 | form = MyUserCreationForm({ 29 | 'username': self.user.username, 30 | 'password1': 'notalamodespassword', 31 | 'password2': 'notalamodespassword', 32 | }) 33 | # Run is_valid() to trigger the validation, which is going to fail 34 | # because the username is already taken 35 | valid = form.is_valid() 36 | self.assertFalse(valid) 37 | 38 | # The form.errors dict should contain a single error called 'username' 39 | self.assertTrue(len(form.errors) == 1) 40 | self.assertTrue('username' in form.errors) 41 | -------------------------------------------------------------------------------- /trax/users/tests/test_models.py: -------------------------------------------------------------------------------- 1 | from test_plus.test import TestCase 2 | 3 | 4 | class TestUser(TestCase): 5 | 6 | def setUp(self): 7 | self.user = self.make_user() 8 | 9 | def test__str__(self): 10 | self.assertEqual( 11 | self.user.__str__(), 12 | 'testuser' # This is the default username for self.make_user() 13 | ) 14 | 15 | def test_get_absolute_url(self): 16 | self.assertEqual( 17 | self.user.get_absolute_url(), 18 | '/users/testuser/' 19 | ) 20 | -------------------------------------------------------------------------------- /trax/users/tests/test_urls.py: -------------------------------------------------------------------------------- 1 | from django.core.urlresolvers import reverse, resolve 2 | 3 | from test_plus.test import TestCase 4 | 5 | 6 | class TestUserURLs(TestCase): 7 | """Test URL patterns for users app.""" 8 | 9 | def setUp(self): 10 | self.user = self.make_user() 11 | 12 | def test_list_reverse(self): 13 | """users:list should reverse to /users/.""" 14 | self.assertEqual(reverse('users:list'), '/users/') 15 | 16 | def test_list_resolve(self): 17 | """/users/ should resolve to users:list.""" 18 | self.assertEqual(resolve('/users/').view_name, 'users:list') 19 | 20 | def test_redirect_reverse(self): 21 | """users:redirect should reverse to /users/~redirect/.""" 22 | self.assertEqual(reverse('users:redirect'), '/users/~redirect/') 23 | 24 | def test_redirect_resolve(self): 25 | """/users/~redirect/ should resolve to users:redirect.""" 26 | self.assertEqual( 27 | resolve('/users/~redirect/').view_name, 28 | 'users:redirect' 29 | ) 30 | 31 | def test_detail_reverse(self): 32 | """users:detail should reverse to /users/testuser/.""" 33 | self.assertEqual( 34 | reverse('users:detail', kwargs={'username': 'testuser'}), 35 | '/users/testuser/' 36 | ) 37 | 38 | def test_detail_resolve(self): 39 | """/users/testuser/ should resolve to users:detail.""" 40 | self.assertEqual(resolve('/users/testuser/').view_name, 'users:detail') 41 | 42 | def test_update_reverse(self): 43 | """users:update should reverse to /users/~update/.""" 44 | self.assertEqual(reverse('users:update'), '/users/~update/') 45 | 46 | def test_update_resolve(self): 47 | """/users/~update/ should resolve to users:update.""" 48 | self.assertEqual( 49 | resolve('/users/~update/').view_name, 50 | 'users:update' 51 | ) 52 | -------------------------------------------------------------------------------- /trax/users/tests/test_views.py: -------------------------------------------------------------------------------- 1 | from django.test import RequestFactory 2 | 3 | from test_plus.test import TestCase 4 | 5 | from ..views import ( 6 | UserRedirectView, 7 | UserUpdateView 8 | ) 9 | 10 | 11 | class BaseUserTestCase(TestCase): 12 | 13 | def setUp(self): 14 | self.user = self.make_user() 15 | self.factory = RequestFactory() 16 | 17 | 18 | class TestUserRedirectView(BaseUserTestCase): 19 | 20 | def test_get_redirect_url(self): 21 | # Instantiate the view directly. Never do this outside a test! 22 | view = UserRedirectView() 23 | # Generate a fake request 24 | request = self.factory.get('/fake-url') 25 | # Attach the user to the request 26 | request.user = self.user 27 | # Attach the request to the view 28 | view.request = request 29 | # Expect: '/users/testuser/', as that is the default username for 30 | # self.make_user() 31 | self.assertEqual( 32 | view.get_redirect_url(), 33 | '/users/testuser/' 34 | ) 35 | 36 | 37 | class TestUserUpdateView(BaseUserTestCase): 38 | 39 | def setUp(self): 40 | # call BaseUserTestCase.setUp() 41 | super(TestUserUpdateView, self).setUp() 42 | # Instantiate the view directly. Never do this outside a test! 43 | self.view = UserUpdateView() 44 | # Generate a fake request 45 | request = self.factory.get('/fake-url') 46 | # Attach the user to the request 47 | request.user = self.user 48 | # Attach the request to the view 49 | self.view.request = request 50 | 51 | def test_get_success_url(self): 52 | # Expect: '/users/testuser/', as that is the default username for 53 | # self.make_user() 54 | self.assertEqual( 55 | self.view.get_success_url(), 56 | '/users/testuser/' 57 | ) 58 | 59 | def test_get_object(self): 60 | # Expect: self.user, as that is the request's user object 61 | self.assertEqual( 62 | self.view.get_object(), 63 | self.user 64 | ) 65 | -------------------------------------------------------------------------------- /trax/users/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, unicode_literals 3 | 4 | from django.conf.urls import url 5 | 6 | from . import views 7 | 8 | urlpatterns = [ 9 | url( 10 | regex=r'^$', 11 | view=views.UserListView.as_view(), 12 | name='list' 13 | ), 14 | url( 15 | regex=r'^~redirect/$', 16 | view=views.UserRedirectView.as_view(), 17 | name='redirect' 18 | ), 19 | url( 20 | regex=r'^(?P[\w.@+-]+)/$', 21 | view=views.UserDetailView.as_view(), 22 | name='detail' 23 | ), 24 | url( 25 | regex=r'^~update/$', 26 | view=views.UserUpdateView.as_view(), 27 | name='update' 28 | ), 29 | ] 30 | -------------------------------------------------------------------------------- /trax/users/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, unicode_literals 3 | 4 | from django.core.urlresolvers import reverse 5 | from django.views.generic import DetailView, ListView, RedirectView, UpdateView 6 | 7 | from django.contrib.auth.mixins import LoginRequiredMixin 8 | 9 | from .models import User 10 | 11 | 12 | class UserDetailView(LoginRequiredMixin, DetailView): 13 | model = User 14 | # These next two lines tell the view to index lookups by username 15 | slug_field = 'username' 16 | slug_url_kwarg = 'username' 17 | 18 | 19 | class UserRedirectView(LoginRequiredMixin, RedirectView): 20 | permanent = False 21 | 22 | def get_redirect_url(self): 23 | return reverse('users:detail', 24 | kwargs={'username': self.request.user.username}) 25 | 26 | 27 | class UserUpdateView(LoginRequiredMixin, UpdateView): 28 | 29 | fields = ['name', ] 30 | 31 | # we already imported User in the view code above, remember? 32 | model = User 33 | 34 | # send the user back to their own page after a successful update 35 | def get_success_url(self): 36 | return reverse('users:detail', 37 | kwargs={'username': self.request.user.username}) 38 | 39 | def get_object(self): 40 | # Only get the User record for the user making the request 41 | return User.objects.get(username=self.request.user.username) 42 | 43 | 44 | class UserListView(LoginRequiredMixin, ListView): 45 | model = User 46 | # These next two lines tell the view to index lookups by username 47 | slug_field = 'username' 48 | slug_url_kwarg = 'username' 49 | -------------------------------------------------------------------------------- /utility/install_os_dependencies.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | WORK_DIR="$(dirname "$0")" 4 | DISTRO_NAME=$(lsb_release -sc) 5 | OS_REQUIREMENTS_FILENAME="requirements-$DISTRO_NAME.apt" 6 | 7 | cd $WORK_DIR 8 | 9 | # Check if a requirements file exist for the current distribution. 10 | if [ ! -r "$OS_REQUIREMENTS_FILENAME" ]; then 11 | cat <<-EOF >&2 12 | There is no requirements file for your distribution. 13 | You can see one of the files listed below to help search the equivalent package in your system: 14 | $(find ./ -name "requirements-*.apt" -printf " - %f\n") 15 | EOF 16 | exit 1; 17 | fi 18 | 19 | # Handle call with wrong command 20 | function wrong_command() 21 | { 22 | echo "${0##*/} - unknown command: '${1}'" >&2 23 | usage_message 24 | } 25 | 26 | # Print help / script usage 27 | function usage_message() 28 | { 29 | cat <<-EOF 30 | Usage: $WORK_DIR/${0##*/} 31 | Available commands are: 32 | list Print a list of all packages defined on ${OS_REQUIREMENTS_FILENAME} file 33 | help Print this help 34 | 35 | Commands that require superuser permission: 36 | install Install packages defined on ${OS_REQUIREMENTS_FILENAME} file. Note: This 37 | does not upgrade the packages already installed for new versions, even if 38 | new version is available in the repository. 39 | upgrade Same that install, but upgrade the already installed packages, if new 40 | version is available. 41 | EOF 42 | } 43 | 44 | # Read the requirements.apt file, and remove comments and blank lines 45 | function list_packages(){ 46 | grep -v "#" "${OS_REQUIREMENTS_FILENAME}" | grep -v "^$"; 47 | } 48 | 49 | function install_packages() 50 | { 51 | list_packages | xargs apt-get --no-upgrade install -y; 52 | } 53 | 54 | function upgrade_packages() 55 | { 56 | list_packages | xargs apt-get install -y; 57 | } 58 | 59 | function install_or_upgrade() 60 | { 61 | P=${1} 62 | PARAN=${P:-"install"} 63 | 64 | if [[ $EUID -ne 0 ]]; then 65 | cat <<-EOF >&2 66 | You must run this script with root privilege 67 | Please do: 68 | sudo $WORK_DIR/${0##*/} $PARAN 69 | EOF 70 | exit 1 71 | else 72 | 73 | apt-get update 74 | 75 | # Install the basic compilation dependencies and other required libraries of this project 76 | if [ "$PARAN" == "install" ]; then 77 | install_packages; 78 | else 79 | upgrade_packages; 80 | fi 81 | 82 | # cleaning downloaded packages from apt-get cache 83 | apt-get clean 84 | 85 | exit 0 86 | fi 87 | } 88 | 89 | # Handle command argument 90 | case "$1" in 91 | install) install_or_upgrade;; 92 | upgrade) install_or_upgrade "upgrade";; 93 | list) list_packages;; 94 | help|"") usage_message;; 95 | *) wrong_command "$1";; 96 | esac 97 | -------------------------------------------------------------------------------- /utility/install_python_dependencies.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | WORK_DIR="$(dirname "$0")" 4 | PROJECT_DIR="$(dirname "$WORK_DIR")" 5 | 6 | pip --version >/dev/null 2>&1 || { 7 | echo >&2 -e "\npip is required but it's not installed." 8 | echo >&2 -e "You can install it by running the following command:\n" 9 | echo >&2 "wget https://bootstrap.pypa.io/get-pip.py --output-document=get-pip.py; chmod +x get-pip.py; sudo -H python3 get-pip.py" 10 | 11 | echo >&2 -e "\n" 12 | echo >&2 -e "\nFor more information, see pip documentation: https://pip.pypa.io/en/latest/" 13 | exit 1; 14 | } 15 | 16 | virtualenv --version >/dev/null 2>&1 || { 17 | echo >&2 -e "\nvirtualenv is required but it's not installed." 18 | echo >&2 -e "You can install it by running the following command:\n" 19 | echo >&2 "sudo -H pip3 install virtualenv" 20 | 21 | echo >&2 -e "\n" 22 | echo >&2 -e "\nFor more information, see virtualenv documentation: https://virtualenv.pypa.io/en/latest/" 23 | exit 1; 24 | } 25 | 26 | if [ -z "$VIRTUAL_ENV" ]; then 27 | echo >&2 -e "\nYou need activate a virtualenv first" 28 | echo >&2 -e 'If you do not have a virtualenv created, run the following command to create and automatically activate a new virtualenv named "venv" on current folder:\n' 29 | echo >&2 -e "virtualenv venv --python=\`which python3\`" 30 | 31 | echo >&2 -e "\nTo leave/disable the currently active virtualenv, run the following command:\n" 32 | echo >&2 "deactivate" 33 | echo >&2 -e "\nTo activate the virtualenv again, run the following command:\n" 34 | echo >&2 "source venv/bin/activate" 35 | echo >&2 -e "\nFor more information, see virtualenv documentation: https://virtualenv.pypa.io/en/latest/" 36 | echo >&2 -e "\n" 37 | exit 1; 38 | else 39 | 40 | pip install -r $PROJECT_DIR/requirements/local.txt 41 | pip install -r $PROJECT_DIR/requirements/test.txt 42 | 43 | fi 44 | 45 | -------------------------------------------------------------------------------- /utility/requirements-jessie.apt: -------------------------------------------------------------------------------- 1 | ##basic build dependencies of various Django apps for Debian Jessie 8.x 2 | #build-essential metapackage install: make, gcc, g++, 3 | build-essential 4 | #required to translate 5 | gettext 6 | python3-dev 7 | 8 | 9 | ##shared dependencies of: 10 | ##Pillow, pylibmc 11 | zlib1g-dev 12 | 13 | ##Postgresql and psycopg2 dependencies 14 | libpq-dev 15 | 16 | ##Pillow dependencies 17 | libtiff5-dev 18 | libjpeg62-turbo-dev 19 | libfreetype6-dev 20 | liblcms2-dev 21 | libwebp-dev 22 | 23 | ##django-extensions 24 | graphviz-dev 25 | -------------------------------------------------------------------------------- /utility/requirements-trusty.apt: -------------------------------------------------------------------------------- 1 | ##basic build dependencies of various Django apps for Ubuntu Trusty 14.04 2 | #build-essential metapackage install: make, gcc, g++, 3 | build-essential 4 | #required to translate 5 | gettext 6 | python3-dev 7 | 8 | 9 | ##shared dependencies of: 10 | ##Pillow, pylibmc 11 | zlib1g-dev 12 | 13 | ##Postgresql and psycopg2 dependencies 14 | libpq-dev 15 | 16 | ##Pillow dependencies 17 | libtiff4-dev 18 | libjpeg8-dev 19 | libfreetype6-dev 20 | liblcms1-dev 21 | libwebp-dev 22 | 23 | ##django-extensions 24 | graphviz-dev 25 | 26 | -------------------------------------------------------------------------------- /utility/requirements-xenial.apt: -------------------------------------------------------------------------------- 1 | ##basic build dependencies of various Django apps for Ubuntu Xenial 16.04 2 | #build-essential metapackage install: make, gcc, g++, 3 | build-essential 4 | #required to translate 5 | gettext 6 | python3-dev 7 | 8 | 9 | ##shared dependencies of: 10 | ##Pillow, pylibmc 11 | zlib1g-dev 12 | 13 | ##Postgresql and psycopg2 dependencies 14 | libpq-dev 15 | 16 | ##Pillow dependencies 17 | libtiff5-dev 18 | libjpeg8-dev 19 | libfreetype6-dev 20 | liblcms2-dev 21 | libwebp-dev 22 | 23 | ##django-extensions 24 | graphviz-dev 25 | 26 | --------------------------------------------------------------------------------